You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Monaco Editor中获取鼠标悬浮单词并匹配数组值展示?

解决Monaco Editor中获取悬浮单词的问题

嘿,我刚好做过类似的需求!你不用费劲去手动计算getValueInRange的起止列,Monaco其实给我们准备了更省心的API来处理这个场景。

关键方法:model.getWordAtPosition()

Monaco的ITextModel提供了getWordAtPosition(position)方法,它能直接返回鼠标悬浮位置对应的单词详情——包括这个单词的起止行列范围,还有单词本身的内容。完全不用自己去猜列数,太方便了!

适配你代码的修改示例

把你的provideHover逻辑改成下面这样,就能轻松拿到悬浮单词并匹配对应的值:

public variableHoverProvider = <monaco.languages.HoverProvider>{
  provideHover: (model, position, token) => {
    const lineContent = model.getLineContent(position.lineNumber);
    if (lineContent.trim() === '') {
      return; // 空白行直接跳过
    }

    // 获取悬浮位置的单词信息
    const wordInfo = model.getWordAtPosition(position);
    if (!wordInfo) {
      return; // 悬浮在非单词区域(比如标点、空白)时返回
    }

    // 拿到悬浮的单词内容
    const hoveredWord = wordInfo.word;
    console.log('当前悬浮的单词:', hoveredWord);

    // 从你的存储中匹配对应变量
    const current = this.store[this.store.length - 1];
    const matchedVariable = current.contextVariables.find(ctxVariable => {
      // 这里根据你实际的变量结构调整匹配逻辑,比如假设变量有name字段对应单词
      return ctxVariable && ctxVariable.name === hoveredWord;
    });

    // 返回对应的悬浮内容
    if (matchedVariable) {
      return {
        contents: [{ value: matchedVariable.value }]
      };
    } else {
      return {
        contents: [{ value: '未找到该单词对应的变量值' }]
      };
    }
  }
};

额外提示

  • 如果你的场景需要自定义单词的识别规则(比如允许特殊字符作为单词的一部分),可以用monaco.languages.setWordDefinitionRules来配置自己的单词分隔规则。
  • 一定要加wordInfo的空判断,不然鼠标悬浮在空白或标点上时会报错哦。

内容的提问来源于stack exchange,提问作者Devid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:51:01