VSCode — Auto-Insert Repeated Code with Snippets
When using VSCode, I wanted repeated code to be auto-inserted via a specific prefix + the Tab key.
This post walks through VSCode’s snippets feature and how to apply it.
[01] Example of Repeated Code
- In Markdown documents (writing a Readme.md for GitLab/GitHub), I sometimes need to apply color and bold to a specific string.
1
2
3
4
5
6
7
8
# red is the desired color
# apple is the desired text
# Color only
$`\textcolor{red}{\textsf{apple}}`$
# Color + bold
**$`\textcolor{red}{\textsf{apple}}`$**
[02] How to Apply
Configure the Tab Key
- In VSCode, press
Ctrl + Shift + P -
Search
>preferences: Open ... settings.json - Check Emmet and Tab Completion settings
-
Emmet: a tool primarily used for HTML/CSS where typing a short abbreviation expands into a longer pre-defined string1 2 3 4
"editor.tabCompletion": "on", "emmet.includeLanguages": { "markdown": "html" }
-
Define the Snippet
- In VSCode, press
Ctrl + Shift + P - Search
Snippets: Configure Snippets -
Select
- If
markdown.jsonexists, edit it - If
markdown.jsondoes not exist, chooseNew Global Snippets file..orNew Global Snippets file for 'xxx'-
If you want the snippet to apply to a Remote VSCode session, create it via
New Global Snippets file for 'xxx'.
-
- If
- Edit the json file
- Type the string set in
prefix, then press Tab to trigger auto-completion. - In
body, write the repeated text. Use$1for places where user input is needed.-
Note: in JSON, to make
\textcolorrecognized, you must escape it as\\textcolor.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
{ // Place your snippets for markdown here. // Each snippet is defined under a snippet name and has a prefix, body and // description. The prefix is what is used to trigger the snippet // and the body will be expanded and inserted. Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, // and ${1:label}, ${2:another} for placeholders. Placeholders with the // same ids are connected. // Example: // "Print to console": { // "prefix": "log", // "body": [ // "console.log('$1');", // "$2" // ], // "description": "Log output to console" // } // Add the snippet below "Color Bold Text": { "prefix": "cb", "body": "**$`\\textcolor{red}{\\textsf{$1}}`$**", "description": "Insert bold text with orange color" } }
-
- Type the string set in
Restart or Reload Window
- In VSCode, press
Ctrl + Shift + P - Search
Reload Windowsand run it
[03] Example
-
In a Markdown file, type
cband pressTab— the configured content is inserted automatically.