VSCode Extension API
Task Objectives
- This Skill is used for: mastering the use of the core APIs for VSCode extension development
- Capabilities include: command registration, window management, workspace operations, debug integration, notifications and dialogs
- Trigger conditions: when the user needs to implement extension functionality or call the VSCode API
Prerequisites
- Environment requirements: completed the vscode-extension-basics-skill study
- Tool requirements: VSCode API type definitions (@types/vscode)
Operation Steps
Standard Process
1. Command Operations (commands)
// 注册命令
const disposable = vscode.commands.registerCommand(
'extension.command',
(args: any) => {
console.log('Command executed');
}
);
// 执行命令
vscode.commands.executeCommand('editor.action.addCommentLine');
// 获取所有命令
const commands = await vscode.commands.getCommands();
2. Window Operations (window)
// 显示消息
vscode.window.showInformationMessage('Hello!', 'Option1', 'Option2');
// 显示输入框
const input = await vscode.window.showInputBox({
prompt: 'Enter your name'
});
// 显示快速选择
const selected = await vscode.window.showQuickPick(
['Option A', 'Option B'],
{ canPickMany: false }
);
// 创建终端
const terminal = vscode.window.createTerminal({
name: 'My Terminal',
shellPath: 'bash'
});
// 创建输出通道
const outputChannel = vscode.window.createOutputChannel('My Extension');
outputChannel.appendLine('Log message');
3. Workspace Operations (workspace)
// 获取配置
const config = vscode.workspace.getConfiguration('myExtension');
const value = config.get('settingKey');
// 获取工作区文件夹
const folders = vscode.workspace.workspaceFolders;
// 读取文件
const document = await vscode.workspace.openTextDocument(uri);
const text = document.getText();
// 创建文件监视
const watcher = vscode.workspace.createFileSystemWatcher('**/*.ts');
4. Debug Operations (debug)
// 启动调试
await vscode.debug.startDebugging(
workspaceFolder,
{ type: 'node', request: 'launch' }
);
// 获取活动调试会话
const session = vscode.debug.activeDebugSession;
// 输出到调试控制台
vscode.debug.activeDebugConsole.appendLine('Debug message');
Optional Branches
When event listening is needed
// 监听文本编辑器变化
vscode.window.onDidChangeActiveTextEditor(editor => {
console.log('Active editor changed');
});
// 监听配置变化
vscode.workspace.onDidChangeConfiguration(event => {
if (event.affectsConfiguration('myExtension')) {
console.log('Configuration changed');
}
});
Resource Index
Domain References
Notes
Resource Cleanup
- All Disposables returned by register need to be added to context.subscriptions
- Event listeners need to be released at the appropriate time
Asynchronous Handling
- Most APIs return Promise/Thenable
- Use async/await to correctly handle asynchronous flows
Type Safety
- Use TypeScript to get complete type hints
- @types/vscode provides API type definitions