如何使用vscode在新行中插入代码段? [英] How can I insert a snippet on a new line with vscode?

查看:298
本文介绍了如何使用vscode在新行中插入代码段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为python创建一个vscode代码段。
假设我有一行这样的代码:

I'm trying to make a vscode snippet for python. Suppose I have a line of code like this:

my_var = call_some_function()

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

I'd like to double click on my_var to select it, hit a key, and it produces the following result:

my_var = call_some_function()
LOGGER.debug("my_var: %s", my_var)
<cursor is here>

它也应适用于表达式,例如如果我在其中选择 x + y + z这行并按下键:

Also it should work for an expression too, like if I select "x + y + z" in this line and hit the key:

call_function(x + y + z)

它应该产生:

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

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

Obviously using a debugger is better. But sometimes you cannot use a debugger.

推荐答案

如@Alex的链接所示,我认为您需要使用宏扩展名才能让它工作。我更喜欢多命令,因为它具有可用的间隔延迟(

As @Alex's link suggests, I think you will need to use a macro extension to get this to work. I prefer multi-command because it has an interval delay available (which is absolutely necessary for some macros but not yours).

在您的设置中:

"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"
          }
        },
      ]
    }
]

这会将您的选择首先复制到剪贴板上稍后可被摘要使用。然后在下面插入一个空行,并在其中插入代码段(以防下面的行中已经有一些代码)。

This will copy your selection first to the clipboard so it can be used later by the snippet. Then insert an empty line below and insert the snippet there (in case the line below already has some code on it).

使用键盘绑定触发此操作:

Trigger this with a keybinding:

{
  "key": "ctrl+alt+d",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.debug" }
},

对两个示例都适用。

这篇关于如何使用vscode在新行中插入代码段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆