How can I highlight code with ACE editor?

Benjamin Atkin picture Benjamin Atkin · Jan 12, 2012 · Viewed 16.4k times · Source

I'd like to syntax highlight more than a dozen small snippets of code and then make them editable with ACE Editor by clicking on them, since I think it would be much faster than setting up the full editor for each. I see there's a simple command for setting up an ACE editor:

<div id="editor">some text</div>
<script src="src/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
window.onload = function() {
    var editor = ace.edit("editor");
};
</script>

Is there a simple way to call into the API to just highlight the text without setting up the editor? The ideal API would take in some text and return HTML with tags that could be used for highlighting. I'm aware there are specialized highlighting libraries for JavaScript, but I would like to try using the same highlighter both for text that's being displayed and text that's being edited.

Answer

megas picture megas · Feb 21, 2012

Highlight the word:

var range = new Range(rowStart, columnStart, rowEnd, columnEnd);
var marker = editor.getSession().addMarker(range,"ace_selected_word", "text");

Remove the highlighted word:

editor.getSession().removeMarker(marker);

Highlight the line:

editor.getSession().addMarker(range,"ace_active_line","background");