Commands

Commands trigger actions in Visual Studio Code. If you have ever configured a keybinding, then you’ve worked with commands. Commands are also used by extensions to expose functionality to users, bind to actions in VS Code’s UI, and implement internal logic.

Using Commands

VS Code includes a large set of built-in commands that you can use to interact with the editor, control the user interface, or perform background operations. Many extensions also expose their core functionality as commands that users and other extensions can leverage.

Programmatically executing a command

The vscode.commands.executeCommand API programmatically executes a command. This lets you leverage VS Code’s built-in functionality, and build on extensions such as VS Code’s built-in Git and Markdown extensions.

The editor.action.addCommentLine command, for example, comments the currently selected lines in the active text editor:

  1. import * as vscode from 'vscode';
  2. function commentLine() {
  3. vscode.commands.executeCommand('editor.action.addCommentLine');
  4. }

Some commands take arguments that control their behavior. Commands may also return a result. The API-like vscode.executeDefinitionProvider command, for example, queries a document for definitions at a given position. It takes a document URI and a position as arguments, and returns a promise with a list of definitions:

  1. import * as vscode from 'vscode';
  2. async function printDefinitionsForActiveEditor() {
  3. const activeEditor = vscode.window.activeTextEditor;
  4. if (!activeEditor) {
  5. return;
  6. }
  7. const definitions = await vscode.commands.executeCommand<vscode.Location[]>(
  8. 'vscode.executeDefinitionProvider',
  9. activeEditor.document.uri,
  10. activeEditor.selection.active
  11. );
  12. for (const definition of definitions) {
  13. console.log(definition);
  14. }
  15. }

To find available commands:

Command URIs

Commands URIs are links that execute a given command. They can be used as clickable links in hover text, completion item details, or inside of webviews.

A command URI uses the command scheme followed by the command name. The command URI for the editor.action.addCommentLine command, for example, is command:editor.action.addCommentLine. Here’s a hover provider that shows a link in the comments of the current line in the active text editor:

  1. import * as vscode from 'vscode';
  2. export function activate(context: vscode.ExtensionContext) {
  3. vscode.languages.registerHoverProvider(
  4. 'javascript',
  5. new (class implements vscode.HoverProvider {
  6. provideHover(
  7. _document: vscode.TextDocument,
  8. _position: vscode.Position,
  9. _token: vscode.CancellationToken
  10. ): vscode.ProviderResult<vscode.Hover> {
  11. const commentCommandUri = vscode.Uri.parse(`command:editor.action.addCommentLine`);
  12. const contents = new vscode.MarkdownString(`[Add comment](${commentCommandUri})`);
  13. // To enable command URIs in Markdown content, you must set the `isTrusted` flag.
  14. // When creating trusted Markdown string, make sure to properly sanitize all the
  15. // input content so that only expected command URIs can be executed
  16. contents.isTrusted = true;
  17. return new vscode.Hover(contents);
  18. }
  19. })()
  20. );
  21. }

The list of arguments to the command is passed as a JSON array that has been properly URI encoded: The example below uses the git.stage command to create a hover link that stages the current file:

  1. import * as vscode from 'vscode';
  2. export function activate(context: vscode.ExtensionContext) {
  3. vscode.languages.registerHoverProvider(
  4. 'javascript',
  5. new (class implements vscode.HoverProvider {
  6. provideHover(
  7. document: vscode.TextDocument,
  8. _position: vscode.Position,
  9. _token: vscode.CancellationToken
  10. ): vscode.ProviderResult<vscode.Hover> {
  11. const args = [{ resourceUri: document.uri }];
  12. const stageCommandUri = vscode.Uri.parse(
  13. `command:git.stage?${encodeURIComponent(JSON.stringify(args))}`
  14. );
  15. const contents = new vscode.MarkdownString(`[Stage file](${stageCommandUri})`);
  16. contents.isTrusted = true;
  17. return new vscode.Hover(contents);
  18. }
  19. })()
  20. );
  21. }

You can enable command URIs in webviews by setting enableCommandUris in the WebviewOptions when the webview is created.

Creating new commands

Registering a command

vscode.commands.registerCommand binds a command id to a handler function in your extension:

  1. import * as vscode from 'vscode';
  2. export function activate(context: vscode.ExtensionContext) {
  3. const command = 'myExtension.sayHello';
  4. const commandHandler = (name: string = 'world') => {
  5. console.log(`Hello ${name}!!!`);
  6. };
  7. context.subscriptions.push(vscode.commands.registerCommand(command, commandHandler));
  8. }

The handler function will be invoked whenever the myExtension.sayHello command is executed, be it programmatically with executeCommand, from the VS Code UI, or through a keybinding.

Creating a user facing command

vscode.commands.registerCommand only binds a command id to a handler function. To expose this command in the Command Palette so it is discoverable by users, you also need a corresponding command contribution in your extension’s package.json:

  1. {
  2. "contributes": {
  3. "commands": [
  4. {
  5. "command": "myExtension.sayHello",
  6. "title": "Say Hello"
  7. }
  8. ]
  9. }
  10. }

The commands contribution tells VS Code that your extension provides a given command, and also lets you control how the command is displayed in the UI. Now our command will show up in the Command Palette:

The contributed command in the Command Palette

We still need to call registerCommand to actually tie the command id to the handler. This means that if the user selects the myExtension.sayHello command from the Command Palette but our extension has not been activated yet, nothing will happen. To prevent this, extensions must register an onCommand activationEvent for all user facing commands:

  1. {
  2. "activationEvents": ["onCommand:myExtension.sayHello"]
  3. }

Now when a user first invokes the myExtension.sayHello command from the Command Palette or through a keybinding, the extension will be activated and registerCommand will bind myExtension.sayHello to the proper handler.

You do not need an onCommand activation event for internal commands but you must define them for any commands that:

  • Can be invoked using the Command Palette.
  • Can be invoked using a keybinding.
  • Can be invoked through the VS Code UI, such as through the editor title bar.
  • Is intended as an API for other extensions to consume.

Controlling when a command shows up in the Command Palette

By default, all user facing commands contributed through the commands section of the package.json show up in the Command Palette. However, many commands are only relevant in certain circumstances, such as when there is an active text editor of a given language or when the user has a certain configuration option set.

The menus.commandPalette contribution point lets you restrict when a command should show in the Command Palette. It takes the id of the target command and a when clause that controls when the command is shown:

  1. {
  2. "contributes": {
  3. "menus": {
  4. "commandPalette": [
  5. {
  6. "command": "myExtension.sayHello",
  7. "when": "editorLangId == markdown"
  8. }
  9. ]
  10. }
  11. }
  12. }

Now the myExtension.sayHello command will only show up in the Command Palette when the user is in a Markdown file.

Enablement of commands

Commands support enablement via an enablement property - its value is a when-clause. Enablement applies to all menus and to registered keybindings.

Note: There is semantic overlap between enablement and the when condition of menu items. The latter is used to prevent menus full of disabled items. For example, a command that analyzes a JavaScript regular expression should show when the file is JavaScript and be enabled only when the cursor is over a regular expression. The when clause prevents clutter, by not showing the command for all other language files. Preventing cluttered menus is highly recommended.

Last, menus showing commands, like the Command Palette or context menus, implement different ways of dealing with enablement. Editor and explorer context menus render enablement/disablement items while the Command Palette filters them.

Using a custom when clause context

If you are authoring your own VS Code extension and need to enable/disable commands, menus, or views by using a when clause context and none of the existing keys suit your needs, then you can add your own context.

The first example below sets the key myExtension:showMyCommand to true, which you can use in enablement of commands or with the when property. The second example stores a value which you could use with a when clause to check if the number of cool open things is greater than 2.

  1. vscode.commands.executeCommand('setContext', 'myExtension:showMyCommand', true);
  2. vscode.commands.executeCommand('setContext', 'myExtension:numberOfCoolOpenThings', 4);