1

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.

ariana777
  • 53
  • 9

1 Answers1

0

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.

Trentium
  • 3,419
  • 2
  • 12
  • 19
  • yes you are right! thank you so much, its working :) However i am unable change the color of line. its adding as text in the textarea. – ariana777 Sep 14 '19 at 16:35
  • @ariana, See Edit above, with update to the code to exemplify using CodeMirror to highlight rows in yellow. – Trentium Sep 14 '19 at 17:11