对 运行 之前或最后的 shell 命令进行键绑定

Make a keybinding to run previous or last shell commands

我经常想快速重新运行我使用的最后一个shell命令。

我知道您可以将焦点转移到终端,向上箭头并输入,但我认为一定有比这三个步骤更好的方法。

vscode 中的 sendSequence 命令变得越来越强大,因此我寻找一种方法来创建一个键绑定,该键绑定将 运行 最后一个 shell 命令快速执行。

来自sendSequence documentation

Send text from a keybinding

The workbench.action.terminal.sendSequence command can be used to send a specific sequence of text to the terminal, including escape sequences. This enables things like sending arrow keys, enter, cursor moves, etc. The example below shows the sorts of things you can achieve with this feature, it jumps over the word to the left of the cursor (Ctrl+Left arrow) and presses backspace:

{
  "key": "ctrl+u",
  "command": "workbench.action.terminal.sendSequence",
  "args": { "text": "\u001b[1;5D\u007f" }
}

This feature supports variable substitution.

Note that the command only works with the \u0000 format for using characters via their character code (not \x00).

terminal supports variables substitution:

{
  "key": "ctrl+shift+t",
  "command": "workbench.action.terminal.sendSequence",
  "args": { "text": ". ${file}" }
}

例如,参见 :

{
    "key": "ctrl+shift+t",
    "command": "workbench.action.terminal.sendSequence",
    "args": { "text": "node '${file}'\u000D" }
}

另请参阅 ,了解如何查看某些受支持的 shell 和 OS 的最近终端命令的快速选择(从 v1.64 开始预览)。


我想到了这个键绑定:

{
  "key": "alt+x",

  "command": "workbench.action.terminal.sendSequence",
      
  "args": { "text": "\u001b[A\u000d" }
},
  1. \u001b是一个转义序列,表示后面的字符有特殊含义。

  2. [A 是一个向上的箭头。参见,例如,xterm function keys:

    Cursor Up    | CSI A
    Cursor Down  | CSI B
    Cursor Right | CSI C
    Cursor Left  | CSI D
    

(“CSI”指的是 ESC\u001b 或后跟 [,代表“控制序列引入器”(CSI 为 0x9b)。)

所以“CSI A”是 \u001b[A,它等于一个向上箭头,它应该将您的终端命令列表循环到上一个命令。

  1. \u000d 是一个 return,所以命令 运行 立即生效。

现在 Alt-x 或您选择的任何键绑定将 运行 最后使用的 shell 命令,焦点可以在编辑器或终端中。

为了好玩,我整理了这个命令:

"args": { "text": "\u0012watch\u001b[1;5C" }    

这将发送 Ctrl-R 到搜索先前命令的终端。

然后会搜索“watch”,然后Ctrl-rightArrow到“ watch" 如果需要,您可以在其中修改参数。

或跳过 Ctrl-rightArrow 部分 (\u001b[1;5C) 并执行 return (\u000d) 到 运行 在您的历史记录中的任何地方找到的命令。显然,您需要一个独特的搜索词才能发挥作用。

[已测试电源shell 和 git bash。未在别处测试。]