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;
}
临时覆盖高亮特定模式:
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);
通过以上方法,您可以灵活地在CodeMirror中实现各种字符高亮效果,提升代码编辑体验。