Creating New Modes for CodeMirror

I want to highlight only keywords that look like this: {KEYWORD} (basically UPPERCASE words enclosed between single parentheses {} )

I tried this by copying the code from the mustache overlay demo and replacing the double brackets with single ones:

 CodeMirror.defineMode('mymode', function(config, parserConfig) { var mymodeOverlay = { token: function(stream, state) { if (stream.match("{")) { while ((ch = stream.next()) != null) if (ch == "}" && stream.next() == "}") break; return 'mymode'; } while (stream.next() != null && !stream.match("{", false)) {} return null; } }; return CodeMirror.overlayParser(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mymodeOverlay); }); 

but it does not work very well :)

Any ideas?

+8
javascript regex codemirror
source share
2 answers

The example of Usachi has special processing, because for processing two-character separators (for example, there are two characters in '{{' and '}}' ). I have never used CodeMirror before, so this is just a hunch, but try something like this:

 CodeMirror.defineMode("mymode", function(config, parserConfig) { var mymodeOverlay = { token: function(stream, state) { if (stream.match("{")) { while ((ch = stream.next()) != null) if (ch == "}") break; return "mymode"; } while (stream.next() != null && !stream.match("{", false)) {} return null; } }; return CodeMirror.overlayParser(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mymodeOverlay); }); 

Edit

it works (although it also highlights words with lowercase letters)

This should work:

 token: function(stream, state) { if (stream.match("{")) { while ((ch = stream.next()) != null && ch === ch.toUpperCase()) if (ch == "}") break; return "mymode"; } while (stream.next() != null && !stream.match("{", false)) {} return null; } 
+6
source share

The accepted answer highlights all characters in brackets.

enter image description here

My version is if someone else is facing the same problem.

enter image description here

 CodeMirror.defineMode('mymode', function (config, parserConfig) { return { /** * @param {CodeMirror.StringStream} stream */ token: function (stream) { // check for { if (stream.match('{')) { // trying to find } // if not a char if (!stream.eatWhile(/[\w]/)) { return null; } if (stream.match('}')) { return 'mymode'; } } while (stream.next() && !stream.match('{', false)) {} return null; } }; }); 
+2
source share

All Articles