如何以编程方式将光标放在 vscode 编辑器扩展中的指定行上?

Tan*_*agi 6 text-editor editor vsix typescript vscode-extensions

我正在开发 vscode TextEditorEdit 扩展。在这里,我需要根据 api 响应内容,在以编辑器打开文件后将光标置于指定行号上。我怎样才能做到这一点?或者什么类或接口提供了执行此操作的功能?

以下是我尝试实现此目的的代码。但两者都不起作用。甚至没有引发任何异常或错误。

尽管这是在编辑器上正确打开并显示文件。但当我尝试更改光标位置时没有任何效果。

  1. 然后使用自定义选择vscode.window.showTextDocument()分配 并分配editor.selection。这对编辑器没有影响。
vscode.workspace.openTextDocument(openPath).then(async doc => {

  let pos1 = new vscode.Position(57, 40)
  let pos2 = new vscode.Position(57, 42)
  let sel = new vscode.Selection(pos1,pos2)
  let rng = new vscode.Range(pos1, pos2)
  
  vscode.window.showTextDocument(doc, vscode.ViewColumn.One).then((editor: vscode.TextEditor) => {
    editor.selection = sel
    //editor.revealRange(rng, vscode.TextEditorRevealType.InCenter) 
  });
});
Run Code Online (Sandbox Code Playgroud)

我也尝试揭示范围,editor.revealRange(rng, vscode.TextEditorRevealType.InCenter)但也没有效果。

  1. options?:在 中添加参数vscode.window.showTextDocument()。但这也没有任何作用。请看下面的代码——
vscode.workspace.openTextDocument(openPath).then(async doc => {
  
  let pos1 = new vscode.Position(57, 40)
  let pos2 = new vscode.Position(57, 42)
  let rng = new vscode.Range(pos1, pos2)
  
  vscode.window.showTextDocument(doc, {selection: rng, viewColumn: vscode.ViewColumn.One})
});
Run Code Online (Sandbox Code Playgroud)

我想,问题在于首先打开文件并将文本文档显示到编辑器中,然后更改光标位置。

Cha*_*les 2

可以使用cursorMoveVSCode的内置命令:

  let openPath = URI.file(mainPath);
  vscode.workspace.openTextDocument(openPath).then(async (doc) => {
    let line = 56;
    let char = 10;
    let pos1 = new vscode.Position(0, 0);
    let pos2 = new vscode.Position(0, 0);
    let sel = new vscode.Selection(pos1, pos2);
    vscode.window.showTextDocument(doc, vscode.ViewColumn.One).then((e) => {
      e.selection = sel;
      vscode.commands
        .executeCommand("cursorMove", {
          to: "down",
          by: "line",
          value: line,
        })
        .then(() =>
          vscode.commands.executeCommand("cursorMove", {
            to: "right",
            by: "character",
            value: char,
          })
        );
    });
  });
Run Code Online (Sandbox Code Playgroud)

此代码片段首先打开文档并在编辑器中显示它,然后将光标移动给定的行数,然后将其移动给定的字符数。