Search code examples
visual-studio-codekey-bindings

Visual Studio Code keybindings - Running two or more commands with one shortcut


I have the following keybinding in VS Code which toggles the position of the cursor between the active document and built-in terminal:

  // Toggle between terminal and editor focus
{
    "key": "oem_8",
    "command": "workbench.action.terminal.focus"
},
{
    "key": "oem_8",
    "command": "workbench.action.focusActiveEditorGroup",
    "when": "terminalFocus"
}

Before i click the shortcut key to move the cursor to the terminal, i first have to save the active file.

I would therefore like to run the file saving command, which after searching on google i believe is workbench.action.files.save

How would i do this? I have tried adding the above code snippet at the end of the "command" line but it has not worked.


Solution

  • Update: released for vscode v1.77, more at run multiple commands like a macro.

    You are able to do this:

    {
      "command": "runCommands",
      "key": "alt+r", // whatever keybinding
      "args": {
        "commands": [
          // commands to run in sequence
          "workbench.action.files.save",
          "workbench.action.terminal.focus",
          // or a command with args
          {
            "command": "workbench.action.terminal.sendSequence",
            "args": {
              "text": "npm run lint\r"
            }
          }
    
        ]
      }
    }
    

    The command runCommands is built-in, so no extension is necessary for your use case. But see the link above, some use cases might require a macro extension.


    Previous answer:

    You would need a macro extension to run multiple commands from one keybinding.

    I now use multi-command and there are other macro extensions now.

    You can use this keybinding (in your keybindings.json) with the multi-command extension - no need for anything in settings.json:

    {
      "key": "oem_8", // or whatever keybinding you wish
      "command": "extension.multiCommand.execute",
      "args": {
        "sequence": [
          "workbench.action.files.save",
          "workbench.action.terminal.focus"
        ]
      },
      "when": "editorTextFocus" // if you want this, you probably do
    }
    

    If you have more complicated macros you can still build them in your settings.json if you wish.