ale93p ale93p - 4 months ago 60
Javascript Question

CodeMirror - Check if cursor is at end of line

I set readonly lines in my editor this way:

editor.on('beforeChange', function(cm, change) {
if (~readOnlyLines.indexOf(change.from.line)) {
change.cancel();
}
}


Where readOnlyLines is an array containing numbers of the lines to be readonly.

The problem is that when I am on an editable row with a readonly one below, if I press "Del" the readonly row comes upside and I can edit it.

The same doesn't work if I have a readonly row above and I press "BackSpace".

I think I should add an if that checks if at the same time:


  1. Del is pressed (I used a catch event)

  2. The line below is readonly (I did it the same way I did with the if in the code above)

  3. The cursor is at the end of line (Does a specific function exist?)


Answer

The cursor is at the end of line (Does a specific function exist?)

if (cm.doc.getLine(change.from.line).length == change.from.ch) {

If the readOnlyLines array is a range of contigous lines you may do something like:

$(function () {
  var editor = CodeMirror.fromTextArea(document.getElementById('txtArea'), {
    lineNumbers: true
  });

  var readOnlyLines = [1,2,3];

  editor.on('beforeChange', function(cm, change) {
    if (~readOnlyLines.indexOf(change.from.line)) {
      change.cancel();
    } else {
      // if you are deleting on the row before the next readonly one
      if ((change.origin == '+delete') && ~readOnlyLines.indexOf(1+change.from.line)) {
        // when you press DEL at the end of current line
        if (cm.doc.getLine(change.from.line).length == change.from.ch) {
          change.cancel();
        }
        // if you are deleting the whole line
        if (cm.doc.getSelection() == cm.doc.getLine(change.from.line)) {
          change.cancel();
        }
        // if the line is empty
        if (cm.doc.getLine(change.from.line).trim().length == 0) {
          change.cancel();
        }
      }
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.16.0/codemirror.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.16.0/codemirror.js"></script>



<textarea id="txtArea">
1111
2222 READ ONLY
3333 READ ONLY
4444 READ ONLY
5555
6666
7777
</textarea>

Comments