【问题标题】:Finding first and last words of paragraph for custom language mode in CodeMirror在 CodeMirror 中为自定义语言模式查找段落的第一个和最后一个单词
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 非常感谢您的回复。既然你提到了“当前模式系统”,这是否意味着其他一些系统正在开发中可以帮助解决这个问题?无论如何,我还有什么选择?有什么解决方法或技巧可以应用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多