如何基于子字符串位置突出显示CodeMirror中的子字符串

时间:2014-11-25 13:28:28

标签: javascript codemirror codemirror-modes

我正在尝试将CodeMirror(http://codemirror.net/)用作具有一些额外功能的基本文本编辑器。其中之一是突出显示由原始字符串中的位置指定的特定单词或单词组。我有一个外部结构存储我想要突出显示的子串位置列表。此结构是一个数组,其中每个元素表示一个文本行,并包含一个对象数组,其中要突出显示子字符串的位置。举个例子,我有这个文本字符串:

The moon
is pale and round
as is
also the sun

要突出显示的词是“月亮”,“苍白”,“圆形”和“太阳”。因此,突出显示结构如下:

[
    [ { iStart:4, iEnd:7 } ], // "moon"
    [ { iStart:3, iEnd:6 }, { iStart:12, iEnd:16 } ], // "pale" and "round"
    [], 
    [ { iStart:9, iEnd:11 } ] // "sun"

]

为了实现这一点,我首先尝试编写自定义语言模式但没有成功(主要是因为我不知道如何管理CodeMirror似乎使用令牌,而不是行,我显然需要知道当前令牌所在的行,以便从突出显示结构中检索正确的数据。)

然后我尝试编写一个外部函数,通过手动添加SPAN标记来应用突出显示,如下所示:

function highlightText()
{
    console.log( "highlightText()" );
    // Get a reference to the text lines in the code editor
    var codeLines = $("#editorContainer .CodeMirror-code pre>span" );
    for( var i=0; i<colorSegments.length; i++ ){
        // If there's text to be highlighted in this line...
        if( colorSegments[i] && colorSegments[i].length > 0 ){
            // Get the right element and do so
            var lineElement = codeLines[i];
            highlightWordsInLine( lineElement, colorSegments[i] );
        }
    }
}

function highlightWordsInLine(element, positions) {     
    // Get the raw text
    var str = $( element ).text();
    // Build a new string with highlighting tags.
    // Start 
    var out = str.substr(0, positions[0].iStart);
    for( var j=0; j<positions.length; j++ ){
        var position = positions[j];
        // Apply the highlighting tag
        out += '<span class="cm-s-ambiance cm-relation">';
        out += str.substr( position.iStart, position.iEnd - position.iStart + 1);
        out += '</span>';
        // Do not forget to incluide unhighlighted text in between
        if( j < positions.length-1 ){
            out += str.substr(  position.iEnd - position.iStart + 1, positions[j+1].iStart );
        }
    }
    // Wrap up to end of line
    out +=  str.substr( position.iEnd + 1);

    // Reset the html element value including applied highlight tags
    element.innerHTML = out;
}

我理解这是一种相当肮脏的方法,它实际上不能100%工作,因为代码编辑器中的一些文本变得无法选择和其他错误,但至少我在控制突出显示方面取得了一些成功。

所以我的问题是,做到这一点的正确方法是什么?如果我坚持语言模式的方法,我该怎么做呢?

我也被建议看看Ace(http://ace.c9.io/#nav=higlighter),但看起来它不支持基于字符串位置而不是关键字列表或正则表达式规则来处理突出显示。

提前致谢。

1 个答案:

答案 0 :(得分:2)

markText方法旨在使这种事情变得简单。

相关问题