我正在为 CodeMirror 编写一个上下文无关的解析器,它一次解析一个字符的代码,并根据所采取的状态转换输出一种样式。代码使用换行符\n 来触发状态转换,但 CodeMirror 似乎从输入文本中删除了这些字符(console.log (char === '\n') 始终返回 false)
是否有办法配置 CodeMirror 以提供\n 作为输入?文档似乎没有提到这个问题。
我的状态对象的格式如下
{
state1: {
active: true,
edges: {
'\n': 'state2'
}
},
state2: {
active: false,
edges: {
'#': 'state1'
}
}
}
如果需要任何其他信息或说明,请告诉我
最佳答案
让 console.log (char === '\n')
始终返回 false
并不一定意味着 CodeMirror 会删除换行符 - 文本按原样传递,即 \n
将作为两个字符传递 - \
和 n
。
尝试在您的模式中使用 token
方法来检测流中的 \n
:
var newLine = '\\n';
token : function(stream) {
var next = stream.next();
var tokenName = null;
if ('\\' === next) {
var match = stream.match(new RegExp(newLine.charAt(1)));
match && (tokenName = 'some-style' || null);
}
return tokenName;
}
您还可以将该方法推广到任何序列,而不仅仅是 \n
:
var sequence = 'some-sequence';
token : function(stream) {
var next = stream.next();
var tokenName = null;
var ch = sequence.charAt(0);
// search for the first letter
if (next === ch) {
// try to match the rest of the sequence
var match = stream.match(new RegExp(sequence.substring(1)));
match && (tokenName = 'some-style' || null);
}
return tokenName;
}
这尚未经过测试,但我怀疑足以实现这一目的。请告诉我您的情况如何。
关于javascript - CodeMirror 中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15989560/