I know how to modify and create code snippets and I know how to modify shortcut keys, but how does one bring those 2 together?
All keyboard shortcuts in VS Code can be customized via the keybindings. json file. To configure keyboard shortcuts through the JSON file, open Keyboard Shortcuts editor and select the Open Keyboard Shortcuts (JSON) button on the right of the editor title bar. This will open your keybindings.
You can define a keyboard shortcut for any task. From the Command Palette (Ctrl+Shift+P), select Preferences: Open Keyboard Shortcuts File, bind the desired shortcut to the workbench.
Note that the line below will open a list of snippets defined for the language you are currently using (and you don't want that)
"args": { "snippet": "'$TM_SELECTED_TEXT'" }
Whereas with the below line the snippet given as argument will be executed right away
"args": { "name": "your_snippets_name" }
Here's how I defined a snippet for HTML where I wanted to select a text and when pressing CTRL+B the text to become enclosed in <strong></strong>
tags:
"make_strong": { "prefix": "strong", "body": [ "<strong>$TM_SELECTED_TEXT${1:}</strong>" ], "description": "Encloses selected text in <strong></strong> tags" }
Note the
${1:}
above - what this does is that it places the cursor there. This enables you to press CTRL+B at cursor and then have the cursor placed inside the<strong></strong>
tags. When selecting a string and pressing CTRL+B, the string will enclosed in<strong>
tags and the cursor will be placed before the closing</strong>
tag. Pressing TAB at this point, will put your cursor after the closing</strong>
tag.
And added in my keybindings.json
the following:
{ "key": "ctrl+b", "command": "editor.action.insertSnippet", "args": { "name": "make_strong" } }
UPDATE JUNE 2nd, 2021
Since this is getting lots of views, I am posting some of the snippets I use, maybe it will be useful to someone
{ "key": "ctrl+alt+u", "command": "editor.action.transformToUppercase" }, { "key": "ctrl+alt+l", "command": "editor.action.transformToLowercase" }, { "key": "ctrl+b", "command": "editor.action.insertSnippet", "args": { "name": "insert_strong" } }, { "key": "ctrl+i", "command": "editor.action.insertSnippet", "args": { "name": "insert_italic" } }, { "key": "ctrl+u", "command": "editor.action.insertSnippet", "args": { "name": "insert_underline" } }, { "key": "ctrl+alt+p", "command": "editor.action.insertSnippet", "args": { "name": "insert_paragraph" } }, { "key": "ctrl+shift+space", "command": "editor.action.insertSnippet", "args": { "name": "insert_nbsp" } }, { "key": "ctrl+enter", "command": "editor.action.insertSnippet", "args": { "name": "insert_br" } },
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With