VSCode:在Language Server中获取编辑器内容

问题描述 投票:0回答:1

我正在尝试使用VS Code将语言服务器开发为新的语言,并且我使用Microsoft示例作为参考(https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample

在他们的示例中,自动完成是在这段代码中完成的:

connection.onCompletion(
    (_textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => {
        // The pass parameter contains the position of the text document in
        // which code complete got requested. For the example we ignore this
        // info and always provide the same completion items. 
        return [
            {
                label: 'TypeScript',
                kind: CompletionItemKind.Text,
                data: 1
            },
            {
                label: 'JavaScript',
                kind: CompletionItemKind.Text,
                data: 2
            }
        ];
    }
);

正如评论所说,这是一个愚蠢的自动完成系统,因为它总是提供相同的建议。

我看到有一个输入参数,类型为TextDocumentPositionParams,并且此类型具有以下接口:

export interface TextDocumentPositionParams {
    /**
     * The text document.
     */
    textDocument: TextDocumentIdentifier;
    /**
     * The position inside the text document.
     */
    position: Position;
}

它具有光标位置和一个TextDocumentIdentifier,但最后一个仅具有uri属性。

我想基于光标位置中单词的对象类型来创建智能的自动完成系统。

此样本非常有限,我有点在这里迷路了。我想我可以在uri属性中读取文件,并且根据光标位置可以确定应该建议哪些项目。但是,什么时候不保存文件呢?如果读取文件,我将读取磁盘上的数据,而不是编辑器中当前显示的数据。

最佳做法是什么?

visual-studio-code vscode-extensions language-server-protocol
1个回答
1
投票
您链接的样本实际上利用了这一点,但是同步本身是从TextDocuments中抽象到vscode-languageserver类中的。结果,server.ts不需要做更多的事情:

let documents: TextDocuments = new TextDocuments(); [...] documents.listen(connection);

然后您可以简单地使用documents.get(uri).getText()获得编辑器中显示的文本。

© www.soinside.com 2019 - 2024. All rights reserved.