VS代码扩展Api获取文档整个文本的范围?

Jer*_*eng 10 typescript visual-studio-code vscode-extensions

我没有找到一个很好的方法来做到这一点.我目前的方法是首先选择所有:

vscode.commands.executeCommand("editor.action.selectAll").then(() =>{
    textEditor.edit(editBuilder => editBuilder.replace(textEditor.selection, code));
    vscode.commands.executeCommand("cursorMove", {"to": "viewPortTop"});
});
Run Code Online (Sandbox Code Playgroud)

这是不理想的,因为它在选择然后更换时会闪烁.

js-*_*yle 15

我希望这个例子可能会有所帮助:

var editor = vscode.window.activeTextEditor;
if (!editor) {
    return; // No open text editor
}

var selection = editor.selection;
var text = editor.document.getText(selection);
Run Code Online (Sandbox Code Playgroud)

来源vscode 扩展示例>文档编辑示例

  • 这不会产生范围 (2认同)

Ric*_*chS 13

这可能不健壮,但我一直在使用它:

var firstLine = textEditor.document.lineAt(0);
var lastLine = textEditor.document.lineAt(textEditor.document.lineCount - 1);
var textRange = new vscode.Range(0, 
                                 firstLine.range.start.character, 
                                 textEditor.document.lineCount - 1, 
                                 lastLine.range.end.character);
Run Code Online (Sandbox Code Playgroud)


mjo*_*ble 6

一个较短的例子:

const fullText = document.getText()

const fullRange = new vscode.Range(
    document.positionAt(0),
    document.positionAt(fullText.length - 1)
)
Run Code Online (Sandbox Code Playgroud)


Jan*_*jsi 5

您可以创建一个Range,它比文档文本长一个字符,并使用validateRange它来将其修剪为正确的字符Range。该方法找到文本的最后一行,并使用最后一个字符作为结束PositionRange

let invalidRange = new Range(0, 0, textDocument.lineCount /*intentionally missing the '-1' */, 0);
let fullRange = textDocument.validateRange(invalidRange);
editor.edit(edit => edit.replace(fullRange, newText));
Run Code Online (Sandbox Code Playgroud)