Skip to main content

Commands API

The Commands API allows you to register and execute commands in VS Code. Commands are functions with unique identifiers that can be invoked from the Command Palette, keyboard shortcuts, menus, or programmatically.

Namespace

All command-related functionality is available through the commands namespace.

Core Functions

registerCommand

Register a command that can be invoked via keyboard shortcuts, menu items, or directly.
string
required
A unique identifier for the command
function
required
The command handler function that will be executed
any
The this context used when invoking the handler
Disposable
Disposable that unregisters the command when disposed

Example

Registering a command with an existing identifier will cause an error. Ensure your command IDs are unique.

registerTextEditorCommand

Register a text editor command that executes only when an active editor is present.
string
required
Unique identifier for the command
function
required
Handler with access to the active TextEditor and TextEditorEdit builder
any
The this context for the handler

Example

The edit builder is only valid during callback execution. Changes are applied atomically when the callback completes.

executeCommand

Execute a command programmatically.
string
required
Identifier of the command to execute
any[]
Parameters passed to the command handler
Thenable<T>
A thenable that resolves to the command’s return value

Example

getCommands

Retrieve the list of all available commands.
boolean
default:"false"
Set to true to exclude internal commands (those starting with underscore)
Thenable<string[]>
List of command identifiers

Example

Command Interface

Commands are referenced using the Command interface:
string
required
Human-readable title displayed in the UI
string
required
The identifier of the command handler
string
Optional tooltip shown when hovering over the command
any[]
Arguments passed to the command handler when invoked

Usage Example

Package.json Contributions

Declare commands in your package.json to make them available in the Command Palette:
package.json

Built-in Commands

VS Code provides many built-in commands you can execute:

Advanced Patterns

Conditional Command Registration

Command Chaining

Error Handling

Best Practices

  • Use a consistent prefix (e.g., myExtension.commandName)
  • Choose descriptive, action-oriented names
  • Avoid generic names that might conflict
  • Document all public commands
  • Keep command handlers lightweight
  • Use async/await for long-running operations
  • Show progress indicators for slow operations
  • Don’t block the UI thread
  • Provide clear feedback when commands execute
  • Handle errors gracefully with user-friendly messages
  • Support undo/redo when modifying text
  • Use appropriate keyboard shortcuts

Common Use Cases

Transform Selected Text

Open External URL

Create New File with Content