首页 > 解决方案 > 实现 Go To Definition 时如何获取当前文本/符号

问题描述

我正在使用语言服务器协议开发我的第一个 vscode 扩展,我需要获取Right click -> Go to definition被触发的文本

在此处输入图像描述

我当前onDefinition的方法只接收textPosition

export default class DefinitionFinder extends Handler {
    constructor(
        protected connection: Connection,
        private refManager: ReferenceManager)
    {
        super();

        this.connection.onDefinition(async (textPosition) => {
            return this.handleErrors(
                this.getDefinition(textPosition), undefined) as Promise<Definition>;
        });
    }
    
private async getDefinition(textPosition: TextDocumentPositionParams): Promise<Location[]> {
    const text = "funABC";

    // instead of hardcoded value I need to get the text/symbol 
    // that is going to be use to go to definition 

    return this.refManager.getDefinitionLocations(text);
}

唯一TextDocumentPositionParams包含,documentUriline(number)character(number)

这是否意味着每次调用onDefinition我都需要打开文档,转到行和字符并获取当前单词?

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

export interface TextDocumentIdentifier {
    /**
     * The text document's uri. (string)
     */
    uri: DocumentUri;
}

export declare namespace Position {
    /**
     * Creates a new Position literal from the given line and character.
     * @param line The position's line.
     * @param character The position's character.
     */

标签: typescriptvisual-studio-codevscode-extensionslanguage-server-protocol

解决方案


语言服务器通常根据接收到的文档更改事件维护一个文本文档缓存。如果你在 TypeScript 中编写语言服务器,你可以简单地使用vscode-languageservervscode-languageserver-textdocument包中的实现。官方样本的相关摘录:

import { TextDocuments } from 'vscode-languageserver';
import { TextDocument } from 'vscode-languageserver-textdocument';

// Create a simple text document manager.
const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);

...

// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);

然后你可以这样做:

documents.get(uri).getText(range)

推荐阅读