如果您不选择变量,而只是将光标放在行尾,则可以使用简单的键绑定来插入片段,而无需宏。键绑定:
{
"key": "alt+w",
"command": "editor.action.insertSnippet",
"args": {
// works with cursor end of line, no selection
// output: print(arr)
"snippet": "\n${TM_CURRENT_LINE/(\\s*)(\\w*)\\b.*/print($2)/}"
}
},
如果您想要此输出print(“arr”: arr)
,请使用此键绑定:
{
"key": "alt+w",
"command": "editor.action.insertSnippet",
"args": {
// works with cursor end of line, no selection
// output: print(“arr”: arr)
"snippet": "\n${TM_CURRENT_LINE/(\\s*)(\\w*)\\b.*/print(\"$2\": $2)/}"
}
},
对于这些更简单的版本,变量必须是行中的第一个单词。
较旧的答案:
不幸的是,这似乎很难用一个简单的片段来完成。将在光标所在的位置插入一个新的片段 - 并且在您选择的变量上的场景下 - 然后第一行的其余部分仍然存在于片段之后。
使用允许您执行多个命令(如多命令或其他命令)的宏扩展相对容易。
安装扩展程序后,在您的设置中:
"multiCommand.commands": [
{
"command": "multiCommand.printVariable",
"sequence": [
"editor.action.clipboardCopyAction",
"editor.action.insertLineAfter",
{
"command": "type",
"args": {
"text": "print("
}
},
"editor.action.clipboardPasteAction",
{
"command": "type",
"args": {
"text": ")"
}
},
]
}
},
然后在 keybindings.json 中设置一些键绑定:
{
"key": "alt+q",
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.printVariable" },
// use the following if you wish to limit the command to python files
"when": "resourceExtname == .py"
},

如演示 gif 所示,选定的文本可以位于该行的任何位置,如果该行紧接在print()
语句下方的代码将插入到您期望的位置。
注意:这会将您选择的变量保存到剪贴板,以便将其覆盖。
如果您的变量始终位于行首并被选中,则可以使用更简单的宏:
"multiCommand.commands": [
{
"command": "multiCommand.printVariable",
"sequence": [
{
"command": "editor.action.insertSnippet",
"args": {
// selected variable is at beginning of line
"snippet": "${TM_CURRENT_LINE}\nprint(${TM_SELECTED_TEXT})"
}
},
"cursorEndSelect", // select to end and delete
"editor.action.clipboardCutAction"
]
}
]