Search code examples
javascriptcodemirror

CodeMirror: Particular lines readonly


Can I set a particular number of lines (sucessive or not) to read-only mode?

For example: I have a document where I don't want the contents of some sections to be changed (like in Word, where you can set Header and Footer sections and you can lock them). Anyone know if CodeMirror supports that feature?

Thanks in advance!


Solution

  • With codemirror version 3 support for on and beforeChange was added; simply catching the change before it happens and canceling should do the trick:

    // the line numbers to be "readonly"
    var readOnlyLines = [0,1,2,3];
    
    // create the CodeMirror instance
    var editor = CodeMirror.fromTextArea(document.getElementById('input'));
    
    // listen for the beforeChange event, test the changed line number, and cancel
    editor.on('beforeChange',function(cm,change) {
        if ( ~readOnlyLines.indexOf(change.from.line) ) {
            change.cancel();
        }
    });