Syntax definitions make Sublime Text aware of programming and markup languages.Most noticeably, they work together with colors to provide syntax highlighting.Syntax definitions define scopes that divide the text in a buffer into namedregions. Several editing features in Sublime Text make extensive use ofthis fine-grained contextual information.
Essentially, syntax definitions consist of regular expressions used to findtext, as well as more or less arbitrary, dot-separated strings called scopesor scope names. For every occurrence of a given regular expression, SublimeText gives the matching text its corresponding scope name.
To create a first snippet in Sublime Text editor, click the Tools menu and select the Snippets option from the drop down window, as shown in the screenshot here. Now, choose Snippet:html from the options displayed. CodeMirror is a versatile text editor implemented in JavaScript for the browser. It is specialized for editing code, and comes with a number of language modes and addons that implement more advanced editing functionality.
Deprecation Notice
For Sublime Text 3 (Build 3084),a new syntax definition format has been addedwith the .sublime-syntax
extension.
It is highly encouraged to be usedin favor of the legacy TextMate formatdescribed in this document,unless compatibility with older versionsor other editors is desired.
Documentation is availableat the official documentation(opens new window).
# Prerequisites
In order to follow this tutorial, you will need to installPackageDev(opens new window), a packageintended to ease the creation of new syntax definitions for SublimeText. Follow the installation notes in the 'Getting Started' section ofthe readme.
# File format
Sublime Text uses property list(opens new window)(Plist) files to store syntax definitions. However, because editing XML files isa cumbersome task, we'll use YAML(opens new window) insteadand convert it to Plist format afterwards. This is where the PackageDev package(mentioned above) comes in.
Note
If you experience unexpected errors during this tutorial, chances arePackageDev or YAML is to blame. Don't immediately think your problem isdue to a bug in Sublime Text.
By all means, do edit the Plist files by hand if you prefer to work inXML, but always keep in mind their differing needs in regards to escapesequences, many XML tags etc.
# Scopes
Scopes are a key concept in Sublime Text. Essentially, they are namedtext regions in a buffer. They don't do anything by themselves, butSublime Text peeks at them when it needs contextual information.
For instance, when you trigger a snippet, Sublime Text checks the scopebound to the snippet and looks at the caret's position in the file. Ifthe caret's current position matches the snippet's scope selector,Sublime Text fires it off. Otherwise, nothing happens.
Info
There's a slight difference between scopes and scope selectors: Scopesare the names defined in a syntax definition, while scope selectors are usedin items like snippets and key bindings to target scopes. When creating anew syntax definition, you care about scopes; when you want to constrain asnippet to a certain scope, you use a scope selector.
Scopes can be nested to allow for a high degree of granularity. You can drilldown the hierarchy very much like with CSS selectors. For instance, thanks toscope selectors, you could have a key binding activated only within singlequoted strings in Python source code, but not inside single quoted strings inany other language.
Sublime Text inherits the idea of scopes from Textmate, a text editor for Mac.Textmate's online manual(opens new window) contains further information about scope selectorsthat's useful for Sublime Text users too. In particular, Color Schemes makeextensive use of scopes to style every aspect of a language in the desiredcolor.
# How Syntax Definitions Work
At their core, syntax definitions are arrays of regular expressionspaired with scope names. Sublime Text will try to match these patternsagainst a buffer's text and attach the corresponding scope name to alloccurrences. These pairs of regular expressions and scope names areknown as rules.
Rules are applied in order, one line at a time. Rules are applied in thefollowing order:
- The rule that matches at the first position in a line
- The rule that comes first in the array
Each rule consumes the matched text region, which therefore will beexcluded from the next rule's matching attempt (save for a fewexceptions). In practical terms, this means that you should take care togo from more specific rules to more general ones when you create a newsyntax definition. Otherwise, a greedy regular expression might swallowparts you'd like to have styled differently.
Syntax definitions from separate files can be combined, and they can berecursively applied too.
# Your First Syntax Definition
By way of example, let's create a syntax definition for Sublime Textsnippets. We'll be styling the actual snippet content, not the whole.sublime-snippet
file.
Note
Since syntax definitions are primarily used to enable syntax highlighting,we'll use the phrase to style to mean to break down a source code fileinto scopes. Keep in mind, however, that colors are a different thing fromsyntax definitions and that scopes have many more uses besides syntaxhighlighting.
Here are the elements we want to style in a snippet:
- Variables (
$PARAM1
,$USER_NAME
..) - Simple fields (
$0
,$1
..) - Complex fields with placeholders (
${1:Hello}
) - Nested fields (
${1:Hello ${2:World}!}
) - Escape sequences (
$
,<
, …) - Illegal sequences (
$
,<
,, …)
Here are the elements we don't want to style because they are too complex forthis example:
- Variable Substitution (
${1/Hello/Hi/g}
)
Note
Before continuing, make sure you've installed the PackageDev package asexplained above.
# Creating A New Syntax Definition
To create a new syntax definition, follow these steps:
- Go to Tools | Packages | Package Development | New SyntaxDefinition
- Save the new file in your
Packages/User
folder as a.YAML-tmLanguage
file.
You now should see a file like this:
Let's examine the key elements.
name
The name that Sublime Text will display in the syntax definitiondrop-down list. Use a short, descriptive name. Typically, you willuse the name of the programming language you are creating the syntaxdefinition for.scopeName
Adobe untuk edit video. The topmost scope for this syntax definition. It takes the formsource.
ortext.
. For programminglanguages, usesource
. For markup and everything else, usetext
.fileTypes
This is a list of file extensions (without the leading dot). Whenopening files of these types, Sublime Text will automaticallyactivate this syntax definition for them.uuid
This is a unique identifier for this syntax definition. Each newsyntax definition gets its own uuid. Even though Sublime Text itselfignores it, don't modify this.patterns
A container for your patterns.
For our example, fill the template with the following information:
Download Sublime Text Editor 3
Note
YAML is not a very strict format, but can cause headaches when you don'tknow its conventions. It supports single and double quotes, but you may alsoomit them as long as the content does not create another YAML literal. Ifthe conversion to Plist fails, take a look at the output panel for moreinformation on the error. We'll explain later how to convert a syntaxdefinition in YAML to Plist. This will also cover the first commented linein the template.
The ---
and ..
are optional.
# Analyzing Patterns
The patterns
array can contain several types of element. We'll look atsome of them in the following sections. If you want to learn more aboutpatterns, refer to Textmate's online manual.
# Matches
Matches take this form:
Sublime Text uses Oniguruma(opens new window)'s syntax for regular expressions insyntax definitions. Several existing syntax definitions make use offeatures supported by this regular expression engine that aren't part ofperl-style regular expressions, hence the requirement for Oniguruma.
match
- A regular expression Sublime Text will use to find matches.
name
- The name of the scope that should be applied to any occurrences of
match
. comment
- An optional comment about this pattern.
Let's go back to our example. It looks like this:
That is, make sure the patterns
array is empty.
Now we can begin to add our rules for Sublime snippets. Let's start withsimple fields. These could be matched with a regex like so:
We can then build our pattern like this:
Choosing the Right Scope Name
Naming scopes isn't obvious sometimes. Check the Textmate namingconventions(opens new window) for guidance on scope names. PackageDev automaticallyprovides completions for scope names according to these conventions. Itis important to re-use the basic categories outlined there if you wantto achieve the highest compatibility with existing colors.
name
The name that Sublime Text will display in the syntax definitiondrop-down list. Use a short, descriptive name. Typically, you willuse the name of the programming language you are creating the syntaxdefinition for.scopeName
Adobe untuk edit video. The topmost scope for this syntax definition. It takes the formsource.
ortext.
. For programminglanguages, usesource
. For markup and everything else, usetext
.fileTypes
This is a list of file extensions (without the leading dot). Whenopening files of these types, Sublime Text will automaticallyactivate this syntax definition for them.uuid
This is a unique identifier for this syntax definition. Each newsyntax definition gets its own uuid. Even though Sublime Text itselfignores it, don't modify this.patterns
A container for your patterns.
For our example, fill the template with the following information:
Download Sublime Text Editor 3
Note
YAML is not a very strict format, but can cause headaches when you don'tknow its conventions. It supports single and double quotes, but you may alsoomit them as long as the content does not create another YAML literal. Ifthe conversion to Plist fails, take a look at the output panel for moreinformation on the error. We'll explain later how to convert a syntaxdefinition in YAML to Plist. This will also cover the first commented linein the template.
The ---
and ..
are optional.
# Analyzing Patterns
The patterns
array can contain several types of element. We'll look atsome of them in the following sections. If you want to learn more aboutpatterns, refer to Textmate's online manual.
# Matches
Matches take this form:
Sublime Text uses Oniguruma(opens new window)'s syntax for regular expressions insyntax definitions. Several existing syntax definitions make use offeatures supported by this regular expression engine that aren't part ofperl-style regular expressions, hence the requirement for Oniguruma.
match
- A regular expression Sublime Text will use to find matches.
name
- The name of the scope that should be applied to any occurrences of
match
. comment
- An optional comment about this pattern.
Let's go back to our example. It looks like this:
That is, make sure the patterns
array is empty.
Now we can begin to add our rules for Sublime snippets. Let's start withsimple fields. These could be matched with a regex like so:
We can then build our pattern like this:
Choosing the Right Scope Name
Naming scopes isn't obvious sometimes. Check the Textmate namingconventions(opens new window) for guidance on scope names. PackageDev automaticallyprovides completions for scope names according to these conventions. Itis important to re-use the basic categories outlined there if you wantto achieve the highest compatibility with existing colors.
Color schemes have hardcoded scope names in them. They could notpossibly include every scope name you can think of, so they target thestandard ones plus some rarer ones on occasion (like for CSS orMarkdown). This means that two color schemes using the same syntaxdefinition may render the text differently!
Bear in mind too that you should use the scope name that best suits yourneeds or preferences. It'd be perfectly fine to assign a scope likeconstant.numeric
to anything other than a number if you have a goodreason to do so.
And we can add it to our syntax definition too:
Note British accent voice changer for skype.
You should use two spaces for indent. This is the recommended indent forYAML and lines up with lists like shown above.
We're now ready to convert our file to .tmLanguage
. Syntax definitions useTextmate's .tmLanguage
extension for compatibility reasons. As explainedabove, they are simply Plist XML files.
Follow these steps to perform the conversion:
- Make sure that
Automatic
is selected in Tools | Build System, orselectConvert to ..
. - Press CtrlB.A
.tmLanguage
file will be generated for you in the same folder asyour.YAML-tmLanguage
file. - Sublime Text will reload the changes to the syntax definition.
In case you are wondering why PackageDev knows what you want to convert yourfile to: It's specified in the first comment line.
You have now created your first syntax definition. Next, open a new file andsave it with the extension .ssraw
. The buffer's syntax name should switch to'Sublime Snippet (Raw)' automatically, and you should get syntax highlighting ifyou type $1
or any other simple snippet field.
Let's proceed to creating another rule for environment variables.
Repeat the above steps to update the .tmLanguage
file.
# Fine Tuning Matches
You might have noticed, for instance, that the entire text in $PARAM1
isstyled the same way. Depending on your needs or your personal preferences, youmay want the $
to stand out. That's where captures
come in. Usingcaptures, you can break a pattern down into components to target themindividually.
Let's rewrite one of our previous patterns to use captures
:
Captures introduce complexity to your rule, but they are pretty straightforward.Notice how numbers refer to parenthesized groups left to right. Of course, youcan have as many capture groups as you want.
Note
Writing 1
on a new line and pressing tab will autocomplete to '1': {name: }
thanks to PackageDev.
Arguably, you'd want the other scope to be visually consistent with this one.Go ahead and change it too.
Note
As with ususal regular expressions and substitutions, the capture group'0'
applies to the whole match.
# Begin-End Rules
Up to now we've been using a simple rule. Although we've seen how todissect patterns into smaller components, sometimes you'll want totarget a larger portion of your source code that is clearly delimited bystart and end marks.
Literal strings enclosed by quotation marks or other delimitingconstructs are better dealt with by begin-end rules. This is a skeletonfor one of these rules:
Well, at least in their simplest version. Let's take a look at one thatincludes all available options:
Some elements may look familiar, but their combination might bedaunting. Let's inspect them individually.
name
- Just like with simple captures this sets the following scope name tothe whole match, including
begin
andend
marks. Effectively,this will create nested scopes forbeginCaptures
,endCaptures
andpatterns
defined within this rule. Optional. contentName
- Unlike the
name
this only applies a scope name to the enclosedtext. Optional. begin
- Regex for the opening mark for this scope.
end
- Regex for the end mark for this scope.
beginCaptures
- Captures for the
begin
marker. They work like captures for simplematches. Optional. endCaptures
- Same as
beginCaptures
but for theend
marker. Optional. patterns
- An array of patterns to match only against the begin-end'scontent; they aren't matched against the text consumed by
begin
orend
themselves. Optional.
We'll use this rule to style nested complex fields in snippets:
This is the most complex pattern we'll see in this tutorial. The begin
andend
keys are self-explanatory: they define a region enclosed between${:
and }
. We need to wrap the begin pattern into quotes becauseotherwise the trailing :
would tell the parser to expect anotherdictionary key. beginCaptures
further divides the begin mark into smallerscopes.
The most interesting part, however, is patterns
. Recursion, and theimportance of ordering, have finally made their appearance here.
We've seen above that fields can be nested. In order to account for this, weneed to style nested fields recursively. That's what the include
rule doeswhen we furnish it the $self
value: it recursively applies our entiresyntax definition to the text captured by our begin-end rule. This portionexcludes the text individually consumed by the regexes for begin
andend
.
Remember, matched text is consumed; thus, it is excluded from the next matchattempt and can't be matched again.
To finish off complex fields, we'll style placeholders as strings. Since we'vealready matched all possible tokens inside a complex field, we can safely tellSublime Text to give any remaining text (.
) a literal string scope. Notethat this doesn't work if we made the pattern greedy (.+
) because thisincludes possible nested references.
Note
We could've used contentName: string.other.ssraw
instead of the lastpattern but this way we introduce the importance of ordering and how matchesare consumed.
# Final Touches
Lastly, let's style escape sequences and illegal sequences, and then wecan wrap up.
The only hard thing here is not forgetting that []
enclose arrays inYAML and thus must be wrapped in quotes. Other than that, the rules arepretty straightforward if you're familiar with regular expressions.
However, you must take care to place the second rule after any othersmatching the $
character, since otherwise it will be consumed andresult in every following expression not matching.
Also, even after adding these two additional rules, note that ourrecursive begin-end rule from above continues to work as expected.
At long last, here's the final syntax definition:
There are more available constructs and code reuse techniques using a'repository', but the above explanations should get you started with thecreation of syntax definitions.
Note
If you previously used JSON for syntax definitions you are still able to dothis because PackageDev is backwards compatible.
If you want to consider switching to YAML (either from JSON or directly fromPlist), it provides a command named PackageDev: Convert to YAML and Rearrange Syntax Definition
which will automatically format the resultingYAML in a pleasurable way.
You'll already be familiar with a text editor if you've taken any Codecademy courses. Below is the Codecademy text editor in full screen at the end of the first module of the HTML course.
While Codecademy's learning environment provides an intuitive and user-friending coding experience, sometimes you'll need to use your own text editor. For example, if you decide to attend a Meetup or in-person coding course, they will use a downloadable text editor, and you'll need to install this to work on projects both in class and at home.
I've dabbled with a few text editors to get a better feel for what suits my needs best. This is crucial as there is no 'best' text editor out there, only the one that you allows you to create your best work.
In this article, I'll provide an in-depth comparison of two of the most popular text editors: Visual Studio and Sublime Text.
Visual Studio
Visual Studio (the text editor is known as Visual Studio Code so we'll refer to that from now on) is Microsoft's free text editor that runs on Windows, Linux, and macOS. It's a recent entrant to the market; Microsoft released the product as a public preview at the end of 2015, posting the open source code to Github, before making it available as a general release in April 2016.
Despite its newbie status, Visual Studio Code has rapidly gained popularity among developers, ranking as the most popular development environment overall in Stack Overflow's 2018 Developer Survey.
The basics
This is what Visual Studio Code's home screen looks like when you write your first line of code or open a file that you have already created:
In the top left panel, you can see the different variations of code you are editing. In this case, I'm editing a file called 'style.css.'
The middle panel is where you edit the code you have written or need to fix; you can open and edit several different files side-by-side.
The Visual Studio layout bears a similarity to Codecademy's own text editor layout in its simplicity and ease of use. Take a look at Codecademy's text editor below for a comparison.
You can, of course, edit the layout as well. Zen Mode is one of my favorites, especially because it sounds so relaxing. In reality, this is a full screen mode that allows you to edit code with no distractions.
More Features
Visual Studio Code allows you to edit code in a wide variety of programming languages. The example I used above is CSS (yes, I am classifying CSS as a coding language!). CSS is one of the built in programming languages, but you can install and configure other languages, such as Python and C#, via the Extension Marketplace.
Debugging
One of the classic exercises you'll do when learning to program is to 'break' some code and then try to fix it again. In my early days of programming, I spent ages staring at lines of code until my eyes went blurry, trying to work out why what I'd written wasn't reflected in the final product.
Thankfully, Visual Studio Code includes debugging functionality to help detect those errors before you reach the blurry-eye stage. To start debugging your code, all you need to do is either press F5 to run it in your current window, or go to the 'Debug' menu.
You can also create 'breakpoints', which are points where the debugging process will automatically stop.
On a more basic debugging level, Visual Studio Code automatically detects minor problems in your code, and takes you directly there so you can solve the problem easily.
Intellisense
When I was learning to code, one of the tips the teacher gave us when we don't know how to do something was to Google it. Microsoft has built a feature in Visual Studio Code called Intellisense, which is an alternative to Googling the problem (or 'Bing-ing' it, in Microsoft's case).
IntelliSense analyzes the semantics (letters) of what you are inputting, as well as the rest of the code you have created, and then provides suggestions on how to finish what you are writing. You can access a whole host of different completions through Intellisense, including language server suggestions, snippets, and word-based textual completions.
IntelliSense is available for the most common programming languages, including HTML, CSS, and Javascript, but for other languages, you'll need to install an extension.
And the rest
Visual Studio Code has a number of other useful features that will help you through your coding journey by helping you better visualize your code and speed up your programming. This includes:
- Support for snippets: This allows you to create a catalog of small parts of reusable code, which you can insert into larger bodies of code
- 'Go to' functionality: This allows you to quickly find and go to symbols, files, lines, and definitions
- Syntax highlighting: This displays code in different colors and fonts in accordance with the kind of coding language being used.
Overall impression
Confession time: I'm a long-time Windows/Microsoft Office user. Part of the reason for this (uncool) decision is that I find Microsoft products familiar and easy to navigate. The same goes for Visual Studio Code.
Even if you're new to text editors, VS Code is easy to pick up and get using straightaway. It has a Microsoft look and feel to it, and it has two layers to it that make it ideal for any type of user.
If you're a novice coder, it's easy to work out the basic commands (plus Microsoft has written loads of documentation for it), but if you're an expert user looking to do some serious programming, there are plenty of advanced features options there too.
Sublime Text (Version 3)
Sublime Text, which was developed by a former Google engineer, has been around since 2007. The first major difference between it and Visual Studio Code (VSC) is that it has a license fee of $80, although it does have a free trial version. Just like VSC, it runs on Windows, Linux, and macOS, and is the fourth most popular development environment in 2018 according to StackOverflow.
The latest version of Sublime Text—Version 3—was in beta for more than four years, from January 2013 until it was released to the public in September 2017.
The basics
When you open Sublime Text for the first time, you get a stripped back text editor. There is no sidebar, no options to search, no option to take you directly to the extension sidebar. It provides a more focused layout to help you concentrate on coding. There is a small minimap in the top right corner to give you an at-a-glance view of your code.
It opened pretty quickly compared to Visual Studio Code and, if you're ready to get down to editing code, it provides the perfect start point. However, if you're new to text editors, the other features and functionality are harder to find. Most of what you need is in the menus at the top, but you'll also want to call up the Command Palette (more on that below) from the Tools menu to more quickly get to what you need.
Sublime Text Features
If you want to get the most out of Sublime Text, you'll want to install extra plugins to give you the extra functionality. To do that, you need to install Package Control, which we'll walk you through below.
Package Control
Package Control is similar to Visual Studio's extension marketplace, but it isn't available out-of-the-box. There are a lot of packages (or plugins) available for people who are new to programming, such as a starter package for C++, a package that will help with Python completions (a bit like Intellisense in Visual Studio), and Emmet, which helps you write HTML and CSS faster by allowing you to use abbreviations, which it automatically expands.
Command Palette
When you use the Command Palette feature, you'll be able to find and navigate your way to any command much quicker than if you have to go searching through menus for it. You can access pretty much anything, and the Command Palette will also autofill for you, so if you're not sure what you're looking for exactly, it'll suggest some options.
For example, if you are working on a project and you need to quickly add a new folder, or save the project you are working on, you can quickly pull up that option. Or if you want to create snippets without having to navigate through the menus, you can do that too.
To access Command Palette, all you need to do is hit ctrl + shift + p.
Goto functionality
There is a menu in Sublime Text dedicated to all of the 'Goto' functionality within this text editor. This is a much more fully-featured version of Visual Studio's own 'Go to' menu.
Some of the highlights include Goto Symbol (added in Sublime Text 3), which lets you easily find all examples of symbols within a file. The example below is for H1 tags (there was only one instance within this file).
Projects
Sublime Text Format Xml
The Projects feature refers to a way of organizing folders and files within Sublime Text. It means that all folders and files are stored in one place and quickly accessible from the sidebar as soon as you open the project, rather than you having to keep manually opening more files. It also means you can search (quickly) across all files within a project at one time.
You can only have one project open in a workspace at a time, so if you want to change projects, you need to select the 'Switch Projects' option.
Visual Studio has a similar feature called 'Workspaces', which allows you to open and work on multiple files at once.
And the rest
Sublime Xml Editor
Sublime Text has a host of other, 'smaller' features, which are worth a mention here. This includes:
- Snippets: These work in the same way as with Visual Studio, but you can also build your own, or install more from extensions
- Multi-edit: When you press ctrl + d, all instances of the word or command you are currently on will be highlighted within the file, you can also press ctrl + f to find and replace words.
Overall impression
Sublime Text is a fast and stripped back text editor that is hot on organizing and searching through the code you have written, and being able to easily jump to any function or symbol quickly. Its 'Goto' functionality and many keyboard shortcuts make it easy for experienced developers to navigate their way around, and to write and find code easily without having to take their hands off the keyboard. For more novice coders (like myself), it takes longer to get used to.
Sublime Text doesn't include a debugging option, which could be a problem for developers who require this functionality.
Which text editor should I choose?
Visual Studio could be classed as an integrated development environment (IDE), because it allows programmers to both write and test code. Sublime Text, on the other hand, is 'just' a text editor (albeit an excellent one) because it focuses on providing the quickest way to organize and write your code, but no ability to test (debug) the code.
Another major difference between Visual Studio Code and Sublime Text is the support that Microsoft provides compared to Sublime Text. Microsoft has created reams of documentation explaining almost every feature and how to use them, as well as blog posts and video tutorials to help users get up to speed with the text editor.
Sublime Text provides some harder to find documentation, a blog post explaining the features in the latest version, and a forum.
Sublime Text is quick and easy to write code and navigate your way around when you know what you're doing. Visual Studio provides more hand-holding and is a great option for its debugging functionality, but might slow some speedy experienced programmers down when it comes to writing code.
There is a lot of debate among programmers about the 'best' text editor out there but, while they all have their personal preferences (which can change depending on their latest project), there is no one-size-fits-all development environment. The best option is to download and try each one and see which has the features you need, and which you get on with best.