要想通过命令执行插件,我们应该配置两处:
package.json
中 contributes.commands
字段vscode.commands.registerCommand
API 注册命令package.json
:
{
"contributes": {
"commands": [
{
// command 对应 vscode 的 registerCommand 的第一个参数
"command": "id.helloworld",
// 用换下 ctrl + p 显示的命令名字
"title": "Hello Wolrd"
}
]
}
}
src/extension.ts
文件:
export function activate(ctx: vscode.ExtensionContent) {
// 注册命令
vscode.commands.registerCommand('id.helloworld', () => {
// 窗口弹出对应信息
vscode.window.showInformationMessage('Hello World')
})
}
键位绑定相比于命令绑定,多了 contribtues.keybindings
字段
{
"contributes": {
"keybindings": [
{
"command": "id.sayKey",
"key": "ctrl+f1",
"max": "ctrl+f1",
"when": "editorTextFoucs"
}
],
"commands": [
{
// 与 keybindings 的 command 绑定
"command": "id.sayKey",
"title": "key bindings test"
}
]
}
}
其中 when
字段表示何时命令绑定会生效,如果我们不指定,那么该指令全局生效
vscode 可以观测两次按键触发事件,这种模式可以在配置 key
字段时加入空格:
"key": "ctrl+f1 ctrl+e"
vscode 有三种数据存储方式:
ExtensionContext.workspaceState
:键值对组成的工作区数据。当同一个工作区再次打开时会重新取出数据。ExtensionContext.globalState
:键值对组成的全局数据。当插件激活时会再次取出这些数据。ExtensionContext.storagePath
:指向你的插件可以读写的本地文件夹的路径。如果你要储存比较大的数据,这是一个非常好的选择。ExtensionContext.globalStoragePath
:指向你的插件可以读写的本地存储的路径。如果你要存储所有工作区内的大文件,这时一个非常好的选择。export function activate(ctx: vscode.ExtensionContext) {
// storagePath 已经废弃了,官方推荐使用 storageUri,其中 fsPath 是格式化好的路径,因为 window 和 linux 路径格式不同,如果是 path,那么格式将会是 /home/xxx
const storagePath = context.storageUri?.fsPath
if (!storagePath) {
return
}
vscode.window.showInformationMessage(storagePath)
if (!fs.existsSync(storagePath)) {
fs.mkdirSync(storagePath)
}
fs.writeFileSync(
path.join(storagePath, 'data.json'),
JSON.stringify({ now: Date.now() }),
)
}
Vscode 提供了三种 API 为用户提示信息,在上面的代码中我们接触了 showInformationMessage
API,完整的通知显示 API 有:
顾名思义,是展示不同状态下的通知
使用 vscode.QuickPick
API
commands.registerCommand('vscode-lang-nesting-config.quickPick', () => {
const options = ['foo', 'bar', 'baz', '42'].map((item) => ({
label: item,
}))
quickPick.items = options
quickPick.onDidChangeSelection((selection) => {
if (selection) {
window.showInformationMessage(JSON.stringify(selection))
quickPick.hide()
}
})
quickPick.onDidHide(() => quickPick.dispose())
quickPick.show()
})
插件可以使用window.showOpenDialog
API打开系统文件选择器,然后选择文件或是文件夹。
commands.registerCommand(
'vscode-lang-nesting-config.openDialog',
async () => {
const files = await window.showOpenDialog()
if (!files?.length) {
return
}
window.showInformationMessage(JSON.stringify(files[0].fsPath))
},
)