Create your own snippets in VS Code

 

Create your own snippets#

You can easily define your own snippets without any extension. To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages. VS Code manages the creation and refreshing of the underlying snippets file(s) for you.

snippet dropdown

Snippets files are written in JSON, support C-style comments, and can define an unlimited number of snippets. Snippets support most TextMate syntax for dynamic behavior, intelligently format whitespace based on the insertion context, and allow easy multiline editing.

Below is an example of a for loop snippet for JavaScript:

// in file 'Code/User/snippets/javascript.json'
{
  "For Loop": {
    "prefix": ["for", "for-const"],
    "body": ["for (const ${2:element} of ${1:array}) {", "\t$0", "}"],
    "description": "A for loop."
  }
}

In the example above:

  • "For Loop" is the snippet name. It is displayed via IntelliSense if no description is provided.
  • prefix defines one or more trigger words that display the snippet in IntelliSense. Substring matching is performed on prefixes, so in this case, "fc" could match "for-const".
  • body is one or more lines of content, which will be joined as multiple lines upon insertion. Newlines and embedded tabs will be formatted according to the context in which the snippet is inserted.
  • description is an optional description of the snippet displayed by IntelliSense.

Additionally, the body of the example above has three placeholders (listed in order of traversal): ${1:array}${2:element}, and $0. You can quickly jump to the next placeholder with Tab, at which point you may edit the placeholder or jump again the next one. The string after the colon (if any) is the default text, for example element in ${2:element}. Placeholder traversal order is ascending by number, starting from one; zero is an optional special case that always comes last, and exits snippet mode with the cursor at the specified position.

Snippet scope#

Snippets are scoped so that only relevant snippets are suggested. Snippets can be scoped by either:

  1. the language(s) to which snippets are scoped (possibly all)
  2. the project(s) to which snippets are scoped (probably all)

Language snippet scope#

Every snippet is scoped to one, several, or all ("global") languages based on whether it is defined in:

  1. language snippet file
  2. global snippet file

Single-language user-defined snippets are defined in a specific language's snippet file (for example javascript.json), which you can access by language identifier through Preferences: Configure User Snippets. A snippet is only accessible when editing the language for which it is defined.

Multi-language and global user-defined snippets are all defined in "global" snippet files (JSON with the file suffix .code-snippets), which is also accessible through Preferences: Configure User Snippets. In a global snippets file, a snippet definition may have an additional scope property that takes one or more language identifiers, which makes the snippet available only for those specified languages. If no scope property is given, then the global snippet is available in all languages.

Most user-defined snippets are scoped to a single language, and so are defined in a language-specific snippet file.

Project snippet scope#

You can also have a global snippets file (JSON with file suffix .code-snippets) scoped to your project. Project-folder snippets are created with the New Snippets file for ''... option in the Preferences: Configure User Snippets dropdown menu and are located at the root of the project in a .vscode folder. Project snippet files are useful for sharing snippets with all users working in that project. Project-folder snippets are similar to global snippets and can be scoped to specific languages through the scope property.

Snippet syntax#

The body of a snippet can use special constructs to control cursors and the text being inserted. The following are supported features and their syntaxes:

Tabstops#

With tabstops, you can make the editor cursor move inside a snippet. Use $1$2 to specify cursor locations. The number is the order in which tabstops will be visited, whereas $0 denotes the final cursor position. Multiple occurrences of the same tabstop are linked and updated in sync.

Placeholders#

Placeholders are tabstops with values, like ${1:foo}. The placeholder text will be inserted and selected such that it can be easily changed. Placeholders can be nested, like ${1:another ${2:placeholder}}.

Choice#

Placeholders can have choices as values. The syntax is a comma-separated enumeration of values, enclosed with the pipe-character, for example ${1|one,two,three|}. When the snippet is inserted and the placeholder selected, choices will prompt the user to pick one of the values.

Variables#

With $name or ${name:default}, you can insert the value of a variable. When a variable isn't set, its default or the empty string is inserted. When a variable is unknown (that is, its name isn't defined) the name of the variable is inserted and it is transformed into a placeholder.

The following variables can be used:

  • TM_SELECTED_TEXT The currently selected text or the empty string
  • TM_CURRENT_LINE The contents of the current line
  • TM_CURRENT_WORD The contents of the word under cursor or the empty string
  • TM_LINE_INDEX The zero-index based line number
  • TM_LINE_NUMBER The one-index based line number
  • TM_FILENAME The filename of the current document
  • TM_FILENAME_BASE The filename of the current document without its extensions
  • TM_DIRECTORY The directory of the current document
  • TM_FILEPATH The full file path of the current document
  • RELATIVE_FILEPATH The relative (to the opened workspace or folder) file path of the current document
  • CLIPBOARD The contents of your clipboard
  • WORKSPACE_NAME The name of the opened workspace or folder
  • WORKSPACE_FOLDER The path of the opened workspace or folder

For inserting the current date and time:

  • CURRENT_YEAR The current year
  • CURRENT_YEAR_SHORT The current year's last two digits
  • CURRENT_MONTH The month as two digits (example '02')
  • CURRENT_MONTH_NAME The full name of the month (example 'July')
  • CURRENT_MONTH_NAME_SHORT The short name of the month (example 'Jul')
  • CURRENT_DATE The day of the month as two digits (example '08')
  • CURRENT_DAY_NAME The name of day (example 'Monday')
  • CURRENT_DAY_NAME_SHORT The short name of the day (example 'Mon')
  • CURRENT_HOUR The current hour in 24-hour clock format
  • CURRENT_MINUTE The current minute as two digits
  • CURRENT_SECOND The current second as two digits
  • CURRENT_SECONDS_UNIX The number of seconds since the Unix epoch

For inserting random values:

  • RANDOM 6 random Base-10 digits
  • RANDOM_HEX 6 random Base-16 digits
  • UUID A Version 4 UUID

For inserting line or block comments, honoring the current language:

  • BLOCK_COMMENT_START Example output: in PHP /* or in HTML <!--
  • BLOCK_COMMENT_END Example output: in PHP */ or in HTML -->
  • LINE_COMMENT Example output: in PHP //

The snippet below inserts /* Hello World */ in JavaScript files and <!-- Hello World --> in HTML files:

{
  "hello": {
    "scope": "javascript,html",
    "prefix": "hello",
    "body": "$BLOCK_COMMENT_START Hello World $BLOCK_COMMENT_END"
  }
}

Variable transforms#

Transformations allow you to modify the value of a variable before it is inserted. The definition of a transformation consists of three parts:

  1. A regular expression that is matched against the value of a variable, or the empty string when the variable cannot be resolved.
  2. A "format string" that allows to reference matching groups from the regular expression. The format string allows for conditional inserts and simple modifications.
  3. Options that are passed to the regular expression.

The following example inserts the name of the current file without its ending, so from foo.txt it makes foo.

${TM_FILENAME/(.*)\\..+$/$1/}
  |           |         |  |
  |           |         |  |-> no options
  |           |         |
  |           |         |-> references the contents of the first
  |           |             capture group
  |           |
  |           |-> regex to capture everything before
  |               the final `.suffix`
  |
  |-> resolves to the filename

Placeholder-Transform#

Like a Variable-Transform, a transformation of a placeholder allows changing the inserted text for the placeholder when moving to the next tab stop. The inserted text is matched with the regular expression and the match or matches - depending on the options - are replaced with the specified replacement format text. Every occurrence of a placeholder can define its own transformation independently using the value of the first placeholder. The format for Placeholder-Transforms is the same as for Variable-Transforms.

Transform examples#

The examples are shown within double quotes, as they would appear inside a snippet body, to illustrate the need to double escape certain characters. Sample transformations and the resulting output for the filename example-123.456-TEST.js.

ExampleOutputExplanation
"${TM_FILENAME/[\\.]/_/}"example-123_456-TEST.jsReplace the first . with _
"${TM_FILENAME/[\\.-]/_/g}"example_123_456_TEST_jsReplace each . or - with _
"${TM_FILENAME/(.*)/${1:/upcase}/}"EXAMPLE-123.456-TEST.JSChange to all uppercase
"${TM_FILENAME/[^0-9^a-z]//gi}"example123456TESTjsRemove non-alphanumeric characters

Grammar#

Below is the EBNF (extended Backus-Naur form) for snippets. With \ (backslash), you can escape $}, and \. Within choice elements, the backslash also escapes comma and pipe characters.

any         ::= tabstop | placeholder | choice | variable | text
tabstop     ::= '$' int
                | '${' int '}'
                | '${' int  transform '}'
placeholder ::= '${' int ':' any '}'
choice      ::= '${' int '|' text (',' text)* '|}'
variable    ::= '$' var | '${' var '}'
                | '${' var ':' any '}'
                | '${' var transform '}'
transform   ::= '/' regex '/' (format | text)+ '/' options
format      ::= '$' int | '${' int '}'
                | '${' int ':' '/upcase' | '/downcase' | '/capitalize' | '/camelcase' | '/pascalcase' '}'
                | '${' int ':+' if '}'
                | '${' int ':?' if ':' else '}'
                | '${' int ':-' else '}' | '${' 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        ::= .*

Using TextMate snippets#

You can also use existing TextMate snippets (.tmSnippets) with VS Code. See the Using TextMate Snippets topic in our Extension API section to learn more.

Assign keybindings to snippets#

You can create custom keybindings to insert specific snippets. Open keybindings.json (Preferences: Open Keyboard Shortcuts File), which defines all your keybindings, and add a keybinding passing "snippet" as an extra argument:

{
  "key": "cmd+k 1",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "snippet": "console.log($1)$0"
  }
}

The keybinding will invoke the Insert Snippet command but instead of prompting you to select a snippet, it will insert the provided snippet. You define the custom keybinding as usual with a keyboard shortcut, command ID, and optional when clause context for when the keyboard shortcut is enabled.

Also, instead of using the snippet argument value to define your snippet inline, you can reference an existing snippet by using the langId and name arguments. The langId argument selects the language for which the snippet denoted by name is inserted, e.g the sample below selects the myFavSnippet that's available for csharp-files.

{
  "key": "cmd+k 1",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "langId": "csharp",
    "name": "myFavSnippet"
  }
}

Next steps#

  • Command Line - VS Code has a rich command-line interface to open or diff files and install extensions.
  • Extension API - Learn about other ways to extend VS Code.
  • Snippet 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 snippets files for use in VS Code. See Using TextMate Snippets in our Extension API documentation.

How do I have a snippet place a variable in the pasted script?#

To have a variable in the pasted script, you need to escape the '$' of the $variable name so that it isn't parsed by the snippet expansion phase.

"VariableSnippet":{
    "prefix": "_Var",
    "body": "\\$MyVar = 2",
    "description": "A basic snippet that places a variable into script with the $ prefix"
  }

This results in the pasted snippet as:

$MyVar = 2

Can I remove snippets from IntelliSense?#

Yes, you can hide specific snippets from showing in IntelliSense (completion list) by selecting the Hide from IntelliSense button to the right of snippet items in the Insert Snippet command dropdown.

Hide from IntelliSense button in Insert Snippet dropdown

You can still select the snippet with the Insert Snippet command but the hidden snippet won't be displayed in IntelliSense.

Continue Reading...

Data Types and Methods in AL

 

TypeDescription
BigIntegerStores very large whole numbers that range from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807.
BigTextHandles large text documents.
BlobIs a complex data type. Variables of this data type differ from normal numeric and string variables in that BLOBs have a variable length. The maximum size of a BLOB(binary large object) is 2 GB.
BooleanIndicates true or false.
ByteStores a single, 8-bit character as a value in the range 0 to 255. You can easily convert this data type from a number to a character and vice versa. This means you can use mathematical operators on Byte variables.
CharStores a single, 16-bit character as a value in the range 0 to 65535. You can convert this data type from a number to a character and vice versa. This means you can use mathematical operators on Char variables.
CodeDenotes a special type of string that is converted to uppercase and removes any trailing or leading spaces.
CodeunitIs a container for AL code that you can use from other application objects.
CompanyPropertyProvides language support for company properties.
DatabaseProvides access to common database functionality.
DateDenotes a date ranging from January 1, 1753 to December 31, 9999.
DateFormulaRepresents a date formula that has the same capabilities as an ordinary input string for the CALCDATE Method (Date). The DateFormula data type is used to provide multilanguage capabilities to the CALCDATE Method (Date).
DateTimeDenotes a date and time ranging from January 1, 1753, 00:00:00.000 to December 31, 9999, 23:59:59.999. An undefined or blank DateTime is specified by 0DT.
DebuggerEnables communication with a debugger.
DecimalDenotes decimal numbers ranging from -999,999,999,999,999.99 to +999,999,999,999,999.99.
DialogRepresents a dialog window.
DictionaryRepresents an unordered collection of keys and values. The Dictionary data type is optimized for fast lookup of values.
DotNetRepresents an unspecified .NET type.
DurationRepresents the difference between two DateTimes. This value can be negative. It is stored as a 64-bit integer. The integer value is the number of milliseconds during the duration.
EnumRepresents the text content of an element or attribute.
ErrorInfoProvides a structure for grouping information about an error.
FieldRefIdentifies a field in a table and gives you access to this field.
FileRepresents a file.
FilterPageBuilderStores filter configurations for a filter page. A filter page is a dynamic page type that contains one or more filter controls that enables users to set filters on fields of the underlying tables.
GuidRepresents a 16 byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which assures this uniqueness.
HttpClientProvides a data type for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
HttpContentRepresents an HTTP entity body and content headers.
HttpHeadersIs a collection of headers and their values.
HttpRequestMessageRepresents an HTTP request message.
HttpResponseMessageRepresents a HTTP response message including the status code and data.
InStreamIs a generic stream object that you can use to read from or write to files and BLOBs. You can define the internal structure of a stream as a flat stream of bytes. You can assign one stream to another. Reading from and writing to a stream occurs sequentially.
IntegerStores whole numbers with values that range from -2,147,483,647 to 2,147,483,647.
IsolatedStorageProvides data isolation for extensions.
AnyThis data type can be substituted by any other data type.
JsonArrayIs a container for any well-formed JSON array. A default JsonArray contains an empty JSON array.
JsonObjectIs a container for any well-formed JSON object. A default JsonObject contains an empty JSON object.
JsonTokenIs a container for any well-formed JSON data. A default JsonToken object contains the JSON value of NULL.
JsonValueIs a container for any well-formed fundamental JSON value. A default JsonValue is set to the JSON value of NULL.
KeyRefIdentifies a key in a table and the fields in this key.
LabelDenotes a string constant that can be optionally translated into multiple languages.
ListRepresents a strongly typed list of ordered objects that can be accessed by index. Contrary to the Array data type, a List is unbounded, such that its dimension does not need to be specified upon declaration.
MediaEncapsulates media files, such as image .jpg and .png files, in application database tables. The Media data type can be used as a table field data type, but cannot be used as a variable or parameter. The Media data type enables you to import a media file to the application database and reference the file from records, making it possible to display the media file in the client user interface. You can also export media from the database to files and streams.
MediaSetEncapsulates media, such as images, in application database tables.
ModuleDependencyInfoProvides information about a dependent module.
ModuleInfoRepresents information about an application consumable from AL.
NavAppProvides information about a NavApp.
NoneIs used implicitly when a method does not return a value.
NotificationProvides a programmatic way to send non-intrusive information to the user interface (UI) in the Business Central Web client.
NumberSequenceIs a complex data type for creating and managing number sequences in the database.
SessionInformationIs a complex data type for exposing Session information into AL.
OptionDenotes an option value. In the code snippet below, you can see how the Option data type is declared.
OutStreamIs a generic stream object that you can use to write to files and BLOBs.
PageContains a number of simpler elements called controls. Controls are used to display information to the user or receive information from the user.
ProductNameAn application can have a full name, marketing name, and short name. The PRODUCTNAME functions enable you to retrieve these name variations.
QueryEnables you to retrieve data from multiple tables and combine the data in single dataset.
RecordIdContains the table number and the primary key of a table.
RecordRefReferences a record in a table.
ReportIs used to display, print, or process information from a database.
RequestPageIs a page that is run before the report starts to execute. Request pages enable end-users to specify options and filters for a report.
SessionRepresents a Microsoft Dynamics Business Central session.
SessionSettingsIs a complex data type for passing user personalization settings for a client session as an object. The object contains properties that correspond to the fields in the system table 2000000073 User Personalization, including: App ID, Company, Language ID, Locale ID, Profile ID, Scope, and Time Zone. You can use the AL methods of the SessionSettings data type to get, set, and send the user personalization settings for the current client session.
TextDenotes a sequence of characters. It can be represented by a string literal, a text value or a code value.
SystemIs a complex data type.
RecordIs a complex data type.
TaskSchedulerIs a complex data type for creating and managing tasks in the task scheduler, which runs codeunits at scheduled times.
TestActionRepresents a test action on a page.
TestFieldRepresents a testable field on a page.
TestFilterRepresents a test filter on a page.
TestFilterFieldRepresents the type of a field filter in a test filter on a page or on a request page.
TestPageRepresents a variable type that can be used to test Page Application Objects.
TestPartRepresents a variable type that can be used to test Page Application Objects of type Part.
TestRequestPageStores test request pages. A test request page part is a logical representation of a request page on a report. A test request page does not display a user interface (UI). The subtype of a test request page is the report whose request page you want to test.
TextDenotes a text string.
TextConstDenotes a multi-language string constant.
TextBuilderRepresents a lighweight wrapper for the .Net implementation of StringBuilder.
TimeDenotes a time ranging from 00:00:00.000 to 23:59:59.999. An undefined or blank time is specified by 0T.
VariantRepresents an AL variable object. The AL variant data type can contain many AL data types.
VersionRepresents a version matching the format: Major.Minor.Build.Revision .
WebServiceActionContextRepresents an AL WebServiceActionContext.
XmlAttributeRepresents an XML attribute.
XmlAttributeCollectionRepresents a collection of XML attributes.
XmlCDataRepresents a CData section.
XmlCommentRepresents an XML comment.
XmlDeclarationRepresents an XML declaration.
XmlDocumentRepresents an XML document.
XmlDocumentTypeRepresents an XML document type.
XmlElementRepresents an XML element.
XmlNamespaceManagerRepresents a namespace manager that can be used to resolve, add and remove namespaces to a collection. It also provides scope management for these namespaces.
XmlNameTableRepresents a table of atomized string objects.
XmlNodeRepresents a XML node which can either be for instance an XML attribute, an XML element or a XML document.
XmlNodeListRepresents a collection of XML nodes.
XmlportXmlPorts are used to export or import data between an external source and a Microsoft Dynamics Business Central database.
XmlProcessingInstructionRepresents a processing instruction, which XML defines to keep processor-specific information in the text of the document.
XmlReadOptionsRepresents the options configuring how XML is loaded from a data source.
XmlTextRepresents the text content of an element or attribute.
XmlWriteOptionsRepresents the options configuring how XML is saved.
ActionRepresents the action that the user took on the page.
AuditCategoryRepresents an audit category for IfX audit telemetry.
ClientTypeRepresents the type of the client executing the operation.
CommitBehaviorSpecifies whether commit is allowed within the scope of the method.
DataClassificationSets the classification of the data in the table or field.
DataScopeIdentifies the scope of stored data in the isolated storage.
DefaultLayoutThe default layout to be used by a report.
ErrorBehaviorSpecifies whether errors will be collected within the scope of the method.
ErrorTypeRepresents the type of error.
ExecutionContextRepresents the context in which a session is running. In certain scenarios, for example during upgrade, the system will run a session in a special context for a limited time.
ExecutionModeThe execution mode of the current session.
FieldClassRepresents the type of a field class.
FieldTypeRepresents the type of a table field.
NotificationScopeSpecifies the context in which the notification appears in the client.
ObjectTypeThe different types of objects.
PageBackgroundTaskErrorLevelSpecifies how an error in the page background task appears in the client.
PermissionObjectTypeThe different types of objects that can have different permissions assigned.
ReportFormatSpecifies the format of the report.
ReportLayoutTypeRepresents the type of a report layout.
SecurityFilterSpecifies how security filters are applied to the record.
SecurityOperationResultRepresents security audit operation result.
TableConnectionTypeUse variables of this data type to specify the type of connection to an external database.
TelemetryScopeRepresents the emission scope of the telemetry signal.
TestPermissionsSpecifies a value that can be used to determine which permission sets are used on tests that are run by test codunits or test functions.
TextEncodingRepresents a file encoding.
TransactionModelRepresents a test transaction model.
TransactionTypeRepresents a transaction type.
VerbosityRepresents the security level of events.
WebServiceActionResultCodeRepresents a web service action status code.
Continue Reading...