Search code examples
javascriptregexcodemirrorcodemirror-modes

code mirror : using regular expression


I am trying to use regular expression for a simple mode in code mirror.

My minimal code for testing it:

CodeMirror.defineMode("regex", function() {
  return {
    token: function(stream, state) {
    console.log(stream);
    a = stream.match(/word/);
    console.log(a);
    stream.skipToEnd();
    return null;
    }
  };
});

The output of the first pass is:

Object { start: 74, pos: 74, string: "This is a sentence with word and key in it, and word and key are repeated.", tabSize: 4, lastColumnValue: 0, lastColumnPos: 0, lineStart: 0 } regex.js:5
null

If I use the string "word" rather than the regex, it logs "undefined" instead of "null".

Documentation of code mirror (http://codemirror.net/doc/manual.html) says (function match):

pattern can be either a string or a regular expression starting with ^

which is unclear to me (^ means 'not' for regex ?)

It is the first time I use codemirror, regular expression and javascript, so I might be missing something obvious.


Solution

  • ok, got it

    a = stream.match(/word/);
    

    checks for the regex at the current position of the stream, i.e. if the stream is at the beginning of:

    "This is a sentence with word and key in it, and word and key are repeated."
    

    then it will check only the first letter, will stop at "T" because it does not match the regex and return "null".

    So, it makes sense to advance the stream while the regex is not met, which explains why the usage of ^ if advised.