CodeMirror 自定义模式 - 如何在关键字上应用样式?

CodeMirror custom mode - how to apply styles on keywords?

我正在尝试编写自己的 CodeMirror 模式,如记录的那样 here

我的objective是改变特定关键字的颜色。例如,任何 "aaa" 单词都需要是红色的,任何 "bbb" 单词都需要是蓝色的。任何其他单词都需要使用默认颜色。

这是我不成功的尝试 (see jsfiddle)。如何实现?

HTML:

<textarea rows="4" cols="30" id="cm" name="cm">aaa bbb ccc</textarea>

CSS:

.style1 { color: red; }
.style2 { color: blue; }

Javascript:

CodeMirror.defineMode("mymode", function() {

  return {
    token: function(stream,state) {

        if (stream.match("aaa") ) {
            console.log("aaa found");
            while ((ch = stream.next()) != null)
                if (ch == " " && stream.next() == " ") break;
            return "style1";
        }
        else if (stream.match("bbb") ) {
            console.log("bbb found");
            while ((ch = stream.next()) != null)
                if (ch == " " && stream.next() == " ") break;   
            return "style2";
        }
     else
         return null;
    }
  };

});


var editor = CodeMirror.fromTextArea(document.getElementById('cm'), {
    mode: "mymode",
    lineNumbers: true
});  

你有两个问题。

  • CodeMirror 前缀为 cm- 到 类 用于样式标记。 CSS 中的样式必须考虑到这一点。

  • 您在找到 "aaa" 或 "bbb" 后跳过了该行的其余部分,尽管您对目标的描述听起来好像您不想那样做。

我已在 the jsfiddle 中修复了这两个问题。您可能还想只匹配完整的单词(目前 fooaaabar 还突出显示了 aaa)。为此,首先让分词器读取整个单词 (stream.eatWhile(/\w/)),然后查看生成的单词是否是您要查找的单词之一 (stream.current() == "aaa")。