Get the 2024 Yearly Goals and Progress Tracker Notion Template for FREE!

How to create your own custom Code Snippets right in your Code Editor

SERIES: The Toolbox

Posted on: Apr 14, 2022

9 mins read

Originally published at www.freecodecamp.org

How to Create Your Own Custom Code Snippets Right in Your Code Editor

Code Snippet is a term used in programming to describe a small portion of reusable source code, machine code, or text. They help programmers reduce the time it takes to type repetitive codes while programming. Code Snippet can be found as a feature on most text editors, code editors, and IDE.

Prerequisite

I assume you can write a decent amount of code in the language you want to create a code snippet for.

And with that on the confirmation,

lady saying let us get started

When I first started learning how to code, the first code snippet I ever used along with other first-time front-enders was the Ctrl + ! and enter to get an HTML5 document template. (I doubt anyone knows how to write that from the heart.) It was cool and I felt like a code ninja.

As I started exploring more into coding, I learned about VsCode extensions that once downloaded made coding faster, code snippets in particular and I then went on a downloading spree.

All was going fine and well until I was frequently using frameworks and libraries in my projects which involved me trying to remember how to link my documents to their packages and also personalized CSS resets and variables. Plus I was always forgetting to link my stylesheets to my HTML pages making me spend an unreasonable amount of time trying to figure out why my pages were not being styled correctly. (I still forget to do so now and then.)

That got me thinking about having my personalized HTML and CSS templates which would have all the base codes I always used in my projects.

At first, I just created the templates and saved them on my system for me to copy the code from any time I started a new project but that also was getting stressful and I wanted to just type in a few letters, press enter and boom have my templates showing on my screen. And that was when I learned about VsCode Code Snippets.

I didn't know it was called code snippets at that time so I spent over 2 weeks trying to find a tool that could help me do this and I almost gave up. Until I randomly stumbled on Brad Travesty's video on one of my daily evenings walks on the YouTube streets without actively searching for it.

It was a lifesaver and every once in a while I add new custom snippets to my collection. (You can check my personalized HTML and CSS templates here.)

I'm sure at one or multiple points in your coding journey you wished you had a custom snippet of a particular code you often used just like me and didn't know how to create or find it. Well, wish no more for I'm about to show you how to easily create yours.

Creating Custom Code Snippets

Creating your custom snippet is very easy and with the help of another tool called Snippet Generator(which I will show you how to use later), it becomes even easier.

Step 1: Checking if your editor lets you create custom snippets

You can check the docs on your code editor to know if the feature is available and how to access it. I am using VsCode for this tutorial. You can download it here.

To access this, you can either click on the settings icon on the sidebar and then click on user snippets or open up the command palette using Cntr + shift + p on Windows or CMD + shift + p on Mac, typing in snippet and clicking on Preferences: Configure User Snippets.

This will give you a drop-down with different language selections to choose from.

video1-open-code-snippet

Step 2: Deciding your Snippet Scope

You can either create a global snippet that can be used across all languages or create a local snippet scoped to a particular language.

So from the drop-down, you can see New Global Snippet File and then a bunch of languages in alphabetical order.

Scroll to the language you want to write your snippet for and click on it or select New Global Snippet File if you want to use your snippets in multiple languages.

If you selected a particular language, HTML for example, the file will automatically open, but if you chose Global snippet, you would be prompted to type in the name of the snippet file before it opens.

For this note, I would be using Global Snippet.

video2-enter-snippet-name

Step 3: Understanding the Syntax

The Syntax for code snippet is quite easy actually. It is written in JSON format and each file can contain an unlimited number of snippets.

json
{
// Code Snippet 1
"Snippet name": {
"scope": "language1, language2"
"prefix": "trigger word 1",
"body": ["your code snippet"],
"description": "description of the code"
},
// Code Snippet 2
"Snippet name": {
"scope": "language1, language2"
"prefix": ["trigger word 1, trigger word 2"],
"body": ["your code snippet"],
"description": "description of the code"
}
}

Snippet Name

The Snippet Name is obviously the name of the snippet. It is also what will be displayed via IntelliSense if no description is provided.

Scope

This determines what languages are allowed to use the snippet. Enter the name of the language(s) separated by a comma. If you leave it empty or omit it, the snippet would be accessed by any language. This part is included in Global Snippets only as Local Snippets files are already locally scoped.

Prefix

This describes one or more trigger words that will prompt IntelliSense to display the snippet.

Body

This can be a string if it is a one-line code or and an array of strings if it is a multi-line code.

Description

This describes the snippet and what it does. If this is omitted, the name of the snippet would be used instead.

Example 1

json
// log to console
"Print to console": {
"scope": "javascript, typescript",
"prefix": "log",
"body": "console.log();",
"description": "Log output to console"
}

From the above example, our snippet name is Print to console, it can only be used in a JavaScript and Typescript file. If you were to type log in a javascript or typescript file, IntelliSense would show it along with the description Log output to console. Once you select it and click enter, console.log() would be seen on the screen.

video3-log

Step 4: Adding Tab Stops

Tabstops allows you to move the editor cursor inside a snippet. $1, $2 specify cursor locations it should move into sequentially when you hit the tab key. $0 represents the final position the cursor should stop.

Example 2

json
// named function
{
"Named Function": {
"scope": "javascript, typescript",
"prefix": "nfn",
"body": ["function $1($2){", " $0", "}"],
"description": ""
}
}

In this example, when you type nfn, our Named Function snippet shows up and once you select it, you would see our snippet on the screen. What you would also see is that our cursor is now before the parenthesis as opposed to being at the end of the code.

Type in the name of the function, "GetUsers" for example, and then hit the tab button. You will notice that the cursor has now moved into the parenthesis. You can type in the parameter if it has one or and hit the tab key again to move the cursor to the next tab stop which is between the curly brackets where our function body will go.

vide04-tabstop

Note: When you are writing multi-line codes, you cannot use a tab to indent your code, you can only use 2 spaces to indent your code or whatever number of spacing indentation you use to write your code.

Step 5: Using Placeholders

These are Tab Stops with values. They help the user easily identify or understand what (s)he is supposed to type at that particular tab stop. The placeholder will be automatically highlighted so you can immediately type in what you want to replace it with.

Example 3

json
// named function
{
// named function
"Named Function": {
"scope": "javascript, typescript",
"prefix": "nfn",
"body": [
"function ${1:functionName}(${2:parameter}){",
" ${0:functionBody}",
"}"
],
"description": ""
}
}

video5-placeholders

Step 6: Creating Choices

Placeholders can have choices as values. Whereby instead of typing in your value, you can choose from a dropdown selection.

Its syntax is writing the values which are separated by a comma between two pipe-character, for example, ${1|one, two, three|}.

Example 4

json
// array method
{
"Array Method": {
"scope": "javascript, typescript",
"prefix": "arrmth",
"body": [
"${1|forEach, map, filter, reduce|}((${2:item}) => {",
" $0",
"})"
],
"description": ""
}
}

video6-choices

Here, once you type in arrmth, select it from IntelliSense, and hit enter, the first tab stop would be a dropdown of array choices to select from. The next tab stop is the parameter and the last stop is the function code.

Snippet Generators

As your snippets begin to grow in line and size, it becomes difficult to type and create them within your code editor. This is where a snippet generator comes in.

A snippet generator will take in your normal code and turn it into a code snippet.

I will be using this Snippet Generator. With this particular snippet generator, you can write code snippets for VsCode, Sublime Text, and Atom.

image1-snippet-generator

Using the Snippet Generator

In the description input, enter the name of the code snippet which would be used as the name and description of the snippet.

In the tab trigger input, enter the prefix of your code snippet.

In the your snippet.. input, enter your code in its natural form as you would without writing it as an array of strings.

After this, you can then add in Tabstops, Placeholders, and Choices as explained above.

Example 5

json
//named function
function ${1:functionName}(${2: parameter}) {
${0:functionBody}
}

image2-arrow-function

Example 6

json
//array method
${1|forEach, map, filter, reduce,|}((${2:item}) => {
$0
)}

Final code

json
{
// log to console
"Print to console": {
"scope": "javascript, typescript",
"prefix": "log",
"body": "console.log();",
"description": "Log output to console"
},
// named function
"Named Function": {
"scope": "javascript, typescript",
"prefix": "nfn",
"body": [
"function ${1:functionName}(${2:parameter}){",
" ${0:functionBody}",
"}"
],
"description": ""
},
// array method
"Array Method": {
"scope": "javascript, typescript",
"prefix": "arrmth",
"body": [
"${1|forEach, map, filter, reduce|}((${2:item}) => {",
" $0",
"})"
],
"description": ""
}
}

image3-array-method

And that's it. Easy peasy lemon squeezy.

Recap

Let's do a recap. We have learned that

  • a Code Snippet is a small portion of re-usable source code, machine code, or text which helps programmers reduce the time it takes to type in repetitive codes while programming.
  • a code snippet file can contain an unlimited number of snippets.
  • you can have a locally scoped snippet used within only one language file or a globally scoped snippet used within two or more language files.
  • code snippets are written in JSON syntax.
  • you can add tabstops, placeholder, and choices to your code snippet.
  • you can also use a snippet generator to generate your snippets.

Resources

Thank you for reading my article. You can Connect With Me on X(Twitter) or LinkedIn to share with me what custom code snippets you would be creating, your comments or questions. And do feel free to share this article with others who might find this useful too. Till next time guys, Byeee!

Mr Beans waving goodbye

Connect With Me

Follow me on X(Twitter), and LinkedIn to stay updated with my latest content.

If you like my notes and want to support me, you can sponsor me on GitHub Sponsor, or you can buy me a virtual ice cream on ByMeACoffee or Selar. I would really appreciate it. 🙏

For other ways to support me, visit my Sponsorship page or Affiliate Links page.

Subscribe to my newsletter 💌

Never miss a beat! Stay updated with my latest tech tutorials, code snippets, how-to guides, productivity tips, personal projects and experiences, and more! 💻📚✨