1
votes

I am trying to use CodeMirror for highlighting of certain text. Unusual thing in this project is that what I have to highlight is not predefined, rather I make a web service call and webserivice's response gives me indexes of what should be highlighted. This is an NLP project and the webservice is giving me context specific "knowledge" and that is what I want to highlight.

Simply put I am getting JSON objects with start and end attributes which denotes positions of chars to be highlighted

Following is what I have so far as the mode definition, I have edited the "diff" mode

CodeMirror.defineMode("diff", function() {
    var i=-1;
    return {
        token: function(stream) {
            i++;
            //      stream.skipToEnd();
            var ch = stream.next();
            if ( bufferedResponse != null && bufferedResponse != "" && bufferedResponse.allergies != null ){
                $.each( bufferedResponse.allergies, function( key, value )
                {
                    if ( key != null && value != null && value != "" )
                    {
                        if(i<value.start && i>value.end){
                            return "minus";
                        }
                    }
                });

            }
        }
    };
});

CodeMirror.defineMIME("text/x-diff", "diff");

My question is how can I get the stream's current relative to start of the string(not line)? I mean if stream is reading the 149th char how can I retrieve this number? "pos", "start" and "columns" give me position in the current line only!

Is this possible using CodeMirror?

1

1 Answers

3
votes

Old Question but if you are trying to find the line/ch values purely from a number you can use:

var editor = CodeMirror.fromTextArea(...
...);

var obj = editor.posFromIndex(number);
alert(obj.line + ', ' + obj.ch);