如何将多行代码片段的一部分粘贴到特定行,其余部分粘贴到另一行

时间:2020-05-22 19:33:06

标签: visual-studio-code code-snippets vscode-snippets

我想为自己的使用情况创建一个自定义代码段,我目前想为@ emotion / core创建一个代码段。

我一直希望/** @jsx jsx */位于我的jsx文件的顶部。因此,当我在第9行上导入模块时,import {css, jsx} from '@emotion/core在第9行上,/** @jsx jsx */在第0行上。 我该如何实现?

当前代码段:

"Import emotion":{
    "prefix":"ime",
    "description": "Import emotion",
    "body": 
    [
        "/** @jsx jsx */",
        "import {css, jsx} from '@emotion/core';"
    ]
},

1 个答案:

答案 0 :(得分:1)

您将不得不将代码片段分解为单独的命令,以在中间步骤中移动光标。这将需要像multi-command这样的宏扩展名。

将其放入您的settings.json中:

"multiCommand.commands": [

  {
    "command": "multiCommand.insertImports",
    "sequence": [
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "snippet": "import {css, jsx} from '@emotion/core';"
        }
      },
      // "editor.action.setSelectionAnchor",   // see note below
      "cursorTop",
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "snippet": "/** @jsx jsx */\n"
        }
      },
      // "editor.action.goToSelectionAnchor",
      // "editor.action.cancelSelectionAnchor",
      "cursorDown"  
    ]
  }
]

和一些用于触发该宏的键绑定:

{
  "key": "ctrl+shift+i",             // whatever keybinding you wish
  "command": "extension.multiCommand.execute",
  "args": {
    "command": "multiCommand.insertImports"
  },
   "when": "editorTextFocus"
},

anchor命令的注意事项

editor.action.setSelectionAnchor
editor.action.goToSelectionAnchor
editor.action.cancelSelectionAnchor

这些命令在Insiders的内部版本中,并且可能在2020年6月初的v1.46版本中。它们在宏中只是为了方便将光标返回到您开始的位置。由于某种原因,命令workbench.action.navigateToLastEditLocation在这里对我不起作用-我认为这样就足够了。

没有这些新命令,光标不会返回到您开始的位置-也许这对您来说不是问题。无论如何,它们很快就会到来。一旦有了版本,就可以取消注释这些命令。这是使用这些命令的演示:

insert import at top of page