如何根据子字符串位置在代码镜像中突出显示子字符串

How to highlight substrings in CodeMirror based on substring positions

本文关键字:字符串 显示 镜像 何根 位置 代码      更新时间:2023-09-26

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

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),但它看起来不支持基于字符串位置而不是关键字列表或正则表达式规则来处理突出显示。

提前谢谢。

markText 方法旨在使这种事情变得容易。