问题
I want to implement a second code formatting. This formatting should be executable by an additional command.
I have already registered a DocumentFormattingEditProvider
and that is fine.
vscode.languages.registerDocumentFormattingEditProvider({ language: 'sosse' }, {
provideDocumentFormattingEdits(document: vscode.TextDocument) {
return formattingAction(document);
},
});
But in my case I need a second formatting action for one-liners, which is executed by an command. I thought about using:
vscode.commands.registerCommand(command, callback)
But I don't know how to access and change the document.
回答1:
But I don't know how to access and change the document.
There's a special variant of registerCommand()
that I think is exactly what you're looking for: registerTextEditorCommand()
. From the API docs:
Text editor commands are different from ordinary commands as they only execute when there is an active editor when the command is called. Also, the command handler of an editor command has access to the active editor and to an edit-builder.
That means the callback
gets passed an instance of a TextEditor as well as a TextEditorEdit.
来源:https://stackoverflow.com/questions/49904658/change-text-by-command-with-vs-code-extension