VSCode — Code Snippets with Keys

</> Pardeep Dhingra
TechBlog
Published in
3 min readMay 29, 2020

--

VS code snippets with shortcut keys

Let’s start by creating our first code snippet.

VS Code keeps its code snippets in JSON files with the name of the language for which we are creating snippets.

You can go to code > Preferences > User Snippets

Once you click on User Snippets, it shows you a list of languages and options to create a new code snippet.

You can select any language for which you want to create a snippet or can choose the New Global Snippets file.

Here I am choosing the New Global Snippets file…

I am creating a code snippet in continuation with my previous article on Internationalization with React Apps.

So, here’s the scenario for adding the translation to any static text we need to wrap that text with <Trans> macro and wrapping that everywhere in your preexisting application could be a big challenge.

We can write a code snippet that automatically wraps any selected text with <Trans>.

Back to code snippet process, so after selecting the New Global Snippets file… it opens a new file where we can write our snippet.

Here transmacro, is the name of the snippet, the prefix is the text after writing that and pressing tab code snippet will automatically insert to our code, and body is the code which we want to automatically insert.

In the body, we are using the variable $TM_SELECTED_TEXT this is one the global variable available in all the snippets. You can get a complete list of variables here.

$TM_SELECTED_TEXT provides the text which the user has selected before pressing the shortcut keys (will tell how to add shortcut keys below).

We just need to save this snippet file and our code snippet is ready. Code snippets can be called by typing prefix and press tab or we can bind them with key shortcuts.

Here I will show you how to bind shortcut keys to execute code snippets.

Go to Code > Preferences > Keyboard Shortcuts or just press [ k S]

It will show you a list of keyboard shortcuts already defined, for adding new keyboard shortcuts, click on open keyboard shortcuts JSON icon.

Keyboard Shortcuts

You can add keybindings to the opened JSON file

Keybindings.json

I am adding a shortcut key to insert the trans code snippet we created above.

Here the key is to specify the shortcut combination you want to use and the command is the action you want to do in the editor and args says the name of snippet we want to execute on the key shortcut.

Congratulations now we are good to use the code snippet with a shortcut key.

Just select any text and press key alt+m and that text will wrap by <Trans>

--

--