在CodeMirror中查找自定义语言模式的段落的第一个单词和最后一个单词

Finding first and last words of paragraph for custom language mode in CodeMirror

本文关键字:单词 段落 第一个 最后一个 模式 CodeMirror 查找 自定义 语言      更新时间:2023-09-26

我正在尝试在Codemirror中编写一个自定义语言模式。我从"简单模式"开始(http://codemirror.net/demo/simplemode.html),但看起来我无法检查段落的开头或结尾(如果我错了,请纠正我)。(段落的定义只需在文本前/后使用双换行符即可)。

所以我切换到正常模式(http://codemirror.net/doc/manual.html#modeapi),但我真的很难理解整个状态机系统的工作原理。

我开始尝试通过定义一个"blankLine"方法并在那里设置一个"prevLineBlank"状态变量来检测第一段的单词,然后在"token"方法中检查该变量,找到下一个空格(或行尾)并返回appropiate样式。这个似乎有效。

现在,为了找到这段话的最后一句话,我在兜圈子。。。我已经设法检测到了每一行的最后一个单词,这很有效,但正如所说,我只需要对段落的最后一句单词进行检测。到目前为止,这是我的代码:

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

你知道如何做到这一点吗?提前谢谢。

使用CodeMirror的当前模式系统无法做到这一点——要知道一行是否是段落中的最后一行,必须向前看下一行,这是不可能的。另请参阅https://github.com/codemirror/CodeMirror/issues/839