Search code examples
visual-studio-codekey-bindings

VS Code keyboard shortcut when multiple lines selected


I am trying to set up different command to keyboard shortcut when one line is selected and different one when multiple lines. I was trying to find example in default keybindings, but without success. Is there any way to achieve this? What when parameter should I use in keybindings file, maybe there is another way?


Solution

  • There are 2 when contexts about selection in the editor

    • editorHasSelection
    • editorHasMultipleSelections

    If you are looking for a case where the selection is a single selection but multiple lines you are out of luck, the context has no knowledge of what is selected.


    Edit

    I have written an extension that fixes this gap in the context for key bindings.

    Use Extra Context and it defines extraContext:editorSelectionHasMultipleLines to be used with when clause.

    An example:

    In settings.json:

      "multiCommand.commands": [
        {
          "command": "multiCommand.terminalSingleLine",
          "sequence": [
            { "command": "workbench.action.terminal.sendSequence",
              "args": { "text": "echo Single Line\u000D" }
            }
          ]
        },
        {
          "command": "multiCommand.terminalMultipleLine",
          "sequence": [
            { "command": "workbench.action.terminal.sendSequence",
              "args": { "text": "echo Multiple Lines\u000D" }
            }
          ]
        }
      ]
    

    In keybindings.json:

      {
        "key": "ctrl+k f5", // or any other key combo
        "command": "multiCommand.terminalSingleLine",
        "when": "editorTextFocus && !extraContext:editorSelectionHasMultipleLines"
      },
      {
        "key": "ctrl+k f5",
        "command": "multiCommand.terminalMultipleLine",
        "when": "editorTextFocus && extraContext:editorSelectionHasMultipleLines"
      }