将按键绑定到使用 Visual Studio 代码中的当前文件的 shell 命令

Leo*_*ada 1 visual-studio-code

有没有办法创建一个键绑定来对文件执行 shell 命令?就像是:

{
    "key": "ctrl+shift+e",
    "command": "run",
    "command": "touch $file",
    "when": "editorTextFocus"
}
Run Code Online (Sandbox Code Playgroud)

我不想使用任务,因为这需要对整个编辑器是全局的,而不是特定的工作区。

Mar*_*ark 5

[请参阅下面的编辑 - 现在更容易做到。]

我想出了一种方法来做你想做的事,但这有点像黑客。您可能知道,如果您可以在 .vscode/tasks.json 中创建任务并使用以下内容,则绑定任务很容易:

{
  "key": "shift+escape",
  "command": "workbench.action.tasks.runTask",
  "args": "Start server and process files"
},
Run Code Online (Sandbox Code Playgroud)

在没有预先存在的任务的情况下通过键绑定运行脚本要复杂得多。但是,您可以尝试以下利用该 "workbench.action.terminal.runSelectedText",命令的方法。但是我们需要先将脚本放入选择中,因此:

使用宏扩展(有点粗糙),以便我们可以将多个命令联系在一起。在您的用户设置中

"runCommandInTerminal": [

   {
     "command": "type",
     "args": {
        "text": "node -v"
     }
  },
  { 
    "command": "cursorMove",
    "args": {
       "to": "wrappedLineStart",
       "by": "wrappedLine",
       "value": 1,
       "select": true
    }
  },
  "workbench.action.terminal.runSelectedText",
  "editor.action.clipboardCutAction",
  //  "workbench.action.terminal.focus"
],
Run Code Online (Sandbox Code Playgroud)

这是一个设置的一般示例,"runCommandInTerminal"然后您可以将其绑定到 keybindings.json 中您希望的任何键和弦,例如

{
    "key": "ctrl+shift+e",
    "command": "macros.runCommandInTerminal"
},
Run Code Online (Sandbox Code Playgroud)

你的例子${file}有点难,因为你想访问一些你不能在设置中做的东西,只有tasks.json和launch.json。幸运的是,有一个命令可以获取当前文件:"copyFilePath". 所以试试

"runCommandInTerminal": [

      "copyFilePath",
      {
        "command": "type",
        "args": {
          "text": "touch "
        }
      },
      "editor.action.clipboardPasteAction",
      { 
      "command": "cursorMove",
        "args": {
        "to": "wrappedLineStart",
        "by": "wrappedLine",
        "value": 1,
        "select": true
        }
      },
      "workbench.action.terminal.runSelectedText",
      "editor.action.clipboardCutAction",
      // "workbench.action.terminal.focus"
],
Run Code Online (Sandbox Code Playgroud)

首先获取文件路径,然后输出脚本命令的第一部分“ touch”。

接下来将文件路径附加到命令的末尾。

移动光标选择前面的。

在终端中运行选择。

从编辑器中剪切选择。

这可以与您的键绑定一起运行。您将看到正在键入和剪切脚本的闪光,但您的编辑器代码不会受到影响。最好从编辑器中的空白行运行它,但如果您愿意,也可以从不相关代码行的开头运行它(但现在缩进可能会丢失)。

这是hacky,但似乎工作。我很想知道是否有扩展或其他方式来做这个清洁工。


2019 年 5 月编辑

由于我的原始答案(如@Jeff 所示)vscode 添加了sendSequence命令。以及在该命令中使用变量的能力。所以现在OP的问题更容易完成:

{
  "key": "alt+x",
  "command": "workbench.action.terminal.sendSequence",
  "args": {"text": "touch ${file}"}
}
Run Code Online (Sandbox Code Playgroud)

在您的 keybindings.json 文件中。使用 sendSequnce 命令查看变量