Search code examples
javascripthtmlcodemirrorcodemirror-modes

How to hightlight source code using codemirror on a html page


I am currently highlighting the source on my website using google's prettyprint like below on my website.

<pre class="prettyprint css">
  div {
    background-color: lightgreen;
    width: 300px;
    padding: 25px;
    border: 25px solid red;
    margin: 25px;
}
</pre>

I will already have some code on file but I only want to hightlight that code. How can I highlight the same using codemirror?


Solution

  • as it shown in codemirror.net

    create an <textarea> element, which will replace yuor current <pre> tag. set textarea to readonly if you prefer no edit.

    <textarea id="myTextarea" readonly>
    ... your code for highlighting goes here ...
    </textarea>
    
    <link rel="stylesheet" href="lib/codemirror.css">
    <script src="lib/codemirror.js"></script>
    <script>
      var editor = CodeMirror.fromTextArea(document.getElementById("myTextarea"), {
        lineNumbers: true
      });
    </script>
    

    multiple instances selected by a common class name:

    var areas = document.getElementsByClassName("myTextareaClass");
    for(var i = 0; i < areas.length; i++) {   
      CodeMirror.fromTextArea(areas.item(i), {lineNumbers: true});
    }