Mark text with only character position

Probably an easier way to do it, but in case it is of use to anyone else:

This lets you highlight a specific character, when all you know is the position of the character in the source, not what line and character number that is converted into by the editor.

var highlightedText;

function highlightParam(pos){

if (typeof highlightedText === "object"){
    highlightedText.clear();
}

var ttl = 0;
var line = 0;

$('.CodeMirror-line').each( function(){

    var s = (ttl === 0) ? ttl : ttl + 1;
    var l = $(this).text().length;
    ttl += l;

    if (line > 0){
        ttl++;
    }

    if (pos >= s && pos <= ttl){
        var diff = ttl - l;
        var posAdjA = pos - diff;
        var posAdjB = posAdjA + 1;
        highlightedText = editor.markText({line: line, ch: posAdjA}, {line: line, ch: posAdjB}, {css: "background:yellow;font-weight:bold;"});
        editor.setCursor({line: line, ch: posAdjA});
    }

    line++;

} );

}
1 Like

As this seems to be the first result for this subject, just though I’d post this here for anybody else landing here that there is a built in method for this now…

cm.doc.markText(
  cm.posFromIndex(15),
  cm.posFromIndex(40),
  {css: "color:red"});