
在 VSCode 扩展开发中,装饰器 API(TextEditorDecorationType)是实现编辑器内文本标记的核心技术之一。它允许开发者高亮、修饰或标注代码中的特定文本范围,广泛应用于语法检查、TODO 提示、错误标记、代码覆盖率显示等场景。
什么是装饰器 API?
VSCode 提供了 vscode.window.createTextEditorDecorationType 方法,用于创建一种“装饰”样式定义。这种样式可以应用到文档中的某些 Range 范围上,从而改变其视觉表现,比如背景色、下划线、前置图标、悬停提示等。
装饰器本身不修改文本内容,只影响显示效果,属于 UI 层的增强。
基本使用步骤
要使用装饰器标记文本,需完成以下几步:
-
定义装饰类型:通过
createTextEditorDecorationType配置外观样式 - 确定目标范围:解析文档内容,找出需要标记的行或字符区间(Range)
-
应用装饰:调用
setDecorations将装饰类型应用到指定的编辑器
const decorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: '#ffcc00',
borderColor: 'red',
borderWidth: '1px',
borderStyle: 'solid',
overviewRulerColor: 'blue',
overviewRulerLane: vscode.OverviewRulerLane.Right,
light: { backgroundColor: '#ffffd0' },
dark: { backgroundColor: '#444' }
});
// 查找匹配文本的位置
const pattern = /TODO/g;
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
const text = document.getText();
const decorations: vscode.DecorationOptions[] = [];
let match;
while ((match = pattern.exec(text))) {
const startPos = document.positionAt(match.index);
const endPos = document.positionAt(match.index + match[0].length);
const range = new vscode.Range(startPos, endPos);
decorations.push({ range });
}
// 应用装饰
editor.setDecorations(decorationType, decorations);
}
常用装饰选项说明
创建装饰类型时,可配置多种视觉属性:
- backgroundColor:背景高亮色
- color:前景文字颜色
-
textDecoration:类似 CSS 的文本修饰,如
underline或line-through - border:为文本添加边框
- before / after:在文本前或后插入内容,支持 contentText 和 iconPath
- overviewRulerColor:在滚动条侧边栏显示标记颜色
- light / dark:针对不同主题提供样式适配
例如,用 before 实现行首图标标记:
const warningDecoration = vscode.window.createTextEditorDecorationType({
before: {
contentText: '⚠️ ',
margin: '0 1em 0 0',
textDecoration: 'none'
},
overviewRulerColor: 'orange'
});
动态更新与性能建议
装饰器不会自动更新。当文档内容变化或需要重新标记时,必须重新计算 Range 并再次调用 setDecorations。
推荐监听以下事件:
- onDidChangeTextDocument:文档内容变更时刷新标记
- onDidChangeActiveTextEditor:切换编辑器时重新应用
- onDidChangeVisibleTextEditors:可视编辑器变化时处理
对于大文件,避免全量扫描。可结合语言服务或正则分页处理,提升响应速度。
基本上就这些。掌握装饰器 API 能让你的扩展更直观地与用户交互,把信息直接“画”在代码上。合理使用,不要过度标记干扰阅读。










