Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make CodeMirror start at a certain number of rows, and expand for as many lines as the user types?

When I start CodeMirror with

     var jsEditor = CodeMirror.fromTextArea(document.getElementById('js'),
      {
        lineNumbers: true,
        mode: 'javascript',
        theme: 'material',
        height: 'auto', 
        viewportMargin: 'Infinity'
      });

It defaults to 10 lines. I would like it to start with 2 lines

like image 715
abalter Avatar asked Jan 25 '26 10:01

abalter


1 Answers

You can use height: fit-content !important or height: auto !important on .CodeMirror. You must use "!important" to override codemirror's styling.

If you want to start with a certain amount of rows in view, you can set a variable minLines and use it like so:

// on initialization

var minLines = 10;
editor.focus();
// Set the cursor at the end of existing content
editor.setCursor(editor.lineCount());

var lineCount = editor.lineCount(); // current number of lines
var n = editor.options.minLines - lineCount; // how many lines we need

var line = editor.getCursor().line;
var ch = editor.getCursor().ch;

for(i = 0; i < n; i++) {
    editor.replaceRange("\n", { line });
    line++;
}

Or, if what you meant was to actually begin the editor with a certain number you can use firstLineNumber in the editor options like so:

var jsEditor = CodeMirror.fromTextArea(document.getElementById('js'),
  {
    lineNumbers: true,
    firstLineNumber: 10,
    mode: 'javascript',
    theme: 'material',
    height: 'auto', 
    viewportMargin: 'Infinity'
  });
like image 131
Souleste Avatar answered Jan 27 '26 00:01

Souleste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!