vscode如何自动跳转到正确的定义

时间:2019-01-21 07:51:20

标签: typescript plugins visual-studio-code

//extension.ts
export function activate(context: vscode.ExtensionContext) {
    console.log('Congratulations, your extension "helloworld" is now active!');

    context.subscriptions.push(vscode.languages.registerDefinitionProvider(
        {language: "plsql"}, new GoDefinitionProvider() ));

}

class GoDefinitionProvider implements vscode.DefinitionProvider {
    public provideDefinition(
        document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken):
        Thenable<vscode.Definition>{
            return new Promise((resolve, reject) =>{
                let definitions:vscode.Definition = [];         
                for (let i = 0; i < document.lineCount; i++) {
                    let eachLine = document.lineAt(i).text.toLowerCase().trim();
                    if (eachLine.startsWith("cursor")) {                    
                        definitions.push({
                            uri: document.uri,
                            range: document.lineAt(i).range
                        });                     
                    }                   
                } 

                resolve(definitions);
            });

    }
}
// testing.txt
cursor a1 is
cursor a2 is
cursor a3 is
cursor a4 is
cursor a5 is
cursor a6 is
cursor a7 is
cursor a8 is
cursor a9 is

a1
a2
a3
a4
a5
a6
a7
a8
a9

例如,现在我们要选择“ a4”来跳转以显示定义,但是定义是自动跳转到“光标a9是”,而不是正确的“光标a4是”。

结果图片:https://i.imgur.com/RNAvWMN.png

如何实现自动跳转到正确的定义?上面是extension.ts的源代码供您参考。

1 个答案:

答案 0 :(得分:0)

代码中的问题是,您返回的是定义数组,而不是单个定义位置。

return new Promise((resolve, reject) =>{
    const range = document.getWordRangeAtPosition(position);
    const selectedWord = document.getText(range);
    let definitions:vscode.Definition = [];         
    for (let i = 0; i < document.lineCount; i++) {
        let eachLine = document.lineAt(i).text.toLowerCase().trim();
        if (eachLine.startsWith("cursor")) { 
            if ( eachLine.includes(selectedWord))  //only selectedWord                  
                definitions.push({
                    uri: document.uri,
                    range: document.lineAt(i).range
                });                     
            }
        }                   
    } 
    resolve(definitions);
});