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

开发VS Code扩展:使用何种API在指定行显示行内错误信息?

在VS Code扩展中为指定行添加错误提示的实现方法

要实现类似附图中指定行显示红色错误提示的效果,核心是使用VS Code的Diagnostic API,以下是具体实现步骤和代码示例:

核心步骤

  1. 创建诊断集合:用于管理所有需要显示的诊断信息
  2. 构造诊断对象:指定错误的位置范围、提示消息和严重级别
  3. 关联诊断到目标文档:将诊断信息绑定到对应的文件,自动在编辑器中渲染
  4. 监听文档变化:实时更新或清除诊断,保证提示的准确性

代码示例

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    // 创建自定义诊断集合,名称可自定义
    const diagnosticCollection = vscode.languages.createDiagnosticCollection('custom-error-diagnostics');

    // 初始化当前活动文档的诊断
    let activeEditor = vscode.window.activeTextEditor;
    activeEditor && updateDiagnostics(activeEditor.document);

    // 监听活动编辑器切换事件
    vscode.window.onDidChangeActiveTextEditor(editor => {
        activeEditor = editor;
        editor && updateDiagnostics(editor.document);
    });

    // 监听文档内容变化事件
    vscode.workspace.onDidChangeTextDocument(event => {
        if (activeEditor && event.document === activeEditor.document) {
            updateDiagnostics(event.document);
        }
    });

    /**
     * 更新文档的诊断信息
     * @param document 目标文档对象
     */
    function updateDiagnostics(document: vscode.TextDocument) {
        // 先清除当前文档的旧诊断
        diagnosticCollection.delete(document.uri);

        // 可限制仅对特定语言生效,这里示例为JavaScript
        if (document.languageId !== 'javascript') return;

        // 目标行:第4行(VS Code行索引从0开始,所以取3)
        const targetLineIndex = 3;
        const targetLine = document.lineAt(targetLineIndex);
        
        // 构造错误范围:可以是整行或特定字符区间
        const errorRange = new vscode.Range(
            targetLineIndex, 0, 
            targetLineIndex, targetLine.text.length
        );

        // 创建诊断对象
        const errorDiagnostic = new vscode.Diagnostic(
            errorRange,
            'undeclared name: adf',
            vscode.DiagnosticSeverity.Error // 错误级别:Error/Warning/Information/Hint
        );

        // 设置诊断来源(会显示在问题面板中)
        errorDiagnostic.source = '你的扩展名称';

        // 将诊断添加到集合,关联目标文档
        diagnosticCollection.set(document.uri, [errorDiagnostic]);
    }

    // 扩展销毁时自动清理诊断集合
    context.subscriptions.push(diagnosticCollection);
}

关键API说明

  • vscode.languages.createDiagnosticCollection:创建诊断集合,用于批量管理诊断信息,支持添加、删除、更新操作
  • vscode.Diagnostic:单个诊断实体,需传入三个核心参数:
    • Range:错误所在的位置范围(行、列索引均从0开始)
    • 提示消息:显示给用户的错误文本
    • DiagnosticSeverity:严重级别,决定提示的样式(红色错误、黄色警告等)
  • 事件监听:通过onDidChangeActiveTextEditor和onDidChangeTextDocument确保诊断随文档切换或内容更新实时同步

使用上述代码后,指定行的左侧会显示红色错误标记,行内文本下方出现波浪线,悬停时会弹出错误提示,同时该错误也会出现在VS Code的「问题」面板中,完全匹配你需要的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:15:14