如何使用 vscode 在新行中插入片段?

Phi*_*lip 5 code-snippets visual-studio-code

我正在尝试为 python 制作一个 vscode 片段。假设我有这样一行代码:

my_var = call_some_function()
Run Code Online (Sandbox Code Playgroud)

我想双击 my_var 来选择它,按下一个键,它会产生以下结果:

my_var = call_some_function()
LOGGER.debug("my_var: %s", my_var)
<cursor is here>
Run Code Online (Sandbox Code Playgroud)

它也应该适用于表达式,就像我在这一行中选择“x + y + z”并按下键:

call_function(x + y + z)
Run Code Online (Sandbox Code Playgroud)

它应该产生:

call_function(x + y + z)
LOGGER.debug("x + y + z: %s", x + y + z)
<cursor is here>
Run Code Online (Sandbox Code Playgroud)

显然使用调试器更好。但有时您不能使用调试器。

Mar*_*ark 5

正如@Alex 的链接所暗示的那样,我认为您需要使用宏扩展才能使其正常工作。我更喜欢多命令,因为它有一个可用的间隔延迟(这对于某些宏是绝对必要的,但不是你的宏)。

在您的设置中:

"multiCommand.commands": [

    {
      "command": "multiCommand.debug",

      "sequence": [
        "editor.action.clipboardCopyAction",
        "editor.action.insertLineAfter",
        {
          "command": "editor.action.insertSnippet",
          "args": {
            "snippet": "LOGGER.debug(\"$CLIPBOARD: %s\", $CLIPBOARD)\n$0"
          }
        },
      ]
    }
]
Run Code Online (Sandbox Code Playgroud)

这将首先将您的选择复制到剪贴板,以便稍后由代码段使用。然后在下面插入一个空行并在那里插入代码片段(以防下面的行上已经有一些代码)。

使用键绑定触发:

{
  "key": "ctrl+alt+d",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.debug" }
},
Run Code Online (Sandbox Code Playgroud)

它适用于您的两个示例。