Search code examples
javascriptace-editor

Highlighting a single character in ace


I want to highlight a single character (at a given position) in an ace editor. It seems that I can use addMarker for this, but documentation is pretty much non-existant and I can't make sense of what is going on in my attempts.

Here is one quick demo attempt (fiddle):

setInterval(function () {
    if (currentMarker) {
        editor.session.removeMarker(currentMarker);
    }

    currentMarker = editor.session.addMarker(new Range(1, x, 2, x+1), "marked", "text", false);

    x = ++x % 25;
}, 250);

I would expect a single character to be highlighted and every quarter second the marker should switch to the character next to it. But that's not what happens.

My questions here would be * Why does it behave this way? * How do I make it behave the way I want to? * I read about "dynamic" markers, but can't find any information on what those are. So – what are they?


Solution

  • you need to add position: absolute; for marked class and to use same row for start and end of the range new Range(1, x, 1, x+1)

    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/javascript");
    
    var Range = ace.require('ace/range').Range;
    
    var currentMarker;
    var x = 0;
    setInterval(function () {
        if (currentMarker)
            editor.session.removeMarker(currentMarker);
    
        currentMarker = editor.session.addMarker(new Range(1, x, 1, x+1), "marked", "text", false);
        x = ++x % 25;
    }, 250);
    #editor {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
    .marked {
        background: red;
        color: red;
        position: absolute;
    }
    <div id="editor">function foo(items) { var x = "All this is syntax highlighted"; return x; }
    function foo(items) { var x = "All this is syntax highlighted"; return x; }
    function foo(items) { var x = "All this is syntax highlighted"; return x; }</div>
    <script src="//cdn.jsdelivr.net/ace/1.1.7/min/ace.js" type="text/javascript" charset="utf-8"></script>