我在扩展触发后更新 VS Code 选择时遇到问题。
const selection = editor.selection;
const text = editor.document.getText(selection);
const modText = "/* " + text + " */";
let edit = new vscode.WorkspaceEdit();
let startPos = new vscode.Position(selection.start.line, selection.start.character);
let endPos = new vscode.Position(selection.start.line + text.split(/\r\n|\r|\n/).length - 1, selection.start.character + text.length);
let range = new vscode.Range(startPos, endPos);
edit.replace(editor.document.uri, range, modText);
return vscode.workspace.applyEdit(edit);
我选择下面的所有内容。
body {
background: blue;
}
触发后的结果为:
/* body {
background: blue;
} */
但是选择缺少开头的 /*
如何更改选择以包含初始的 /* ???
尝试将其添加到代码末尾:
await vscode.workspace.applyEdit(edit); // add the next line
editor.selections = [new vscode.Selection(startPos, new vscode.Position(endPos.line, endPos.character+6))];
看到它添加了 6 个字符来表示
/*
和 */
到 Selection
,其中应包括您的整个评论字符和所包含的文本。
这段代码做了同样的事情,而且更加紧凑:
editor.selections = [new vscode.Selection(startPos, endPos.translate(0, 6))];
更好的是使用
editBuilder
,因为它比 WorkspaceEdit
更好地处理跨编辑的保留选择。这就是为什么在原始答案中,您必须在编辑后手动操作选择来处理新文本的不同长度 - 长 6 个字符。
但是使用
editBuilder
,您可以简单地执行以下操作:
// make sure this is in an async block so you can use await below
let disposable = vscode.commands.registerCommand('myExtensionID.myCommandName', async (args) => {
const editor = vscode.window.activeTextEditor;
const selection = editor.selection;
const text = editor.document.getText(selection);
const modText = "/* " + text + " */";
await editor.edit(editBuilder => {
editBuilder.replace(selection, modText);
});
}
在简单的场景中,您应该能够使用
editBuilder
,但在一些更复杂的情况下,可能很难使用 editBuilder
方法,然后您可以使用 WorkspaceEdit
。