簡體   English   中英

如何以編程方式將光標放在 vscode 編輯器擴展中的指定行上?

[英]How to put cursor on specified line in vscode editor extension programatically?

我正在研究 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) 
  });
});

我還嘗試使用editor.revealRange(rng, vscode.TextEditorRevealType.InCenter)顯示范圍,但也沒有效果。

  1. vscode.window.showTextDocument()添加options?:參數。 但這也沒有任何作用。 請看下面的代碼-
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})
});

我想,問題在於首先打開文件並將文本文檔顯示到編輯器中,然后更改光標位置。

您可以使用cursorMove內置命令:

  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,
          })
        );
    });
  });

此代碼段首先打開文檔並將其顯示在編輯器中,然后將光標移動給定的行數,然后將其移動給定的字符數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM