为CodeMirror创建新模式

Ale*_*lex 9 javascript regex codemirror

我想只突出显示如下的关键字:( {KEYWORD} 基本上是单个{}括号之间的大写单词)

我尝试通过复制Mustache Overlay演示中的代码,并将双括号替换为单个括号:

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);
});
Run Code Online (Sandbox Code Playgroud)

但它不是很好:)

有任何想法吗?

Mat*_*all 6

在Mustache示例中有特殊处理,因为它需要处理2个字符的分隔符(例如,在'{{'和中有两个字符'}}').我之前从未使用过CodeMirror,所以这只是一个猜测,但尝试这样的事情:

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);
});
Run Code Online (Sandbox Code Playgroud)

编辑

它有效(虽然它也突出了小写字母的单词)

应该工作:

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;
}
Run Code Online (Sandbox Code Playgroud)