Sublime Text Unofficial Documentation
Sublime Text Unofficial Documentation
Release 2.0
guillermooo
CONTENTS
ii
CHAPTER
ONE
CHAPTER
TWO
INSTALLATION
The process of installing Sublime Text is different for each platform.
Make sure to read the conditions for use on the official site. Sublime Text is not free.
For OS X, you can ignore this section: there is only one version of Sublime Text for OS X.
2.2 Windows
2.2.1 Portable or Not Portable?
Sublime Text comes in two flavors for Windows: normal, and portable. If you need the portable installation, you
probably know already. Otherwise, go with the normal one.
Normal installations separate data between two folders: the installation folder proper, and the data directory. These
concepts are explained later in this guide. Normal installations also integrate Sublime Text with the Windows context
menu.
Portable installations will keep all files Sublime Text needs to run in one single folder. You can then move this folder
around and the editor will still work.
2.3 OS X
Download and open the .dmg file, and then drag the Sublime Text 2 bundle into the Applications folder.
2.4 Linux
You can download the package and uncompress it manually. Alternatively, you can use the command line:
cd /path/to/your/apps
wget http://url/to/sublime.tar.bz2
tar vxjf sublime.tar.bz2
If you want, you can also create a symbolic link to the executable for convenience:
sudo ln -s /path/to/sublime_text /usr/bin/subl
Chapter 2. Installation
CHAPTER
THREE
BASIC CONCEPTS
Here well explain concepts that the reader needs to be familiar with in order to fully understand the contents of this
guide.
For portable installations, look inside Sublime Text 2/Data. Here, the Sublime Text 2 part refers to the directory to
which youve extracted the contens of the compressed file containing Sublime Text 2.
Note that only for portable installations does a directory named Data exist. For the other types of installation, the data
directory is the location indicated above.
3.6 Packages, Plugins, Resources and Other Things That May Not
Make Sense to You Now
For now, just keep in mind that almost everything in Sublime Text can be adapted to your needs. This vast flexibility is
the reason why you will learn about so many settings files: there simply must be a place to specify all your preferences.
Configuration files in Sublime Text let you change the editors behavior, add macros, snippets or create new features
where feature means anything you can think of. Ok, maybe not anything, but Sublime Text definitely hands you
over a good deal of control.
These settings files are simply text files following a special structure or format: JSON predominates, but youll find
XML files too.
In this guide, we refer collectively to all these disparate configuration files as resources. Sublime Text will look for
resources inside the packages directory. To keep things tidy, the editor has a notion of a package, which is a directory
containing resources that belong together (maybe they all help write emails faster or code in a certain programming
language).
3.8 Vi Emulation
This information is mainly useful for dinosaurs and people who like to drop the term RSI in conversations. Vi is an
ancient modal editor that lets the user perform all operations from the keyboard. Vim, a modern version of vi, is still
in widespread use.
Sublime Text provides vi emulation through the Vintage package. The Vintage package is ignored by default. Read
more about Vintage in the official documentation.
3.9 Emacs
This information is hardly useful for anyone. Emacs is... Well, nobody really knows what emacs is, although some
people edit text with it.
If you are an emacs user, youre probably not reading this.
CHAPTER
FOUR
EDITING
4.1 Overview
Sublime Text is full to the brim with editing features. This topic just scratches the surface of whats possible.
10
Chapter 4. Editing
CHAPTER
FIVE
Alt +
Alt +
Alt +
Enter
Shift
Alt +
R
C
W
+ Enter
Enter
5.1.4 Tips
Other Ways of Searching in Buffers
Goto Anything provides the operator # to search in the current buffer. The search term will be the part following the
# operator.
11
F3
Shift + F3
Alt + F3
Multiline Search
You can type a multiline search pattern. To enter a newline character, press Ctrl + Enter in the search panel.
Note that the search panel is resizable too.
Alt + R
Alt + C
Alt + W
Enter
12
F4
Shift + F4
Well examine them in turn, but lets talk about a powerful tool for searching text first: regular expressions.
13
14
CHAPTER
SIX
6.1.1 Example
Heres an example of a build system:
{
"cmd": ["python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
cmd Required. This option contains the actual command line to be executed:
python -u /path/to/current/file.ext
file_regex A Perl-style regular expression to capture error information out of the external programs output. This
information is then used to help you navigate through error instances with F4.
selector If the Tools | Build System | Automatic option is set, Sublime Text will automatically find the corresponding build system for the active file by matching selector to the files scope.
In addition to options, you can also use some variables in build systems, like we have done above with $file, which
expands to the the active buffers file name.
15
16
CHAPTER
SEVEN
This instructs Sublime Text to perform a fuzzy search for treasure in the file whose name matches island. Pressing
Ctrl+; will open Goto Anything and type # for you.
And theres more:
To search symbols in the active buffer, press Ctrl+R. The operator @ can be used as explained above too.
To go to a line number, press Ctrl+G. The operator : can be used as explained above too.
Searching for symbols will only work for file types that have symbols defined for them.
7.2 Sidebar
The sidebar gives you an overview of your project. Files and folders added to the sidebar will be available in Goto
Anything and project-wide actions. Projects and the sidebar are closely related. Theres always an open project,
whether its implicit or explicit.
To open or close the sidebar, press Ctrl+K, Ctrl+B.
The sidebar can be navigated with the arrow keys, but first you need to give it the input focus by pressing Ctrl+0.
To return input focus to the buffer, press Esc. Alternatively, you can use the mouse to the same effect, but why would
you?
The sidebar also provides basic file management operations through the context menu.
17
7.3 Projects
Projects group sets of files and directories you need to work on as a unit. Once youve set up your project the way that
suits you by adding folders, save it and give it a name.
To save a project, go to Project | Save Project As....
To quickly switch between projects, press Ctrl+Alt+P.
Project data are stored in JSON files with a .sublime-project extension. Wherever theres a .sublime-project file, you
will find an ancillary .sublime-workspace file too. The second one is used by Sublime Text and you shouldnt edit it
yourself.
Project files can define settings specific to that project only. More on that in the official documentation.
You can open a project from the command line by passing the .sublime- project file as an argument.
18
CHAPTER
EIGHT
8.1 Settings
Sublime Text stores configuration data in .sublime-settings files. Flexibility comes at the price of a slightly complex
system for applying settings. However, heres a rule of thumb:
Always place your personal settings files under Packages/User to guarantee that they will take precedence over any
other conflicting settings files.
With that out of the way, lets unveil the mysteries of how settings work to please masochistic readers.
8.1.1 Format
Settings files use JSON and have the .sublime-settings extension.
19
Also, let us emphasize that under Pakages/User only Python.sublime-settings would be read, but not any Python
(<platform>).sublime-settings variant.
Regardless of its location, any file-type-specific settings file has precedence over every global settings file affecting
file types.
20
8.2 Indentation
See Also:
Indentation Official Sublime Text Documentation.
8.2. Indentation
21
Passing Arguments
Arguments are specified in the args key:
{ "keys": ["shift+enter"], "command": "insert", "args": {"characters": "\n"} }
This key binding translates to clear snippet fields and resume normal editing if there is a next field available. Thus,
pressing ESC when you are not cycling through snippet fields will not trigger this key binding (however, something
else might occur instead if ESC happens to be bound to a different context too and thats likely to be the case for
ESC).
8.4 Menus
No documenation available about this topic.
But heres Bruce Lee screaming.
22
CHAPTER
NINE
9.1 Commands
Commands are ubiquitous in Sublime Text: key bindings, menu items and macros all work through the command
system. They are found in other places too.
Some commands are implemented in the editors core, but many of them are provided as python plugins. Every
command can be called from a python plugin.
See Also:
Reference for commands Command reference.
9.2 Macros
Macros are a basic automation facility consisting in sequences of commands. Use them whenever you need to repeat
the exact same steps to perform an operation.
Macro files are JSON files with the extension .sublime-macro. Sublime Text ships with a few macros providing
core functionality, such as line and word deletion. You can find these under Tools | Macros.
23
9.3 Snippets
Whether you are coding or writing the next vampire best-seller, youre likely to need certain short fragments of text
again and again. Use snippets to save yourself tedious typing. Snippets are smart templates that will insert text for you
and adapt it to their context.
To create a new snippet, select Tools | New Snippet. . . . Sublime Text will present you with an skeleton for a new
snippet.
Snippets can be stored under any packages folder, but to keep it simple while youre learning, you can save them to
your Packages/User folder.
24
<scope>source.python</scope>
<!-- Optional: Description to show in the menu -->
<description>My Fancy Snippet</description>
</snippet>
The snippet element contains all the information Sublime Text needs in order to know what to insert, whether to
insert it and when. Lets see all of these parts in turn.
content The actual snippet. Snippets can range from simple to fairly complex templates. Well look at examples
of both later.
Keep the following in mind when writing your own snippets:
If you want the get a literal $, you have to escape it like this: \$.
When writing a snippet that contains indentation, always use tabs. The tabs will be transformed
into spaces when the snippet is inserted if the option translateTabsToSpaces is set to
true.
The content must be included in a <![CDATA[...]]> section. Snippets wont work if you
dont do this!
tabTrigger Defines the sequence of keys you will press to insert this snippet. The snippet will kick in as soon as
you hit the Tab key after typing this sequence.
A tab trigger is an implicit key binding.
scope Scope selector determining the context where the snippet will be active. See Scopes for more information.
description Used when showing the snippet in the Snippets menu. If not present, Sublime Text defaults to the
name of the snippet.
With this information, you can start writing your own snippets as described in the next sections.
Note: In the interest of brevity, were only including the content elements text in examples unless otherwise
noted.
9.3. Snippets
25
$PARAM1, $PARAM2. . .
$SELECTION
$TM_CURRENT_LINE
$TM_CURRENT_WORD
$TM_FILENAME
$TM_FILEPATH
$TM_FULLNAME
$TM_LINE_INDEX
$TM_LINE_NUMBER
$TM_SELECTED_TEXT
$TM_SOFT_TABS
$TM_TAB_SIZE
Fields
With the help of field markers, you can cycle through positions within the snippet by pressing the Tab key. Fields are
used to walk you through the customization of a snippet once its been inserted.
First Name: $1
Second Name: $2
Address: $3
In the example above, the cursor will jump to $1 if you press Tab once. If you press Tab a second time, it will
advance to $2, etc. You can also move backwards in the series with Shift+Tab. If you press Tab after the highest
tab stop, Sublime Text will place the cursor at the end of the snippets content so that you can resume normal editing.
If you want to control where the exit point should be, use the $0 mark.
You can break out of the field cycle any time by pressing Esc.
Mirrored Fields
Identical field markers mirror each other: when you edit the first one, the rest will be populated with the same value in
real time.
First Name: $1
Second Name: $2
Address: $3
User name: $1
26
In this example, User name will be filled out with the same value as First Name.
Place Holders
By expanding the field syntax a little bit, you can define default values for a field. Place holders are useful when theres
a general case for your snippet but you still want to keep its customization convenient.
First Name: ${1:Guillermo}
Second Name: ${2:Lpez}
Address: ${3:Main Street 1234}
User name: $1
And you can nest place holders within other place holders too:
Test: ${1:Nested ${2:Placeholder}}
Substitutions
Warning: This section is a draft and may contain inaccurate information.
In addition to the place holder syntax, tab stops can specify more complex operations with substitutions. Use substitutions to dynamically generate text based on a mirrored tab stop.
The substitution syntax has the following syntaxes:
${var_name/regex/format_string/}
${var_name/regex/format_string/options}
var_name The variable name: 1, 2, 3. . .
regex Perl-style regular expression: See the Boost library reference for regular expressions.
format_string See the Boost library reference for format strings.
options
Optional. May be any of the following:
i Case-insensitive regex.
g Replace all occurrences of regex.
m Dont ignore newlines in the string.
With substitutions you can, for instance, underline text effortlessly:
Original: ${1:Hey, Joe!}
Transformation: ${1/./=/g}
# Output:
9.3. Snippets
27
9.4 Completions
See Also:
Reference for completions Complete documentation on all available options.
Sublime Text Documentation Official documentation on this topic.
Completions provide functionality in the spirit of IDEs to suggest terms and insert snippets. Completions work through
the completions list or, optionally, by pressing Tab.
Note that completions in the broader sense of words that Sublime Text will look up and insert for you are not limited
to completions files, because other sources contribute to the list of words to be completed, namely:
Snippets
API-injected completions
Buffer contents
However, .sublime-completions files are the most explicit way Sublime Text provides you to feed it completions. This topic deals with the creation of .sublime-completions files as well as with the interaction between
all sources for completions.
scope Determines when the completions list will be populated with this list of completions. See Scopes for more
information.
In the example above, weve used trigger-based completions only, but completions files support simple completions
too. Simple completions are just plain strings. Expanding our example with a few simple completions, wed end up
with a list like so:
28
{
"scope": "text.html - source - meta.tag, punctuation.definition.tag.begin",
"completions":
[
{ "trigger": "a", "contents": "<a href=\"$1\">$0</a>" },
{ "trigger": "abbr", "contents": "<abbr>$0</abbr>" },
{ "trigger": "acronym", "contents": "<acronym>$0</acronym>" },
"ninja",
"robot",
"pizza"
]
}
9.4. Completions
29
When tab_completion is enabled, you can press Shift+Tab to insert a literal tab character.
9.5.1 Overview
The command palette is an interactive list bound to Ctrl+Shift+P whose purpose is to execute commands. The
command palette is fed entries with commands files. Usually, commands that dont warrant creating a key binding of
their own are good candidates for inclusion in a .sublime-commands file.
{ "caption": "Preferences: Default File Settings", "command": "open_file", "args": {"file": "${pa
{ "caption": "Preferences: User File Settings", "command": "open_file", "args": {"file": "${packa
{ "caption": "Preferences: Default Global Settings", "command": "open_file", "args": {"file": "${
30
{ "caption": "Preferences: User Global Settings", "command": "open_file", "args": {"file": "${pac
{ "caption": "Preferences: Browse Packages", "command": "open_dir", "args": {"dir": "$packages"}
]
9.6.1 Prerequisites
In order to follow this tutorial, you will need to install AAAPackageDev, a package intended to ease the creation of
new syntax definitions for Sublime Text. AAAPackageDev lives on a public Mercurial repository at Bitbucket.
Download the latest .sublime-package file and install it as described in Installation of .sublime-package Files.
Mercurial and Bitbucket
Mercurial is a distributed version control system (DVCS). Bitbucket is an online service that provides hosting for
Mercurial repositories. If you want to install Mercurial, there are freely available command-line and graphical
clients.
31
By all means, do edit the Plist files by hand if you prefer to work in XML, but keep always in mind the differing needs
with regards to escape sequences, etc.
9.6.3 Scopes
Scopes are a key concept in Sublime Text. Essentially, they are named text regions in a buffer. They dont do anything
by themselves, but Sublime Text peeks at them when it needs contextual information.
For instance, when you trigger a snippet, Sublime Text checks the scope the snippets bound to and looks at the carets
position in the file. If the carets current scope matches the snippets scope selector, Sublime Text fires the snippet off.
Otherwise, nothing happens.
Scopes vs Scope Selectors
Theres a slight difference between scopes and scope selectors: scopes are the names defined in a syntax definition, whilst scope selectors are used in items like snippets and key bindings to target scopes. When creating a
new syntax definition, you care about scopes; when you want to constrain a snippet to a certain scope, you use a
scope selector.
Scopes can be nested to allow for a high degree of granularity. You can drill down the hierarchy very much like with
CSS selectors. For instance, thanks to scope selectors, you could have a key binding activated only within single
quoted strings in python source code, but not inside single quoted strings in any other language.
Sublime Text implements the idea of scopes from Texmate, a text editor for Mac. Textmates online manual contains
further information about scope selectors thats useful for Sublime Text users too.
32
Note: JSON is a very strict format, so make sure to get all the commas and quotes right. If the conversion to Plist
fails, take a look at the output panel for more information on the error. Well explain later how to convert a syntax
definition in JSON to Plist.
33
Matches
They take this form:
{ "match": "[Mm]y \s+[Rr]egex",
"name": "string.ssraw",
"comment": "This comment is optional."
}
match A regular expression Sublime Text will use to try and find matches.
name Name of the scope that should be applied to the occurrences of match.
comment An optional comment about this pattern.
Lets go back to our example. Make it look like this:
{ "name": "Sublime Snippet (Raw)",
"scopeName": "source.ssraw",
"fileTypes": ["ssraw"],
"patterns": [
],
"uuid": "ca03e751-04ef-4330-9a6b-9b99aae1c418"
}
However, because were writing our regex in JSON, we need to factor in JSONs own escaping rules. Thus, our
previous example becomes:
\\$\\d+
With escaping out of the way, we can build our pattern like this:
{ "match": "\\$\\d+",
"name": "keyword.source.ssraw",
"comment": "Tab stops like $1, $2..."
}
34
Were now ready to convert our file to .tmLanguage. Syntax definitions use Textmates .tmLanguage extension
for compatibility reasons. As explained further above, they are simply XML files in the Plist format.
Follow these steps to perform the conversion:
Select Json to tmLanguage in Tools | Build System
Press F7
A .tmLanguage file will be generated for you in the same folder as your .JSON-tmLanguage file
Sublime Text will reload the changes to the syntax definition
You have now created your first syntax definition. Next, open a new file and save it with the extension .ssraw. The
buffers syntax name should switch to Sublime Snippet (Raw) automatically, and you should get syntax highlighting
if you type $1 or any other simple snippet field.
Lets proceed to creating another rule for environment variables.
{ "match": "\\$[A-Za-z][A-Za-z0-9_]+",
"name": "keyword.source.ssraw",
"comment": "Variables like $PARAM1, $TM_SELECTION..."
}
Repeat the steps above to update the .tmLanguage file and restart Sublime Text.
Fine Tuning Matches
You might have noticed that the entire text in $PARAM1, for instance, is styled the same way. Depending on your
needs or your personal preferences, you may want the $ to stand out. Thats where captures come in. Using
captures, you can break a pattern down into components to target them individually.
Lets rewrite one of our previous patterns to use captures:
9.6. Syntax Definitions
35
{ "match": "\\$([A-Za-z][A-Za-z0-9_]+)",
"name": "keyword.ssraw",
"captures": {
"1": { "name": "constant.numeric.ssraw" }
},
"comment": "Variables like $PARAM1, $TM_SELECTION..."
}
Captures introduce complexity to your rule, but they are pretty straightforward. Notice how numbers refer to parenthesized groups left to right. Of course, you can have as many capture groups as you want.
Arguably, youd want the other scope to be visually consistent with this one. Go ahead and change it too.
Begin-End Rules
Up to now weve been using a simple rule. Although weve seen how to dissect patterns into smaller components,
sometimes youll want to target a larger portion of your source code clearly delimited by start and end marks.
Literal strings enclosed in quotation marks and other delimited constructs are better dealt with with begin-end rules.
This is a skeleton for one of these rules:
{ "name": "",
"begin": "",
"end": ""
}
Well, at least in their simplest version. Lets take a look at one including all available options:
{ "name": "",
"begin": "",
"beginCaptures": {
"0": { "name": "" }
},
"end": "",
"endCaptures": {
"0": { "name": "" }
},
"patterns": [
{ "name": "",
"match": ""
}
],
"contentName": ""
}
Some elements may look familiar, but their combination might be daunting. Lets see them individually.
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 simple matches. Optional.
endCaptures Same as beginCaptures but for the end marker. Optional.
contentName Scope for the whole matched region, from the begin marker to the end marker, inclusive. This will
effectively create nested scopes for beginCaptures, endCaptures and patterns defined within this
rule. Optional.
36
patterns An array of patterns to match against the begin-end content only they are not matched against the text
consumed by begin or end.
Well use this rule to style nested complex fields in snippets:
{ "name": "variable.complex.ssraw",
"begin": "(\\$)(\\{)([0-9]+):",
"beginCaptures": {
"1": { "name": "keyword.ssraw" },
"3": { "name": "constant.numeric.ssraw" }
},
"patterns": [
{ "include": "$self" },
{ "name": "string.ssraw",
"match": "."
}
],
"end": "\\}"
}
This is the most complex pattern well see in this tutorial. The begin and end keys are self-explanatory: they define
a region enclosed between ${<NUMBER>: and }. beginCaptures further divides the begin mark into smaller
scopes.
The most interesting part, however, is patterns. Recursion and the importance of ordering have finally made an
appearance here.
Weve seen further above that fields can be nested. In order to account for this, we need to recursively style nested
fields. Thats what the include rule does when furnished the $self value: it recursively applies our entire syntax
definition to the portion of text contained in our begin-end rule, excluding the text consumed by both begin and end.
Remember that matched text is consumed and is excluded from the next match attempt.
To finish off complex fields, well style place holders as strings. Since weve already matched all possible tokens
inside a complex field, we can safely tell Sublime Text to give any remaining text (.) a literal string scope.
Final Touches
Lastly, lets style escape sequences and illegal sequences, and wrap up.
{
"name": "constant.character.escape.ssraw",
"match": "\\\\(\\$|\\>|\\<)"
},
{
"name": "invalid.ssraw",
"match": "(\\$|\\<|\\>)"
The only hard thing here is getting the number of escape characters right. Other than that, the rules are pretty straightforward if youre familiar with regular expressions.
However, you must take care to put the second rule after any others matching the $ character, since otherwise you may
not get the desired result.
Also, note that after adding these two additional rules, our recursive begin-end rule above keeps working as expected.
At long last, heres the final syntax definition:
{
37
"fileTypes": ["ssraw"],
"patterns": [
{ "match": "\\$(\\d+)",
"name": "keyword.ssraw",
"captures": {
"1": { "name": "constant.numeric.ssraw" }
},
"comment": "Tab stops like $1, $2..."
},
{ "match": "\\$([A-Za-z][A-Za-z0-9_]+)",
"name": "keyword.ssraw",
"captures": {
"1": { "name": "constant.numeric.ssraw" }
},
"comment": "Variables like $PARAM1, $TM_SELECTION..."
},
{ "name": "variable.complex.ssraw",
"begin": "(\\$)(\\{)([0-9]+):",
"beginCaptures": {
"1": { "name": "keyword.ssraw" },
"3": { "name": "constant.numeric.ssraw" }
},
"patterns": [
{ "include": "$self" },
{ "name": "string.ssraw",
"match": "."
}
],
"end": "\\}"
},
{ "name": "constant.character.escape.ssraw",
"match": "\\\\(\\$|\\>|\\<)"
},
{ "name": "invalid.ssraw",
"match": "(\\$|\\>|\\<)"
}
],
"uuid": "ca03e751-04ef-4330-9a6b-9b99aae1c418"
}
There are more available constructs and code reuse techniques, but the above explanations should get you started with
the creation of syntax definitions.
9.7 Plugins
See Also:
API Reference More information on the Python API.
Plugins Reference More information about plugins.
Sublime Text 2 is programmable with Python scripts. Plugins reuse existing commands or create new ones to build a
feature. Plugins are rather a logical entity than a physical one.
38
9.7.1 Prerequisites
In order to write plugins, you must be able to program in Python.
The sublime and sublime_plugin modules are both provided by Sublime Text 2.
New commands derive from the *Command classes defined in sublime_plugin (more on this later).
The rest of the code is concerned with particulars of the TextCommand or the API that well discuss in the next
sections.
Before moving on, though, well look at how we called the new command: We first opened the python console, and
then issued a call to view.run_command(). This is a rather inconvenient way of using plugins, but its often
useful when youre in the development phase. For now, keep in mind that your commands can be accessed through
key bindings or other means, just as other commands are.
9.7. Plugins
39
40
Note: Make sure you dont keep this plugin around after trying it or it will interefere with the autocompletion system.
9.8 Packages
Packages are simply directories under Packages. They exist mainly for organizational purposes, but Sublime Text
follows a few rules when dealing with them. More on this later.
Heres a list of typical resources living inside packages:
build systems (.sublime-build)
key maps (.sublime-keymap)
9.8. Packages
41
macros (.sublime-macro)
menus (.sublime-menu)
plugins (.py)
preferences (.tmPreferences)
settings (.sublime-settings)
syntax definitions (.tmLanguage)
snippets (.sublime-snippet)
themes (.sublime-theme)
Some packages may include support files for other packages or core features. For example, the spell checker uses
PackagesLanguage - English as a data store for English dictionaries.
42
9.8. Packages
43
44
CHAPTER
TEN
45
46
CHAPTER
ELEVEN
REFERENCE
In this section you will find concise information about many aspects of Sublime Text.
If youre looking for a slow-paced introduction to any of these topics, try the general index.
11.1 Snippets
11.1.1 Compatibility with Textmate
Sublime Text snippets are generally compatible with Textmate snippets.
47
11.1.5 Fields
Mark positions to cycle through by pressing TAB or SHIFT + TAB.
Syntax: $1 .. $n
$0 Exit mark. Position at which normal text editing should be resumed. By default, Sublime Text implicitly sets this
mark at the end of the snippets content element.
Fields with the same name mirror each other.
11.1.7 Substitutions
Syntax:
${var_name/regex/format_string/}
${var_name/regex/format_string/options}
var_name The fields name to base the substitution on: 1, 2, 3. . .
regex Perl-style regular expression: See the Boost library documentation for regular expressions.
format_string See the Boost library documentation for format strings.
options
Optional. Any of the following:
i Case-insensitive regex.
g Replace all occurrences of regex.
m Dont ignore newlines in the string.
48
49
name Descriptive name for the syntax definition. Shows up in the syntax definition dropdown menu located in the
bottom right of Sublime Text interface. Its usually the name of the programming language or equivalent.
scopeName Name of the top-level scope for this syntax definition. Either source.<lang> or text.<lang>.
Use source for programming languages and text for everything else.
fileTypes And array of file type extensions for which this syntax should be automatically activated. Include the
extensions without the leading dot.
uuid Unique indentifier for this syntax definition. Currently ignored.
foldingStartMarker Currently ignored. Used for code folding.
foldingStopMarker Currently ignored. Used for code folding.
patterns Array of patterns to match against the buffers text.
repository Array of patterns abstracted out from the patterns element. Useful to keep the syntax definition tidy
as well as for specialized uses like recursive patterns. Optional.
Examples:
// Simple
{ "name": "constant.character.escape.ssraw",
"match": "\\\\(\\$|\\>|\\<)"
"comment". "Sequences like \$, \> and \<"
}
// With captures
{ "match": "\\$(\\d+)",
"name": "keyword.ssraw",
"captures": {
"1": { "name": "constant.numeric.ssraw" }
},
"comment": "Tab stops like $1, $2..."
}
include Includes items in the repository, other syntax definitions or the current one.
References:
$self
#itemName
source.js
50
Examples:
// Requires presence of DoubleQuotedStrings element in the repository.
{ "include": "#DoubleQuotedStrings" }
// Recursively includes the current syntax definition.
{ "include": "$self" }
// Includes and external syntax definition.
{ "include": "source.js" }
Example:
{ "name": "variable.complex.ssraw",
"begin": "(\\$)(\\{)([0-9]+):",
"beginCaptures": {
"1": { "name": "keyword.control.ssraw" },
"3": { "name": "constant.numeric.ssraw" }
},
"patterns": [
{ "include": "$self" },
{ "name": "string.ssraw",
"match": "."
}
],
"end": "\\}"
}
11.2.4 Repository
Can be referenced from patterns or from itself in an include element. See include for more information.
The repository can contain the following elements:
Simple elements:
"elementName": {
"match": "some regexp",
"name":
"some.scope.somelang"
}
Complex elements:
"elementName": {
"patterns": [
{ "match": "some regexp",
"name":
"some.scope.somelang"
51
},
{ "match":
"name":
}
"other regexp",
"some.other.scope.somelang"
]
}
Examples:
"repository": {
"numericConstant": {
"patterns": [
{ "match": "\\d*(?<!\\.)(\\.)\\d+(d)?(mb|kb|gb)?",
"name":
"constant.numeric.double.powershell",
"captures": {
"1": { "name": "support.constant.powershell" },
"2": { "name": "support.constant.powershell" },
"3": { "name": "keyword.other.powershell" }
}
},
{ "match": "(?<!\\w)\\d+(d)?(mb|kb|gb)?(?!\\w)",
"name":
"constant.numeric.powershell",
"captures": {
"1": { "name": "support.constant.powershell" },
"2": { "name": "keyword.other.powershell" }
}
}
]
},
"scriptblock": {
"begin": "\\{",
"end":
"\\}",
"name":
"meta.scriptblock.powershell",
"patterns": [
{ "include": "$self" }
]
},
}
The Sublime Text command then receives the data stored in the .sublime-build file. At this point, it can do whatever it needs to build the files. By default, build systems will use the exec command, implemented in Packages/Default/exec.py. As well explain below, you can override this command.
Lastly, the external program may be a shell script youve created to process your files, or a well-known utility like
make or tidy. Usually, these executable files will receive paths to files or directories, along with switches and
options to be run with.
Note that build systems need not call any external program at all if there isnt any reason to; you could implement a
build system entirely in a Sublime Text command.
11.3.2 Options
cmd Array containing the command to run and its desired arguments. If you dont specify an absolute path, the
external program will be searched in your PATH, one of your systems environmental variables.
On Windows, GUIs are supressed.
file_regex Optional. Regular expression (Perl-style) to capture error output of cmd. See the next section for
details.
line_regex Optional. If file_regex doesnt match on the current line, but line_regex exists, and it does
match on the current line, then walk backwards through the buffer until a line matching file regex is found,
and use these two matches to determine the file and line to go to.
selector Optional. Used when Tools | Build System | Automatic is set to true. Sublime Text uses this scope
selector to find the appropriate build system for the active view.
working_dir Optional. Directory to change the current directory to before running cmd. The original current
directory is restored afterwards.
encoding Optional. Output encoding of cmd. Must be a valid python encoding. Defaults to UTF-8.
target Optional. Sublime Text command to run. Defaults to exec (Packages/Default/exec.py). This command
receives the configuration data specified in the .build-system file.
Used to override the default build system command. Note that if you choose to override the default command
for build systems, you can add arbitrary variables in the .sublime-build file.
env Optional. Dictionary of environment variables to be merged with the current process before passing them to
cmd.
Use this element, for example, to add or modify environment variables without modifying your systems settings.
shell Optional. If true, cmd will be run through the shell (cmd.exe, bash. . . ).
path Optional. This string will replace the current process PATH before calling cmd. The old PATH value will be
restored after that.
Use this option to add directories to PATH without having to modify your systems settings.
53
variants Optional. A list of dictionaries of options to override the main build systems options. Variant names
will appear in the Command Palette for easy access if the build systems selector matches for the active file.
name Only valid inside a variant (see variants). Identifies variant build systems. If name is Run, the variant
will show up under the Tools | Build System menu and be bound to Ctrl + Shift + B.
Capturing Error Output with file_regex
The file_regex option uses a Perl-style regular expression to capture up to four fields of error information from
the build programs output, namely: file name, line number, column number and error message. Use groups in the
pattern to capture this information. The file name field and the line number field are required.
When error information is captured, you can navigate to error instances in your projects files with F4 and Shift+F4.
If available, the captured error message will be displayed in the status bar.
Platform-specific Options
The windows, osx and linux elements let you provide platform-specific data in the build system. Heres an
example:
{
"cmd": ["ant"],
"file_regex": "^ *\\[javac\\] (.+):([0-9]+):() (.*)$",
"working_dir": "${project_path:${folder}}",
"selector": "source.java",
"windows":
{
"cmd": ["ant.bat"]
}
}
In this case, ant will be executed for every platform except Windows, where ant.bat will be used instead.
Variants
Heres a contrived example of a build system with variants:
{
"selector": "source.python",
"cmd": ["date"],
"variants": [
{ "cmd": ["ls -l *.py"],
"name": "List Python Files",
"shell": true
},
{ "cmd": ["wc", "$file"],
"name": "Word Count (current file)"
},
{ "cmd": ["python", "-u", "$file"],
"name": "Run"
}
54
]
}
Given these settings, Ctrl + B would run the date command, Crtl + Shift + B would run the Python interpreter and the
remaining variants would appear in the Command Palette whenever the build system was active.
This will emit the name of the current project if there is one, otherwise Default.
${file/\.php/\.txt/}
This will emit the full path of the current file, replacing .php with .txt.
55
See Also:
Managing Environment Variables in Windows Search Microsoft knowledge base for this topic.
Setting environment variables in OSX StackOverflow topic.
56
Structure of a Context
key Name of a context operand to query.
operator Type of test to perform against key.
operand Value against which the result of key is tested.
match_all Requires the test to succeed for all selections. Defaults to false.
Context Operands
57
insert
home
end
pageup
pagedown
backspace
delete
tab
enter
pause
escape
space
keypad0
keypad1
keypad2
keypad3
keypad4
keypad5
keypad6
keypad7
keypad8
keypad9
keypad_period
keypad_divide
keypad_multiply
keypad_minus
keypad_plus
keypad_enter
clear
f1
f2
f3
f4
f5
f6
f7
58
f8
f9
f10
f11
f12
f13
f14
f15
f16
f17
f18
f19
f20
sysreq
break
context_menu
browser_back
browser_forward
browser_refresh
browser_stop
browser_search
browser_favorites
browser_home
Modifiers
shift
ctrl
alt
super (Windows key, Command key. . . )
Warning about Bindable Keys
If youre developing a package, keep this in mind:
Ctrl+Alt+<alphanum> should not be used on any Windows key bindings.
Option+<alphanum> should not be used on any OS X key bindings.
In both cases, the users ability to insert non-ascii characters would be compromised.
If you are the end-user, you are free to remap those key combinations.
59
11.4.6 Troubleshooting
See sublime.log_commands(flag) to enable command logging. It may help when debugging key maps.
60
no_antialias,
gray_antialias,
draw_centered If set to true, text will be drawn centered rather than left-aligned.
match_brackets Set to false to disable underlining the brackets surrounding the cursor.
match_brackets_content Set to false is youd rather only highlight the brackets when the cursor is next to
one.
match_brackets_square Set to false to stop highlighting square brackets.
match_brackets is true.
61
Automatic Behavior
auto_match_enabled Toggles automatic pairing of quotes, brackets, etc.
save_on_focus_lost Set to true to automatically save files when switching to a different file or application.
find_selected_text If true, the selected text will be copied into the find panel when its shown.
word_separators Characters considered to separate words in actions like advancing the cursor, etc. They are not
used in all contexts where a notion of a word separator is useful (e. g.: word wrapping). In such other contexts,
the text might be tokenized based on other criteria (e. g. the syntax definition rules).
ensure_newline_at_eof_on_save Always adds a new line at the end of the file if not present when saving.
System and Miscellaneous Settings
is_widget Returns true if the buffer is an input field in a dialog as opposed to a regular buffer.
spell_check Toggles the spell checker.
dictionary Word list to be used by the spell checker. Accepts a path rooted at the data directory (e. g.:
Packages/Language - English/en_US.dic). You can add more dictionaries.
fallback_encoding The encoding to use when the encoding cant be determined automatically. ASCII, UTF-8
and UTF-16 encodings will be automatically detected.
default_line_ending Determines what characters to use to designate new lines. Valid values: system (OSdependant), windows (CRLF) and unix (LF).
tab_completion Determines whether pressing Tab will insert completions.
Build and Error Navigation Settings
result_file_regex Regular expression used to extract error information from some output dumped into a view
or output panel. Follows the same rules as error capturing in build systems.
result_line_regex Regular expression used to extract error information from some output dumped into a view
or output panel. Follows the same rules as error capturing in build systems.
result_base_dir Directory to start looking for offending files in based on information extracted with
result_file_regex and result_line_regex.
build_env List of paths to add to build systems by default.
File and Directory Settings
default_dir Sets the default save directory for the view.
Input Settings
command_mode If set to true, the buffer will ignore key strokes. Useful to emulate Vim.
62
"caption":
"caption":
"caption":
"caption":
"caption":
"Preferences:
"Preferences:
"Preferences:
"Preferences:
"Preferences:
11.7 Completions
Completions provide an IDE-like functionality to insert dynamic content through the completions list or by pressing
Tab.
63
{
"scope": "text.html - source - meta.tag, punctuation.definition.tag.begin",
"completions":
[
{ "trigger": "a", "contents": "<a href=\"$1\">$0</a>" },
{ "trigger": "abbr", "contents": "<abbr>$0</abbr>" },
{ "trigger": "acronym", "contents": "<acronym>$0</acronym>" }
]
}
Trigger-based Completions
trigger Text that will be displayed in the completions list and will cause the contents to be inserted when
validated.
contents Text to be inserted in the buffer. Can use snippet features.
If the list of completions can be narrowed down to one choice, the autocomplete dialog will be bypassed and the
corresponding content will be inserted straight away according to the priority rules stated above.
11.8 Plugins
See Also:
API Reference More information on the Python API.
Plugins are Python scripts implementing *Command classes from sublime_plugin.
11.8. Plugins
65
Command Arguments
*****************
All user-provided arguments to commands must be valid JSON types. Only
Sublime Text can pass other types of arguments to commands (such as edit
objects, view instances, etc.).
66
Its important to call view.end_edit() after each view.begin_edit(), otherwise the buffer will be in an
inconsistent state. An attempt will be made to fix it automatically if the edit object gets collected, but that often
doesnt happen when you expect, and will result in a warning printed to the console. In other words, you should
always bracket an edit in a try..finally block.
The command name passed to begin_edit() is used for repeat, macro recording, and for describing the action
when undoing/redoing it. If youre making an edit outside of a TextCommand, you should almost never supply a
command name.
If you have created an edit object, and call a function that creates another one, thats fine: the edit is only considered
finished when the outermost call to end_edit() runs.
As well as grouping modifications, you can use edit objects for grouping changes to the selection, so theyre undone
in a single step.
11.8.9 Multithreading
Only the .set_timeout() function is safe to call from different threads.
67
11.10 Commands
11.10.1 Overview
This list of commands is a work in progress.
11.10.3 Commands
build Runs a build system.
variant [String]: Optional. The name of the variant to be run.
run_macro_file Runs a .sublime-macro file.
file [String]: Path to the macro file.
insert_snippet Inserts a snippet from a string or .sublime-snippet file.
contents [String]: Snippet as a string to be inserted.
name [String]: Path to the .sublime-snippet file to be inserted.
insert Inserts a string.
characters [String]: String to be inserted.
68
11.10. Commands
69
70
11.10. Commands
71
toggle_bookmark Sets or unsets a bookmark for the active region(s). (Bookmarks can be accessed via the regions
API using "bookmarks" as the key.)
clear_bookmarks Removes all bookmarks.
select_all_bookmarks Selects all bookmarked regions.
wrap_lines Wraps lines. By default, it wraps lines at the first rulers column.
width [Int]: Specifies the column at which lines should be wrapped.
upper_case Makes the selection upper case.
lower_case Makes the selection lower case.
set_mark XXX
select_to_mark XXX
delete_to_mark XXX
swap_with_mark XXX
yank XXX
show_at_center XXX
increase_font_size Increases the font size.
decrease_font_size Decreases the font size.
fold XXX
unfold XXX
fold_by_level XXX
context_menu Shows the context menu.
72
11.11.1 Editing
Keypress
Ctrl + X
Ctrl +
Ctrl + +
Ctrl + +
Ctrl + +
Ctrl + L
Ctrl + D
Ctrl + M
Ctrl + + M
Ctrl + KK
Ctrl + K +
Ctrl + ]
Ctrl + [
Ctrl + + D
Ctrl + J
Ctrl + /
Ctrl + + /
Ctrl + Y
Ctrl + + V
Ctrl + Space
Ctrl + U
Command
Delete line
Insert line after
Insert line before
Move line/selection up
Move line/selection down
Select line - Repeat to select next lines
Select word - Repeat select others occurrences
Jump to closing parentheses Repeat to jump to opening parentheses
Select all contents of the current parentheses
Delete from cursor to end of line
Delete from cursor to start of line
Indent current line(s)
Un-indent current line(s)
Duplicate line(s)
Join line below to the end of the current line
Comment/un-comment current line
Block comment current selection
Redo, or repeat last keyboard shortcut command
Paste and indent correctly
Select next auto-complete suggestion
soft undo; jumps to your last change before undoing change when repeated
Command
Quick-open files by name
Goto symbol
Goto word in current file
Goto line in current file
11.11.3 General
Keypress
Ctrl + + P
Ctrl + KB
Ctrl + + Alt + P
Command
Command prompt
Toggle side bar
Show scope in status bar
11.11.4 Find/Replace
Keypress
Ctrl + F
Ctrl + H
Ctrl + + F
Command
Find
Replace
Find in files
73
11.11.5 Tabs
Keypress
Ctrl + + t
Ctrl + PgUp
Ctrl + PgDn
Ctrl +
Alt + [NUM]
Command
Open last closed tab
Cycle up through tabs
Cycle down through tabs
Find in files
Switch to tab number [NUM] where [NUM] <= number of tabs
Command
Split view into two columns
Revert view to single column
Set view to grid (4 groups)
Jump to group where num is 1-4
Move file to specified group where num is 1-4
11.11.7 Bookmarks
Keypress
Ctrl + F2
F2
+ F2
Ctrl + + F2
Command
Toggle bookmark
Next bookmark
Previous bookmark
Clear bookmarks
Command
Transform to Uppercase
Transform to Lowercase
74
11.12.1 Editing
Keypress
+X
+
+ +
+ +
+ +
+L
+D
+M
+ +M
+ K, + K
+K+
+]
+[
+ +D
+/
+ +/
+Y
+ +V
+ Space
+U
Command
Delete line
Insert line after
Insert line before
Move line/selection up
Move line/selection down
Select line - Repeat to select next lines
Select word - Repeat select others occurrences
Jump to closing parentheses Repeat to jump to opening parentheses
Select all contents of the current parentheses
Delete from cursor to end of line
Delete from cursor to start of line
Indent current line(s)
Un-indent current line(s)
Duplicate line(s)
Join line below to the end of the current line
Comment/un-comment current line
Block comment current selection
Redo, or repeat last keyboard shortcut command
Paste and indent correctly
Select next auto-complete suggestion
soft undo; jumps to your last change before undoing change when repeated
Command
Quick-open files by name
Goto symbol
Goto word in current file
Goto line in current file
11.12.3 General
Keypress
+ +P
+ K, + B
+ +P
Command
Command prompt
Toggle side bar
Show scope in status bar
11.12.4 Find/Replace
Keypress
+F
+ +F
Command
Find
Replace
Find in files
75
11.12.5 Tabs
Keypress
+ +t
Command
Open last closed tab
Cycle up through tabs
Cycle down through tabs
Find in files
Command
Split view into two columns
Revert view to single column
Set view to grid (4 groups)
Jump to group where num is 1-4
Move file to specified group where num is 1-4
11.12.7 Bookmarks
Keypress
+ F2
F2
+ F2
+ + F2
Command
Toggle bookmark
Next bookmark
Previous bookmark
Clear bookmarks
76
Command
Transform to Uppercase
Transform to Lowercase
CHAPTER
TWELVE
GLOSSARY
buffer Data of a loaded file and additional metadata. Associated with one or more views. The distinction between
buffer and view is technical. Most of the time, both terms can be used interchangeably.
view Graphical display of a buffer. Multiple views can show the same buffer.
plugin A feature impemented in Python. It can consist of a single command or multiple commands. It can be
contained in one .py file or many .py files.
package This term in ambiguous in the context of Sublime Text, because it can refer to a Python package (unlikely), a
directory inside Packages or a .sublime-package file. Most of the time, it means a directory inside Packages
containing resources that belong together to build a new feature or provide support for a programming or markup
language.
panel An input/output widget such as a search panel or the output panel.
overlay An input widget of a special kind. Goto Anything is an overlay.
77