Ameen
Ameen

Reputation: 1857

How to bind one key to multiple commands in VSCode

I'm trying to make the key Ctrl+UpArrow execute both commands cursorUp and scrollLineUp.

I was hoping that this would work, but it doesn't:

{
  "key": "ctrl+up",
   "command": ["cursorUp", "scrollLineUp"], // This doesn't work
   "when": "editorTextFocus"
}

How do I do that in VSCode?

Upvotes: 13

Views: 5369

Answers (3)

KhaledMohamedP
KhaledMohamedP

Reputation: 5522

You can use the newly feature runCommands

e.g.

 {
    "key": "cmd+up",
    "command": "runCommands",
    "args": {
      "commands": ["cursorUp", "scrollLineUp"]
    },
    "when": "editorTextFocus"
  }

Reference: https://code.visualstudio.com/docs/getstarted/keybindings#_running-multiple-commands

Upvotes: 4

Dae
Dae

Reputation: 2427

There's a new way to achieve this without an extension:

  1. Run "Tasks: Open User Tasks" command to create or open a user level tasks file.

  2. Define commands as separate tasks, like so:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "ctrlUp1",
            "command": "${command:cursorUp}"
        },
        {
            "label": "ctrlUp2",
            "command": "${command:scrollLineUp}"
        },
        {
            "label": "ctrlUpAll",
            "dependsOrder": "sequence",
            "dependsOn": [
                "ctrlUp1",
                "ctrlUp2"
            ],
            "problemMatcher": []
        }
    ]
}
  1. In your keybindings.json:
{
    "key": "ctrl+up",
    "command": "workbench.action.tasks.runTask",
    "args": "ctrlUpAll",
    "when": "editorTextFocus"
}

("ctrlUpNNN" label format chosen for readability, task labels can be anything).

Upvotes: 7

HaaLeo
HaaLeo

Reputation: 11662

This is currently not possible, but the corresponding feature request is tracked here. However you should take a look to the macros extension. It enables you to chain different commands to a single custom command. This custom command then can be bound to a hotkey. In your case you could add this to your settings.json:

"macros": {
    "myCustomCommand": [
        "cursorUp",
        "scrollLineUp"
    ]
}

And then add your custom hotkey to the keybindings.json:

{
  "key": "ctrl+up",
  "command": "macros.myCustomCommand"
}

Upvotes: 13

Related Questions