參加你附近的 ,瞭解 VS Code 中的 AI 輔助開發。

程式化語言功能

程式語言功能是一組由 vscode.languages.* API 提供支援的智慧編輯功能。在 Visual Studio Code 中,有兩種常見的方法可以提供動態語言功能。我們以 懸停 為例

vscode.languages.registerHoverProvider('javascript', {
  provideHover(document, position, token) {
    return {
      contents: ['Hover Content']
    };
  }
});

如您所見,vscode.languages.registerHoverProvider API 提供了一種簡單的方法來為 JavaScript 檔案提供懸停內容。此擴充套件啟用後,無論何時您將滑鼠懸停在 JavaScript 程式碼上,VS Code 都會查詢所有 JavaScript 檔案的 HoverProvider,並在懸停小部件中顯示結果。下面的 語言功能列表 和動圖提供了一種簡單的方法,讓您定位您的擴充套件所需的 VS Code API / LSP 方法。

另一種方法是實現一個支援 語言伺服器協議 的語言伺服器。它的工作原理是:

  • 一個擴充套件為 JavaScript 提供一個語言客戶端和一個語言伺服器。
  • 語言客戶端就像任何其他 VS Code 擴充套件一樣,在 Node.js 擴充套件主機上下文中執行。當它啟用時,它會在另一個程序中生成語言伺服器,並透過 語言伺服器協議 與其通訊。
  • 您在 VS Code 中將滑鼠懸停在 JavaScript 程式碼上
  • VS Code 將懸停事件通知語言客戶端
  • 語言客戶端向語言伺服器查詢懸停結果,並將其傳送回 VS Code
  • VS Code 在懸停小部件中顯示懸停結果

這個過程看起來更復雜,但它提供了兩個主要優勢

  • 語言伺服器可以用任何語言編寫
  • 語言伺服器可以重複使用,為多個編輯器提供智慧編輯功能

有關更深入的指南,請查閱 語言伺服器擴充套件指南


語言功能列表

此列表包括每個語言功能的以下專案

  • VS Code 中語言功能的圖示
  • 相關 VS Code API
  • 相關 LSP 方法
VS Code API LSP 方法
createDiagnosticCollection PublishDiagnostics
registerCompletionItemProvider Completion & Completion Resolve
registerHoverProvider Hover
registerSignatureHelpProvider SignatureHelp
registerDefinitionProvider Definition
registerTypeDefinitionProvider TypeDefinition
registerImplementationProvider Implementation
registerReferenceProvider 參考
registerDocumentHighlightProvider DocumentHighlight
registerDocumentSymbolProvider DocumentSymbol
registerCodeActionsProvider CodeAction
registerCodeLensProvider CodeLens & CodeLens Resolve
registerDocumentLinkProvider DocumentLink & DocumentLink Resolve
registerColorProvider DocumentColor & Color Presentation
registerDocumentFormattingEditProvider 格式化
registerDocumentRangeFormattingEditProvider RangeFormatting
registerOnTypeFormattingEditProvider OnTypeFormatting
registerRenameProvider Rename & Prepare Rename
registerFoldingRangeProvider FoldingRange

提供診斷資訊

診斷是指出程式碼問題的一種方式。

Diagnostics indicating a misspelled method name

語言伺服器協議

您的語言伺服器向語言客戶端傳送 textDocument/publishDiagnostics 訊息。該訊息攜帶一個資源 URI 的診斷專案陣列。

注意:客戶端不會向伺服器請求診斷資訊。伺服器會將診斷資訊推送給客戶端。

直接實現

let diagnosticCollection: vscode.DiagnosticCollection;

export function activate(ctx: vscode.ExtensionContext): void {
  ...
  ctx.subscriptions.push(getDisposable());
  diagnosticCollection = vscode.languages.createDiagnosticCollection('go');
  ctx.subscriptions.push(diagnosticCollection);
  ...
}

function onChange() {
  let uri = document.uri;
  check(uri.fsPath, goConfig).then(errors => {
    diagnosticCollection.clear();
    let diagnosticMap: Map<string, vscode.Diagnostic[]> = new Map();
    errors.forEach(error => {
      let canonicalFile = vscode.Uri.file(error.file).toString();
      let range = new vscode.Range(error.line-1, error.startColumn, error.line-1, error.endColumn);
      let diagnostics = diagnosticMap.get(canonicalFile);
      if (!diagnostics) { diagnostics = []; }
      diagnostics.push(new vscode.Diagnostic(range, error.msg, error.severity));
      diagnosticMap.set(canonicalFile, diagnostics);
    });
    diagnosticMap.forEach((diags, file) => {
      diagnosticCollection.set(vscode.Uri.parse(file), diags);
    });
  })
}

基礎

報告開啟的編輯器的診斷資訊。最低限度,這需要在每次儲存時發生。更好的是,診斷資訊應該根據編輯器的未儲存內容進行計算。

高階

不僅為開啟的編輯器,還為開啟資料夾中的所有資源報告診斷資訊,無論它們是否曾在編輯器中開啟過。

顯示程式碼補全建議

程式碼補全為使用者提供上下文敏感的建議。

Code Completion prompting variable, method, and parameter names while writing code

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供補全功能,以及是否支援 completionItem\resolve 方法來為計算出的補全項提供額外資訊。

{
    ...
    "capabilities" : {
        "completionProvider" : {
            "resolveProvider": "true",
            "triggerCharacters": [ '.' ]
        }
        ...
    }
}

直接實現

class GoCompletionItemProvider implements vscode.CompletionItemProvider {
    public provideCompletionItems(
        document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken):
        Thenable<vscode.CompletionItem[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(getDisposable());
    ctx.subscriptions.push(
        vscode.languages.registerCompletionItemProvider(
            GO_MODE, new GoCompletionItemProvider(), '.', '\"'));
    ...
}

基礎

您不支援解析提供者。

高階

您支援解析提供者,它們為使用者選擇的補全建議計算額外資訊。此資訊與選定專案一起顯示。

顯示懸停資訊

懸停顯示滑鼠游標下方的符號/物件的資訊。這通常是符號的型別和描述。

Showing details about a workspace and a method when hovering over them

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供懸停功能。

{
    ...
    "capabilities" : {
        "hoverProvider" : "true",
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/hover 請求。

直接實現

class GoHoverProvider implements HoverProvider {
    public provideHover(
        document: TextDocument, position: Position, token: CancellationToken):
        Thenable<Hover> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerHoverProvider(
            GO_MODE, new GoHoverProvider()));
    ...
}

基礎

顯示型別資訊,如果可用,包括文件。

高階

以您為程式碼著色的相同樣式為方法簽名著色。

函式和方法簽名幫助

當用戶輸入函式或方法時,顯示正在呼叫的函式/方法的資訊。

Showing information about the getPackageInfo method including the necessary parameters

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供簽名幫助。

{
    ...
    "capabilities" : {
        "signatureHelpProvider" : {
            "triggerCharacters": [ '(' ]
        }
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/signatureHelp 請求。

直接實現

class GoSignatureHelpProvider implements SignatureHelpProvider {
    public provideSignatureHelp(
        document: TextDocument, position: Position, token: CancellationToken):
        Promise<SignatureHelp> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerSignatureHelpProvider(
            GO_MODE, new GoSignatureHelpProvider(), '(', ','));
    ...
}

基礎

確保簽名幫助包含函式或方法的引數文件。

高階

無其他。

顯示符號定義

允許使用者在變數/函式/方法正在使用的地方直接檢視其定義。

Right click a variable, function, or method and select "Go to Definition" to jump to the definition

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供 goto-definition 位置。

{
    ...
    "capabilities" : {
        "definitionProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/definition 請求。

直接實現

class GoDefinitionProvider implements vscode.DefinitionProvider {
    public provideDefinition(
        document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken):
        Thenable<vscode.Location> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerDefinitionProvider(
            GO_MODE, new GoDefinitionProvider()));
    ...
}

基礎

如果一個符號是模稜兩可的,您可以顯示多個定義。

高階

無其他。

查詢符號的所有引用

允許使用者檢視特定變數/函式/方法/符號在原始碼中的所有使用位置。

Right clicking and selecting "Find All References" to highlight all the locations where that symbol is used

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供符號引用位置。

{
    ...
    "capabilities" : {
        "referencesProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/references 請求。

直接實現

class GoReferenceProvider implements vscode.ReferenceProvider {
    public provideReferences(
        document: vscode.TextDocument, position: vscode.Position,
        options: { includeDeclaration: boolean }, token: vscode.CancellationToken):
        Thenable<vscode.Location[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerReferenceProvider(
            GO_MODE, new GoReferenceProvider()));
    ...
}

基礎

返回所有引用的位置(資源 URI 和範圍)。

高階

無其他。

突出顯示文件中符號的所有出現

允許使用者在開啟的編輯器中檢視符號的所有出現。

Select a symbol to highlight all occurrences

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供符號文件位置。

{
    ...
    "capabilities" : {
        "documentHighlightProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/documentHighlight 請求。

直接實現

class GoDocumentHighlightProvider implements vscode.DocumentHighlightProvider {
    public provideDocumentHighlights(
        document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken):
        vscode.DocumentHighlight[] | Thenable<vscode.DocumentHighlight[]>;
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerDocumentHighlightProvider(
            GO_MODE, new GoDocumentHighlightProvider()));
    ...
}

基礎

您返回編輯器文件中找到引用的範圍。

高階

無其他。

顯示文件中的所有符號定義

允許使用者快速導航到開啟的編輯器中的任何符號定義。

Navigate to a symbol definition in the open editor using @

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供符號文件位置。

{
    ...
    "capabilities" : {
        "documentSymbolProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/documentSymbol 請求。

直接實現

class GoDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
    public provideDocumentSymbols(
        document: vscode.TextDocument, token: vscode.CancellationToken):
        Thenable<vscode.SymbolInformation[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerDocumentSymbolProvider(
            GO_MODE, new GoDocumentSymbolProvider()));
    ...
}

基礎

返回文件中的所有符號。定義符號的型別,例如變數、函式、類、方法等。

高階

無其他。

顯示資料夾中的所有符號定義

允許使用者快速導航到在 VS Code 中開啟的資料夾(工作區)中的任何符號定義。

Navigate to symbol definitions in the workspace using #

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供全域性符號位置。

{
    ...
    "capabilities" : {
        "workspaceSymbolProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 workspace/symbol 請求。

直接實現

class GoWorkspaceSymbolProvider implements vscode.WorkspaceSymbolProvider {
    public provideWorkspaceSymbols(
        query: string, token: vscode.CancellationToken):
        Thenable<vscode.SymbolInformation[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerWorkspaceSymbolProvider(
            new GoWorkspaceSymbolProvider()));
    ...
}

基礎

返回開啟資料夾中原始碼定義的所有符號。定義符號的型別,例如變數、函式、類、方法等。

高階

無其他。

錯誤或警告的可能操作

在錯誤或警告旁邊為使用者提供可能的糾正措施。如果操作可用,錯誤或警告旁邊會出現一個燈泡。當用戶單擊燈泡時,會顯示可用程式碼操作的列表。

Selecting a light bulb to view a list of available Code Actions

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供程式碼操作。

{
    ...
    "capabilities" : {
        "codeActionProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/codeAction 請求。

直接實現

class GoCodeActionProvider implements vscode.CodeActionProvider<vscode.CodeAction> {
    public provideCodeActions(
        document: vscode.TextDocument, range: vscode.Range | vscode.Selection,
        context: vscode.CodeActionContext, token: vscode.CancellationToken):
        Thenable<vscode.CodeAction[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerCodeActionsProvider(
            GO_MODE, new GoCodeActionProvider()));
    ...
}

基礎

為錯誤/警告糾正操作提供程式碼操作。

高階

此外,提供原始碼操作,例如重構。例如,提取方法

CodeLens - 在原始碼中顯示可操作的上下文資訊

為使用者提供可操作的、上下文相關的資訊,這些資訊與原始碼交錯顯示。

CodeLens providing context

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供 CodeLens 結果,以及它是否支援 codeLens\resolve 方法來將 CodeLens 繫結到其命令。

{
    ...
    "capabilities" : {
        "codeLensProvider" : {
            "resolveProvider": "true"
        }
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/codeLens 請求。

直接實現

class GoCodeLensProvider implements vscode.CodeLensProvider {
    public provideCodeLenses(document: TextDocument, token: CancellationToken):
        CodeLens[] | Thenable<CodeLens[]> {
    ...
    }

    public resolveCodeLens?(codeLens: CodeLens, token: CancellationToken):
         CodeLens | Thenable<CodeLens> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerCodeLensProvider(
            GO_MODE, new GoCodeLensProvider()));
    ...
}

基礎

定義文件可用的 CodeLens 結果。

高階

透過響應 codeLens/resolve 將 CodeLens 結果繫結到命令。

顯示顏色裝飾器

允許使用者預覽和修改文件中的顏色。

Showing the color picker

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供顏色資訊。

{
    ...
    "capabilities" : {
        "colorProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/documentColortextDocument/colorPresentation 請求。

直接實現

class GoColorProvider implements vscode.DocumentColorProvider {
    public provideDocumentColors(
        document: vscode.TextDocument, token: vscode.CancellationToken):
        Thenable<vscode.ColorInformation[]> {
    ...
    }
    public provideColorPresentations(
        color: Color, context: { document: TextDocument, range: Range }, token: vscode.CancellationToken):
        Thenable<vscode.ColorPresentation[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerColorProvider(
            GO_MODE, new GoColorProvider()));
    ...
}

基礎

返回文件中的所有顏色引用。提供支援的顏色格式的顏色表示(例如 rgb(...),hsl(...))。

高階

無其他。

格式化編輯器中的原始碼

為使用者提供格式化整個文件的支援。

Right click and select format code

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供文件格式化。

{
    ...
    "capabilities" : {
        "documentFormattingProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/formatting 請求。

直接實現

class GoDocumentFormatter implements vscode.DocumentFormattingEditProvider {
    provideDocumentFormattingEdits(
        document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken)
        : vscode.ProviderResult<vscode.TextEdit[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerDocumentFormattingEditProvider(
            GO_MODE, new GoDocumentFormatter()));
    ...
}

基礎

不提供格式化支援。

高階

您應該始終返回導致原始碼格式化的最小可能的文字編輯。這對於確保診斷結果等標記正確調整且不丟失至關重要。

格式化編輯器中選定的行

為使用者提供格式化文件中選定行範圍的支援。

Select lines, right click, and select format code

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供行範圍的格式化支援。

{
    ...
    "capabilities" : {
        "documentRangeFormattingProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/rangeFormatting 請求。

直接實現

class GoDocumentRangeFormatter implements vscode.DocumentRangeFormattingEditProvider{
    public provideDocumentRangeFormattingEdits(
        document: vscode.TextDocument, range: vscode.Range,
        options: vscode.FormattingOptions, token: vscode.CancellationToken):
        vscode.ProviderResult<vscode.TextEdit[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerDocumentRangeFormattingEditProvider(
            GO_MODE, new GoDocumentRangeFormatter()));
    ...
}

基礎

不提供格式化支援。

高階

您應該始終返回導致原始碼格式化的最小可能的文字編輯。這對於確保診斷結果等標記正確調整且不丟失至關重要。

使用者鍵入時逐步格式化程式碼

為使用者提供在鍵入時格式化文字的支援。

注意:使用者 設定 editor.formatOnType 控制使用者鍵入時是否格式化原始碼。

Visual indicators for formatting as code is typed

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供使用者鍵入時格式化功能。它還需要告訴客戶端應該在哪些字元上觸發格式化。moreTriggerCharacters 是可選的。

{
    ...
    "capabilities" : {
        "documentOnTypeFormattingProvider" : {
            "firstTriggerCharacter": "}",
            "moreTriggerCharacter": [";", ","]
        }
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/onTypeFormatting 請求。

直接實現

class GoOnTypingFormatter implements vscode.OnTypeFormattingEditProvider{
    public provideOnTypeFormattingEdits(
        document: vscode.TextDocument, position: vscode.Position,
        ch: string, options: vscode.FormattingOptions, token: vscode.CancellationToken):
        vscode.ProviderResult<vscode.TextEdit[]> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerOnTypeFormattingEditProvider(
            GO_MODE, new GoOnTypingFormatter()));
    ...
}

基礎

不提供格式化支援。

高階

您應該始終返回導致原始碼格式化的最小可能的文字編輯。這對於確保診斷結果等標記正確調整且不丟失至關重要。

重新命名符號

允許使用者重新命名符號並更新對該符號的所有引用。

Rename a symbol and update all references to the new name

語言伺服器協議

在對 initialize 方法的響應中,您的語言伺服器需要宣佈它提供重新命名功能。

{
    ...
    "capabilities" : {
        "renameProvider" : "true"
        ...
    }
}

此外,您的語言伺服器需要響應 textDocument/rename 請求。

直接實現

class GoRenameProvider implements vscode.RenameProvider {
    public provideRenameEdits(
        document: vscode.TextDocument, position: vscode.Position,
        newName: string, token: vscode.CancellationToken):
        Thenable<vscode.WorkspaceEdit> {
    ...
    }
}

export function activate(ctx: vscode.ExtensionContext): void {
    ...
    ctx.subscriptions.push(
        vscode.languages.registerRenameProvider(
            GO_MODE, new GoRenameProvider()));
    ...
}

基礎

不提供重新命名支援。

高階

返回需要執行的所有工作區編輯的列表,例如包含符號引用的所有檔案中的所有編輯。