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.
// Execute a built-in commandawait vscode.commands.executeCommand('workbench.action.files.save');// Execute your own command with argumentsconst result = await vscode.commands.executeCommand( 'extension.calculate', 10, 20);console.log('Result:', result);// Open a fileawait vscode.commands.executeCommand( 'vscode.open', vscode.Uri.file('/path/to/file.txt'));
Primitive Types
VS Code Types
Copy
Ask AI
// Only primitive types are allowed for built-in commandsawait vscode.commands.executeCommand( 'editor.action.insertSnippet', { snippet: 'console.log($1);' });
Copy
Ask AI
// Position, Range, Uri, and Location are also allowedawait vscode.commands.executeCommand( 'editor.action.goToLocations', document.uri, new vscode.Position(10, 5), locations);
// Get all commands including internalconst allCommands = await vscode.commands.getCommands();console.log(`Total commands: ${allCommands.length}`);// Get only public commandsconst publicCommands = await vscode.commands.getCommands(true);const extensionCommands = publicCommands.filter(cmd => cmd.startsWith('extension.'));console.log('Extension commands:', extensionCommands);
// In a CodeLensconst codeLens = new vscode.CodeLens(range, { title: 'Run Test', command: 'extension.runTest', arguments: [testId, testFile]});// In a tree itemconst treeItem = new vscode.TreeItem('Item');treeItem.command = { title: 'Open File', command: 'vscode.open', arguments: [uri]};
VS Code provides many built-in commands you can execute:
Copy
Ask AI
// Save the active fileawait vscode.commands.executeCommand('workbench.action.files.save');// Format documentawait vscode.commands.executeCommand('editor.action.formatDocument');// Toggle sidebarawait vscode.commands.executeCommand('workbench.action.toggleSidebarVisibility');