Excerpts from Visual Studio code (2023)

Code snippets are templates that make it easy to insert repetitive code patterns, such as loops or conditional statements.

In Visual Studio Code, snippets appear in IntelliSense (⌃Espacio(Windows, LinuxCtrl+Spacebar)) mixed with other suggestions, as well as in a dedicated snippet picker (insert snippeton the command palette). Tab completion is also supported - enable it with"editor.tabCompletion": "enabled", Write infragment prefix(activation text) and presseyelashto insert a snippet.

The syntax of the fragment follows aTextMate-Fragmentsyntaxexcept for 'interpolated shellcode' and using\you; both are incompatible.

Excerpts from Visual Studio code (1)

embedded fragments

VS Code has built-in snippets for many languages ​​such as JavaScript, TypeScript, Markdown and PHP.

Excerpts from Visual Studio code (2)

You can see available snippets for a language by running theinsert snippeton the command palette for a list of snippets for the current file's language. Note, however, that this list also includes custom code snippets and any snippets provided by extensions you have installed.

Install Fragments from Marketplace

Manyextensionsabout itUS code marketCutouts included. You can look for extensions that contain fragments (⇧⌘X(Windows, LinuxCtrl+Shift+X)) Use of@category:"Fragmentos"Filter.

(Video) VS Code tips — The extract function/method refactorings for JavaScript and TypeScript

Excerpts from Visual Studio code (3)

If you find an extension you want to use, install it and restart VS Code and the new snippets will be available.

Create your own snippets

You can easily define your own snippets without any extensions. To create or edit your own snippets, selectConfigure User Fragmentslowfile>preferences(Code>preferenceson macOS), then select the language (for example,language identifier) for which the fragments should appear, or theNew global snippets fileOption if they should appear for all languages. VS Code manages creating and updating the underlying snippet files for you.

Excerpts from Visual Studio code (4)

Snippet files are written in JSON, support C-style comments, and can define an unlimited number of snippets. Snippets support most TextMate syntaxes for dynamic behavior, intelligently format spaces based on pasting context, and allow for easy multi-line editing.

Below is an example offorLoop length for JavaScript:

// no Datei 'Code/User/snippets/javascript.json'{ "in loop": { "Prefix": ["for","para-const"], "Body": ["for (const ${2:element} of ${1:array}) {","\T$ 0","}"], "Description":"A bucle for".}}

In the example above:

  • "For Loop" is the name of the fragment. Shown via IntelliSense if notDescriptionIt is planned.
  • prefixdefines one or more trigger words that display the fragment in IntelliSense. Substring matching is done using prefixes, so in this case fc can match for-const.
  • Bodyis one or more lines of content that are merged into multiple lines when inserted. Line breaks and embedded tabs are formatted according to the context in which the snippet is inserted.
  • Descriptionis an optional description of the snippet that IntelliSense displays.

also theBodyabove has three placeholders (listed in order of execution):${1:Matrix},${2:element}, j$ 0. With you can quickly jump to the next placeholdereyelash, at this point you can edit the placeholder or move on to the next one. The string after the colon:(if any) is the default text, e.g.ElementEm${2:element}. The wildcard traversal order is ascending by number, starting with one; Null is an optional special case that always comes last and exits fragment mode with the cursor at the specified position.

Excerpts from file templates

You can add thoseisFileTemplateTell your snippet definition whether the snippet should complete or replace the contents of a file. File template snippets appear in a drop-down menu when you run theSnippets: Populate file from snippetCommand in a new or existing file.

area fragment

Snippets are limited to only suggesting relevant snippets. Fragments can be delimited by:

(Video) Visual Studio Code Crash Course

  1. ANDlanguages)which fragments apply (possibly all)
  2. ANDproject(s)which fragments apply (probably all)

Language fragment scope

Each snippet is limited to one, several, or all ("global") languages, depending on whether it is set to:

  1. ALanguagefragment file
  2. Aglobalfragment file

Single language custom snippets are defined in a snippet file for a specific language (for examplejavascript.json), which you can access using the language identifierSettings: Configure User Fragments. A snippet can only be accessed by editing the language it was set to.

Global and multilingual custom snippets are stored in "global" snippet files (JSON with.code parts), which can also be accessed bySettings: Configure User Fragments. In a global snippet file, a snippet definition can be ato reachProperty lasting one or morelanguage identifier, which makes the snippet available only for the specified languages. Butto reachproperty is given, so the global fragment is available atnolanguages

Most custom snippets are limited to a single language and are therefore defined in a language-specific snippet file.

Project snippet scope

You can also create a global snippets file (JSON with the file suffix.code parts) as part of your project. Project folder fragments are created with theNew snippet file for ''...option onSettings: Configure User Fragmentsdrop-down menu and are located at the root of the project in a.vscodeFile. Project snippet files are useful for sharing snippets with everyone working on that project. Project folder snippets are similar to global snippets and can be restricted to specific languages ​​using theto reachProperty.


ANDBodyInside a fragment you can use special constructs to control the cursor and the inserted text. The following are the supported functions and their syntax:

The table

Tab stops allow you to move the editor's cursor within a passage. To load$ 1,$ 2to set the cursor positions. The number is the order in which the tabs are visited while$ 0denotes the final position of the cursor. Multiple instances of the same tab are linked and updated synchronously.


Placeholders are tabs with values, such as${1:foo}. The placeholder text is inserted and selected so that it can be easily modified. Wildcards can be nested, such as${1:other ${2:placeholder}}.


Placeholders can have options as values. The syntax is a comma-separated enumeration of values ​​between, for example, the pipe character${1|one, two, three|}. When the snippet is pasted and the placeholder is selected, the options will prompt the user to select one of the values.


Swindler$nameÖ${Name:Default}, you can enter the value of a variable. If a variable is not defined, it isStandardor the empty string is inserted. If a variable is unknown (that is, its name is undefined), the variable name is inserted and becomes a placeholder.

(Video) How to use Prettier in VS Code - Code Formatting

The following variables can be used:

  • TM_SELECTED_TEXTThe currently selected text or empty string
  • TM_CURRENT_LINEThe content of the current line
  • TM_CURRENT_WORDThe content of the word under the cursor or the empty string
  • TM_LINE_INDEXRow number is based on index zero
  • TM_LINE_NUMBERRow number based on an index
  • TM_FILENAMEThe filename of the current document.
  • TM_FILENAME_BASEThe filename of the current document without its extensions.
  • TM_DIRECTORYThe current document directory
  • TM_FILEPATHThe full file path of the current document
  • RELATIVE_FILEPATHThe relative file path (to the workspace or open folder) of the current document
  • CLIPBOARDThe contents of your clipboard
  • WORKSPACE_NAMEThe name of the workspace or open folder
  • WORKSPACE_FOLDERThe path of the workspace or open folder
  • INDEX_CURSORThe cursor number based on index zero
  • CURSOR_NUMBERThe cursor number based on an index

To enter the current date and time:

  • CURRENT YEARthe current year
  • CURRENT_YEAR_SHORTThe last two digits of the current year
  • MONTH ISThe month with two digits (example '02')
  • CURRENT_MONTH_NAMEThe full name of the month (example "July")
  • CURRENT_MONTH_SHORT_NAMEThe abbreviated name of the month (example "Jul")
  • CURRENT DATEThe two-digit day of the month (example '08')
  • NOMBRE_CURRENT_DAYThe name of the day (example "Monday")
  • SHORT_NAME_CURRENT_DAYThe abbreviated name of the day (example 'Mon')
  • CURRENT TIMEThe current time in 24-hour format
  • CURRENT_MINUTEThe current minute as two digits
  • CURRENT_SECONDCurrent second as two digits
  • CURRENT_SECONDS_UNIXThe number of seconds since the days of Unix

To enter random values:

  • ARBITRARILY6 random digits in base 10
  • RAND_HEX6 random bases 16 digits
  • UUIDA version 4 UUID

Insert line or block comment respecting the current language:

  • BLOCK_COMMENT_STARTExample output: in PHP/*o de HTML<!--
  • BLOCK_COMMENT_ENDExample output: in PHP*/o de HTML-->
  • LINE_COMMENTExample output: in PHP//

The following snippet is inserted/* Hello World */in JavaScript files and<!-- Hello world -->in HTML files:

{ "Hello": { "to reach":"javascript, html", "Prefix":"Hello", "Body":"$BLOCK_COMMENT_START Hello Welcome $BLOCK_COMMENT_END"}}

variable transformations

Transformations allow you to change the value of a variable before entering it. The definition of a transformation consists of three parts:

  1. A regular expression that is compared to the value of a variable or the empty string if the variable cannot be resolved.
  2. A "format string" that allows matching groups of the regular expression to be referenced. The format string allows conditional insertions and simple modifications.
  3. Options passed to the regular expression.

The following example enters the current filename without an extension, i.e. as long asfoo.txttutFoo.

${TM_FILENAME/(.*)\\..+$/$1/} | | | | | | | |-> no options | | | | | |-> refers to the content of the first | | capture group | | | |-> Regular expression to match everything before | capture final `.suffix` | |-> resolve to filename

placeholder transformation

As with a variable transformation, a placeholder transformation allows you to change the text entered into the placeholder by moving to the next tab stop. The entered text is compared against the regular expression, and the match or matches are replaced with text of the specified replacement format, depending on the option. Each occurrence of a placeholder can independently define its own transformation using the value of the first placeholder. The format for placeholder transformations is the same as for variable transformations.

transform examples

Examples are shown enclosed in double quotes as they would appear in a code snippet to illustrate the need to double escape certain characters. Example transformations and resulting output for filenameSample-123.456-TEST.js.

"${TM_FILENAME/[\\.]/_/}"Sample-123_456-TEST.jsreplace the first.swindler_
"${TM_FILENAME/[\\.-]/_/g}"example_123_456_TEST_jsreplace each one.Ö-swindler_
"${TM_FILENAME/(.*)/${1:/uppercase}/}"EXAMPLE-123.456-TEST.JSswitch to upper case
"${TM_FILENAME/[^0-9^a-z]//gi}"exemplo123456TESTjsRemove non-alphanumeric characters


Below is the EBNF (Extended Backus-Naur form) for fragments. With\(backslash), you can escapep.s,}, j\. In selection elements, the backslash also escapes the comma and vertical bar.

(Video) Visual Studio Code Tips, Tricks, Keyboard Shortcuts and Features Tutorial (VS Code)

any ::= tab | Placeholder | choose | variable | texttabstop ::= '$' int | '${' int '}' | '${' int transform '}'placeholder ::= '${' int ':' any '}'choice ::= '${' int '|' text (',' text)* '|}'variable ::= '$' var | '${' var '}' | '${' var ':' any '}' | '${' var transform '}'transform ::= '/' regex '/' (format | text)+ '/' optionformat ::= '$' int | '${' int '}' | '${' int ':' '/upper case' | '/lower case' | '/upper case' | 'camel box' | '/pascalcase' '}' | '${' int ':+' if '}' | '${' int ':?' if ':' plus '}' | '${' int ':-' plus '}' | '${' int ':' else '}'regex ::= JavaScript regular expression value (ctor-string)Options ::= JavaScript regular expression option (ctor-options)var ::= [_a-zA -Z ] [ _a-zA-Z0-9]*int ::= [0-9]+text ::= .*if ::= textelse ::= text

Using TextMate Fragments

You can also use existing TextMate snippets (.tmSnippets) with VS Code. watch themUsing TextMate FragmentsThread in our Extensions API section for more information.

Map snippets to keyboard shortcuts

You can create customkeyboard shortcutsinsert specific snippets. Openkeybindings.json(Settings: Open keyboard shortcuts file) which defines all keyboard shortcuts and adds a valid keyboard shortcut"Rest"as an additional argument:

{ "I like":"cmd+k 1", "Domain":"editor.action.insertSnippet", "with":"editorTextFocus", "Arguments": { "Rest":"console.log($1)$0"}}

The key combination invokes theinsert snippetBut instead of asking you to choose a snippet, the provided snippet is inserted. You set the custombinding keyas usual with keyboard shortcut, command ID and optionalif the context of the clausewhen the keyboard shortcut is enabled.

Also instead of using theRestArgument value to set your inline fragment, you can refer to an existing fragment usingSprach-IDjNameArguments TheSprach-IDArgument selects the language for which the fragment is specifiedNameis entered, for example, select the following examplemifragmentoFavthat is available fortissue- files.

{ "I like":"cmd+k 1", "Domain":"editor.action.insertSnippet", "with":"editorTextFocus", "Arguments": { "Language":"scharf", "Name":"miFragmentoFav"}}

Next steps

  • Command Line- VS Code has an advanced command line interface for opening or comparing files and installing extensions.
  • Extension API- Learn about other ways to extend VS Code.
  • section guide- You can package snippets for use in VS Code.

common questions

What if I want to use existing TextMate snippets from a .tmSnippet file?

You can easily package TextMate snippet files for use in VS Code. To seeUsing TextMate Fragmentsin our extension API documentation.

How do I get a snippet to insert a variable into the inserted script?

To have a variable in the included script you need to escape the '$' of$variableName so that it is not parsed by the fragment expansion phase.

"Variable Fragment":{ "Prefix":"_Epochs", "Body":"\\$MiVar = 2", "Description":"A simple snippet that inserts a variable prefixed with $ into the script"}

This gives the inserted snippet as:

$MinhaVar =

Can I remove IntelliSense snippets?

Yes, you can hide specific snippets from displaying in IntelliSense (completion list) by selectingHide from IntelliSensebutton to the right of the fragment elements in theinsert snippetCommand drop-down menu.

Excerpts from Visual Studio code (5)

You can still select the fragment withinsert snippetbut the hidden snippet is not displayed in IntelliSense.

(Video) Visual Studio Code Extensions to Improve Your Productivity



1. How to Code a VSCode Extension
(Ben Awad)
2. Docker, Terraform & Ansible tutorials || Demo - 3 || by Mr. Chaitanya On 10-02-2023 @10:30AM IST
(Durga Software Solutions)
3. VSCode = React Extensions To Look Out For In 2022
4. Salesforce Development with Visual Studio Code
(Salesforce Developers)
5. VS Code tips — Select all occurrences of find match
(Code 2020)
6. 15 VS Code Extensions For Front-End Developers in 2019
(Traversy Media)


Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated: 23/09/2023

Views: 6139

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.