idk
idk

Reputation: 113

Is it possible to add custom keyboard shortcuts in Visual Studio Code?

I'd like to add in custom keyboard shortcuts - rather than just remapping existing key bindings. Is this possible?

The idea is to map a shortcut that will allow me to include an easily identifiable comment header to help index my projects - in this format:

/*--------------------------------------------------------------
# Header
--------------------------------------------------------------*/

Upvotes: 3

Views: 977

Answers (2)

Raphael Fernandes
Raphael Fernandes

Reputation: 861

For those looking for a way VS Code to suggest a block when someone is typing a keyword, I found the way on this answer: How can I add custom suggestions in VS Code?

  • F1 then search for "Snippets: Configure Snippets"
  • Create a new profile, if you don't have one
  • On the json file generated, add the following
    "cHeader": {
        "prefix": "cHeader",
        "body": ["/*--------------------------------------------------------------",
        "# Header",
        "--------------------------------------------------------------*/"]
    }
  • Save and start typing "cHeader" for example. A suggestion will pop and can be accepted with enter or by clicking

And a keyboard shortcut can be associated with this suggestion as in Mark's answer, by editing the JSON file (F1 then Preferences: Open Keyboard Shortcuts (JSON) )

Upvotes: 0

Mark
Mark

Reputation: 182571

Here is a snippet (which is triggered by typing cHeader):

"Custom Header": {
  "prefix": ["cHeader"],
  "body": [
    "/*---------------------------------------------------------------",
      "# $1",
    "---------------------------------------------------------------*/"
    ]
}

You can make that to whatever length you want. For more complicated situations, see https://stackoverflow.com/a/56874352/836330 or https://stackoverflow.com/a/58722958/836330.

If you want to set a keybinding to that, use this:

{
  "key": "ctrl+alt+r",            // whatever you want as a keybinding
  "command": "editor.action.insertSnippet",
  "args": {
    "name": "Custom Header"      // name from your snippet above
  },
  "when": "editorTextFocus"
}

Upvotes: 1

Related Questions