我有这个工作热键:
{
"key": "cmd+t",
"command": "editor.action.insertSnippet",
"args": {
"name": "TryCatch"
}
},
它将选定的文本包装到 tryCatch block 中,并添加所需的日志和错误报告。
但是,我想将其与其他热键或任务序列链接。
我在 tasks.json
中有这个任务,当尝试执行上述命令时触发时,它会提示我输入用户输入,因为我不知道如何传递名称片段作为参数,类似于上面示例 1 中的 hotKey 绑定(bind)配置所做的事情。
这是任务:
{
"label": "insertSnippet",
"command": "${command:editor.action.insertSnippet}",
"args": [
// "${name:TryCatch}",
],
},
我一直在尝试让任务执行,而不必等待用户输入或按 enter
例如,但可怕地失败了。我找不到等待来拦截任务的执行并传递数据或从菜单中选择一个项目。
有关设置单个热键然后触发两个或更多命令的帮助吗?
请注意,我需要在编辑器中执行命令/任务,而不是在终端或 shell 中。我遇到的所有解决方案都是针对shell的。输入或文本也可以在 shell 或编辑器中使用,但不能在下拉列表中使用,如下图所示,这些是由任务触发的。
谢谢。
编辑,最后效果如何。非常感谢@Mark
{
"version": "2.0.0",
"tasks": [
{
"label": "insertTryCatchSnippet",
"command": [
"workbench.action.tasks.runTask",
"${input:tryCatchInput}"
]
},
{
"label": "save",
"command": "${command:workbench.action.files.save}",
},
{
"label": "TryCatch",
"dependsOrder": "sequence",
"dependsOn": [
"insertTryCatchSnippet",
"save",
],
},
],
"inputs": [
{
"id": "tryCatchInput",
"type": "command",
"command": "editor.action.insertSnippet",
"args": {
"name": "TryCatch"
}
}
]
}
这个热键快捷键:
{
"key": "cmd+t",
"command": "workbench.action.tasks.runTask",
"args": "TryCatch"
},
无需使用宏或扩展即可完美实现。再次感谢。
最佳答案
您可以运行 vscode 命令,例如 editor.action.insertSnippet
。但是,如果它们接受参数,我相信您必须使用 tasks.json
的 inputs
来提供参数。在您的 tasks.json
中:
{
"version": "2.0.0",
"tasks": [
{
"label": "insertTryCatchSnippet",
"command": [
"${input:tryCatchInput}"
],
}
],
"inputs": [
{
"id": "tryCatchInput",
"type": "command",
"command": "editor.action.insertSnippet",
"args": {
"name": "tryCatch"
}
}
您的代码段名称
在某些代码段文件中定义。
然后,您可以将此任务直接分配给这样的键绑定(bind)(在您的 keybindings.json
中):
{
"key": "alt+w",
"command": "workbench.action.tasks.runTask",
"args": "insertTryCatchSnippet",
"when": "editorFocus"
}
如果您想要的命令不需要任何参数,那么您可以在任务中执行类似的操作:
{
"label": "SplitTerminal",
"command": "${command:workbench.action.terminal.split}",
"type": "shell",
"problemMatcher": []
}
您也可以在一个任务中使用多个 vscode 命令(尽管有些命令可能需要等待前一个命令完成,并且您应该创建 2 个以上的任务,然后使用 dependsOrder
)从主任务运行> 属性序列
):
{
"label": "open new terminal and then saveAll",
// "type": "shell",
"command": [
"${command:workbench.action.terminal.new}",
"${command:workbench.action.files.saveAll}"
]
}
关于visual-studio-code - 如何将参数传递给 vscode 中执行链接到热键的代码片段的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74888109/