目录

---------

命令

要想通过命令执行插件,我们应该配置两处:

  1. package.jsoncontributes.commands 字段
  2. 入口文件使用 vscode.commands.registerCommand API 注册命令

package.json:

JSON
{
  "contributes": {
    "commands": [
      {
        // command 对应 vscode 的 registerCommand 的第一个参数
        "command": "id.helloworld",
        // 用换下 ctrl + p 显示的命令名字
        "title": "Hello Wolrd"
      }
    ]
  }
}

src/extension.ts 文件:

Typscript
export function activate(ctx: vscode.ExtensionContent) {
  // 注册命令
  vscode.commands.registerCommand('id.helloworld', () => {
    // 窗口弹出对应信息
    vscode.window.showInformationMessage('Hello World')
  })
}

键位绑定

键位绑定相比于命令绑定,多了 contribtues.keybindings 字段

JSON
{
  "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 字段时加入空格:

PlainText
"key": "ctrl+f1 ctrl+e"

数据存储

vscode 有三种数据存储方式:

Typscript
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

Typscript
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.showOpenDialogAPI打开系统文件选择器,然后选择文件或是文件夹。

Typscript
commands.registerCommand(
  'vscode-lang-nesting-config.openDialog',
  async () => {
    const files = await window.showOpenDialog()
    if (!files?.length) {
      return
    }
    window.showInformationMessage(JSON.stringify(files[0].fsPath))
  },
)