如何在Visual Studio Code中配置快捷键用自定义函数包裹选中代码?
实现VSCode选中Python代码包裹为指定函数参数的快捷键配置
需求:配置VSCode快捷键,将选中的Python代码包裹为指定函数的参数(示例:把 delta 转为 somefunction("delta")),函数名通过弹窗输入,目前未找到适配的Python扩展,需高效配置方案。
原待完善配置思路:
{ "key": "ctrl+alt+j", "command": "runCommands", "args": { "commands": [ // to do: "vscode.window.showInputBox()", // show dialog box // combine the editor.selection and dialog box response as response + "(" + editor.selection + ")" // Delete editor selection and insert the combination instead ] } },
解决方案
VSCode原生runCommands无法直接处理输入框返回值与选中内容的联动,需借助multi-command扩展实现多命令协作,步骤如下:
- 安装
multi-command扩展(VSCode扩展市场搜索即可) - 在
settings.json中添加自定义宏配置:
"multiCommand.commands": [ { "command": "multiCommand.wrapWithFunction", "sequence": [ { "command": "extension.multiCommand.execute", "args": { "command": "vscode.window.showInputBox", "args": { "prompt": "请输入函数名", "placeHolder": "例如: somefunction" }, "then": [ { "command": "editor.action.insertSnippet", "args": { // 若需要给选中内容自动加引号,改为 "${input:0}(\"${TM_SELECTED_TEXT}\")" "snippet": "${input:0}(${TM_SELECTED_TEXT})" } } ] } } ] } ]
- 在
keybindings.json中绑定快捷键:
{ "key": "ctrl+alt+j", "command": "multiCommand.wrapWithFunction", "when": "editorTextFocus && editorHasSelection && editorLangId == 'python'" }
配置说明
- 仅在Python文件、有文本选中且编辑器聚焦时触发快捷键,避免误操作
- 输入函数名后,自动替换选中内容为
函数名(选中内容)格式;若需要给选中内容添加引号,修改snippet中的模板即可 - 弹窗支持输入提示和占位符,提升输入体验
参考资料:
- 弹窗输入框:学习
vscode.window.showInputBox的使用方式及输入验证方法 - 自定义弹窗:了解VSCode中自定义弹窗的实现逻辑
内容的提问来源于stack exchange,提问作者Uwe.Schneider
相关产品推荐
相关产品推荐

