に参加して、VS Code の AI 支援開発について学びましょう。

プログラムによる言語機能

プログラム言語機能は、vscode.languages.* API を利用したスマート編集機能のセットです。Visual Studio Code で動的な言語機能を提供する一般的な方法は 2 つあります。ホバーを例にとってみましょう。

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

上記のとおり、vscode.languages.registerHoverProvider API は、JavaScript ファイルにホバーコンテンツを簡単に提供する方法を提供します。この拡張機能がアクティブ化されると、JavaScript コードにカーソルを合わせるたびに、VS Code は JavaScript のすべてのHoverProviderにクエリを発行し、その結果をホバーウィジェットに表示します。言語機能リストと以下の GIF は、どの VS Code API / LSP メソッドが拡張機能に必要かを見つける簡単な方法を提供します。

別の方法は、Language Server Protocolを話すLanguage Serverを実装することです。その仕組みは次のとおりです。

  • 拡張機能が JavaScript 用の Language Client と Language Server を提供します。
  • Language Client は他の VS Code 拡張機能と同様に、Node.js 拡張機能ホストのコンテキストで実行されます。アクティブ化されると、別のプロセスで Language Server を起動し、Language Server Protocolを介して通信します。
  • VS Code で JavaScript コードにカーソルを合わせます。
  • VS Code は Language Client にホバーを通知します。
  • Language Client は Language Server にホバーの結果を問い合わせ、VS Code に返します。
  • VS Code はホバーの結果をホバーウィジェットに表示します。

このプロセスはより複雑に見えますが、2 つの大きな利点があります。

  • Language Server は任意の言語で記述できます。
  • Language Server は、複数のエディターにスマート編集機能を提供するために再利用できます。

より詳細なガイドについては、Language Server 拡張機能ガイドをご覧ください。


言語機能リスト

このリストには、各言語機能について次の項目が含まれます。

  • VS Code での言語機能の図
  • 関連する VS Code API
  • 関連する LSP メソッド
VS Code API LSP メソッド
createDiagnosticCollection PublishDiagnostics
registerCompletionItemProvider 補完 & 補完解決
registerInlineCompletionItemProvider
registerHoverProvider Hover
registerSignatureHelpProvider SignatureHelp
registerDefinitionProvider 定義
registerTypeDefinitionProvider TypeDefinition
registerImplementationProvider 実装
registerReferenceProvider リファレンス
registerDocumentHighlightProvider DocumentHighlight
registerDocumentSymbolProvider DocumentSymbol
registerCodeActionsProvider CodeAction
registerCodeLensProvider CodeLens & CodeLens 解決
registerDocumentLinkProvider DocumentLink & DocumentLink 解決
registerColorProvider DocumentColor & Color Presentation
registerDocumentFormattingEditProvider フォーマット
registerDocumentRangeFormattingEditProvider RangeFormatting
registerOnTypeFormattingEditProvider OnTypeFormatting
registerRenameProvider 名前変更 & 名前変更準備
registerFoldingRangeProvider FoldingRange

診断情報の提供

診断情報は、コードの問題を示す方法です。

Diagnostics indicating a misspelled method name

Language Server Protocol

言語サーバーは、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

Language Server Protocol

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(), '.', '\"'));
    ...
}

基本

解決プロバイダーはサポートしていません。

高度な設定

ユーザーが選択した補完提案の追加情報を計算する解決プロバイダーをサポートします。この情報は、選択されたアイテムと共に表示されます。

インライン補完を表示する

インライン補完は、エディターに直接マルチトークンの提案を表示します(ゴーストテキスト)。

Inline Completions suggesting code as ghost text while writing code

直接実装

vscode.languages.registerInlineCompletionItemProvider({ language: 'javascript' }, {
    provideInlineCompletionItems(document, position, context, token) {
        const result: vscode.InlineCompletionList = {
            items: [],
            commands: [],
        };

        ...

        return result;
    }
});

インライン補完のサンプル拡張機能で完全な例を確認できます。

基本

現在の行の内容に基づいて、特定の言語の既知のパターンリストに対してのみインライン補完を返します。

高度な設定

ドキュメント全体またはワークスペースの内容、およびより複雑なパターンに基づいてインライン補完を返します。

ホバーを表示する

ホバーは、マウスカーソルの下にあるシンボル/オブジェクトに関する情報を表示します。これは通常、シンボルの型と説明です。

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

Language Server Protocol

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

Language Server Protocol

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

Language Server Protocol

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

Language Server Protocol

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

Language Server Protocol

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 @

Language Server Protocol

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 #

Language Server Protocol

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

Language Server Protocol

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()));
    ...
}

基本

エラー/警告を修正するアクションのコードアクションを提供します。

高度な設定

さらに、リファクタリングなどのソースコード操作アクションを提供します。例えば、Extract Method

CodeLens - ソースコード内に操作可能なコンテキスト情報を表示

ソースコードと混在して表示される、操作可能なコンテキスト情報をユーザーに提供します。

CodeLens providing context

Language Server Protocol

initialize メソッドへの応答で、言語サーバーは CodeLens の結果を提供すること、および CodeLens をコマンドにバインドするための codeLens\resolve メソッドをサポートするかどうかを通知する必要があります。

{
    ...
    "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

Language Server Protocol

initialize メソッドへの応答で、言語サーバーは色の情報を提供することを通知する必要があります。

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

さらに、言語サーバーは textDocument/documentColor および textDocument/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

Language Server Protocol

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

Language Server Protocol

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

Language Server Protocol

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

Language Server Protocol

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()));
    ...
}

基本

名前変更サポートは提供しません。

高度な設定

実行する必要があるすべてのワークスペース編集のリスト、例えば、シンボルへの参照を含むすべてのファイルにわたるすべての編集を返します。

© . This site is unofficial and not affiliated with Microsoft.