An overview of the

Programmatic Language Features are intelligent editing capabilities provided by vscode.languages.* series of interfaces. There are usually two ways to provide dynamic Language Features, with Hover as an example:

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

As mentioned see vscode. Languages. RegisterHoverProvider interface implements a convenient hover for JavaScript file contents. The “List of language features” in section 1 of this article will help you find the API/LSP that your plug-in needs

In addition, another way is to implement a Language Server that complies with the Language Server Protocol (LSP). The principle is as follows:

  • The plug-in provides a Language Client (LC) and a Language Server (LS)
  • LCYou can view it as a basicVS CodePlug-ins that run in the context of node.js plug-ins whenLCIt will start when activatedLSProcess and utilizeLSPCommunicate with
  • The user inVS CodeHover a JavaScript code
  • VS CodeWill hover to informLC
  • LCfromLSTo query the result of hover, and return it toVS Code
  • VS CodeDisplays the results of hover

The above process is tedious, but has two major advantages:

  • LSIs language independent and can be used in any development language
  • LSCan be reused in other editors

More information about LS will be covered in a future article. This article will focus on the various programming language features VS Code provides

Feature list

The rest of this article is based on the following list of VS Code apis and their corresponding LSPS

VS Code API LSP method
createDiagnosticCollection PublishDiagnostics
registerCompletionItemProvider Completion & Completion Resolve
registerHoverProvider Hover
registerSignatureHelpProvider SignatureHelp
registerDefinitionProvider Definition
registerTypeDefinitionProvider TypeDefinition
registerImplementationProvider Implementation
registerReferenceProvider References
registerDocumentHighlightProvider DocumentHighlight
registerDocumentSymbolProvider DocumentSymbol
registerCodeActionsProvider CodeAction
registerCodeLensProvider CodeLens & CodeLens Resolve
registerDocumentLinkProvider DocumentLink & DocumentLink Resolve
registerColorProvider DocumentColor & Color Presentation
registerDocumentFormattingEditProvider Formatting
registerDocumentRangeFormattingEditProvider RangeFormatting
registerOnTypeFormattingEditProvider OnTypeFormatting
registerRenameProvider Rename & Prepare Rename
registerFoldingRangeProvider FoldingRange

Characteristics of details

The code in the diagnosis of

We use code diagnostics to point out problems with the current code

LSP way

LS send textDocument/publishDiagnostics messages to LC, message is an array, each item is a diagnosis. It should be noted that LC does not send the request for message transmission, but LS actively pushes the message to LC

API methods

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(a); 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); }); })}Copy the code

The base application

Do a minimal code diagnosis each time you save, and if you do a good job, you can diagnose only the content of the save changes, only the open files

Advanced applications

Do code diagnostics for every file in the folder, whether it’s open or not


Code completion suggestions

The main purpose of code completion is to provide the user with context-specific suggestions

LSP way

LS declares support for code completion in the onInitialize method and whether the completionItem\resolve method is supported to provide additional code completion information

{..."capabilities" : {
        "completionProvider" : {
            "resolveProvider": "true"."triggerCharacters": [ '. ']}... }}Copy the code

API methods

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

The base application

Does not provide completionItem \ resolve

Advanced applications

Provide completionItem\resolve support to give the user additional information about additional complex recommendations


Display hover

The hover function displays information, usually a description or data type, about the code currently under the mouse

LSP way

We need LS to declare support for hover in the onInitialize method:

{..."capabilities" : {
        "hoverProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/hover

API methods

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()));
    // ...
}
Copy the code

The base application

Display type information and add some remarks if possible

Advanced applications

Color the signature with the same style as the code coloring method


Displays help information about functions and methods

Display information about a method or function as the user enters it

LSP way

We need LS to declare support for help in the onInitialize method:

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

In addition, the LS to textDocument/signatureHelp to respond

API methods

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(), '('.', ')); . }Copy the code

The base application

A document that provides parameters to a function or class method


Show the definition

Allows the user to view the definition of variables, functions, and methods where they are used

LSP way

We need LS to declare support for jumping to the defined position in the onInitialize method:

{..."capabilities" : {
        "definitionProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/ Definition

API methods

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,newGoDefinitionProvider())); . }Copy the code

The base application

Display of multiple definitions is supported


Find all the references

Allows users to view all usage positions of a variable, function, method, or symbol

LSP way

We need LS to declare support for symbol reference positioning in the onInitialize method:

{..."capabilities" : {
        "referencesProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/ References

API methods

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,newGoReferenceProvider())); . }Copy the code

The base application

Return all reference locations (file URIs and ranges)

Symbol highlight

You can view the usage of the same character in the entire document

LSP way

We need LS to declare support for symbol document positioning in the onInitialize method:

{..."capabilities" : {
        "documentHighlightProvider" : "true". }}Copy the code

In addition, the LS to textDocument/documentHighlight to respond

API methods

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,newGoDocumentHighlightProvider())); . }Copy the code

The base application

Returns the reference position of the symbol


Displays all definitions of the current document

Allows users to quickly browse through all symbol definitions in an open document

LSP way

We need LS to declare support for symbol document positioning in the onInitialize method:

{..."capabilities" : {
        "documentSymbolProvider" : "true". }}Copy the code

In addition, the LS to textDocument/documentSymbol to respond

API methods

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,newGoDocumentSymbolProvider())); . }Copy the code

The base application

Returns all applications in a document, defining symbol types such as variables, functions, classes, methods, and so on


Show all character definitions in the folder

Allows users to quickly browse all symbol definitions in the workspace

LSP way

We need LS to declare support for global symbol positioning in the onInitialize method:

{..."capabilities" : {
        "workspaceSymbolProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/ Symbol

API methods

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(newGoWorkspaceSymbolProvider())); . }Copy the code

The base application

Returns all character definitions in the workspace, defining the types of symbols such as variables, functions, classes, methods, and so on


Provides possible error or alarm repair information

Provide the user with possible corrective actions next to errors or warnings, alert the user through a light bulb, and display a list of fixes available when the user clicks the bulb

LSP way

We need LS to declare support for coding guidance in the onInitialize method:

{..."capabilities" : {
        "codeActionProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/codeAction

API methods

class GoCodeActionProvider implements vscode.CodeActionProvider {
    public provideCodeActions(
        document: vscode.TextDocument, range: vscode.Range,
        context: vscode.CodeActionContext, token: vscode.CancellationToken): Thenable<vscode.Command[]> { ... }}export function activate(ctx: vscode.ExtensionContext) :void {... ctx.subscriptions.push( vscode.languages.registerCodeActionsProvider( GO_MODE,newGoCodeActionProvider())); . }Copy the code

The base application

Provides troubleshooting measures for errors or alarms

Advanced application,

Provide automation measures such as code refactoring


CodeLens

Provides the user with actionable context information, displayed in the source code

LSP way

We need LS to declare support for CodeLens in the onInitialize method and whether CodeLens \resolve is supported:

{..."capabilities" : {
        "codeLensProvider" : {
            "resolveProvider": "true"}... }}Copy the code

In addition, LS needs to respond to textDocument/codeLens

API methods

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,newGoCodeLensProvider())); . }Copy the code

The base application

Define CodeLens results that can be used for the document

Advanced applications

Bind the CodeLens result to a command as a response to CodeLens /resolve


Display color picker

Users can preview and modify the colors in the document

LSP way

We need LS to declare the function that provides color information in the onInitialize method:

{..."capabilities" : {
        "colorProvider" : "true". }}Copy the code

In addition, the LS to textDocument/documentColor and textDocument/colorPresentation to respond

API methods

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,newGoColorProvider())); . }Copy the code

The base application

Returns all colors in a file, providing color representation for supported color formats such as RGB, HSL


Document code formatting

Provides the user the ability to format the entire document

LSP way

LS supports document formatting in the onInitialize method:

{..."capabilities" : {
        "documentFormattingProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/formatting

API methods

class GoDocumentFormatter implements vscode.DocumentFormattingEditProvider {
    public formatDocument(document: vscode.TextDocument): Thenable<vscode.TextEdit[]> { ... }}export function activate(ctx: vscode.ExtensionContext) :void {... ctx.subscriptions.push( vscode.languages.registerDocumentFormattingEditProvider( GO_MODE,newGoDocumentFormatter())); . }Copy the code

The base application

Formatting support is not provided

Advanced features

Returns as little text editing as possible that results in source formatting. To ensure that adjustments such as diagnostic results are correct and not lost


Format the selected content

LSP way

We need LS to declare support for formatting the selected content in the onInitialize method:

{..."capabilities" : {
        "documentRangeFormattingProvider" : "true". }}Copy the code

In addition, the LS to textDocument/rangeFormatting to respond

API methods

class GoDocumentRangeFormatter implements vscode.DocumentRangeFormattingEditProvider{
    public provideDocumentRangeFormattingEdits(
        document: vscode.TextDocument, range: vscode.Range,
        options: vscode.FormattingOptions, token: vscode.CancellationToken): Thenable<vscode.TextEdit[]>; . }}export function activate(ctx: vscode.ExtensionContext) :void {... ctx.subscriptions.push( vscode.languages.registerDocumentRangeFormattingEditProvider( GO_MODE,newGoDocumentRangeFormatter())); . }Copy the code

The base application

Formatting support is not provided

Advanced features

Returns as little text editing as possible that results in source formatting. To ensure that adjustments such as diagnostic results are correct and not lost


Progressive automatic formatting

Supports automatic formatting after the user types a line, whether the user configures editor.formatOnType to enable this function

LSP way

LS supports automatic formatting in the onInitialize method and tells LC which character triggers automatic formatting. MoreTriggerCharacters are optional:

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

In addition, the LS to textDocument/onTypeFormatting to respond

API methods

class GoOnTypingFormatter implements vscode.OnTypeFormattingEditProvider{
    public provideOnTypeFormattingEdits(
        document: vscode.TextDocument, position: vscode.Position,
        ch: string, options: vscode.FormattingOptions, token: vscode.CancellationToken): Thenable<vscode.TextEdit[]>; . }}export function activate(ctx: vscode.ExtensionContext) :void {... ctx.subscriptions.push( vscode.languages.registerOnTypeFormattingEditProvider( GO_MODE,newGoOnTypingFormatter())); . }Copy the code

The base application

Formatting support is not provided

Advanced features

Returns as little text editing as possible that results in source formatting. To ensure that adjustments such as diagnostic results are correct and not lost


rename

Allows the user to rename a symbol and automatically update all references

LSP way

We need LS to declare support for renaming in the onInitialize method:

{..."capabilities" : {
        "renameProvider" : "true". }}Copy the code

In addition, LS needs to respond to textDocument/ References

API methods

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,newGoRenameProvider())); . }Copy the code

The base application

Renaming is not provided

Advanced applications

Returns a list of all workspace edits that need to be performed, for example, cross-file character reference edits

Related articles

  • VS Code Plug-in Development Tutorial (1) Overview

  • VS Code plug-in Development Tutorial (2

  • VS Code Plug-in Development Tutorial (3

  • VS Code Plug-in Development Tutorial (4

  • VS Code plug-in development tutorial (5) Using Command

  • VS Code Plugin development Tutorial (6) Color Theme overview

  • VS Code plug-in development tutorial (7) Tree View

  • VS Code Plug-in Development Tutorial (8) Webview

  • Build a Custom Editor

  • VS Code Plug-in Development Tutorial (10

  • Language Server Extension Guide Language Server Extension Guide