10

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

我通过复制Mustache Overlay demo中的代码并用单个括号替换双括号来尝试此操作:

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

但效果不是很好:)

有任何想法吗?

4

2 回答 2

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

编辑

它有效(尽管它也用小写字母突出显示单词)

应该有效:

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;
}
于 2011-06-15T22:06:40.430 回答
3

接受的答案突出显示括号中的每个字符。

在此处输入图像描述

我的版本,如果其他人遇到同样的问题。

在此处输入图像描述

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;
        }
    };
});
于 2014-10-13T12:12:03.233 回答