Overview
Thevscode.commands namespace provides functions to register and execute commands. Commands are central to how users interact with VS Code, accessible via keyboard shortcuts, menus, actions, and the Command Palette.
Key Functions
registerCommand
Registers a command that can be invoked via keyboard shortcut, menu item, or Command Palette.A unique identifier for the command (e.g.,
"myExtension.doSomething")The command handler function that executes when the command is invoked
The
this context used when invoking the handler functionregisterTextEditorCommand
Registers a text editor command with access to the active editor and edit builder.A unique identifier for the command
Handler with access to TextEditor and TextEditorEdit
executeCommand
Executes a command by its identifier.Identifier of the command to execute
Parameters passed to the command function
When executing editor commands, only primitive types (string, boolean, number, undefined, null) and VS Code types (Position, Range, Uri, Location) are allowed as arguments.
getCommands
Retrieves the list of all available commands.Set
true to exclude internal commands (those starting with underscore)Common Built-in Commands
VS Code provides many built-in commands you can execute:File Operations
File Operations
workbench.action.files.save- Save active fileworkbench.action.files.saveAll- Save all filesworkbench.action.files.newUntitledFile- Create new fileworkbench.action.closeActiveEditor- Close active editor
Editor Operations
Editor Operations
editor.action.formatDocument- Format documenteditor.action.commentLine- Toggle line commenteditor.action.selectAll- Select all texteditor.action.clipboardCopyAction- Copy to clipboard
Navigation
Navigation
Best Practices
Naming Convention
Use reverse domain notation for command IDs:
publisher.extension.commandNameDispose Properly
Always add command disposables to
context.subscriptionsUse Text Editor Commands
For editor modifications, use
registerTextEditorCommand for automatic edit builder accessError Handling
Wrap command logic in try-catch to handle errors gracefully
Related Resources
Contribution Points
Learn how to declare commands in package.json