Trying to "Overlay"

I was looking into using “overlays” (trying to make use of the “mustache” example) and don’t quite seem to be able to get it working the way I wanted.

What I am trying to do is have things looking like ${variable} highlighted.

Now, I am using different modes already in the editor: “text/plain”, “text/html”, “text/x-sql” and “application/json” and want to have these ${variable} sequences highlighted no matter the mode.

The first thing I believe I should know is whether, when I call “CodeMirror.overlayMode()”, can I actually add to the logic of an existing mode (like “text/plain” or “text/html”). Is that what this is for or did I get that wrong and when I define an overlay it is expected that I will be using it INSTEAD of the other modes at any given time?

Let me know.



The second argument to overlayMode specifies the inner mode, and creates a new mode. It does not replace the inner mode, it just creates a mode object based on it. You could override a mode with its overlaid variant, but that’s slightly tricky since you’ll still need access to the original mode’s constructor. Something like this (where we use the old mode’s proper name, htmlmixed to be able to access it after having overridden the mime type text/html):

CodeMirror.defineMode("text/html", function(conf) {
  return CodeMirror.overlayMode({/* your logic */ }, CodeMirror.getMode(conf, "htmlmixed"));

I tried the following:

In the “style” section:

.cm-AppJSONOverlay {color: #FF6600;} // Orange

In the “script” section:

CodeMirror.defineMode(“application/json”, function(config)
var AppJSONOverlay =
token: function(stream, state)
var ch;

        if (stream.match("${")) 
            while ((ch = != null)
                if (ch == "}") 
                    return "application/json";
        while (( != null) && !stream.match("${", false)) {}
        return null;

return CodeMirror.overlayMode(AppJSONOverlay, CodeMirror.getMode(config, "javascript"));


But when I type in, say, ${abc} it doesn’t end up displayed in orange.

When I trace through the code I see that the editor’s mode is indeed “application/json”.

Any ideas as to what I am not doing?


My example should have called defineMIME, not defineMode. It’s likely that that’s the problem.

Well, I must still be doing something wrong because change defineMode() for defineMIME() still doesn’t work - typing in “${abc}” doesn’t get highlighted as I was hoping for.

Funny how sometimes the easiest looking things take the most time to get right…