首页 > 解决方案 > 如何将 VS Code 的大纲同步到编辑器中的当前位置

问题描述

我正在使用一种通常具有非常大且难以导航文件的语言,所以我想随时查看我在使用什么功能,因为这通常是最大的烦恼(翻页约 20 次以找到当前函数名,然后向下翻页)。

我看到了如何通过注册一个文档符号提供程序来编写一个扩展来列出所有功能。不过,在我走得太远之前,我想知道是否有某种方法可以自动且不断地在大纲视图中显示哪些节点代表代码编辑器中的当前位置。如果没有,我可能只需要创建自己的树视图(会有这种能力吗?)。

标签: typescriptvisual-studio-codevscode-extensions

解决方案


是的,这是可能的。您的树提供者需要一种将符号与树项匹配的方法,然后调用TreeView.reveal(). 这是我用来在操作列表中选择一个条目的代码,具体取决于插入符号在当前源代码编辑器中的位置:

public update(editor: TextEditor) {
    let position = editor.selection.active;

    let action = Utils.findInListFromPosition(this.actions, position.character, position.line + 1);
    if (action) {
        this.actionTree.reveal(action, { select: true });
        return;
    }
    let predicate = Utils.findInListFromPosition(this.predicates, position.character, position.line + 1);
    if (predicate) {
        this.actionTree.reveal(predicate, { select: true });
        return;
    }
}

从主扩展文件中注册的选择更改事件调用此方法:

window.onDidChangeTextEditorSelection((event: TextEditorSelectionChangeEvent) => {
    if (event.textEditor.document.languageId === "antlr" && event.textEditor.document.uri.scheme === "file") {
        ...
        actionsProvider.update(event.textEditor);
    }
});

推荐阅读