【问题标题】:Creating new modes for CodeMirror为 CodeMirror 创建新模式
【发布时间】:2011-06-15 21:52:19
【问题描述】:

我只想突出显示如下所示的关键字:{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);
});

但效果不是很好:)

有什么想法吗?

【问题讨论】:

  • 在哪些方面不起作用?
  • 它会突出显示从{ 到行尾的所有内容(并且不区分大小写)

标签: javascript regex codemirror


【解决方案1】:

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

【讨论】:

  • 它可以工作(尽管它也会用小写字母突出显示单词)。谢谢:p
  • 对不起,我完全错过了仅匹配大写单词的部分。查看我的编辑。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多