Search code examples
javascriptjquerycodemirror

highlighting error lines within codemirror textarea


I have textarea consisting C code. I want to highlight lines onClick based on few keywords. I am storing the line in variable and checking each line with keyword.

$('#error').click(
        function() {
            var editor= $("textarea[id='c-code']");
            var lines = editor.val().split('\n');
            editor.val(" ");
            for (var i = 0; i < lines.length; i++) {
                if (lines[i].contains("flag")) {
                    var value = '<mark>'
                            + lines[i] + '</mark>';
             editor.append(value );
            editor.append('\n');
                }
            }
        });

However its not working. Here is my jsfiddle testfiddle

Thank you.


Solution

  • The main issue you're running into is that Codemirror manages the textArea for you, so you need to get and set the textArea with the CodeMirror functions getValue() and setValue( val ).

    var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
        lineNumbers: true,
        matchBrackets: true,
        mode: "text/x-csrc",
        gutters: ["CodeMirror-lint-markers"],
        lint: true
      });
    
    $('#error').click(
      function () {
      var lines = cEditor.getValue().split('\n');
      for (var i = 0; i < lines.length; i++) {
        if (0 < lines[i].indexOf("flag")) {
          lines[i] = '<mark>' + lines[i] + '</mark>\n';
        }
      }
      cEditor.setValue(lines.join('\n'));
    });
    

    Hope this helps.

    EDIT: Per comment, tweaking the script to highlight an entire line in color.

    To highlight the entire line in color, the following links help provide guidance: CodeMirror markText is not working and https://github.com/perak/codemirror/issues/24. Using this guidance, the code above can be modified to...

    var cEditor = CodeMirror.fromTextArea(document.getElementById("c-code"), {
        lineNumbers: true,
        matchBrackets: true,
        mode: "text/x-csrc",
        gutters: ["CodeMirror-lint-markers"],
        lint: true
      });
    
    $('#error').click(
      function () {
      var lines = cEditor.getValue().split('\n');
      for (var i = 0; i < lines.length; i++) {
        if (0 < lines[i].indexOf("flag")) {
          cEditor.getDoc().markText({line:i,ch:0},{line:i,ch:lines[i].length},{css: "background-color: yellow"});
        }
      }
    });
    

    ...and now the lines with the word flag will have a background in yellow.