Javascript 为CodeMirror创建新模式
我只想突出显示如下所示的关键字:Javascript 为CodeMirror创建新模式,javascript,regex,codemirror,Javascript,Regex,Codemirror,我只想突出显示如下所示的关键字:{KEYWORD} (基本上是大写的单词,环绕在单个{}括号中) 我尝试从中复制代码,并将双括号替换为单括号: CodeMirror.defineMode('mymode', function(config, parserConfig) { var mymodeOverlay = { token: function(stream, state) { if (stream.match("{")) { while ((ch =
{KEYWORD}
(基本上是大写的单词,环绕在单个{}
括号中)
我尝试从中复制代码,并将双括号替换为单括号:
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);
});
但效果不太好:)
有什么想法吗?在Mustache示例中有特殊处理,因为它需要处理两个字符分隔符(例如,
'{{'
和'}}'
中有两个字符)。我以前从未使用过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);
});
编辑 它是有效的(尽管它也用小写字母突出显示单词) 这应该起作用:
已接受的答案突出显示括号中的每个字符 我的版本,如果其他人遇到同样的问题
codemirr.defineMode('mymode',函数(config,parserConfig){
返回{
/**
*@param{CodeMirror.StringStream}stream
*/
令牌:函数(流){
//查证{
if(stream.match('{')){
//试图找到}
//如果不是字符
如果(!stream.eatwile(/[\w]/)){
返回null;
}
if(stream.match('}')){
返回“mymode”;
}
}
而(stream.next()&&!stream.match('{',false)){}
返回null;
}
};
});
在哪些方面不起作用?它突出显示了从{
到行尾的所有内容(并且它不区分大小写)它起作用(尽管它也突出显示小写字母的单词)。谢谢:pSorry,我完全错过了关于只匹配大写单词的部分。请参阅我的编辑。
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;
}