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

HTML混合模式下Codemirror自定义自动补全提示词过滤相关问题咨询

实现自定义提示词过滤

你当前直接全量插入自定义提示词,没有关联用户输入的匹配规则,所以不会随输入内容过滤。你需要先获取光标前的输入文本作为匹配前缀,过滤自定义词后再加入结果列表。

同时注入自定义提示到HTML和JS补全

你可以把自定义提示的合并逻辑封装成公共函数,分别包装CodeMirror.hint.html和CodeMirror.hint.javascript即可,不需要重复编写两套逻辑。

以下是完整实现代码:

// 公共自定义提示词库
const myHints = ["{{Test}}","{{Simple}}","{{Example.getFunction()}}"];

// 通用hint包装函数,可复用给任意语言的hint方法
function wrapHint(origHint) {
  return function(cm) {
    // 调用原生hint方法获取原有提示结果
    const inner = origHint(cm) || { from: cm.getCursor(), to: cm.getCursor(), list: [] };
    const cursor = cm.getCursor();
    // 获取当前行光标之前的文本
    const lineBeforeCursor = cm.getLine(cursor.line).slice(0, cursor.ch);
    // 提取匹配前缀:取最后一段连续非空白字符作为匹配依据,可根据你的需求调整规则
    // 如果仅需要输入{{后才触发自定义提示,可将正则改为 /\{\{[^\s}]*$/
    const prefixMatch = lineBeforeCursor.match(/[^\s<>{}]*$/);
    const prefix = prefixMatch ? prefixMatch[0] : '';

    // 过滤自定义提示词:此处用不区分大小写的包含匹配,可改为前缀匹配等其他规则
    const filteredHints = myHints.filter(item => 
      item.toLowerCase().includes(prefix.toLowerCase())
    );

    // 合并原生提示和过滤后的自定义提示
    inner.list = [...inner.list, ...filteredHints];
    // 可选:对所有提示项按字典序排序
    inner.list.sort((a, b) => a.localeCompare(b));

    return inner;
  }
}

// 分别包装HTML和JavaScript的提示方法,即可在两类场景下都生效
CodeMirror.hint.html = wrapHint(CodeMirror.hint.html);
CodeMirror.hint.javascript = wrapHint(CodeMirror.hint.javascript);

你可以根据实际需求调整前缀提取规则、匹配规则,比如改为仅前缀匹配、区分大小写等,适配你的使用场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 22:15:02