【问题标题】:Set selection range in the Visual Studio Code document在 Visual Studio Code 文档中设置选择范围
【发布时间】:2018-04-25 07:56:08
【问题描述】:

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

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

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

【问题讨论】:

  • textEditor.selection = new vscode.Selection(firstLine.lineNumber, firstLine.range.start.character, lastLine.lineNumber, lastLine.range.end.character) ?
  • 它有效,我不知道为什么,但我认为textEditor.selection 是只读的......我改用textEditor.selection = new vscode.Selection(range.start, range.end); 来简化代码。谢谢!

标签: typescript visual-studio-code vscode-extensions


【解决方案1】:

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】:

为了注册一个设置光标位置的命令,我使用了这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2017-07-27
    • 2015-09-17
    • 2021-07-09
    • 2013-07-14
    • 2012-01-21
    • 2020-04-21
    相关资源
    最近更新 更多