Search code examples
javascriptcodemirror

CodeMirror: make atomic range of token


I'm implementing CodeMirror to use as an editor for special files that require some syntax highlighting. I wrote my own parser for it, but now I face the following problem: there is a specific kind of token that I would always like to mark as an atomic range (with doc.markText).

I would have thought that there would exist some event handler for when tokens have been parsed, containing {line, ch} objects for its start and end positions. Reading through the docs, this does not seem to exist, so I would write my own, but the problem is that there seems to be no way to get any kind of position data whatsoever related to the parser.

What would be the best way to go about this? There are really crude ways like registering a change handler or iterating over the whole contents every few seconds, but of course this should be avoided.


Solution

  • I've forked the CodeMirror github repo and made an event that fires when a token gets parsed.

    The syntax is this:

    "tokenParsed" (instance: CodeMirror, start: {ch, line}, end: {ch, line}, style: String, text: String)
    

    And then I handle it as follows:

    myCodeMirror.on("tokenParsed", function(instance, start, end, style, text) {
        if(!instance.findMarksAt(end).length) { //check if the mark doesn't exist yet
            if(style && style.indexOf("param") > -1) {
                instance.markText(start, end, {atomic: true});
            }
        }
    });
    

    If anyone wants this, see my repository.