peni4142
peni4142

Reputation: 545

Change text by Command with VS-Code-Extension

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.

Upvotes: 1

Views: 1276

Answers (1)

Gama11
Gama11

Reputation: 34148

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.

Upvotes: 1

Related Questions