Monaco 中有一个文字高亮的功能,就是选中一个单词,会高亮文字文档中所有出现该单词的位置,效果如下:
Monaco 默认就有这个功能,可以根据具体需求进行定制。通过 registerDocumentHighlightProvider 进行注册
实现 provideDocumentHighlights 方法,返回 DocumentHighlight 数组
代码实现如下, 代码有个 DocumentHighlightKind 枚举类,包括 Text、Read 和 Write,从效果上来看没有啥区别。
export function documentHighlightProvider(editor: monacoEditor.editor.IStandaloneCodeEditor, monaco: typeof monacoEditor){return monaco.languages.registerDocumentHighlightProvider("javascript",{provideDocumentHighlights: (model, position, token) => {const word = model.getWordAtPosition(position);if (!word) {return [];}const wordRange = new monaco.Range(position.lineNumber,word.startColumn,position.lineNumber,word.endColumn);const matches: monacoEditor.languages.DocumentHighlight[] = [];// Search the entire document for the wordconst regex = new RegExp(`\\b${word.word}\\b`, 'g');for (let i = 1; i <= model.getLineCount(); i++) {const lineText = model.getLineContent(i);let match: RegExpExecArray | null;while ((match = regex.exec(lineText)) !== null) {matches.push({range: new monaco.Range(i,match.index + 1,i,match.index + 1 + word.word.length),kind: monaco.languages.DocumentHighlightKind.Read});}}return matches;}})
}