Monaco 使用 DocumentHighlightProvider

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 word
      const 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;
    }
  })
}

相关推荐

  1. 使用 Monaco Editor 开发 SQL 编辑器

    2024-07-18 04:14:03       28 阅读
  2. vue3.0-monaco组件封装

    2024-07-18 04:14:03       35 阅读
  3. monaco-editor设置语言、值等

    2024-07-18 04:14:03       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 04:14:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 04:14:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 04:14:03       57 阅读
  4. Python语言-面向对象

    2024-07-18 04:14:03       68 阅读

热门阅读

  1. 记一次Mysql连接失败的处理过程

    2024-07-18 04:14:03       28 阅读
  2. 从入门到高手的99个python案例

    2024-07-18 04:14:03       18 阅读
  3. Springboot Excel 导出工具 -- EasyPoi 简介

    2024-07-18 04:14:03       22 阅读
  4. 智能家居的优缺点有哪些?

    2024-07-18 04:14:03       17 阅读
  5. RedisServer解析(一)

    2024-07-18 04:14:03       24 阅读
  6. 【算法模板】数论:杨辉三角求组合数

    2024-07-18 04:14:03       23 阅读
  7. 【算法】位运算

    2024-07-18 04:14:03       21 阅读