vscode插件快餐教程(4) - 语言服务器协议lsp

简介: 在有lsp之前,存在三个主要问题: 一是语言相关的扩展都是用该语言母语写的,不容易集成到插件中去。毕竟现在大量的语言都带有运行时。 二是语言扫描相关的工作都比较占用CPU资源,运行在vscode内部不如放在独立进程,甚至远程服务器上更好。

vscode插件快餐教程(4) - 语言服务器协议lsp

语言服务器协议lsp是vscode为了解决语言扩展中的痛点来实现的一套协议。如下图所示:
lsp_languages_editors

总体说来,在有lsp之前,存在三个主要问题:
一是语言相关的扩展都是用该语言母语写的,不容易集成到插件中去。毕竟现在大量的语言都带有运行时。
二是语言扫描相关的工作都比较占用CPU资源,运行在vscode内部不如放在独立进程,甚至远程服务器上更好。
三是如上图左边所示,缺少一套协议的话,每种语言服务需要适配多个编辑器。同样,每种编辑器也需要各种语言服务。这造成了较大的资源浪费。

LSP协议概述

LSP是基于json rpc的协议。
我们先来看一个例子:

Content-Length: ...\r\n
\r\n
{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "textDocument/didOpen",
    "params": {
        ...
    }
}

jsonrpc是json rpc协议的头,LSP主要是定义了method和params。

从服务端发给客户端的,是Request,客户端返回Response。客户端主动发起的是Notification.

下面我们用一张图来看看LSP目前都支持哪些功能:
LSP_

最大的一块是语言功能,这些也通可以通过本地的Provider等方法来实现。

生命周期管理

服务器的生命周期通过客户端发送initialize请求开始,负载为一个InitializeParameter对象:

interface InitializeParams {
    /**
     * The process Id of the parent process that started
     * the server. Is null if the process has not been started by another process.
     * If the parent process is not alive then the server should exit (see exit notification) its process.
     */
    processId: number | null;

    /**
     * The rootPath of the workspace. Is null
     * if no folder is open.
     *
     * @deprecated in favour of rootUri.
     */
    rootPath?: string | null;

    /**
     * The rootUri of the workspace. Is null if no
     * folder is open. If both `rootPath` and `rootUri` are set
     * `rootUri` wins.
     */
    rootUri: DocumentUri | null;

    /**
     * User provided initialization options.
     */
    initializationOptions?: any;

    /**
     * The capabilities provided by the client (editor or tool)
     */
    capabilities: ClientCapabilities;

    /**
     * The initial trace setting. If omitted trace is disabled ('off').
     */
    trace?: 'off' | 'messages' | 'verbose';

    /**
     * The workspace folders configured in the client when the server starts.
     * This property is only available if the client supports workspace folders.
     * It can be `null` if the client supports workspace folders but none are
     * configured.
     *
     * Since 3.6.0
     */
    workspaceFolders?: WorkspaceFolder[] | null;
}

而服务端返回的,是服务器的能力:

interface InitializeResult {
    /**
     * The capabilities the language server provides.
     */
    capabilities: ServerCapabilities;
}

ServerCapabilities的定义如下。主要对应了Workspace和TextDocument两大类型的API:

interface ClientCapabilities {
    /**
     * Workspace specific client capabilities.
     */
    workspace?: WorkspaceClientCapabilities;

    /**
     * Text document specific client capabilities.
     */
    textDocument?: TextDocumentClientCapabilities;

    /**
     * Experimental client capabilities.
     */
    experimental?: any;
}

客户端收到initialize result之后,按照三次握手的原则,将返回一个initialized消息做确认。至此,一个服务端与客户端通信的生命周期就算是成功建立。

LSP协议的实现

除了整个协议的详细描述之外,微软还为我们准备了LSP的SDK,源码在:https://github.com/microsoft/vscode-languageserver-node

我们首先从server侧来讲解LSP sdk的用法。

createConnection

服务端首先要获取一个Connection对象,通过vscode-languageserver提供的createConnection函数来创建Connection.

let connection = createConnection(ProposedFeatures.all);

Connection中对于LSP的消息进行了封装,比如:

        onInitialize: (handler) => initializeHandler = handler,
        onInitialized: (handler) => connection.onNotification(InitializedNotification.type, handler),
        onShutdown: (handler) => shutdownHandler = handler,
        onExit: (handler) => exitHandler = handler,
...
        onDidChangeConfiguration: (handler) => connection.onNotification(DidChangeConfigurationNotification.type, handler),
        onDidChangeWatchedFiles: (handler) => connection.onNotification(DidChangeWatchedFilesNotification.type, handler),
...
        onDidOpenTextDocument: (handler) => connection.onNotification(DidOpenTextDocumentNotification.type, handler),
        onDidChangeTextDocument: (handler) => connection.onNotification(DidChangeTextDocumentNotification.type, handler),
        onDidCloseTextDocument: (handler) => connection.onNotification(DidCloseTextDocumentNotification.type, handler),
        onWillSaveTextDocument: (handler) => connection.onNotification(WillSaveTextDocumentNotification.type, handler),
        onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(WillSaveTextDocumentWaitUntilRequest.type, handler),
        onDidSaveTextDocument: (handler) => connection.onNotification(DidSaveTextDocumentNotification.type, handler),

        sendDiagnostics: (params) => connection.sendNotification(PublishDiagnosticsNotification.type, params),
...
        onHover: (handler) => connection.onRequest(HoverRequest.type, handler),
        onCompletion: (handler) => connection.onRequest(CompletionRequest.type, handler),
        onCompletionResolve: (handler) => connection.onRequest(CompletionResolveRequest.type, handler),
        onSignatureHelp: (handler) => connection.onRequest(SignatureHelpRequest.type, handler),
        onDeclaration: (handler) => connection.onRequest(DeclarationRequest.type, handler),
        onDefinition: (handler) => connection.onRequest(DefinitionRequest.type, handler),
        onTypeDefinition: (handler) => connection.onRequest(TypeDefinitionRequest.type, handler),
        onImplementation: (handler) => connection.onRequest(ImplementationRequest.type, handler),
        onReferences: (handler) => connection.onRequest(ReferencesRequest.type, handler),
        onDocumentHighlight: (handler) => connection.onRequest(DocumentHighlightRequest.type, handler),
        onDocumentSymbol: (handler) => connection.onRequest(DocumentSymbolRequest.type, handler),
        onWorkspaceSymbol: (handler) => connection.onRequest(WorkspaceSymbolRequest.type, handler),
        onCodeAction: (handler) => connection.onRequest(CodeActionRequest.type, handler),
        onCodeLens: (handler) => connection.onRequest(CodeLensRequest.type, handler),
        onCodeLensResolve: (handler) => connection.onRequest(CodeLensResolveRequest.type, handler),
        onDocumentFormatting: (handler) => connection.onRequest(DocumentFormattingRequest.type, handler),
        onDocumentRangeFormatting: (handler) => connection.onRequest(DocumentRangeFormattingRequest.type, handler),
        onDocumentOnTypeFormatting: (handler) => connection.onRequest(DocumentOnTypeFormattingRequest.type, handler),
        onRenameRequest: (handler) => connection.onRequest(RenameRequest.type, handler),
        onPrepareRename: (handler) => connection.onRequest(PrepareRenameRequest.type, handler),
        onDocumentLinks: (handler) => connection.onRequest(DocumentLinkRequest.type, handler),
        onDocumentLinkResolve: (handler) => connection.onRequest(DocumentLinkResolveRequest.type, handler),
        onDocumentColor: (handler) => connection.onRequest(DocumentColorRequest.type, handler),
        onColorPresentation: (handler) => connection.onRequest(ColorPresentationRequest.type, handler),
        onFoldingRanges: (handler) => connection.onRequest(FoldingRangeRequest.type, handler),
        onExecuteCommand: (handler) => connection.onRequest(ExecuteCommandRequest.type, handler),

协议中的所有的消息都有封装。

onInitialize

通过createConnection创建了Connection对象之后,我们就可以调用connection.listen()来实现对client的监听了。
在监听之前,我们需要把处理监听事件的回调函数设好。
首先是处理initialize消息的onInitialize,之前我们讲协议时介绍了,主要工作是告知client这个服务端的能力:

connection.onInitialize((params: InitializeParams) => {
    let capabilities = params.capabilities;

    return {
        capabilities: {
            textDocumentSync: documents.syncKind,
            // Tell the client that the server supports code completion
            completionProvider: {
                resolveProvider: true
            }
        }
    };
});

根据三次握手的原则,客户端还会返回initialized notification进行通知,服务端可以借用处理这个notification的返回值进行一些初始化的工作。例:

connection.onInitialized(() => {
    if (hasWorkspaceFolderCapability) {
        connection.workspace.onDidChangeWorkspaceFolders(_event => {
            connection.console.log('Workspace folder change event received.');
        });
    }
});
目录
相关文章
|
18天前
|
Linux
linux下搭建tftp服务器教程
在Linux中搭建TFTP服务器,需安装`tftp-server`(如`tftpd-hpa`)。步骤包括:更新软件包列表,安装`tftpd-hpa`,启动并设置开机自启,配置服务器(编辑`/etc/default/tftpd-hpa`),添加选项,然后重启服务。完成后,可用`tftp`命令进行文件传输。例如,从IP`192.168.1.100`下载`file.txt`: ``` tftp 192.168.1.100 <<EOF binary put file.txt quit EOF ```
28 4
|
1月前
|
SQL 弹性计算 安全
购买阿里云活动内云服务器之后设置密码、安全组、增加带宽、挂载云盘教程
当我们通过阿里云的活动购买完云服务器之后,并不是立马就能使用了,还需要我们设置云服务器密码,配置安全组等基本操作之后才能使用,有的用户还需要购买并挂载数据盘到云服务器上,很多新手用户由于是初次使用阿里云服务器,因此并不知道这些设置的操作流程,下面给大家介绍下这些设置的具体操作流程。
购买阿里云活动内云服务器之后设置密码、安全组、增加带宽、挂载云盘教程
|
1月前
|
人工智能 自然语言处理 算法
国产新型AI编程助手—DevChat AI插件在VSCode中的应用
国产新型AI编程助手—DevChat AI插件在VSCode中的应用
|
2天前
|
XML Java 数据格式
Servlet 教程 之 Servlet 服务器 HTTP 响应 3
`Servlet`教程示例展示了如何创建一个HTTP响应,使用`@WebServlet("/Refresh")`的`Refresh`类继承`HttpServlet`。在`doGet`方法中,设置了`Refresh`头以每5秒自动刷新,并用`setContentType("text/html;charset=UTF-8")`设定内容类型。还使用`Calendar`和`SimpleDateFormat`获取并格式化当前时间显示。相应的`web.xml`配置指定了Servlet路径。当访问此Servlet时,页面将每5秒更新一次显示的系统时间。
14 4
|
3天前
|
安全 Unix Linux
Windows如何远程连接服务器?服务器远程连接图文教程
服务器操作系统可以实现对计算机硬件与软件的直接控制和管理协调,任何计算机的运行离不开操作系统,服务器也一样,服务器操作系统主要分为四大流派:Windows Server、Netware、Unix和Linux。今天驰网飞飞将和你分享Windows server远程连接图文教程,希望可以帮助到你
16 4
Windows如何远程连接服务器?服务器远程连接图文教程
|
16天前
Vscode 插件-代码敲出不同的特效
Vscode 插件-代码敲出不同的特效
|
21天前
|
弹性计算 关系型数据库 MySQL
阿里云数据库服务器价格表,数据库创建、连接和使用教程
阿里云数据库使用流程包括购买和管理。选择所需数据库类型如MySQL,完成实名认证后购买,配置CPU、内存和存储。确保数据库地域与ECS相同以允许内网连接。创建数据库和账号,设置权限。通过DMS登录数据库,使用账号密码连接。同一VPC内的ECS需添加至白名单以进行内网通信。参考官方文档进行详细操作。
123 3
|
1月前
|
Shell Linux Apache
【Shell 命令集合 网络通讯 】Linux 管理Apache HTTP服务器 apachectl命令 使用教程
【Shell 命令集合 网络通讯 】Linux 管理Apache HTTP服务器 apachectl命令 使用教程
162 1
|
1月前
|
存储 固态存储 网络安全
云服务器注册教程
本文概述了云服务器的优势,如价格亲民、按小时计费、SSD存储和高性能,并介绍了云服务器的注册及创建虚拟专用服务器的步骤。注册过程包括邮箱验证、激活账号和绑定支付方式。创建云服务器时,选择操作系统、计划、数据中心等配置,然后通过SSH连接。云服务器因其易用性和经济性受到开发人员和小型企业青睐。文章还提及了使用WordPress搭建个人博客的教程。
162 0
云服务器注册教程
|
1月前
|
弹性计算 关系型数据库 MySQL
阿里云服务器经济型e实例2核2G3M带宽99元搭建网站图文教程参考
经济型e实例2核2G,3M固定带宽,40G ESSD Entry云盘,价格只要99元,这是阿里云精心为开发者和普通企业用户推出的一款上云首选必备产品,可用于中小型的web应用以及企业应用。本文为大家展示使用这款云服务器搭建网站的相关教程,以供参考。
阿里云服务器经济型e实例2核2G3M带宽99元搭建网站图文教程参考