<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Snippet - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Snippet - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 08:56:34 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/snippet/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create Your Own Custom Code Snippets Right in Your Code Editor ]]>
                </title>
                <description>
                    <![CDATA[ By Timonwa Akintokun A code Snippet is a programming term that refers to a small portion of re-usable source code, machine code, or text.  Snippets help programmers reduce the time it takes to type in repetitive information while coding. Code Snippet... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-your-own-custom-code-snippets/</link>
                <guid isPermaLink="false">66d4614ca326133d12440a8c</guid>
                
                    <category>
                        <![CDATA[ editor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Snippet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 14 Jan 2022 18:46:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/20220114_210958_0000.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Timonwa Akintokun</p>
<p>A code Snippet is a programming term that refers to a small portion of re-usable source code, machine code, or text. </p>
<p>Snippets help programmers reduce the time it takes to type in repetitive information while coding. Code Snippets are a feature on most text editors, code editors, and IDEs.</p>
<p>In this tutorial, we're going to learn how to write our own custom snippets.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>For this tutorial, I'll assume that you can write a decent amount of code in the language you want to create a code snippet for.</p>
<p>And with that confirmed...</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/gtL8MNgSES.gif" alt="lady saying lets get started" width="600" height="400" loading="lazy"></p>
<h2 id="heading-why-code-snippets-are-useful">Why Code Snippets are Useful</h2>
<p>When I first started learning how to code, the first code snippet I ever used was <strong>Ctrl + ! and enter</strong> to get an HTML5 document template. (I doubt anyone knows how to write that by heart.) It was cool and I felt like a code ninja. </p>
<p>(PS: if you don't want to read the back story and just wanna dive right into the tutorial, then <a class="post-section-overview" href="#creating-custom-code-snippets">jump right into it</a>.)</p>
<p>As I started exploring more into coding, I learned about VSCode extensions that made coding faster – code snippets in particular – and I then went on a downloading spree.</p>
<p>All was going fine and well until I started frequently using frameworks and libraries in my projects. This involved me trying to remember how to link my documents to their packages and also use personalized CSS resets and variables. </p>
<p>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.)</p>
<p>That got me thinking about having my personalized HTML and CSS templates which would have all the base code I always used in my projects.</p>
<p>At first, I just created the templates and saved them on my system so I could copy the code 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.</p>
<p>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 evening wanderings on the streets of YouTube without actively searching for it.</p>
<p>It was a lifesaver, and every once in a while I add new custom snippets to my collection. You can check out my personalized HTML and CSS templates <a target="_blank" href="https://github.com/timonwa/my-templates.git">here</a>.</p>
<p>You've likely often wished that you had a custom snippet of a particular piece of code you use all the time but didn't know how to create or find it. Well, wish no more for I'm about to show you how to easily create your own.</p>
<h2 id="heading-how-to-create-custom-code-snippets">How to Create Custom Code Snippets</h2>
<p>Creating your own custom snippet is quite easy. And with the help of another tool called <strong>Snippet Generator</strong> (which I will show you how to use shortly), it becomes even easier.</p>
<h3 id="heading-step-1-check-if-your-editor-lets-you-create-custom-snippets">Step 1: Check if your editor lets you create custom snippets</h3>
<p>You can check the docs on your code editor to find out if the feature is available and how to access it. </p>
<p>I am using VsCode for this tutorial. You can download it <a target="_blank" href="https://code.visualstudio.com/download">here</a>.</p>
<p>To access this setting, you can either click on the <strong>settings icon</strong> on the sidebar and then click on <strong>user snippets</strong> or open up the command palette using Cntr + shift + p on Windows or CMD + shift + p on Mac, typing in "snippet" and clicking on <strong>Preferences: Configure User Snippets</strong>.</p>
<p>This will give you a drop-down with different language selections to choose from.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/video1-open-code-snippet.gif" alt="video1-open-code-snippet" width="600" height="400" loading="lazy"></p>
<h3 id="heading-step-2-decide-your-snippet-scope">Step 2: Decide your Snippet Scope</h3>
<p>You can either create a global snippet that you can use across all languages or create a local snippet scoped to a particular language.</p>
<p>So from the drop-down, you can see <strong>New Global Snippet File</strong> and then a bunch of languages in alphabetical order.</p>
<p>Scroll to the language you want to write your snippet for and click on it (or select <strong>New Global Snippet File</strong> if you want to use your snippets in multiple languages).</p>
<p>If you selected a particular language, HTML for example, the file will automatically open. But if you chose Global snippet, you'll be prompted to type in the name of the snippet file before it opens.</p>
<p>For this one, I'll be using a Global Snippet.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/video2-enter-snippet-name.gif" alt="video2-enter-snippet-name" width="600" height="400" loading="lazy"></p>
<h3 id="heading-step-3-understand-the-syntax">Step 3: Understand the Syntax</h3>
<p>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.</p>
<pre><code class="lang-json">{
<span class="hljs-comment">// Code Snippet 1</span>
  <span class="hljs-attr">"Snippet name"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"language1, language2"</span> 
    <span class="hljs-string">"prefix"</span>: <span class="hljs-string">"trigger word 1"</span>,
    <span class="hljs-attr">"body"</span>: [<span class="hljs-string">"your code snippet"</span>],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"description of the code"</span>
  },
<span class="hljs-comment">// Code Snippet 2</span>
  <span class="hljs-attr">"Snippet name"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"language1, language2"</span> 
    <span class="hljs-string">"prefix"</span>: [<span class="hljs-string">"trigger word 1, trigger word 2"</span>],
    <span class="hljs-attr">"body"</span>: [<span class="hljs-string">"your code snippet"</span>],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"description of the code"</span>
  }
}
</code></pre>
<p>Let's see what's going on in this code:</p>
<h4 id="heading-snippet-name">Snippet Name</h4>
<p>The Snippet Name is the name of the snippet. It is also what will be displayed via IntelliSense if no description is provided.</p>
<h4 id="heading-scope">Scope</h4>
<p>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 can be accessed by any language. This part is included in Global Snippets only, as Local Snippets files are already locally scoped. </p>
<h4 id="heading-prefix">Prefix</h4>
<p>This describes one or more trigger words that will prompt IntelliSense to display the snippet.</p>
<h4 id="heading-body">Body</h4>
<p>This can be a string if it is one-line code or an array of strings if it is multi-line code.</p>
<h4 id="heading-description">Description</h4>
<p>This describes the snippet and what it does. If this is omitted, the name of the snippet will be used instead.</p>
<p>Snippet example 1:</p>
<pre><code class="lang-json">{
<span class="hljs-comment">// log to console</span>
  <span class="hljs-attr">"Print to console"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"log"</span>,
    <span class="hljs-attr">"body"</span>: <span class="hljs-string">"console.log();"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Log output to console"</span>
  }
}
</code></pre>
<p>From the above example, our snippet name is <strong>Print to console</strong>, and it can only be used in a <strong>JavaScript and TypeScript file</strong>. If you were to type <strong>log</strong> in a JavaScript or TypeScript file, IntelliSense would show it along with the description <strong>Log output to console</strong>. Once you select it and click enter, you'd see <strong>console.log()</strong> on the screen.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/video3-log.gif" alt="video3-log" width="600" height="400" loading="lazy"></p>
<h3 id="heading-step-4-add-tab-stops">Step 4: Add Tab Stops</h3>
<p>Tabstops allow you to move the editor cursor inside a snippet. $1, $2, ..., $n specify cursor locations it should move into sequentially when you hit the tab key. $0 represents the final position the cursor should stop.</p>
<p>Snippet example 2:</p>
<pre><code class="lang-json"><span class="hljs-comment">// named function</span>
{
  <span class="hljs-attr">"Named Function"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"nfn"</span>,
    <span class="hljs-attr">"body"</span>: [
      <span class="hljs-string">"function $1($2){"</span>,
      <span class="hljs-string">"  $0"</span>,
      <span class="hljs-string">"}"</span>
    ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>
  }
}
</code></pre>
<p>In this example, when you type <strong>nfn</strong>, our Named Function snippet shows up. Once you select it, you'll see your snippet on the screen. You'll also see that the cursor is now before the parenthesis as opposed to being at the end of the code.</p>
<p>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. </p>
<p>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.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/vide04-tabstop.gif" alt="vide04-tabstop" width="600" height="400" loading="lazy"></p>
<p>Note: When you are writing multi-line code, you cannot use a tab to indent your code in the JSON syntax. You can only use 2 spaces to indent your code, or whatever number of spacing indentation you use to write your code.</p>
<h3 id="heading-step-5-use-placeholders">Step 5: Use Placeholders</h3>
<p>These are Tab Stops with values. They help the user easily identify or understand what they are supposed to type at that particular tab stop. </p>
<p>The placeholder will be automatically highlighted so you can immediately type in what you want to replace it with.</p>
<p>Snippet example 3:</p>
<pre><code class="lang-json"><span class="hljs-comment">// named function</span>
{
  <span class="hljs-attr">"Named Function"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"nfn"</span>,
    <span class="hljs-attr">"body"</span>: [
      <span class="hljs-string">"function ${1:functionName}(${2:parameter}){"</span>,
      <span class="hljs-string">"  ${0:functionBody}"</span>,
      <span class="hljs-string">"}"</span>
    ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>
  }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/video5-placeholders.gif" alt="video5-placeholders" width="600" height="400" loading="lazy"></p>
<h3 id="heading-step-6-create-choices">Step 6: Create Choices</h3>
<p>Placeholders can have choices as values. This means that instead of typing in your value, you can choose from a dropdown selection.</p>
<p>To create one, you write the values which are separated by a comma between two pipe-characters, for example, ${1|one, two, three|}.</p>
<p>Snippet example 4:</p>
<pre><code class="lang-json"><span class="hljs-comment">// array method</span>
{
<span class="hljs-attr">"Array Method"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"arrmth"</span>,
    <span class="hljs-attr">"body"</span>: [
      <span class="hljs-string">"${1|forEach, map, filter, reduce|}((${2:item}) =&gt; {"</span>,
      <span class="hljs-string">"  $0"</span>,
      <span class="hljs-string">"})"</span>
    ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>
  }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/video6-choices.gif" alt="video6-choices" width="600" height="400" loading="lazy"></p>
<p>Here, once you type in <code>arrmth</code>, select it from IntelliSense and hit enter. The first tab stop will be a dropdown of array choices to select from. The next tab stop is the parameter and the last stop is the function code.</p>
<h2 id="heading-snippet-generators">Snippet Generators</h2>
<p>As your snippets begin to grow in lines and size, it becomes difficult to type and create them within your code editor. This is where a snippet generator comes in.</p>
<p>A snippet generator will take in your regular code and turn it into a code snippet.</p>
<p>I will be using <a target="_blank" href="https://snippet-generator.app/">Snippet Generator</a> for this tutorial. With this particular snippet generator, you can write code snippets for VsCode, Sublime Text, and Atom.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image1-snippet-generator.png" alt="image1-snippet-generator" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-the-snippet-generator">How to Use the Snippet Generator</h3>
<p>In the <strong>description</strong> input, enter the name of the code snippet which will be used as the name and description of the snippet.</p>
<p>In the <strong>tab trigger</strong> input, enter the prefix of your code snippet.</p>
<p>In the <strong>your snippet..</strong> input, enter your code in its natural form as you would without writing it as an array of strings.</p>
<p>After this, you can then add in Tabstops, Placeholders, and Choices as explained above.</p>
<p>Snippet example 5:</p>
<pre><code class="lang-js"><span class="hljs-comment">//named function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">$</span></span>{<span class="hljs-number">1</span>:functionName}(${<span class="hljs-number">2</span>: parameter}) {
  ${<span class="hljs-number">0</span>:functionBody}
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image2-arrow-function.png" alt="image2-arrow-function" width="600" height="400" loading="lazy"></p>
<p>Snippet example 6:</p>
<pre><code class="lang-js"><span class="hljs-comment">//array method</span>
${<span class="hljs-number">1</span>|forEach, map, filter, reduce,|}(<span class="hljs-function">(<span class="hljs-params">${<span class="hljs-number">2</span>:item}</span>) =&gt;</span> {
 $<span class="hljs-number">0</span>
)}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image3-array-method.png" alt="image3-array-method" width="600" height="400" loading="lazy"></p>
<h2 id="heading-final-snippet-code">Final Snippet Code</h2>
<pre><code class="lang-json">{
  <span class="hljs-comment">// log to console</span>
  <span class="hljs-attr">"Print to console"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"log"</span>,
    <span class="hljs-attr">"body"</span>: <span class="hljs-string">"console.log();"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Log output to console"</span>
  },
  <span class="hljs-comment">// named function</span>
  <span class="hljs-attr">"Named Function"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"nfn"</span>,
    <span class="hljs-attr">"body"</span>: [
      <span class="hljs-string">"function ${1:functionName}(${2:parameter}){"</span>,
      <span class="hljs-string">"  ${0:functionBody}"</span>,
      <span class="hljs-string">"}"</span>
    ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>
  },
  <span class="hljs-comment">// array method</span>
  <span class="hljs-attr">"Array Method"</span>: {
    <span class="hljs-attr">"scope"</span>: <span class="hljs-string">"javascript, typescript"</span>,
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"arrmth"</span>,
    <span class="hljs-attr">"body"</span>: [
      <span class="hljs-string">"${1|forEach, map, filter, reduce|}((${2:item}) =&gt; {"</span>,
      <span class="hljs-string">"  $0"</span>,
      <span class="hljs-string">"})"</span>
    ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>
  }
}
</code></pre>
<p>And that's it. Easy peasy lemon squeezy. </p>
<h2 id="heading-recap">Recap</h2>
<p>Let's do a recap. We have learned that:</p>
<ul>
<li>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.</li>
<li>a code snippet file can contain an unlimited number of snippets.</li>
<li>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.</li>
<li>code snippets are written in JSON syntax.</li>
<li>you can add tabstops, placeholders, and choices to your code snippets.</li>
<li>you can also use a snippet generator to generate your snippets.</li>
</ul>
<p>Thank you for reading my article. You can connect with me on <a target="_blank" href="https://twitter.com/timonwa_">Twitter</a>, <a target="_blank" href="https://linkedIn.com/in/pelumi-akintokun">LinkedIn</a> or <a target="_blank" href="https://blog.timonwa.com">my Blog</a>. </p>
<p>I would love to know if you'll be creating your own custom snippets and what they might be. And do feel free to share this article with others who might find this useful too. Byeee!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/HoDL1vbXj.gif" alt="Mr Beans waving goodbye" width="600" height="400" loading="lazy"></p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><a target="_blank" href="https://youtu.be/JIqk9UxgKEc">Brad's Custom Snippets video</a></li>
<li><a target="_blank" href="https://code.visualstudio.com/docs/editor/userdefinedsnippets">VsCode Snippet Documentation</a></li>
<li><a target="_blank" href="https://snippet-generator.app/">Snippet Generator</a></li>
<li><a target="_blank" href="https://github.com/timonwa/my-templates.git">View my Custom HTML and CSS Templates</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Automatically Generate C# Code Snippets in Visual Studio ]]>
                </title>
                <description>
                    <![CDATA[ By Gilad Bar Ilan When you use code snippets in Visual Studio, it can make your coding process a lot easier and faster. But what are code snippets? And how can you use them? In this article, we'll look at how you can create code snippets in C#. Just ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-automatically-generate-code-snippets-visual-studio/</link>
                <guid isPermaLink="false">66d45ede4a7504b7409c33d9</guid>
                
                    <category>
                        <![CDATA[ automation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Snippet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ visual studio ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 09 Jul 2021 18:28:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/gbi.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Gilad Bar Ilan</p>
<p>When you use code snippets in Visual Studio, it can make your coding process a lot easier and faster. But what are code snippets? And how can you use them?</p>
<p>In this article, we'll look at how you can create code snippets in C#. Just keep in mind that snippets are available in other languages in Visual Studio as well.</p>
<p>If you already know what code snippets are, then you can skip down to the <strong>“How to Auto-Generate Code Snippets”</strong> section.</p>
<h2 id="heading-what-are-code-snippets">What are Code Snippets?</h2>
<p>If you regularly work with Visual Studio, you might already know what code snippets are. Code snippets represent a shortcut for a larger piece of code. </p>
<p>As an example, open a C# project in Visual Studio and write “for” and then press the tab key twice. As you can see, instead of writing the full for loop we created a for loop just by writing “for”.</p>
<p>There are a lot more pre-defined code snippets you can use. For example, if you write “cw” and then press the tab key twice you’ll see an auto-completion that writes this:</p>
<pre><code class="lang-cs">Console.WriteLine();
</code></pre>
<p>You can check out the full list of the pre-defined code snippets in the docs here:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://docs.microsoft.com/en-us/visualstudio/ide/visual-csharp-code-snippets?view=vs-2019">https://docs.microsoft.com/en-us/visualstudio/ide/visual-csharp-code-snippets?view=vs-2019</a></div>
<h2 id="heading-how-to-create-custom-code-snippets">How to Create Custom Code Snippets</h2>
<p>Now that you understand what a code snippet is, we can now go over how to create one.</p>
<p>To create your first code snippet, create a “.snippet” file. I called my file “MySnippet.snippet”, but you can call it whatever you want.</p>
<p>After the creation of the code snippet file, open the file in Visual Studio and add the following piece of code into the file.</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">CodeSnippets</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">""</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">CodeSnippet</span> <span class="hljs-attr">Format</span>=<span class="hljs-string">"1.0.0"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Header</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Title</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Title</span>&gt;</span>    
            <span class="hljs-tag">&lt;<span class="hljs-name">Author</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Author</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Description</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Description</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Shortcut</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">Shortcut</span>&gt;</span> 
        <span class="hljs-tag">&lt;/<span class="hljs-name">Header</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Snippet</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Code</span> <span class="hljs-attr">Language</span>=<span class="hljs-string">""</span>&gt;</span>
                &lt;![CDATA[]]&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">Code</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Snippet</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">CodeSnippet</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">CodeSnippets</span>&gt;</span>
</code></pre>
<p>In the example above, we use the basic structure of a code snippet file. Now, we’ll edit it and create a code snippet that will convert “cr” to <code>Console.ReadLine()</code>.</p>
<h4 id="heading-title-tag">Title Tag</h4>
<p>The title tag contains the title of the snippet (not the shortcut name). In this example we’ll call the title “ReadLineSnippet”.</p>
<h4 id="heading-author-tag">Author Tag</h4>
<p>In the Author tag, you can insert your name/company to get credit for the snippet creation.</p>
<h4 id="heading-description-tag">Description Tag</h4>
<p>In the description tag, insert a short description of what the snippet does exactly.</p>
<h4 id="heading-shortcut-tag">Shortcut Tag</h4>
<p>The name in the shortcut tag is the name that calls the larger piece of code. For example:</p>
<pre><code class="lang-cs">cw -&gt; Console.WriteLine();
</code></pre>
<p>The “cw” is specified as the name in the shortcut tag.</p>
<h4 id="heading-language">Language</h4>
<p>Because we're working with C# we should specify that in the language:</p>
<pre><code class="lang-cs">&lt;Code Language = <span class="hljs-string">"CSharp"</span>&gt;
</code></pre>
<h4 id="heading-">&lt;![CDATA[]]&gt;</h4>
<p>The &lt;![CDATA[]]&gt; holds the value of our snippet. In our example, inside the squared brackets we’ll insert <code>Console.ReadLine()</code> like this:</p>
<pre><code class="lang-cs">&lt;![CDATA[Console.ReadLine();]]&gt;
</code></pre>
<h3 id="heading-additional-code-snippet-options">Additional Code Snippet Options</h3>
<h4 id="heading-defining-variables">Defining Variables:</h4>
<p>We can also define variables and give them a default value. By defining a variable we can use it multiple times in the snippet, and we give the user the option to change all the occurrences of the default value at once.</p>
<p>For example, if our snippet creates the following code:</p>
<pre><code class="lang-cs">arr -&gt; 
Object[] arr = <span class="hljs-keyword">new</span> Object[<span class="hljs-number">100</span>];
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; arr.Length; i++)
{   
    arr[i] = <span class="hljs-keyword">default</span>(Object);
}
</code></pre>
<p>And we define “Object” as a variable, we can replace all its occurrences. All we need to do is to write in the first occurrence a different name – for example “int” – and then tab twice and it will turn all occurrences of “Object” to “int”.</p>
<p>If we had defined <code>arr</code> as a variable too, we could move from one variable to another by pressing tab (when you create the snippet the first variable will be selected in red/cyan color – you can move to the other by pressing tab).</p>
<h3 id="heading-how-to-define-a-variable">How to define a variable</h3>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">CodeSnippets</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">""</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">CodeSnippet</span> <span class="hljs-attr">Format</span>=<span class="hljs-string">"1.0.0"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Header</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Title</span>&gt;</span>init array.<span class="hljs-tag">&lt;/<span class="hljs-name">Title</span>&gt;</span>    
            <span class="hljs-tag">&lt;<span class="hljs-name">Author</span>&gt;</span>Gilad Bar-Ilan<span class="hljs-tag">&lt;/<span class="hljs-name">Author</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Description</span>&gt;</span>creates and initializes an array.<span class="hljs-tag">&lt;/<span class="hljs-name">Description</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Shortcut</span>&gt;</span>myArr<span class="hljs-tag">&lt;/<span class="hljs-name">Shortcut</span>&gt;</span> 
        <span class="hljs-tag">&lt;/<span class="hljs-name">Header</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Snippet</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Code</span> <span class="hljs-attr">Language</span>=<span class="hljs-string">"CSharp"</span>&gt;</span>
                &lt;![CDATA[$typeName$[] $varName$ = new $typeName$[100];
                for(int $i$ = 0; $i$ &lt; $varName$.Length; $i$++)
                {
                  $varName$[$i$] = default($typeName$);
                }]]&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">Code</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Declarations</span>&gt;</span>      
                <span class="hljs-tag">&lt;<span class="hljs-name">Literal</span>&gt;</span>      
                    <span class="hljs-tag">&lt;<span class="hljs-name">ID</span>&gt;</span>varName<span class="hljs-tag">&lt;/<span class="hljs-name">ID</span>&gt;</span>      
                    <span class="hljs-tag">&lt;<span class="hljs-name">ToolTip</span>&gt;</span>variable name.<span class="hljs-tag">&lt;/<span class="hljs-name">ToolTip</span>&gt;</span>         
                    <span class="hljs-tag">&lt;<span class="hljs-name">Default</span>&gt;</span>arr<span class="hljs-tag">&lt;/<span class="hljs-name">Default</span>&gt;</span>        
                <span class="hljs-tag">&lt;/<span class="hljs-name">Literal</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">Literal</span>&gt;</span>      
                    <span class="hljs-tag">&lt;<span class="hljs-name">ID</span>&gt;</span>typeName<span class="hljs-tag">&lt;/<span class="hljs-name">ID</span>&gt;</span>      
                    <span class="hljs-tag">&lt;<span class="hljs-name">ToolTip</span>&gt;</span>type name.<span class="hljs-tag">&lt;/<span class="hljs-name">ToolTip</span>&gt;</span>         
                    <span class="hljs-tag">&lt;<span class="hljs-name">Default</span>&gt;</span>Object<span class="hljs-tag">&lt;/<span class="hljs-name">Default</span>&gt;</span>        
                <span class="hljs-tag">&lt;/<span class="hljs-name">Literal</span>&gt;</span>
                 <span class="hljs-tag">&lt;<span class="hljs-name">Literal</span>&gt;</span>      
                    <span class="hljs-tag">&lt;<span class="hljs-name">ID</span>&gt;</span>i<span class="hljs-tag">&lt;/<span class="hljs-name">ID</span>&gt;</span>      
                    <span class="hljs-tag">&lt;<span class="hljs-name">ToolTip</span>&gt;</span>iterator name.<span class="hljs-tag">&lt;/<span class="hljs-name">ToolTip</span>&gt;</span>         
                    <span class="hljs-tag">&lt;<span class="hljs-name">Default</span>&gt;</span>i<span class="hljs-tag">&lt;/<span class="hljs-name">Default</span>&gt;</span>        
                <span class="hljs-tag">&lt;/<span class="hljs-name">Literal</span>&gt;</span>
             <span class="hljs-tag">&lt;/<span class="hljs-name">Declarations</span>&gt;</span>     
        <span class="hljs-tag">&lt;/<span class="hljs-name">Snippet</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">CodeSnippet</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">CodeSnippets</span>&gt;</span>
</code></pre>
<p>As you can see in the example above, each variable we use needs to be inside the <code>&lt;Literal&gt;</code> tag under the <code>&lt;Declarations&gt;</code> tag.</p>
<ul>
<li><code>&lt;ID&gt;</code>  — How we call the variable in the <code>&lt;![CDATA[]]&gt;</code></li>
<li><code>&lt;ToolTip&gt;</code> — A short description of the variable.</li>
<li><code>&lt;Default&gt;</code>  — The default value of the variable.</li>
</ul>
<p><strong>NOTE</strong> — When you use a variable in the <code>&lt;![CDATA[]]&gt;</code> you should write it in the following structure: <code>$&lt;here you put the variable name&gt;$</code>.</p>
<h3 id="heading-how-to-add-the-code-snippet-to-your-project">How to add the code snippet to your project</h3>
<p>After we’ve created our code snippet file, we want to use it in our projects. To do so we should put the file inside the custom snippet folder of Visual Studio. This will automatically add the code snippet to our project.</p>
<p>If you want to find the folder path:</p>
<ul>
<li>Open a C# project.</li>
<li>Go to Tools -&gt; Code Snippets Manager</li>
<li>Copy the path you see in the head of the box opened where it says “Location”.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/image-200.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>After you’ve got the path, simply add the file into the path.</p>
<p><strong>NOTE —</strong> Your “My Code Snippets” folder may be located in a different place on your computer, so don't rely on the path in the picture.</p>
<h2 id="heading-how-to-auto-generate-code-snippets">How to Auto-Generate Code Snippets</h2>
<p>Now we can now go over what it means to auto-generate code snippets.</p>
<p>We know that adding “.snippet” files into the “My Code Snippets” folder adds the snippets automatically into our project. So now we can use that behaviour to create code that will automatically create snippet files and add them to our project.</p>
<h3 id="heading-what-kind-of-code-snippets-do-we-want">What kind of code snippets do we want?</h3>
<p>In this project, we are going to create a snippet for objects with a default constructor where the shortcut name will be the type name. For example:</p>
<pre><code class="lang-cs">Random + tab twice -&gt; Random random = <span class="hljs-keyword">new</span> Random();
</code></pre>
<p>The idea of the project is to read the namespaces we use in our project and make a custom snippet for each object that follows the conditions. </p>
<p>We want to add the snippets for the types of every namespace we use. This means that even if we specify a namespace in the ‘using’ but don’t use any of its objects, we’ll still include a code snippet for its members (those who follow the condition).</p>
<p>In addition to the namespaces, we are also going to create a snippet for our defined types.</p>
<h4 id="heading-things-we-need-to-take-care-of">Things we need to take care of:</h4>
<ul>
<li>Remove the no longer needed types’ code snippets (if we removed types we’ve created or removed namespaces from the project).</li>
<li>Update the code snippets every time the user runs the program (we don’t update in the background).</li>
<li>Add new snippets for new namespaces we use / types we create.</li>
<li>Make a structure for the types’ code snippet.</li>
</ul>
<h3 id="heading-how-to-get-all-of-our-defined-objects">How to get all of our defined objects</h3>
<p>If we want to get the full list of the user-defined types there are two ways to do so.</p>
<p>The first way – which is not as good as the second – is by using Regular Expressions. By using regular expressions, we can go over each file in our project and match for a default constructor in a class/declaration of a struct (because structs always have a default constructor).</p>
<h4 id="heading-problems-with-the-regex-technique">Problems with the Regex technique</h4>
<p>If the user separates the files we can check before using the regex if the file was modified. By doing that we can avoid repeating files that haven’t been modified.</p>
<p>But minor changes in the file will cause us to read the file again even if there is no difference in the objects. It'll also result in unorganized files that have a lot of code in a single file which can cause us to read the file over and over. (If the whole code is in a single file or just a few we won’t be able to avoid reading unchanged parts from the code.)</p>
<h4 id="heading-the-second-technique-reflection">The Second Technique — Reflection</h4>
<p>Instead of using Regex we can use reflection and get the classes we created by reading the metadata instead of reading each file as a text.</p>
<pre><code class="lang-cs">
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> Returns a list of all the types we created.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;returns&gt;</span><span class="hljs-doctag">&lt;/returns&gt;</span></span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List&lt;Type&gt; <span class="hljs-title">GetCustomTypes</span>(<span class="hljs-params"></span>)</span>
        {
            StackTrace myStackTrace = <span class="hljs-keyword">new</span> StackTrace();

            <span class="hljs-comment">//contains the name of the namesapce of the project</span>
            <span class="hljs-comment">//using stackframe we get's the first calling method (main - the bottom of the stack) and then we check the namespace of the type where the method is located.</span>
            <span class="hljs-comment">//in our case main is located under 'Program' then we check what is the namespace of Program.</span>
            <span class="hljs-keyword">string</span> namespace_ = myStackTrace.GetFrame(myStackTrace.FrameCount - <span class="hljs-number">1</span>).GetMethod().DeclaringType.Namespace;

            Assembly assembly = Assembly.GetExecutingAssembly();

            <span class="hljs-comment">//holds all the custom types.</span>
            <span class="hljs-comment">//assembly.GetTypes() =&gt; returns all the types.</span>
            <span class="hljs-comment">//then we remove all the types which is not related to our namesapce.</span>
            <span class="hljs-comment">//then we remove all the compiler created types.</span>
            <span class="hljs-comment">//then we remove all the types which doesn't have a default constructor.</span>
            <span class="hljs-keyword">var</span> types = assembly.GetTypes().Where(x =&gt; x.Namespace == namespace_).Where(x =&gt; !x.Name.Contains(<span class="hljs-string">"&lt;&gt;c"</span>))
                        .Where(x =&gt; x.GetConstructors().Any(x =&gt; x.GetParameters().Length == <span class="hljs-number">0</span>));
            <span class="hljs-keyword">return</span> types.ToList();
        }
</code></pre>
<h3 id="heading-how-to-get-the-libraries-objects">How to get the libraries’ objects</h3>
<p>We'll run into a lot of problems in this part of the project. Let's look at what might go wrong.</p>
<h4 id="heading-problem-1">Problem 1</h4>
<p>If we read the assemblies we use in our project using Reflection we won’t have the option to get the types from libraries we defined in the ‘using’ but that we don’t actually use. For example:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> System.IO;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"></span>)</span>
{  
    <span class="hljs-keyword">int</span>[] arr = Enumerable.Range(<span class="hljs-number">0</span>,<span class="hljs-number">100</span>).ToArray(); <span class="hljs-comment">//Linq's functionallity</span>
}
</code></pre>
<p>In the example above ,we only use Linq functionality, which means that if we are going to read the used assemblies in the project we won’t see System.IO even though we want it to be shown.</p>
<h4 id="heading-problem-2">Problem 2</h4>
<p>Another possible problem happens even when we do use the library. This is because a namespace can have multiple assemblies and due to efficiency the compiler won’t call all the assemblies when it doesn’t need to. So even if we use the library it doesn't mean we’ll have all the assemblies.</p>
<h4 id="heading-how-can-we-solve-the-problem">How can we solve the problem?</h4>
<p>This problem is complicated because we cannot change the way the compiler works. So if we want to solve the problem we’ll have to be creative.</p>
<p>Our solution won't be very efficient, but we don’t have a lot of options for how to solve this.</p>
<h4 id="heading-we-can-use-an-algorithm">We can use an algorithm</h4>
<ul>
<li>We get all the namespaces we use in all of our “.cs” files in the project.</li>
<li>Then we iterate over all the System DLL files and we check if the types there relate to one of the namespaces we use in the project.</li>
<li>We add to this list also our defined types, as well as references we added to the project, if the reference is defined in the ‘using’ we add his types even if we don‘t use his types in the program itself.</li>
<li>After we do that we check if the type has a default constructor.</li>
</ul>
<p>The code for solving the problem is quite complicated, so let’s go over it.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Reflection;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> System.IO;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Diagnostics;
<span class="hljs-keyword">using</span> System.Text.RegularExpressions;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Reader</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TypeReader</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List&lt;Type&gt; <span class="hljs-title">GetAllTypes</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> GetSystemLibrary Files</span>
            <span class="hljs-keyword">string</span> systemDllPath = <span class="hljs-keyword">typeof</span>(<span class="hljs-keyword">string</span>).Assembly.Location; <span class="hljs-comment">//gets the dll of the string type.</span>
            systemDllPath = Path.GetDirectoryName(systemDllPath);
            <span class="hljs-keyword">string</span>[] systemLibraries = Directory.GetFiles(systemDllPath); <span class="hljs-comment">//the list of the system libraies dlls.  </span>
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> Namespaces in project files.</span>
            <span class="hljs-keyword">string</span>[] namespaces_ = Directory.GetFiles(GetSourceCodePath())
                                      .Where(x =&gt; x.EndsWith(<span class="hljs-string">".cs"</span>)).ToArray();
            namespaces_ = GetNamespaces(namespaces_).ToArray();<span class="hljs-comment">//we remove the semi colon</span>
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> Check the system libraries.</span>
            List&lt;Type&gt; types = systemLibraries.Where(x =&gt; x.EndsWith(<span class="hljs-string">".dll"</span>)).Select(x =&gt;
            {
                Assembly asm = <span class="hljs-literal">null</span>;
                <span class="hljs-keyword">try</span>
                {
                    asm = Assembly.LoadFile(x);

                }
                <span class="hljs-keyword">catch</span>
                {
                    asm = <span class="hljs-literal">null</span>;
                }

                <span class="hljs-keyword">return</span> asm;
            }).SelectMany(x =&gt; x != <span class="hljs-literal">null</span> ? x.GetTypes() : <span class="hljs-keyword">new</span> Type[] { })
                        .Where(x =&gt; x != <span class="hljs-literal">null</span> &amp;&amp; !x.Name.Contains(<span class="hljs-string">"&lt;&gt;c"</span>)).Where(x =&gt; namespaces_.Contains(x.Namespace))
                        .Where(x =&gt; x.IsPublic &amp;&amp; (x.IsClass || x.IsValueType)).ToList();
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> add assemblies we use in our program.</span>
            types.AddRange(AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(x =&gt; x.GetTypes().Where(x =&gt; !x.Name.Contains(<span class="hljs-string">"&lt;&gt;c"</span>)).Where(x =&gt; namespaces_.Contains(x.Namespace)))
                           .Where(x =&gt; x.IsPublic &amp;&amp; (x.IsClass || x.IsValueType)));
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> add custom types we created.</span>
            types.AddRange(GetCustomTypes()); <span class="hljs-comment">//adds our custom created snippets</span>
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> add types belongs to refrences we didn't use in our project.</span>
            types.AddRange(GetUnUsedRefrenecedTypes(namespaces_)); <span class="hljs-comment">//adds the refrenced libraries we specify but don't use.</span>
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> filter types.</span>
            types = types.Where(x =&gt; x.IsValueType || x.GetConstructors().Any(x =&gt; x.GetParameters().Length == <span class="hljs-number">0</span>)).ToList();
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> remove duplicated type names.</span>
            types = types.GroupBy(x =&gt; x.FullName).Select(x =&gt; x.First()).ToList();
            <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>

            <span class="hljs-keyword">return</span> types;
        }

        <span class="hljs-comment">//Returns the assembly of the main function.</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetMainAssemblyLocation</span>(<span class="hljs-params"></span>)</span>
        {
            StackTrace main = <span class="hljs-keyword">new</span> StackTrace();
            <span class="hljs-keyword">string</span> path = main.GetFrame(main.FrameCount - <span class="hljs-number">1</span>).GetMethod().DeclaringType.Assembly.Location;
            <span class="hljs-keyword">return</span> Path.GetDirectoryName(path);
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetSourceCodePath</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">string</span> projectPath = GetMainAssemblyLocation();

            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">while</span> (!Directory.GetFiles(projectPath).Any(x =&gt; x.EndsWith(<span class="hljs-string">".cs"</span>)))
                {
                    projectPath = projectPath.Remove(projectPath.LastIndexOf(<span class="hljs-string">"\\"</span>));
                }
            }
            <span class="hljs-keyword">catch</span>
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> SourceCodeNotFoundException();
            }

            <span class="hljs-keyword">return</span> projectPath;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">GetNamespaces</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] files</span>)</span>
        {
            List&lt;<span class="hljs-keyword">string</span>&gt; namespaces = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;();

            <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">string</span> file_ <span class="hljs-keyword">in</span> files)
            {
                StreamReader fileStream = <span class="hljs-keyword">new</span> StreamReader(file_);
                Regex matchUsing = <span class="hljs-keyword">new</span> Regex(<span class="hljs-string">@"using([ ]|\t|\n)+\S+;"</span>);
                <span class="hljs-keyword">string</span>[] fileNamespaces = matchUsing.Matches(fileStream.ReadToEnd()).Select(x =&gt; x.Value)
                                          .Select(x =&gt; x.Remove(x.IndexOf(<span class="hljs-string">"using"</span>), <span class="hljs-string">"using"</span>.Length).Trim()).ToArray();
                namespaces.AddRange(fileNamespaces);

                fileStream.Close();
            }

            <span class="hljs-keyword">return</span> namespaces.Select(x =&gt; x.Remove(x.Length - <span class="hljs-number">1</span>, <span class="hljs-number">1</span>)).Distinct().ToList();
        }

        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> This is used in case we have a custom refrenced library (could be a dll we created)</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> and we specify that in the using, however, we don't use his assemblies.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;returns&gt;</span><span class="hljs-doctag">&lt;/returns&gt;</span></span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List&lt;Type&gt; <span class="hljs-title">GetUnUsedRefrenecedTypes</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] namespaces_</span>)</span>
        {
            <span class="hljs-keyword">string</span> sourceCode = GetMainAssemblyLocation();
            List&lt;Type&gt; otherTypes = <span class="hljs-keyword">new</span> List&lt;Type&gt;();

            <span class="hljs-keyword">string</span>[] fileNames = Directory.GetFiles(Path.GetDirectoryName(sourceCode));

            <span class="hljs-keyword">if</span> (fileNames.Any(x =&gt; x.EndsWith(<span class="hljs-string">".dll"</span>)))
            {
                fileNames = fileNames.Where(x =&gt; x.EndsWith(<span class="hljs-string">".dll"</span>)).ToArray();

                <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> file <span class="hljs-keyword">in</span> fileNames)
                {
                    Assembly asm;

                    <span class="hljs-keyword">try</span>
                    {
                        asm = Assembly.LoadFile(file);
                    }
                    <span class="hljs-keyword">catch</span>
                    {
                        <span class="hljs-keyword">continue</span>;
                    }

                    otherTypes.AddRange(asm.GetTypes().Where(x =&gt; !x.Name.Contains(<span class="hljs-string">"&lt;&gt;c"</span>))
                                        .Where(x =&gt; x.IsPublic &amp;&amp; (x.IsClass || x.IsValueType))
                                        .Where(x =&gt; namespaces_.Contains(x.Namespace)).GroupBy(x =&gt; x.Name)
                                        .Select(x =&gt; x.First()));
                }
            }

            <span class="hljs-keyword">return</span> otherTypes;
        }

        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> Returns a list of all the types we created.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;returns&gt;</span><span class="hljs-doctag">&lt;/returns&gt;</span></span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List&lt;Type&gt; <span class="hljs-title">GetCustomTypes</span>(<span class="hljs-params"></span>)</span>
        {
            StackTrace myStackTrace = <span class="hljs-keyword">new</span> StackTrace();
            Type mainType = myStackTrace.GetFrame(myStackTrace.FrameCount - <span class="hljs-number">1</span>).GetMethod().DeclaringType;

            <span class="hljs-comment">//contains the name of the namesapce of the project</span>
            <span class="hljs-comment">//using stackframe we get's the first calling method (main - the bottom of the stack) and then we check the namespace of the type where the method is located.</span>
            <span class="hljs-comment">//in our case main is located under 'Program' then we check what is the namespace of Program.</span>
            <span class="hljs-keyword">string</span> namespace_ = mainType.Namespace;
            Assembly assembly = mainType.Assembly;

            <span class="hljs-comment">//holds all the custom types.</span>
            <span class="hljs-comment">//assembly.GetTypes() =&gt; returns all the types.</span>
            <span class="hljs-comment">//then we remove all the types which is not related to our namesapce.</span>
            <span class="hljs-comment">//then we remove all the compiler created types.</span>
            <span class="hljs-comment">//then we remove all the types which doesn't have a default constructor.</span>
            <span class="hljs-keyword">var</span> types = assembly.GetTypes().Where(x =&gt; x.Namespace == namespace_).Where(x =&gt; !x.Name.Contains(<span class="hljs-string">"&lt;&gt;c"</span>)); ;
            <span class="hljs-keyword">return</span> types.ToList();
        }
    }

    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SourceCodeNotFoundException</span> : <span class="hljs-title">Exception</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> Message =&gt; <span class="hljs-string">"Could not load the '.cs' files, please make sure\n"</span> +
                                    <span class="hljs-string">"your files located in the default place / you have a valid project type."</span>;
    }
}
</code></pre>
<h4 id="heading-important-note"><strong>Important Note:</strong></h4>
<pre><code class="lang-cs"><span class="hljs-comment">//If I mention in the explanation the words "main function" I mean:</span>

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"></span>)</span>
{   
    TypeReader.GetAllTypes();
}
<span class="hljs-comment">//Which means that the main function does not located in the </span>
<span class="hljs-comment">//TypeReader class it's the main function who calls the class.</span>
</code></pre>
<h3 id="heading-getsystemlibrary-files-region">GetSystemLibrary Files Region</h3>
<p>In these lines, we get all the library files of “System”.</p>
<ul>
<li>We check where the assembly of one of the system DLLs is located (in our case where the assembly of ‘string’ is).</li>
<li>Then we remove the file name from the path so we’ll have only the directory.</li>
<li>Then we take only the library files from the directory (“.dll”).</li>
</ul>
<p>We do so because all of the System libraries files are located in the same directory.</p>
<h3 id="heading-namespaces-in-the-project-files-region">Namespaces in the project files Region</h3>
<p>In these lines, we get all the namespaces we use in all of our project files.</p>
<h4 id="heading-custom-methods-we-use-in-these-lines">Custom methods we use in these lines</h4>
<p><strong>GetSourceCodePath —</strong> This function returns the path of our source code. First, we get the path of the main function’s dll. By assuming that the user works with the default way of sorting directories in Visual Studio, we ‘remove’ directories from our path until we reach a directory with .cs files.</p>
<p><strong>GetMainAssemblyLocation</strong> — We use StackTrace to get the assembly location of the main function. An example for 'Removing' is<br>C:\Users\File1\File2 -&gt; C:\Users\File1</p>
<p>If we can’t find any directory we throw <strong>SourceCodeNotFoundException</strong>.</p>
<p><strong>GetNamespaces —</strong> The method returns all the namespaces within the files we entered. It iterates over each file and reads all the namespaces we are using in each one of them using Regex.</p>
<p>For each namespace we’ll get <code>using &lt;Something&gt;;</code> then we’ll remove all of the extra characters and we only keep the <code>&lt;Something&gt;</code>.</p>
<h4 id="heading-in-getalltypes">In GetAllTypes</h4>
<ul>
<li>We read all the files from our source code directory</li>
<li>We only keep the files with an extension of “.cs”</li>
<li>We get the namespaces of the files.</li>
</ul>
<h3 id="heading-check-the-system-libraries-region">Check the system libraries Region</h3>
<p>In these lines, we check the system libraries. These lines fix both problems we mentioned before.</p>
<ul>
<li>We get all the files in the system DLL's directory and we only keep those that represent a dll (with an extension of “.dll”).</li>
<li>We try to load each one of these files.</li>
<li>If we can load the file then we get the types in the assembly.</li>
<li>We remove all the compiler created types “&lt;&gt;c”.</li>
<li>We only keep the types related to one of the namespaces in our project.</li>
<li>Then we only keep the public types and those that are class or struct.</li>
</ul>
<h4 id="heading-why-do-we-do-it-like-this">Why do we do it like this?</h4>
<p>The problems we mentioned before were caused because we tried to check what the program <strong>actually</strong> uses in runtime. But the compiler makes optimizations, and that’s why we cannot really reach the cases mentioned in the problems.</p>
<p>So for solving this problem, we need to get creative and check the namespaces we use in our project files. Then we load the assemblies, and at the end check that each type if its namespace is one of the namespaces we use in our project.</p>
<h3 id="heading-add-assemblies-we-use-in-our-program-region">add assemblies we use in our program Region</h3>
<p>In these lines, we add the assemblies we use in our program.</p>
<p>For each one of the assemblies, we make the same check for the type it contains.</p>
<ul>
<li>If the type is public</li>
<li>If it’s struct or class</li>
<li>If it’s not a compiler-created type.</li>
<li>If it’s related to one of the namespaces we use in our project.</li>
</ul>
<h3 id="heading-add-custom-types-we-created-region">add custom types we created Region</h3>
<p>In this line, we add all of the custom types we’ve created.</p>
<p><strong>GetCustomTypes —</strong> The function uses StackTrace for getting the namespace and the assembly of the main function.</p>
<p>After we have the assembly we get the types that related to the main’s namespace.</p>
<h3 id="heading-add-types-belongs-to-references-we-didnt-use-in-our-program-region">add types belongs to references we didn't use in our program Region</h3>
<p>In this line, we add the types that belong to references we didn’t use in the program and that were specified in the ‘using’ (just like we did for the system types, but this time we do that for the references we added manually, not ‘System’).</p>
<p><strong>GetUnUsedReferencedTypes</strong> </p>
<ul>
<li>We go over the source code directory (the manually added references located there).</li>
<li>We try to load the ‘.dll’ files and add all the types that pass the conditions we did in previous checks in main.</li>
</ul>
<h3 id="heading-filter-types-region">filter types Region</h3>
<p>In this line, we only keep value types and classes that have a default constructor (if they are value types they have a default constructor for sure).</p>
<h3 id="heading-remove-duplicated-type-names-region">remove duplicated type names Region</h3>
<p>We remove duplicated types by name.</p>
<h2 id="heading-how-to-build-the-snippets">How to Build the Snippets</h2>
<p>We've gotten through the hard part, so now it’s time to build the snippets!</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.IO;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> Reader;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">SnippetGenerator2</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CodeSnippetGenerator</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> SnippetLocation;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CodeSnippetGenerator</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> snippetLocation</span>)</span>
        {
            <span class="hljs-keyword">this</span>.SnippetLocation = snippetLocation.EndsWith(<span class="hljs-string">"\\"</span>) ? snippetLocation : snippetLocation + <span class="hljs-string">"\\"</span>;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">UpdateSnippets</span>(<span class="hljs-params"></span>)</span>
        {
            List&lt;Type&gt; allTypes = TypeReader.GetAllTypes();
            Func&lt;Type, <span class="hljs-keyword">string</span>&gt; makeFileName = x =&gt; SnippetLocation + x.Name + <span class="hljs-string">"-"</span> + x.Namespace + <span class="hljs-string">".snippet"</span>;

            DirectoryInfo myCodeSnippets = <span class="hljs-keyword">new</span> DirectoryInfo(SnippetLocation);
            <span class="hljs-keyword">string</span>[] snippetFileNames = allTypes.Select(x =&gt; makeFileName(x)).ToArray();
            <span class="hljs-keyword">string</span>[] previous = myCodeSnippets.GetFiles().Where(x =&gt; x.Name.EndsWith(<span class="hljs-string">".snippet"</span>)).Select(x =&gt; x.Name).ToArray();

            <span class="hljs-comment">//we only keep the files that no longer exsisted.</span>
            previous = previous.Where(x =&gt; !snippetFileNames.Contains(x)).ToArray();
            previous.ToList().ForEach(x =&gt;
            {
                <span class="hljs-keyword">try</span>
                {
                    File.Delete(SnippetLocation + x);
                }
                <span class="hljs-keyword">catch</span> { }
            });<span class="hljs-comment">//we remove the files we don't need.</span>

            allTypes.ForEach(x =&gt; 
            {
                <span class="hljs-keyword">if</span> (!Directory.GetFiles(SnippetLocation).Contains(makeFileName(x)))
                    CreateSnippet(x);
            }
            ); <span class="hljs-comment">//we create snippets for the types.</span>
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">RemoveAllCodeSnippets</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">string</span>[] files = Directory.GetFiles(SnippetLocation).ToArray();
            List&lt;<span class="hljs-keyword">string</span>&gt; notDeleted = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;();


            files.ToList().ForEach(x =&gt;
            {
                StreamReader snippetFile = <span class="hljs-keyword">new</span> StreamReader(x);

                <span class="hljs-keyword">if</span> (snippetFile.ReadToEnd().Contains(<span class="hljs-string">"&lt;Author&gt;AUTO-GENERATOR&lt;/Author&gt;"</span>))
                {
                    snippetFile.Close();

                    <span class="hljs-keyword">try</span>
                    {
                        File.Delete(x);
                    }
                    <span class="hljs-keyword">catch</span>
                    {
                        notDeleted.Add(x);
                    }
                }
            });

            <span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;
            <span class="hljs-keyword">while</span>(i &lt; notDeleted.Count)
            {
                i++;
                <span class="hljs-keyword">try</span>
                {
                    File.Delete(notDeleted[i]);
                }
                <span class="hljs-keyword">catch</span>
                {
                    <span class="hljs-keyword">continue</span>;
                }
                notDeleted.Remove(notDeleted[i]);
            }

            <span class="hljs-keyword">return</span> notDeleted;
        }


        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> Creates a snippet.</span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;/summary&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;param name="type"&gt;</span>The type to make the default create for.<span class="hljs-doctag">&lt;/param&gt;</span></span>
        <span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;param name="description"&gt;</span>The description of the snippet.<span class="hljs-doctag">&lt;/param&gt;</span></span>
        <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CreateSnippet</span>(<span class="hljs-params">Type type,
                                       <span class="hljs-keyword">string</span> description = <span class="hljs-string">"DefaultDescription"</span></span>)</span>
        {

            <span class="hljs-keyword">string</span> snippet_structure = <span class="hljs-string">$@"&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
  &lt;CodeSnippets xmlns = """"&gt;  
     &lt;CodeSnippet Format = ""1.0.0""&gt;   
         &lt;Header&gt;    
            &lt;Title&gt;<span class="hljs-subst">{type.Name}</span>-<span class="hljs-subst">{type.Namespace}</span>&lt;/Title&gt;    
            &lt;Author&gt;AUTO-GENERATOR&lt;/Author&gt;
            &lt;Description&gt; <span class="hljs-subst">{description}</span>&lt;/Description&gt;
            &lt;Shortcut&gt; <span class="hljs-subst">{type.Name}</span> &lt;/Shortcut&gt;   
         &lt;/Header&gt;   
         &lt;Snippet&gt;  
           &lt;Code Language = ""CSharp""&gt;    
                 &lt;![CDATA[<span class="hljs-subst">{type.Name}</span> $obj$ = new <span class="hljs-subst">{type.Name}</span>();]]&gt;     
             &lt;/Code&gt;     
             &lt;Declarations&gt;      
                &lt;Literal&gt;      
                    &lt;ID&gt;obj&lt;/ID&gt;      
                    &lt;ToolTip&gt;variable name.&lt;/ToolTip&gt;         
                       &lt;Default&gt;<span class="hljs-subst">{type.Name.ToLower()}</span>&lt;/Default&gt;        
                   &lt;/Literal&gt;       
                &lt;/Declarations&gt;         
             &lt;/Snippet&gt;        
           &lt;/CodeSnippet&gt;
         &lt;/CodeSnippets&gt;"</span>;

            <span class="hljs-comment">//write the snippet into the snippets directory.</span>
            File.WriteAllText(SnippetLocation + type.Name + <span class="hljs-string">"-"</span> + type.Namespace + <span class="hljs-string">".snippet"</span>, snippet_structure);
        }
    }
}
</code></pre>
<p>Let's talk about this code:</p>
<ul>
<li>“Reader” is the namespace of the class we’ve built before.</li>
<li>TypeReader is the name of the class we’ve built before.</li>
<li>The file names of the Snippets will be written as <code>&lt;TypeName&gt;-&lt;NamespaceName&gt;.snippet</code></li>
</ul>
<h4 id="heading-the-constructor">The Constructor</h4>
<ul>
<li>The constructor accepts the path for the “My Code Snippets” directory from the user.</li>
</ul>
<h4 id="heading-the-createsnippet-method">The CreateSnippet method</h4>
<p>The “CreateSnippet” method creates a snippet with a common structure.</p>
<ul>
<li>Title — The <code>&lt;typeName&gt;-&lt;namespace&gt;</code></li>
<li>Author — AUTO-GENERATOR, we call all of them by the same name so we’ll know what snippets were created by the CodeSnippetGenerator and what were created by the user.</li>
<li>We create a structure of:</li>
</ul>
<pre><code class="lang-cs"><span class="hljs-function">TypeName <span class="hljs-title">typename</span>(<span class="hljs-params"><span class="hljs-keyword">in</span> small letters</span>)</span> = <span class="hljs-keyword">new</span> TypeName();
</code></pre>
<ul>
<li>We set the “shortcut” to be the type name also.</li>
</ul>
<h4 id="heading-the-removeallsnippets-method">The RemoveAllSnippets method</h4>
<p>The RemoveAllSnippets method removes all the snippets <strong>that the CodeSnippetGenerator</strong> created. </p>
<p>We know if files were created by the code snippet generator by checking if the Author tag contains “AUTO-GENERATOR”. </p>
<p>We try again to delete files that were not deleted the first time. If we can’t delete them at the second time we return a list of the file names that we couldn't delete.</p>
<h4 id="heading-the-updatesnippets-method">The UpdateSnippets method</h4>
<p>The UpdateSnippets method updates the snippets each run. On each run:</p>
<ul>
<li>We read the names of the types we use in our main program (not in the CodeSnippetGenerator class).</li>
<li>We read the names of the .snippet files we have from the previous run.</li>
<li>We make an array of filenames for each one of our types from our current run.</li>
<li>We see what snippet files we no longer need by comparing what names of snippet files we had in our previous run that don't exist in the filenames of the current run.</li>
<li>We remove these files.</li>
<li>Then we create a “.snippet” file for each type that doesn’t already have one.</li>
</ul>
<h2 id="heading-how-to-use-the-snippet-auto-generator-program">How to Use the Snippet Auto-Generator Program</h2>
<p>If you want to use the program, simply open a C# project and at the beginning of the main function write:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">var</span> csg = <span class="hljs-keyword">new</span> CodeSnippetGenerator(<span class="hljs-string">"path of 'My Code Snippets'&gt;);
csg.UpdateSnippets(); //to create &amp; update the snippets in 
project.csg.RemoveAllSnippets(); //to remove the created snippets.</span>
</code></pre>
<p>Congratulations! You’ve now created your own CodeSnippetGenerator.</p>
<p>I hope these come in handy and save you time when you're writing your code. Thanks for reading :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Visual Studio Code Snippets – the Definitive VS Code Snippet Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Rob O'Leary Snippets can add a touch of magic to your editor. It's like an incantation. Utter a short phrase (type a prefix), wave your wand (press Enter or Tab), and presto! A wonderful event unfolds in front of you. ✨ Most code editors support s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/definitive-guide-to-snippets-visual-studio-code/</link>
                <guid isPermaLink="false">66d460c5bd438296f45cd3a6</guid>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Snippet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 24 Sep 2020 18:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/09/harry-hd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Rob O'Leary</p>
<p>Snippets can add a touch of magic to your editor. It's like an incantation. Utter a short phrase (type a prefix), wave your wand (press <code>Enter</code> or <code>Tab</code>), and presto! A wonderful event unfolds in front of you. ✨</p>
<p>Most code editors support snippets out of the box. The code editor I will use to showcase snippets is Visual Studio Code (VS Code), the most popular editor of the day.</p>
<p>Also, there are some "text expander" apps that allow you to use snippets globally (across all apps). I will briefly cover how you can utilise these apps to get even more out of snippets.</p>
<p>Let's dive into all things snippets. ?</p>
<h2 id="heading-definition">Definition</h2>
<blockquote>
<p> A snippet is a template that can be inserted into a document. It is inserted by a command or through some trigger text. </p>
</blockquote>
<p>With snippets, you can create a boilerplate file, and insert commonly used blocks of text. The general idea is to save you typing out the same things completely again and again, and again. ?</p>
<h2 id="heading-why-should-you-use-snippets">Why should you use Snippets?</h2>
<p>I'm not going to shock you with this statement: the internet is home to a lot conflicting opinions! Snippets do not escape this ignominy, but I don't think it is a topic that make people's blood pressure soar! </p>
<p>For the sake of balance, I will present a cross-section of those opinions here. </p>
<p>You don't have to pick a camp and be all-for or all-against snippets. I suggest you adopt them to a degree that serves you best.</p>
<h3 id="heading-yay-camp">Yay Camp ?</h3>
<ul>
<li>Snippets can boost your productivity, saving you keystrokes and reducing input errors.</li>
<li>Snippets leaves me with more mental CPU and enjoyment to spend on writing the code that I care about and want to focus on.</li>
<li>Snippets can help you to remember to include something important!</li>
<li>Integrating snippets into your workflow implicitly encourages you to use the mouse less often. Well-written snippets offer a logical path which you can tab through, stopping to edit along the way to complete the template exactly the way you want, and when you are done, you arrive on the other side ready to write your next line</li>
</ul>
<h3 id="heading-nay-camp">Nay Camp ?</h3>
<ul>
<li>I refrain from using them, mostly because I don't like being reliant on any given tool.</li>
<li>I never use snippets. I prefer to invest time in avoiding repetition rather than making it easier.</li>
<li>I found that at some point I forgot how to write the code without using the snippet. For trivial stuff that I understand, it is OK, but I don't want to forget some other stuff!</li>
<li>Most, if not all, snippets I've seen online, for code I'm looking for, have mistakes in them. I've not once been able to find a numerical algorithm that didn't have floating point errors in it. I can't imagine there being any resource of perfectly clean code snippets.</li>
</ul>
<h2 id="heading-when-should-you-use-snippets">When should you use snippets?</h2>
<p>Donald Knuth, one of the grand-wizards of computer science, said "premature optimization [of code] is the root of all evil". </p>
<p>I think this is relevant to snippets also. Snippets are an optimization of code production. If you don't know a language or framework very well, implementing a slew of snippets for that language or framework is likely to be a premature move.</p>
<p>If you are comfortable, then try some out!</p>
<h2 id="heading-what-i-use-snippets-for">What I use snippets for</h2>
<p>Personally, I use snippets often but judiciously. I use a set of snippets for Markdown and most of the languages I work with.</p>
<p>I haven't used snippets much for frameworks. I started using some snippets for Vue recently, but I only use the boilerplate snippet. I will probably adopt more of them once my Vue IQ has risen. </p>
<p>I haven't used snippets for algorithms.</p>
<h2 id="heading-types-of-snippets">Types of Snippets</h2>
<p>Snippets can be classified according to the scope of interactivity between the snippet and the editor. </p>
<h4 id="heading-static-snippets">Static Snippets</h4>
<p>You can think of it as a copy-and-paste of some source text as a single command. </p>
<h4 id="heading-dynamic-snippets">Dynamic Snippets</h4>
<p>A dynamic snippet can be customised to provide a wizard-like experience for completion of a snippet.  </p>
<p>It can include:</p>
<ul>
<li><em>Tab Stops</em>: You can number stops that can be tabbed through in order,</li>
<li><em>Mirrored Tab Stops</em>: There are times when you need to provide the same value in several places in the inserted text. You can mirror a tab stop to achieve this, and any edit will be reflected in the related tab stops instantly.</li>
<li><em>Placeholders</em> : It is a tab stop with a default value which can be overwritten on focus.</li>
<li><em>Choices</em> : At a tab stop you are presented with a dropdown list of values to choose from.</li>
<li><em>Variables</em>: Input values from the environment such as: the selected text in the editor, system dates, or content from the clipboard.</li>
</ul>
<p>Here is an example of a markdown snippet which adds a task list with 2 tasks. It uses <em>tab stops</em>, <em>placeholders</em>, and <em>choices</em> for checking a task.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/task.gif" alt="task" width="600" height="400" loading="lazy"></p>
<h4 id="heading-macro-snippets">Macro Snippets</h4>
<p>The top level of sorcery is to have the capability to transform input. Transformations allow you to alter the value of a variable before they are inserted, or alter a placeholder after you have made an edit. </p>
<p>For example, you may want to capitalise a class name once it is entered.  </p>
<p>Anything that you can think of doing with a regex is typically possible.  Some editors offer more advanced scripting possibilities. </p>
<h2 id="heading-snippets-in-visual-studio-code">Snippets in Visual Studio Code</h2>
<p>In VS Code, snippets appear in <strong>IntelliSense</strong> (<code>Ctrl+Space</code> gives you a suggestion list), they are mixed in with other suggestions. </p>
<p>You can also access them in a dedicated snippet picker by using the <strong>'Insert Snippet' command</strong>. This combines all user, extension, and built-in snippets for that language into a single list. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/insert-snippet-list.png" alt="insert-snippet-list" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://www.emmet.io/">Emmet</a> is integrated into VS Code and has it's own CSS-selector inspired syntax for inserting HTML and CSS snippets. </p>
<p>Emmet is it's own thing really, but the mechanics are the same. You can learn about Emmet with the <a target="_blank" href="https://code.visualstudio.com/docs/editor/emmet">Emmet in Visual Studio Code guide</a>.</p>
<h3 id="heading-related-user-settings">Related User Settings</h3>
<p>Snippets will appear as <strong>quick suggestions</strong> if the setting <code>editor.quickSuggestions</code> is set to true for the language you are working in. Quick suggestions are enabled by default for most languages except markdown. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/quick-suggestions-js.png" alt="quick-suggestions-js" width="600" height="400" loading="lazy"></p>
<p>Snippets support <strong>tab-completion</strong>. You can type a snippet prefix (the trigger text), and press <code>Tab</code> to insert a snippet.  You can enable it with the setting <code>editor.tabCompletion</code>.</p>
<p>The values are:</p>
<ul>
<li><code>on</code>: Tab completion is enabled for all sources.</li>
<li><code>off</code>: Disable tab completions. This is the <em>default value</em>.</li>
<li><code>onlySnippets</code>: Tab completion only for snippets. </li>
</ul>
<pre><code class="lang-json"><span class="hljs-string">"editor.tabCompletion"</span>: <span class="hljs-string">"onlySnippets"</span>,
</code></pre>
<p>If you would like to control how <strong>snippets suggestions</strong> are shown, you can edit the setting <code>editor.snippetSuggestions</code>.</p>
<p>The values are:</p>
<ul>
<li><code>top</code>: Show snippet suggestions on top of other suggestions. I use this value.</li>
<li><code>bottom</code>: Show snippet suggestions below other suggestions.</li>
<li><code>inline</code>: Show snippets suggestions with other suggestions. This is the <em>default value</em>.</li>
<li><code>none</code>: Do not show snippet suggestions.</li>
</ul>
<pre><code class="lang-json"><span class="hljs-string">"editor.snippetSuggestions"</span>: <span class="hljs-string">"top"</span>,
</code></pre>
<p>These are the most important settings for snippets, but there are a few more. You can check out this <a target="_blank" href="https://code.visualstudio.com/docs/getstarted/settings#_default-settings">list of the default settings</a> to explore more, or do a search in the Settings UI.</p>
<h3 id="heading-are-there-built-in-snippets">Are there built-in snippets?</h3>
<p>Yes! </p>
<p>They aren't documented in the VS Code docs, though. And inside VS Code, there is no central point to browse them. So, you may not know what they are. </p>
<p>So, how can you find out what languages have built-in snippets?</p>
<p>Long story short, I was frustrated by this scenario, so I wrote an extension called <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=robole.snippets-ranger"><strong>Snippets Ranger</strong></a> to give a nice UI to explore snippets easily. Think of it as a <em>Marauder's Map</em> for snippets!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/snippets-ranger.png" alt="snippets-ranger" width="600" height="400" loading="lazy"></p>
<h4 id="heading-but-i-want-to-find-the-snippets-for-myself">But I want to find the snippets for myself?</h4>
<p>You can, it just requires a bit more effort.</p>
<p>As I mentioned earlier, the <strong>'Insert Snippet' command</strong> will show you all snippets for the language of the active document. </p>
<p>Remember though, this is an <em>aggregate</em> of all of the user, extension, and built-in snippets.  So, if you want to find out if a particular language has built-in snippets, you need to open a file for that language, and run the command to see that list. </p>
<p>If you have an snippets extension installed for that language that makes it too hard to identify which is which, you could disable it to ensure that only the built-in snippets are showing. ?</p>
<p>If you want to track down the source file yourself, the built-in snippets live inside each individual language extension directory. The file is located at <code>«app root»\resources\app\extensions\«language»\snippets\«language».code-snippets</code> on Windows. The location is similar for Mac and Linux.</p>
<h3 id="heading-snippets-extensions">Snippets Extensions</h3>
<p>The Visual Studio Marketplace has a <a target="_blank" href="https://marketplace.visualstudio.com/search?target=VSCode&amp;category=Snippets&amp;sortBy=Installs">snippets category</a> where you can find snippets for almost anything.</p>
<p>A lot of Programming Language Pack extensions include snippets also (Python, C#, Go, Java, and C/C++ amongst others).</p>
<h3 id="heading-how-do-i-write-my-own">How do I write my own?</h3>
<p>Snippets files are written in JSON. You can also add C-style comments if you wish (technically it is Microsoft's "JSONC" format).</p>
<p>You can create snippets for different scopes: global, workspace, and for a particular language. </p>
<p>To create the snippets file, run the <strong>'Preferences: Configure User Snippets' command</strong>, which opens a quickpick dialog as below. Your selection will open a file for editing.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/user-snippets.png" alt="user snippets" width="600" height="400" loading="lazy"></p>
<p>If you would prefer to write a snippet in a GUI, you can use the <a target="_blank" href="https://snippet-generator.app">snippet generator web app</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/snippet-generator.png" alt="snippet generator" width="600" height="400" loading="lazy"></p>
<p>Let's look at an example to get familiar with the syntax.</p>
<h4 id="heading-example">Example</h4>
<p>Here is a markdown snippet that comes with VS Code. </p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"Insert heading level 1"</span>: {
       <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"heading1"</span>,
       <span class="hljs-attr">"body"</span>: [<span class="hljs-string">"# ${1:${TM_SELECTED_TEXT}}$0"</span>],
       <span class="hljs-attr">"description"</span> : <span class="hljs-string">"Insert heading level 1"</span>
    }
}
</code></pre>
<p>This snippet inserts a level 1 heading which wraps the markdown around the current selection (if there is one).</p>
<p>A snippet has the following properties:</p>
<ol>
<li>"Insert heading level 1"  is the snippet name. This is the value that is displayed in the IntelliSense suggestion list if no <code>description</code> is provided.</li>
<li>The<code>prefix</code> property defines the trigger phrase for the snippet. It can be a string or an array of strings (if you want multiple trigger phrases). Substring matching is performed on prefixes, so in this case, typing "h1" would match our example snippet.</li>
<li>The <code>body</code> property is the content that is inserted into the editor. It is an array of strings, which is one or more lines of content. The content is joined together before insertion. </li>
<li>The <code>description</code> property can provide more information about the snippet. It is optional. </li>
<li>The <code>scope</code> property allows you to target specific languages, and you can supply a comma-separated list in the string. It is optional. Of course, it is redundant for a language-specific snippet file.</li>
</ol>
<p>The body of this snippet has 2 tab stops and uses the variable <code>${TM_SELECTED_TEXT}</code>. </p>
<p>Let's get into the syntax to understand this fully.</p>
<h4 id="heading-snippet-syntax">Snippet syntax</h4>
<p>VS Code's snippet syntax is the same as the <a target="_blank" href="https://manual.macromates.com/en/snippets">TextMate snippet syntax</a>. However, it does not support 'interpolated shell code' and the use of the <code>\u</code> transformation.</p>
<p>The <code>body</code> of a snippet supports the following features:</p>
<h4 id="heading-1-tab-stops">1. Tab Stops</h4>
<p>Tab stops are specified by a dollar sign and an ordinal number e.g. <code>$1</code> . <code>$1</code> will be the first location, <code>$2</code> will the second location, and so on. <code>$0</code> is the final cursor position, which exits the snippet mode. </p>
<p>For example, let's say we want to make an HTML <em>div</em> snippet and we want the first tab stop to be between the opening and closing tags. We also want to allow the user to tab outside of the tags to finish the snippet. </p>
<p>Then we could make a snippet like this:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"Insert div"</span>: {
        prefix: <span class="hljs-string">"div"</span>,
        body: [<span class="hljs-string">"&lt;div&gt;"</span>,<span class="hljs-string">"$1"</span>,<span class="hljs-string">"&lt;/div&gt;"</span>, <span class="hljs-string">"$0"</span>]
    }
}
</code></pre>
<h4 id="heading-2-mirrored-tab-stops">2. Mirrored Tab Stops</h4>
<p>There are times when you need to provide the same value in several places in the inserted text. In these situations you can re-use the same ordinal number for tab stops to signal that you want them mirrored. Then your edits are synced. </p>
<p>A typical example is a <em>for</em> loop which uses an <em>index</em> variable multiple times. Below is a JavaScript example of a <em>for</em> loop.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"For Loop"</span>: {
        <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"for"</span>,
        <span class="hljs-attr">"body"</span>: [
            <span class="hljs-string">"for (let ${1:index} = 0; ${1:index} &lt; ${2:array}.length; ${1:index}++) {"</span>,
            <span class="hljs-string">"\tconst ${3:element} = ${2:array}[${1:index}];"</span>,
            <span class="hljs-string">"\t$0"</span>,
            <span class="hljs-string">"}"</span>
        ]
    }
}
</code></pre>
<h4 id="heading-3-placeholders">3. Placeholders</h4>
<p>Placeholders are tab stops with default values. They are wrapped in curly braces, for example <code>${1:default}</code>. The placeholder text is selected on focus such that it can be easily edited. Placeholders can be nested, like this: <code>${1:first ${2:second}}</code>.</p>
<h4 id="heading-4-choices">4. Choices</h4>
<p>Choices present the user with a list of values at a tab stop. They are written as a comma-separated list of values enclosed in pipe-characters e.g. <code>${1|yes,no|}</code>. </p>
<p>This is the code for the markdown example shown earlier for inserting a task list. The choices are 'x' or a blank space.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"Insert task list"</span>: {
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"task"</span>,
    <span class="hljs-attr">"body"</span>: [<span class="hljs-string">"- [${1| ,x|}] ${2:text}"</span>, <span class="hljs-string">"${0}"</span>]
}
</code></pre>
<h4 id="heading-5-variables">5. Variables</h4>
<p>There is a good selection of variables you can use. You simply prefix the name with a dollar sign to use them, for example <code>$TM_SELECTED_TEXT</code>. </p>
<p>For example, this snippet will create a block comment for any language with today's date:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"Insert block comment with date"</span>: {
        prefix: <span class="hljs-string">"date comment"</span>,
        body: [<span class="hljs-string">"${BLOCK_COMMENT_START}"</span>,
               <span class="hljs-string">"${CURRENT_YEAR}/${CURRENT_MONTH}/${CURRENT_DATE} ${1}"</span>,
               <span class="hljs-string">"${BLOCK_COMMENT_END}"</span>]
    }
}
</code></pre>
<p>You can specify a default for a variable if you wish, like <code>${TM_SELECTED_TEXT:default}</code>. If a variable does not have a value assigned, the default or an empty string is inserted. </p>
<p>If you make a mistake and include a variable name that is not defined, the name of the variable is transformed into a placeholder.</p>
<p>The following workspace variables can be used:</p>
<ul>
<li><code>TM_SELECTED_TEXT</code>: The currently selected text or the empty string,</li>
<li><code>TM_CURRENT_LINE</code>: The contents of the current line,</li>
<li><code>TM_CURRENT_WORD</code>: The contents of the word under cursor or the empty string,</li>
<li><code>TM_LINE_INDEX</code>: The zero-index based line number,</li>
<li><code>TM_LINE_NUMBER</code>: The one-index based line number,</li>
<li><code>TM_FILENAME</code>: The filename of the current document,</li>
<li><code>TM_FILENAME_BASE</code>: The filename of the current document without its extensions,</li>
<li><code>TM_DIRECTORY</code>: The directory of the current document,</li>
<li><code>TM_FILEPATH</code>: The full file path of the current document,</li>
<li><code>CLIPBOARD</code>: The contents of your clipboard,</li>
<li><code>WORKSPACE_NAME</code>: The name of the opened workspace or folder.</li>
</ul>
<p>The following time-related variables can be used:</p>
<ul>
<li><code>CURRENT_YEAR</code>: The current year,</li>
<li><code>CURRENT_YEAR_SHORT</code>: The current year's last two digits,</li>
<li><code>CURRENT_MONTH</code>: The month as two digits (example '07'),</li>
<li><code>CURRENT_MONTH_NAME</code>: The full name of the month (example 'July'),</li>
<li><code>CURRENT_MONTH_NAME_SHORT</code>: The short name of the month (example 'Jul'),</li>
<li><code>CURRENT_DATE</code>: The day of the month,</li>
<li><code>CURRENT_DAY_NAME</code>: The name of day (example 'Monday'),</li>
<li><code>CURRENT_DAY_NAME_SHORT</code>: The short name of the day (example 'Mon'),</li>
<li><code>CURRENT_HOUR</code>: The current hour in 24-hour clock format,</li>
<li><code>CURRENT_MINUTE</code>: The current minute,</li>
<li><code>CURRENT_SECOND</code>: The current second,</li>
<li><code>CURRENT_SECONDS_UNIX</code>: The number of seconds since the Unix epoch.</li>
</ul>
<p>The following comment variables can be used. They honour the syntax of the document's language:</p>
<ul>
<li><code>BLOCK_COMMENT_START</code>: For example, <code>&lt;!--</code> in HTML,</li>
<li><code>BLOCK_COMMENT_END</code>: For example ,  <code>--&gt;</code> in HTML,</li>
<li><code>LINE_COMMENT</code>: For example,  <code>//</code> in JavaScript.</li>
</ul>
<h4 id="heading-6-transformations">6. Transformations</h4>
<p>Transformations can be applied to a variable or a placeholder. If you are familiar with regular expressions (regex), most of this should be familiar.</p>
<p>The format of a transformation is: <code>${«variable or placeholder»/«regex»/«replacement string»/«flags»}</code>. It is similar to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">String.protoype.replace()</a> in JavaScript. The "parameters" do the following:</p>
<ul>
<li><code>«regex»</code>: This is a regular expression that is matched against the value of the variable or placeholder. The JavaScript regex syntax is supported.</li>
<li><code>«replacement string»</code>: This is the string you want to replace the original text with. It can reference capture groups from the <code>«regex»</code>, perform case formatting (using the special functions: <code>/upcase</code>, <code>/downcase</code>, and <code>/capitalize</code>), and perform conditional insertions. See <a target="_blank" href="https://macromates.com/manual/en/regular_expressions#replacement_string_syntax_format_strings">TextMate Replacement String Syntax</a> for more in-depth information.</li>
<li><code>«flags»</code>: Flags that are passed to the regular expression. The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2">JavaScript regex flags</a> can be used: <ul>
<li><code>g</code> : Global search, </li>
<li><code>i</code> : Case-insensitive search, </li>
<li><code>m</code> : Multi-line search,  </li>
<li><code>s</code> : Allows <code>.</code> to match newline characters,</li>
<li><code>u</code> : Unicode. Treat the pattern as a sequence of Unicode code points, </li>
<li><code>y</code> : Perform a "sticky" search that matches starting at the current position in the target string.</li>
</ul>
</li>
</ul>
<p>To reference a capture group, use <code>$n</code> where <code>n</code> is the capture group number. Using <code>$0</code> means the entire match. </p>
<p>This can be a bit confusing since tab stops have the same syntax. Just remember that if it is contained within forward slashes, then it is referencing a capture group.</p>
<p>The easiest way to understand the syntax fully is to check out a few examples.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Snippet <em>body</em></td><td>Input</td><td>Output</td><td>Explanation</td></tr>
</thead>
<tbody>
<tr>
<td><code>["${TM_SELECTED_TEXT/^.+$/• $0/gm}"]</code></td><td>line1<br>line2</td><td>• line1<br>• line2</td><td>Put a bullet point before each non-empty line of the selected text.</td></tr>
<tr>
<td><code>["${TM_SELECTED_TEXT/^(\\w+)/${1:/capitalize}/}"]</code></td><td>the cat is on the mat.</td><td>The cat is on the mat.</td><td>Capitalize the first word of selected text.</td></tr>
<tr>
<td><code>["${TM_FILENAME/.*/${0:/upcase}/}"]</code></td><td>example.js</td><td>EXAMPLE.JS</td><td>Insert the filename of the current file uppercased.</td></tr>
<tr>
<td><code>[</code><br><code>"[",</code><br><code>"${CLIPBOARD/^(.+)$/'$1',/gm}",</code><br><code>"]"</code><br><code>]</code></td><td>line1<br>line2</td><td>['line1', 'line2',]</td><td>Turn the contents of the clipboard into a string array. Each non-empty line is an element.</td></tr>
</tbody>
</table>
</div><p>As you can see from the second example above, metacharacter sequences must be escaped, for example insert <code>\\w</code> for a word character.</p>
<h4 id="heading-placeholder-transformations">Placeholder Transformations</h4>
<p><strong>Placeholder transforms do <u>not</u> allow a default value or choices</strong>! Maybe it is more suitable to call them tab stop transformations.</p>
<p>The example below will uppercase the text of the first tab stop.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/placeholder-transform.gif" alt="placeholder transform" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"Uppercase first tab stop"</span>: {
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"up"</span>,
    <span class="hljs-attr">"body"</span>: [<span class="hljs-string">"${1/.*/${0:/upcase}/}"</span>, <span class="hljs-string">"$0"</span>]
  }
}
</code></pre>
<p>You can have a placeholder and perform a transformation on a mirrored instance. The transformation will not be performed on the initial placeholder. ? </p>
<p>Would you use this behaviour somewhere? I find it confusing initially, so it may have the same affect on others.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"Uppercase second tab stop instance only"</span>: {
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"up"</span>,
    <span class="hljs-attr">"body"</span>: [<span class="hljs-string">"${1:title}"</span>, <span class="hljs-string">"${1/(.*)/${1:/upcase}/}"</span>, <span class="hljs-string">"$0"</span>]
  }
}
</code></pre>
<h3 id="heading-how-do-i-assign-keyboard-shortcuts-for-snippets">How do I assign Keyboard Shortcuts for snippets?</h3>
<p>By adding your shortcuts to <code>keybindings.json</code> . You can open the file by running the <strong>'Preferences: Open Keyboard Shortcuts File (JSON)'</strong> command.</p>
<p>For example, to add a shortcut for the built-in markdown snippet "Insert heading level 1":</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"key"</span>: <span class="hljs-string">"ctrl+m ctrl+1"</span>,
    <span class="hljs-attr">"command"</span>: <span class="hljs-string">"editor.action.insertSnippet"</span>,
    <span class="hljs-attr">"when"</span>: <span class="hljs-string">"editorTextFocus &amp;&amp; editorLangId == markdown"</span>,
    <span class="hljs-attr">"args"</span>: {
        <span class="hljs-attr">"langId"</span>: <span class="hljs-string">"markdown"</span>,
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Insert heading level 1"</span>
    }
}
</code></pre>
<p>You define a shortcut by specifying the key combination you want to use, the command ID, and an optional <a target="_blank" href="https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts">when clause context</a> for the context when the keyboard shortcut is enabled. </p>
<p>Through the <code>args</code> object, you can target an existing snippet by using the <code>langId</code> and <code>name</code> properties. The <code>langId</code> argument is the <a target="_blank" href="https://code.visualstudio.com/docs/languages/identifiers#_known-language-identifiers">language ID</a> of the language that the snippets were written for. The <code>name</code> is the snippet's name as it is defined in the snippet file. </p>
<p>You can define an inline snippet if you wish using the <code>snippet</code> property.</p>
<pre><code class="lang-json">[
  {
    <span class="hljs-attr">"key"</span>: <span class="hljs-string">"ctrl+k 1"</span>,
    <span class="hljs-attr">"command"</span>: <span class="hljs-string">"editor.action.insertSnippet"</span>,
    <span class="hljs-attr">"when"</span>: <span class="hljs-string">"editorTextFocus"</span>,
    <span class="hljs-attr">"args"</span>: {
      <span class="hljs-attr">"snippet"</span>: <span class="hljs-string">"${BLOCK_COMMENT_START}${CURRENT_YEAR}/${CURRENT_MONTH}/${CURRENT_DATE} ${1} ${BLOCK_COMMENT_END}"</span>
    }
  }
]
</code></pre>
<p>You can use the <em>Keyboard Shortcuts UI</em> also, but it does not have the ability to add a new shortcut. </p>
<p>Another downside of the UI is that it does not show the <code>args</code> object, which makes it more difficult to find and edit your custom shortcuts. ?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/shortcuts-ui.png" alt="shortcuts-ui" width="600" height="400" loading="lazy"></p>
<h2 id="heading-a-question-of-style">A question of style</h2>
<p>Something that I found offputting initially with snippets was the propensity for people to create snippets with abbreviated prefixes. Do I have to learn a big list of gibberish acronyms to use someone else's snippets? </p>
<p>What do I mean by abbreviated prefixes?  The table below list a few of the snippets from the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=xabikos.JavaScriptSnippets">JavaScript (ES6) code snippets</a> VS Code extension. You can see in the <em>Trigger</em> column, the prefixes listed are abbreviations, for example <em>fre</em> to represent a "for each" loop.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/es6-snippets-excerpt.png" alt="es6 snippets excerpt" width="600" height="400" loading="lazy"></p>
<p>This is unnecessary in two ways.</p>
<p>Firstly, the quick suggestions offered by VS Code are produced from a <strong>fuzzy substring search</strong>. If I type "fe" and the prefix of a snippet is "foreach", this will match and be offered as a quick suggestion.  </p>
<p>As you can see below, this is the second match.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/fe-quick-suggestion.png" alt="fe quick suggestion" width="600" height="400" loading="lazy"></p>
<p>The first match is <em>fre</em>, which is a snippet from the extension. Which suggestion is more descriptive? ?</p>
<p>If you use the "Insert Snippet" command for snippets, it does not make much of a difference. The description field makes amends for this shortcoming. I don't use snippets in this way, so I would prefer a more descriptive prefix.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/insertsnippet-foreach.png" alt="insert snippet foreach" width="600" height="400" loading="lazy"></p>
<p>Secondly, <em>fre</em> is a <strong>duplicate</strong> of the built-in snippet <em>foreach</em>.</p>
<p>Some people turn off quick suggestions for snippets and use tab completion only. In this case, you need to type a prefix out without getting visual feedback. Some people may prefer to use an abbreviated prefix to save keystrokes here. </p>
<p>The same fuzzy substring search is being performed in the background, so the first snippet match is inserted when you hit tab. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/snippet-tab-completion.gif" alt="snippet-tab-completion" width="600" height="400" loading="lazy"></p>
<p>Looking at the example above, you can see that typing "fr" and hitting <em>tab</em> inserts the <em>fre</em> snippet. Typing "fore" and hitting tab inserts the <em>foreach</em> snippet. </p>
<p>So, you do not need to type out the entire prefix, if you really don't want to! ? If you have many similarly named snippet prefixes for a language, it would be impractical I imagine. </p>
<p>It is more practical to learn the prefixes properly, and type them out entirely before hitting tab.</p>
<p>There are some trade-offs depending on your preferences for using snippets. </p>
<p>Personally, I like to use quick suggestions as I like the visual feedback. I have snippets set to be the top suggestions, that way I can type abbreviated versions of the prefixes without needing to memorise them. </p>
<p>Some snippet authors have rigid patterns to overcome this, but that's just something I can't get into easily.</p>
<p>If you use a lot of snippets for a language, you may want to choose snippets that are written in a similar style. </p>
<p>If you use snippets for different frameworks and libraries in a language, they can add up and overlap. I haven't needed to do this, but you may need to do it eventually.</p>
<h2 id="heading-global-snippets">Global Snippets</h2>
<p>Outside of your code editor, you can benefit from snippets also. Having snippets available in every app offers more possibilities.</p>
<p>Common use cases are:</p>
<ul>
<li>canned responses for messages, </li>
<li>autocorrecting common typos,</li>
<li>adding contact information or signatures to documents,</li>
<li>inserting dates,</li>
<li>formatting of selected text and pasted text,</li>
<li>inserting search phrases for your search engine or app,</li>
<li>HTML snippets available inside your email client,</li>
<li>adding different templates to documents.</li>
</ul>
<p>Most of the apps for snippets are touted as "text expanders", but quite a few task and productivity apps also include snippet-esque features. </p>
<p>Global snippets are <strong>bit more limited that code editor snippets</strong>, as you cannot use tab stops and placeholders. In most apps you can use some dynamic variables such as dates. </p>
<h3 id="heading-app-review">App Review</h3>
<h4 id="heading-autohotkey-windows">Autohotkey (Windows)</h4>
<p><a target="_blank" href="https://www.autohotkey.com/">AutoHotkey</a> is a <strong>free, open-source scripting language for Windows</strong> to do all kinds of tasks. </p>
<p>It has it's own unique syntax. You can install the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=slevesque.vscode-autohotkey">AutoHotKey extension</a> to add language support to VS Code for a better editing experience.</p>
<p>For defining prefixes to trigger a snippet insertion, you use the following format: <code>::&lt;&lt;prefix&gt;&gt;::&lt;&lt;text to insert&gt;&gt;</code>. The following script will insert Rob's email address when you type "robmail" and hit <em>space</em> or <em>tab</em> or <em>enter</em>.</p>
<pre><code>::robmail::rob@someservername.com
</code></pre><p>The following script will insert the text "This is the snippet text" when you press <code>Ctrl+D</code>.</p>
<pre><code>^d::  Send This is the snippet text
</code></pre><p>You can read the <a target="_blank" href="https://www.autohotkey.com/docs/AutoHotkey.htm">docs</a> to learn more.</p>
<h4 id="heading-phraseexpress-windows-mac-ios">PhraseExpress (Windows, Mac, iOS)</h4>
<p><a target="_blank" href="https://www.phraseexpress.com/">PhraseExpress</a> is "a text expander software, that manages frequently used text templates for insertion into any program". </p>
<p>It is a <strong>freemium, GUI-based app</strong>. It is aimed at a wider audience than <em>AutoHotKey</em>.</p>
<p>It is quite polished and easy to use. You set it to run on start-up and it will be active in the background. </p>
<p>Your snippets can be organized into custom folders and synced using cloud services.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/09/phrase-express.png" alt="phrase-express" width="600" height="400" loading="lazy"></p>
<h4 id="heading-espanso-windows-mac-linux">Espanso (Windows, Mac, Linux)</h4>
<p>This is a <strong>open-source, cross-platform text expander written in Rust</strong>. </p>
<p>It uses a <strong>file-based configuration approach</strong>. The config files are written in <a target="_blank" href="https://en.wikipedia.org/wiki/YAML">YAML</a>.</p>
<p>The <code>default.yml</code> file contains the main configuration. The config below will insert Rob's email address when you type "robmail" .</p>
<pre><code class="lang-yaml"><span class="hljs-attr">matches:</span>
 <span class="hljs-bullet">-</span> <span class="hljs-attr">trigger:</span> <span class="hljs-string">":robmail"</span>
   <span class="hljs-attr">replace:</span> <span class="hljs-string">"rob@someservername.com"</span>
</code></pre>
<p>You can <strong>specify the initial cursor position</strong>, however you cannot define tab stops.</p>
<p>You can <strong>add extensions</strong> to increase the capability of Espanso. There are extensions for running external scripts, including dates, generating random text, and including clipboard data.</p>
<p>And that's about it! I hope you learned something about snippets today, and you can use them to make yourself more productive. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Guide to Sublime Text Snippets ]]>
                </title>
                <description>
                    <![CDATA[ By Jimmy Zhang I recently switched jobs, which involves a lot of acclimation: new coworkers to befriend, new terms to learn, a new development environment to internalize. But most of all, the switch came with a change in programming languages, away f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-guide-to-preserving-your-wrists-with-sublime-text-snippets-7541662a53f2/</link>
                <guid isPermaLink="false">66c342ae790a62b5fbf7b850</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Snippet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 04 Jan 2018 17:49:42 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*m0_LP6bcNEN_ZPBad6ekfA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jimmy Zhang</p>
<p>I recently switched jobs, which involves a lot of acclimation: new coworkers to befriend, new terms to learn, a new development environment to internalize. But most of all, the switch came with a change in programming languages, away from the tidy aesthetic of Python, and straight into the angled and curly world of JavaScript.</p>
<p>As I continued to misplace brackets and omit parenthesis, I searched for something that would help me navigate the unfamiliar territory. Luckily, I found Sublime Text Snippets.</p>
<p>I love Sublime Text Snippets because they reduce cumbersome definitions to a few keystrokes, like this:</p>
<h3 id="heading-overview">Overview</h3>
<p>Sublime Text Snippets expedite the act of writing code by providing a quick way to insert blocks of text that show up repeatedly in a project. They are both easy to understand and straightforward to write, making them a great tool for saving time and eliminating errors while developing.</p>
<p>A snippet maps a trigger word to a pre-defined block of text, both of which you define. To invoke the snippet, type the trigger word and press <code>tab</code>. This simple action expands the trigger word into the mapped block of text — replete with as many brackets, parentheses, and semi-colons as necessary, always matching and in the correct order.</p>
<p><strong>Note:</strong> The examples given below apply mostly to JavaScript and React, but the information about snippets can be applied to any programming language or framework.</p>
<h3 id="heading-creating-snippets">Creating Snippets</h3>
<p>To create a new snippet in Sublime Text 3, go to:</p>
<pre><code>Tools -&gt; Developer -&gt; New Snippet...
</code></pre><p>This opens a new window containing a new snippet template, which looks like this:</p>
<p>There are four parts to a snippet. Although only one part is required, defining all four is recommended.</p>
<h4 id="heading-1-the-content-line-3-required"><strong>1) The Content (Line 3): Required</strong></h4>
<pre><code>&lt;content&gt;&lt;![CDATA[  Hello, ${<span class="hljs-number">1</span>:<span class="hljs-built_in">this</span>} is a ${<span class="hljs-number">2</span>:snippet}.]]&gt;&lt;/content&gt;
</code></pre><p>Define the block of text to be expanded by the snippet by editing the line(s) between the <code>&lt;![CDA</code>TA[ a<code>nd</code> ]]&gt; tags. (From now on, the block of text that is expanded after the snippet is invoked will be referred to as the snip<strong>pet’s c</strong>_on_tent).</p>
<p>You’ll notice the presence of words surrounded by a dollar sign, braces, numbers, and prefixed by a number. This optional markup specifies a <strong>Field Marker</strong><em>,</em> which controls the cursor position after the snippet is invoked.</p>
<p>After content is expanded, the cursor moves automatically to the first field marker (<code>${1:this}</code> above). Pressing tab again moves the cursor to the next numbered field marker, or to the end of the snippet’s content if there are no fields left (see <strong>pro tip</strong> below).</p>
<p>Text after the colon in a field marker is optional. If specified, it is automatically selected as part of the cursor movement, meaning it can be deleted in one swift stroke. This makes text after the colon great for “placeholder” values that provide guidance of what should be filled in, or for optional default values, such as the <code>isRequired</code> field in the example below.</p>
<p><strong>Pro tip</strong><br>Use the <code>$0</code> field marker (the exit marker) to explicitly define where the cursor will exit after all field markers have been cycled through. This is useful if you want to rebind the <code>tab</code> key to auto-completion after the snippet is invoked. To do so, place the exit marker immediately after the first field marker, like this:<code>${1:example}$0</code></p>
<h4 id="heading-2-the-trigger-word-line-6-optional"><strong>2: The Trigger Word (Line 6): Optional</strong></h4>
<pre><code>&lt;tabTrigger&gt;hello&lt;/tabTrigger&gt;
</code></pre><p>Short and mnemonic trigger words work best. For example, the <a target="_blank" href="https://github.com/babel/babel-sublime-snippets">Babel React Snippet</a> package maps <code>cwm</code> to <code>componentWillMount</code> and <code>cwr</code> to <code>componentWillReceiveProps</code>.</p>
<p>Trigger words are optional because there is an alternative way to invoke snippets, which we will cover in the Advanced Usage section.</p>
<h4 id="heading-3-a-scope-line-8-optional"><strong>3: A Scope (Line 8): Optional</strong></h4>
<pre><code>&lt;scope&gt; source: python &lt;/scope&gt;
</code></pre><p>Scopes limit where your snippet can be invoked, improving precision and preventing collisions. For example, with scopes, the same trigger word can have different meanings for different programming languages.</p>
<p>This <a target="_blank" href="https://gist.github.com/J2TeaM/a54bafb082f90c0f20c9">gist</a> lists how to define scopes for a long list of programming languages, but scopes are capable of much more. We will cover scopes in more detail in the Advanced Usage section.</p>
<h4 id="heading-4-a-description-line-10-optional"><strong>4: A Description (Line 10): Optional</strong></h4>
<pre><code>&lt;description&gt; demo description &lt;/description&gt;
</code></pre><p>For some reason, the description tag doesn’t show up in the create snippet template. However, providing one will come in handy.</p>
<p>Snippets show up in Sublime Text’s auto-complete menu, along with a descriptive phrase. Without a description, this phrase defaults to the snippet’s filename, which isn’t guaranteed to have enough context when multiple snippets share the same prefix.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*6kQO9TXQwXs0NcSqqFx1sw.png" alt="Image" width="712" height="423" loading="lazy">
<em>Descriptions help me untangle my import snippets</em></p>
<p><strong>Pro tip</strong><br>Create a keyboard shortcut to quickly create a new snippet. Go to <code>Preferences -&gt; Keybindi</code>ngs and add the following line to the “User” configuration file (of course, repla<code>ce cmd+al</code>t+n with whatever combination suits you best):</p>
<pre><code>{ <span class="hljs-string">"keys"</span>: [<span class="hljs-string">"cmd+alt+n"</span>], <span class="hljs-string">"command"</span>: <span class="hljs-string">"new_snippet"</span> }
</code></pre><h3 id="heading-saving-snippets">Saving Snippets</h3>
<p>After creating your snippet, make sure to save it in a file ending in <code>sublime-snippet</code>. On Mac, user created snippets are saved at:</p>
<pre><code>~<span class="hljs-regexp">/Library/</span>Application Support/Sublime Text <span class="hljs-number">3</span>/Packages/User
</code></pre><p>Creating a new snippet through the menu item or keyboard shortcut automatically prompts this location on save.</p>
<h3 id="heading-advanced-usage">Advanced Usage</h3>
<h4 id="heading-environment-variables">Environment Variables</h4>
<p>We’ve covered the four aspects of creating a static snippet. However, it is possible to create dynamic snippets through the use of environment variables, which contain references to the context in which a snippet was invoked.</p>
<p>Context is a vague term, so see the <a target="_blank" href="http://docs.sublimetext.info/en/latest/extensibility/snippets.html#environment-variables">Sublime Text Snippet Documentation</a> for a table of environment variables and their exact meanings.</p>
<p>For an example of how environment variables can be used, my team follows a convention where a component’s stylesheet is saved under the same file name as the component, and given a <code>.scss</code> extension.</p>
<p>The component file can then leverage this convention with a snippet using the <code>$TM_FILENAME</code> environment variable.</p>
<pre><code>&lt;content&gt;&lt;![CDATA[  <span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">'./$TM_FILENAME${1:}scss'</span>]]&gt;&lt;/content&gt;
</code></pre><p>The <code>$TM_SELECTED_TEXT</code> or <code>$SELECTION</code> environment variable serves a more general purpose. Remember how I mentioned there was an alternative way of invoking snippets? Instead of keying the trigger word and hitting <code>tab</code>, you can also invoke snippets through the Command Palette.</p>
<p>On Mac, hit <code>cmd+shift+p</code> to bring up the Palette, type ‘Snippet’ and select the desired snippet from the drop-down. This roundabout approach has one major benefit — it is possible to invoke a snippet with a block of text selected, and for that text to be included as part of a snippet’s content. This allows you to create “wrapping” snippets, which wrap selected text with an if clause, for example.</p>
<p><strong>Pro tip</strong><br><a target="_blank" href="http://docs.sublimetext.info/en/latest/editing/editing.html?highlight=selection#other-ways-of-selecting-text">Expand selection shortcuts</a> are great for quickly selecting text to wrap with snippets like the one above.</p>
<h4 id="heading-advanced-scopes">Advanced Scopes</h4>
<p>We’ve talked about limiting snippets to certain source code files, but snippets often have more granular contexts in which they are valid. As an example, a method such as <code>componentWillUpdate</code> typically only makes sense within a component (class) definition, which the following snippet definition makes explicit:</p>
<p>The inclusion of <code>meta.class.js</code> on line 8 means that the snippet is only valid in situations where the source code file being edited is a JavaScript file, <em>and</em> the cursor is “within” a class definition. If you tried to invoke the snippet in a blank JavaScript file, nothing would happen.</p>
<p>To fully leverage the power of scopes, you need to have a little understanding of syntax, scopes and scope selectors. These are nuanced topics worthy of their own post, so I’ll explain them at a very high level, with links to the documentation to fill in the gaps:</p>
<ul>
<li>a language <a target="_blank" href="http://docs.sublimetext.info/en/latest/extensibility/syntaxdefs.html">syntax</a> defines how source code is divided into scopes.</li>
<li><a target="_blank" href="http://docs.sublimetext.info/en/latest/extensibility/syntaxdefs.html#scopes">scopes</a> are labeled regions of text that correspond to the “units” of a programming language, such as class or function definitions. Every position within a source code file has an associated scope. <a target="_blank" href="https://www.sublimetext.com/docs/3/scope_naming.html#meta">Meta</a> scopes are most relevant to snippets.</li>
<li><a target="_blank" href="https://manual.macromates.com/en/scope_selectors">scope selectors</a> “query” scopes. Scopes selectors are bound to actions (such as snippets, or keyboard shortcuts), and are used to determine if the action is appropriate given the current scope.</li>
</ul>
<p><strong>Pro tip</strong><br>The best way to learn about scopes is play around with them. Move your cursor to different positions within a file, and use the <code>cmd+shift+p</code> keyboard shortcut to bring up a pop-up menu displaying the associated scope:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*7uR3g9cWm3U_CYShUZQtKw.png" alt="Image" width="669" height="382" loading="lazy"></p>
<p>Snippets take mere seconds to create. Yet they save much more in effort, and not just by saving how much you have to type. By providing a quick, reproducible way to expand content, snippets reduce errors. They also abstract away hard-to-remember details, such as method names and their signatures. All of this frees your fingers — and your brain — to focus on what they want to do most: write great code.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
