Omar Shamali

Add Custom Snippet Visual Studio Code for Faster Programming

Author: Omar Shamali
Writing Date:

We write same snippet codes over and over again all over our program, it does not matter if it's a website, mobile app, or system. Saving time and reduce typos becomes crucial for our advancement.

Most IDEs comes with feature of suggesting snippets in the programing language you are using. But when it comes to functions or custom methods built, a developer would like to instantly get that code snippet and do minimum modifications and go to the next task.

How to add custom snippet code in Visual Studio Code (aka as VS Code) on Mac?

Step 1: From Visual Studio Code menu, click Code > Settings > Configure User Snippets.

visual-studio-settings-configure-snippets-png

Step 2: A menu will popup, choose New Global Snippets file..

visual-studio-code-custom-snippets-png

Step 3: Write the new custom snippet file name.

name-the-custom-snippet-code-file-png

Step 4: The Visual Studio Code will create the new file; in it an explanation with a small example. But for the sake of readers, here is a copy of it:

	// Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
	// is left empty or omitted, the snippet gets applied to all languages. 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": {
	// 	"scope": "javascript,typescript",
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }

Step 5: Make some function for the sake of testing.

function myFunc($arr){
    foreach($arr as &$name){
        $name=$name.' is awesome';
    }
    return $arr;
}

Step 6: Make a custom code snippet caller.

"awesome": {
		"scope": "php",
		"prefix": "awesome",
		"body": [
			"\\$result=myFunc(['omar','george','eleanor']);"
			"for(\\$i=0;\\$i<count(\\$result);\\$i++){"
			"	echo \\$result[\\$i].'<br>';"
			"}"
			"$0"
		],
		"description": "Quick call for myFunc"
	}

Step 7: Test the custom snippet called awesome! In any file in start typing awesome, the suggestion menu will pop. (don't mind the error while you are typing)

suggestion-code-snippet-visual-studio-code-png

Step 8: You have now created your first custom code snippet in VS Code. Congratulations!

$result=myFunc(['omar','george','eleanor']);
for($i=0;$i<count($result);$i++){
    echo $result[$i].'<br>';
}