typescript - 实现 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
包含,documentUri
和line(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.
*/
解决方案
语言服务器通常根据接收到的文档更改事件维护一个文本文档缓存。如果你在 TypeScript 中编写语言服务器,你可以简单地使用vscode-languageserver
和vscode-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)
推荐阅读
- node.js - 如何使用 puppeteer 按名称或文本单击按钮?
- c++ - 围栏-codechef 2019 年 4 月长期挑战
- laravel - 我想在 laravel 中使用相同形式的两个文件输入上传两个文件
- selenium - 在 IE11 浏览器上通过 Jenkins(远程)执行 selenium 脚本时遇到缓慢
- angular - 如何在 nativescript-datetimepicker 插件上设置 5 分钟的间隔?
- keras - ValueError:检查目标时出错:预期 lstm_27 有 2 个维度,但得到了形状为 (1, 11, 1) 的数组
- android - 派凌空连接
- python - 如何将 save_screenshot 添加到 If 语句?
- java - Java中自定义文件的自定义图标
- mysql - 通过cmd运行时如何将参数传递给MySQL脚本?