gpt4 book ai didi

javascript - 如何根据子串位置在CodeMirror中突出显示子串

转载 作者:行者123 更新时间:2023-11-29 21:54:34 25 4
gpt4 key购买 nike

我正在尝试使用 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似乎使用 token 而不是行的事实,我显然需要知道当前标记所在的行,以便从高亮结构中检索正确的数据)。

然后我尝试编写一个外部函数,通过手动添加 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方法旨在使这种事情变得简单。

关于javascript - 如何根据子串位置在CodeMirror中突出显示子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27128059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com