代码之家  ›  专栏  ›  技术社区  ›  lmcarreiro

在Visual Studio代码文档中设置选择范围

  •  4
  • lmcarreiro  · 技术社区  · 8 年前

    我在扩展中有一个命令,在运行该命令之前,我想更改选择范围以获得整行。。。

    const sel = textEditor.selection;
    const firstLine = textEditor.document.lineAt(sel.start.line);
    const lastLine = textEditor.document.lineAt(sel.end.line);
    
    const range = new vscode.Range(firstLine.lineNumber, firstLine.range.start.character, lastLine.lineNumber, lastLine.range.end.character);
    

    我已经创建了一个新范围,但我不知道如何将文档的选择设置为一个新范围。。。

    2 回复  |  直到 8 年前
        1
  •  4
  •   Alex    6 年前

    new Selection() 有2个重载(2个或4个参数):

    1. Selection(anchor: vscode.Position, active: vscode.Position)
    2. Selection(anchorLine: number, anchorCharacter: number, activeLine: number, activeCharacter: number)

    例如,使用4个参数:

    textEditor.selection = new vscode.Selection(firstLine.lineNumber, firstLine.range.start.character, 
    lastLine.lineNumber, lastLine.range.end.character)
    

    要创建多个光标,需要设置 textEditor.selections

    textEditor.selections = [
        new vscode.Selection(0, 0, 0, 10),
        new vscode.Selection(1, 0, 1, 10),
    ];
    
        2
  •  1
  •   yaya    5 年前

    为了注册用于设置光标位置的命令,我使用了以下命令:

    let cmd = vscode.commands.registerTextEditorCommand('extension.mysnippet', (te) => {
      // selection start = line 3, char 5 ||| selection end = line 3, char 5
      te.selection = new vscode.Selection(5, 3, 5, 3)
    });
    context.subscriptions.push(cmd);