Creating new modes for CodeMirror

和自甴很熟 提交于 2019-12-04 03:01:44

There is special handling in the Mustache example because it needs to handle 2-character delimiters (e.g. there are two characters in '{{' and '}}'). I've never used CodeMirror before, so this is just a guess, 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 (though it highlights words with lowercase letters too)

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;
}

Accepted answer highlight every chars in brackets.

My version, if someone else encounter same issue.

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;
        }
    };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!