【发布时间】:2014-10-22 12:55:30
【问题描述】:
我正在尝试在 Codemirror 中编写自定义语言模式。我从“简单模式”(http://codemirror.net/demo/simplemode.html)开始,但看起来我无法检查段落的开头或结尾(如果我错了,请纠正我)。 (段落仅通过在文本之前/之后使用双换行符来定义)。
所以我切换到正常模式 (http://codemirror.net/doc/manual.html#modeapi),但我真的很难理解整个状态机系统的工作原理。
我开始尝试通过定义“blankLine”方法并在那里设置“prevLineBlank”状态变量来检测第一段的单词,然后在“token”方法中检查该变量,找到下一个空格(或行尾)并返回适当的样式。这个好像行得通。
现在,试图找到段落的最后一个单词,我在兜圈子......我已经设法检测到每一行的最后一个单词,并且它有效,但正如所说,我只需要做同样的事情与段落的最后一句话。到目前为止,这是我的代码:
CodeMirror.defineMode("netlang", function() {
return {
// This will detect empty lines to be used when detecting paragraph's first word
blankLine: function(state){
console.log( "netlang: BLANK line: ", state );
state.prevLineBlank = true;
},
// Just initialise state object
startState: function(){
console.log( "netlang: start state");
return {
prevLineBlank: true
};
},
token: function(stream, state) {
console.log( "netlang: token ", stream );
// Detect if we are starting a paragraph
if( state.prevLineBlank ){
// If we are, reset the variable since it is not a "start of paragraph" anymore
state.prevLineBlank = false;
// Find the next blank space
var nextSpace = stream.string.indexOf(" ");
// If found, move position there to style only the first word
if( nextSpace > -1 ){
stream.pos = nextSpace;
// If not, it means there's only one word, so tak the whole line
}else{
stream.skipToEnd();
}
// Return the style name
return "firstWord"
}
// If we're not at start of paragraph...
else
{
var lastSpace = stream.string.lastIndexOf(" ");
// No blank spaces, so only one word in line
if( lastSpace == -1 )
{
stream.skipToEnd();
return "lastWord";
}else{
// Still not in last word...
if( stream.pos < lastSpace ){
stream.next();
return null;
}else{
// Last word in line
stream.skipToEnd();
return "lastWord";
}
}
}
}
};
});
知道如何实现这一目标吗?提前致谢。
【问题讨论】:
标签: javascript codemirror