插件窝 干货文章 如何在CodeMirror中高亮特定字符?完整实现教程

如何在CodeMirror中高亮特定字符?完整实现教程

如何在CodeMirror中高亮特定字符?

CodeMirror是一款强大的在线代码编辑器,很多开发者想知道如何实现特定字符的高亮显示。本文将详细介绍三种实现方法。

方法一:使用标记文本功能

// 标记特定文本
const editor = CodeMirror(document.body, {
  lineNumbers: true
});

// 高亮所有'function'单词
const marks = [];
function highlightText() {
  // 先清除旧标记
  marks.forEach(mark => mark.clear());
  marks.length = 0;
  
  // 搜索并标记
  const cursor = editor.getSearchCursor('function');
  while (cursor.findNext()) {
    marks.push(editor.markText(
      cursor.from(), 
      cursor.to(),
      {className: 'highlighted-text'}
    ));
  }
}

// 添加CSS样式
.highlighted-text {
  background-color: yellow;
  font-weight: bold;
}

方法二:自定义语法模式

对于更复杂的高亮需求,可以创建自定义语法模式:

CodeMirror.defineMode('custom', function() {
  return {
    token: function(stream) {
      if (stream.match('TODO')) {
        return 'todo';
      }
      stream.next();
      return null;
    }
  };
});

// 使用自定义模式
const editor = CodeMirror(document.body, {
  mode: 'custom',
  lineNumbers: true
});

// 添加CSS
.CodeMirror .cm-todo {
  color: red;
  font-weight: bold;
}

方法三:使用addOverlay方法

临时覆盖高亮特定模式:

const overlay = {
  token: function(stream) {
    if (stream.match('error')) {
      return 'error';
    }
    while (stream.next() != null && !stream.match('error', false)) {}
    return null;
  }
};

editor.addOverlay(overlay);

// 移除覆盖
// editor.removeOverlay(overlay);

最佳实践建议

  • 对于简单高亮,推荐使用markText方法
  • 对于语法相关高亮,建议自定义模式
  • 临时高亮可以使用addOverlay
  • 注意性能影响,避免在大型文档中频繁操作

通过以上方法,您可以灵活地在CodeMirror中实现各种字符高亮效果,提升代码编辑体验。