Sublime Text 非官方文档

中文翻译 by 白汀

部分章节里的内容(搜索和替换,构建系统,定制化,参考手册,术语)引用了 这个项目 的成果

英文原版 by Guillermo López-Anglada

本文档适用于Sublime Text 3

Sublime Text 3官方文档可以查看 这里

关于此文档

这是Sublime Text编辑器的非官方文档。

sublime是什么?

Sublime Text 是一个代码编辑器。它可以避免很多重复的任务,所有你可以专注于你的工作。它用起来非常有趣!

如果你第一次浏览到这里,建议你先阅读一下 基本概念 章节。

Happy learning!

安装

Sublime Text在每个平台的安装过程有些不一样。

确认阅读下官方网站的 使用条件 。Sublime Text不是免费的。

32-位还是64-位?

如果你运行的是64-位系统选择64-位版本的,如果是32-位系统选择32-位版本的。

**Windows**下,如果你不确定的话,可选择32-位版本。64-位Windows系统也可以运行32-位软件。译者注:建议还是使用32-位版本的,

(译者注:建议还是使用32-位版本的,本人64-位Windows系统使用64-位版本时,貌似Side Bar的菜单有点问题)

Linux 下可以运行下面的命令来查看操作系统的类型:

uname -m

OS X, 可以忽略这个选项,OS X下只有一个版本的Sublime Text。

Windows

便携的 or 非便携的?

Sublime Text对Windows有两种风格的版本:普通版,和便携版。如果你对便携版有所了解可以使用它,否则最好使用普通版本。

普通安装版 把数据分开在两个目录:对应的安装文件夹,和 data 目录。后面会解释这些概念。普通安装版同时也会集成Sublime Text到Windows菜单。

便携安装版 把所有Sublime Text所有需要运行的文件都放在一个目录下。 你可以把这个文件夹移动到其它地方,编辑器仍可以正常工作。

如何安装普通版Sublime Text

下载安装程序,运行并按界面提示安装。

如何安装便携版Sublime Text

下载压缩吧,解压到指定位置。 解压目录下会有 sublime_text.exe 可执行文件。

OS X

以Sublime Text 2为例

下载并打开 *.dmg*文件,然后把Sublime Text 2拖拽到 *Applications*文件夹下。

Linux

以Sublime Text 2为例

你可以手动下载安装包并解压。不过你可以通过命令行来完成。

For i386

cd ~
wget http://c758482.r82.cf2.rackcdn.com/Sublime\ Text\ 2.0.1.tar.bz2
tar vxjf Sublime\ Text\ 2.0.1.tar.bz2

For x64

cd ~
wget http://c758482.r82.cf2.rackcdn.com/Sublime Text 2.0.1 x64.tar.bz2
tar vxjf Sublime\ Text\ 2.0.1\ x64.tar.bz2

把解压的目录转移到合适的位置。

sudo mv Sublime\ Text\ 2 /opt/

最后,给命令行调用创建一个 符号链接(symbolic link)

sudo ln -s /opt/Sublime\ Text\ 2/sublime_text /usr/bin/sublime

Ubuntu下,如果你要把Sublime Text添加到Unity启动器的话,继续阅读。

首先需要创建一个新的文件。

sudo sublime /usr/share/applications/sublime.desktop

把下面这些内容复制进去。

[Desktop Entry]
Version=2.0.1
Name=Sublime Text 2
# Only KDE 4 seems to use GenericName, so we reuse the KDE strings.
# From Ubuntu's language-pack-kde-XX-base packages, version 9.04-20090413.
GenericName=Text Editor

Exec=sublime
Terminal=false
Icon=/opt/Sublime Text 2/Icon/48x48/sublime_text.png
Type=Application
Categories=TextEditor;IDE;Development
X-Ayatana-Desktop-Shortcuts=NewWindow

[NewWindow Shortcut Group]
Name=New Window
Exec=sublime -n
TargetEnvironment=Unity

如果你已经注册了Sublime Text许可,但是每次启动时都要你输入license,可以尝试执行下面这个命令。

sudo chown -R username:username /home/username/.config /sublime-text-2

username 替换成你的用户名。这样就可以避免输入license之后以root权限打开Sublime Text的权限错误。

勇于尝试 or Not

Sublime Text 有三个发布 通道:

如果你做的是NASA项目或者正处于deadline的话,你还是使用stable releases吧。 Stable releases 经过良好的测试,比其它版本都更加稳定。大于一个月会发布一次更新。 大多数用户都只需要使用稳定版本

devnightly 通道是不稳定版本,意味着他们可能有很多bug,不那么可靠。它们比stable releases更新得更频繁。

Dev builds 所有人都可以使用。平均来看,每2个月会发布一次。它并不是给所有人准备的,它们会展现一些新功能。

nightly builds 是一个边缘版本,会频繁的更新,同时也会频繁的引发问题。尝试它们会非常的有趣,不过你要自己承担风险。Nightly 版本 只开放给注册用户使用

基本概念

概述

为了能更清晰完整的明白整个文档手册,你需要熟悉一下本小节中提到的概念。

约定

我们从一个Windows用户的视角来编写文档,大部分说明只需要一点小变化就可适用于其它平台。

相对路径, 比如 Packages/User, 如果没有特定说明的话都是开始于 data目录data目录 后面会说明。

当提到快捷键时我们都假定默认的键盘绑定。 如果你适用non-English键盘布局,注意 有一些键盘绑定与你的键盘区域不匹配。这要归结于Sublime Text命令的按键映射。

因强大而引发的一些问题

对于编程人员来说它无疑是一个多功能的工具,你不需要为了某一个功能而去使用Sublime Text,也不需要做很多配置。如果你是一个hacker,它将会给你带来很多惊喜。

Sublime Text可以无限制的自定义和扩展。在它原始的状态下你也可以非常有效率的开始使用它,不过花一些时间来定制它,以满足更精确的需求,给你带来的好处将会远超过你花费的精力。

这部手册将会教你如何配置Sublime Text。

你不用一天就掌握Sublime Text,不过它是一个基于随处渗透着一致性和易于理解的指导思想构建起来的额系统。

后面几个段落中,我们将会介绍几个关键点,会令你在花了一点时间使用该编辑器之后心旷神怡。乐于尝试,随手翻阅这部手册,最后一切都会水到渠成。

Data 目录

基本上所有与用户相关的文件都在data目录下。 根据系统平台的不同:

  • Windows: %APPDATA%\Sublime Text 3
  • OS X: ~/Library/Application Support/Sublime Text 3
  • Linux: ~/.config/sublime-text-3

如果是 portable installations(便携安装的版本), 在子目录 Sublime Text 3/Data*下。这里 *Sublime Text 3 指的是你解压的便携式压缩包的目录。

注意之后便携式版本有 *Data*子目录。 其它安装版本,data目录在上面对应的位置。

Packages 目录

这是一个 关键目录: 所有用于支持编程和标记语言的资源都存放在这里。一个 package 就是一个包含对于Sublime Text有特定意义文件的目录。

你可以通过(Preferences | Browse Packages...)菜单来访问packages目录,或者通过API调用: sublime.packages_path() 。在这部手册中,我们把它定义为这个路径定义为 Packages, packages path, packages folder 或者 packages directory

User

Packages/User 是一个包含自定义插件(plugins),代码片段(snippets),宏命令(macros)之类的目录。可以把它认为是在packages目录下你的个人区域。Sublime Text在更新时将不会覆盖 Packages/User 下的内容。

Python 控制台和 Python API

这部分信息可能对于编程人员来说比较感兴趣。对已其它用户来说,你只需要知道Sublime Text允许用户利用他们的编程技能来给编辑器添加他们自己的特性。(所以学会编程吧,它真的很有趣!)

Sublime Text 内嵌了一个Python解析器。它是一个非常有用的工具,可用于检查编辑器的配置,开发插件时可用于快速的测试API调用。

要打开Python控制台,Ctrl+` 或者通过菜单 View | Show Console

还是困惑? 那我们慢点来讲述下:

Python 是一个对于初学者来说容易上手且强大的编程语言。 API 是’Application Programming Interface’的简称,换句话说Sublime Text 3就是用这种方式为用户提供可编程性。Subime Text让用户通过Python来访问其内部。console(控制台) 是Sublime Text内的一个小窗口,你可以输入Python代码并运行它们。控制台同时也会显示Sublime Text或者其插件的输出。

系统的Python vs Sublime Text 3内置的Python

WindowsLinux 下,Sublime Text 3有它自己的Python解析器,而且是与系统安装的Python是分开的。

OS X 下使用的是系统给的Python。修改系统的Python版本,比如替换成MacPorts版本,将会导致Sublime Text出问题。

内置的解析器仅是为与插件API交互而准备的,而不是为一般性编程准备的。

Packages, Plugins, Resources以及其它一些你现在可能未理解的东西

几乎Sublime Text的所有方面都可以被修改,扩展和自定义。这一点你现在必须明白。 正因为其广大的灵活性,所以你现在需要学些这么多的配置文件:必须要有个地方来指定你的偏好。

此外,你可以修改编辑器的行为,添加macros(宏命令)和代码片段,扩展菜单...甚至是创建一个全新的特性 – 特性 的意思就是 ‘所有你能想到的’。好了,或许有些事情你是不能做的,不过这已经足够你选择了。

这些配置文件是JSON *格式*的普通文本文件,不过同时你也会发现XML文件和Python文件。

在这部手册中,我们统一把这些配置文件定义为 resources(资源)

Sublime Text会检查packages目录下的资源文件。为了整洁,编辑器有一个 *package(包)*的概念,它是一个把资源文件(它们可能适用于帮助编写邮件,更高效的编写HTML,提升C,Ruby,Go代码编写体验等等)归档在一起的目录。

Textmate兼容性

这部分信息可能对于丢弃Textmate,在Sublime Text中找到一个全新世界的人来说比较有用。Textmate是Mac下的一个编辑器。

Sublime Text与Textmate兼容的非常好,除了命令之外。另外,Sublime Text要求所有语法定义 .tmLanguage*为格式,所有偏好设置文件为 *.tmPreferences 格式。这意味着 .plist 文件将会被忽略,尽管它们放在 Syntaxes 或者 Preferences 子目录下。

Vi/Vim 仿真

这部分信息主要对恐龙或者那些比较喜欢与RSI术语打交道的人来说有用。 Vi是一个可以让用户所有操作都通过键盘来完成的古老的编辑器。Vim, 是vi的一个更现代的版本,仍然在广泛使用。

Sublime Text通过 Vintage 包提供里vi仿真。Vintage包默认是 ignored 。可以在官方文档中阅读更多关于 Vintage 的信息。

一个Vintage变种,Vintageous 提供了更好的Vi编辑体验而且比Vintage更新更频繁。 Vintageous 是一个开源项目。

Emacs

这部分信息对于所有人都很难有点用处。Emacs这玩意...,没人真的知道emacs是啥,不过确实有些人用它来编辑文本。

如果你是一个emacs用户,你可能就不会阅读这些内容了。

用Sublime吧,骚年

借用下 Bruce Lee’s wisdom, Sublime Text几乎可以成为任何你想要的东西。好帮手, blah, blah, blah.

Empty your mind; be sublime, my friend.

编辑

概述

Sublime Text充满着各种编辑功能。这里只粗浅的讲述下哪些是可以做的。

列选择

列选择可用于选择一个文件里的矩形区域。列选择并不是通过一个单独模式完成的,而是使用多重选择。

你可以添加选区域来选择多个文本块,或者减少选区来移除选择块。

使用鼠标

Windows

  • 鼠标右键 ``+ ⇧ ``
  • 或: 鼠标中键

  • 添加到选区: Ctrl
  • 从选区移除: Alt

Linux

  • 鼠标右键 +

  • 添加到选区: Ctrl
  • 从选区移除: Alt

OS X

  • 鼠标左键 +
  • 或: 鼠标中键

  • 添加到选区:
  • 从选区移除: +

使用键盘

Windows: Ctrl + Alt + Up and Ctrl + Alt + Down

Linux: Alt + + Up and Alt + + Down

OS X: + + Up and + + Down

多区域选择

多重选择可以让你有效率的进行大范围的文本修改。

对多重选择的任何赞美都过于轻淡了,这是因为:

你可以选择某个文本然后 Ctrl + D 添加更多 实体(可参考 官方文档部分)。 如果想 跳过当前实体, 可以 Ctrl + K, Ctrl + D

如果选择过多, Ctrl + U取消选择 当前实体。

把多选区分割成行

Ctrl + L 扩展选择到行。 Ctrl + Shift + L 把选区分割成行。

你可以把多重选择的行复制到一个单独的缓冲区,编辑它们,然后再复制编辑后的内容,然后把它们在原来的地方粘贴回去。像下面这样:

_images/copy_edit.gif

其它选择文本的方式

方式有很多种,可以在 **Selection**菜单下找到。举几个例子:

  • Select subwords (Alt + Shift + <arrow>)
  • Expand selection to brackets (Ctrl + Shift + M)
  • Expand selection to indentation (Ctrl + Shift + J)
  • Expand selection to scope (Ctrl + Shift + Space)

置换

``Ctrl + T``可以将光标位置前后2个字符位置置换.

更多...

Edit, Selection, FindGoto 这些菜单下面包含了大量的编辑指令。可能最终你只会用到其中的少部分,不过当你需要的时候仍有大量的方式可供选择。

搜索和替换

Sublime Text提供2种类型的搜索:

搜索和替换 - 单个文件

搜索

Ctrl + F 可以打开当前缓冲区的 搜索面板。可通过下面这些指令对搜索面板进行控制:

(译者注:关于缓冲区,请参考 词汇表 这个章节)

增量搜索

增量搜索面板 可以通过``Ctrl + I``打开。与正常的搜索面板相比,唯一的区别在于 回车

键的作用:在增量搜索中,按下回车键将选中缓冲区中下一段与搜索条件匹配的文字,并自动关闭面板。 一般来说,可以根据个人的喜好来决定是选择增量搜索面板还是普通搜索面板。

替换文本

可以通过 Ctrl + H 来打开替换面板。

替换全部内容: Ctrl + Alt + Enter

小技巧

搜索文本的其他方法

可以在Goto Anything(快速跳转)(译者注:ctrl+P唤出,或者菜单栏->Goto->Goto Anything)面板中使用 # 操作符在当前缓冲区中进行搜索。跟在 # 操作符后面的内容将被识别为搜索关键字。

文本搜索的其他快捷键

下面的这些快捷键在搜索面板不可见的情况下仍然有效。

使用最近一次的搜索模式进行前向搜索 F3
使用最近一次的搜索模式进行后向搜索 Shift + F3
使用最近一次的搜索模式进行全搜索 Alt + F3
多行搜索

你可以输入一个多行搜素模式。在搜索面板中使用 Ctrl + 回车 键来输入换行符。值得一提的是, 搜索面板的大小是可以调整的。

搜索与替换 - 多文件

搜索

使用 Ctrl + Shift + F 键可以打开多文件搜索面板。搜索面板与搜索动作可以使用快捷键进行操作:

切换正则表达式开关 Alt + R
切换大小写敏感开关 Alt + C
切换准确匹配开关 Alt + W
查找下一个 Enter

搜索范围

搜索面板中的 Where 字段决定搜索文件的范围。你可以通过以下几种方式来确定文件的搜索作用域:

  • 添加一个独立的目录 (需要使用 Unix风格的文件路径,在Windows平台也是如此)
  • 使用某种模式来添加/删除某些文件
  • 添加链接位置(<open folders>, <open files>)

你可以在一次搜索中组合使用以上确定作用域的方式,并且在不同方式之间用逗号分隔,例如:

/C/Users/Joe/Top Secret,-*.html,<open files>

通过在搜索面板中按 ... 按钮来显示包含这些选项的菜单。

(译者注:Unix风格的文件路径指的是使用 / 来区分目录结构,例如 /Users/voidmain/ ,在 Windows平台上,可以使用 /C/Users/ 来指定盘符)

搜索结果显示方式

在搜索面板中,可以使用下面的选项来自定义搜索结果的显示方式:

  • 在单独的缓冲区/输出面板中显示
  • 显示上下文

搜索结果跳转

一旦找到了符合要求的内容,你就可以使用以下的快捷键进行结果之间的跳转:

转到下一个匹配项 F4
转到前一个匹配相 Shift + F4

我们将依次讲解它们,不过我们先讲下一个强大的搜索利器:正则表达式。

正则表达式

正则表达式可查找文本中的 复杂模式。要全面的掌握Sublime Text的搜索功能,你至少应该学会基本的正则表达式。本手册中我们不讲解如何使用正则表达式。

下面就是一个正则的样子:

(?:Sw|P)i(?:tch|s{2})\s(?:it\s)?of{2}!

正则以令人痛苦而出名。

要使用正则,首先你要在搜索面板的模式中激活它。否则,搜索词将按字面意思查找。

Sublime Text使用正则表达式中的 Boost语法

(译者注:正则表达式有很多类型的方言)

构建系统(批处理)

通过构建系统,你能够使用像 maketidy 这样的外部程序以及各种解释器 来运行你的文件。

在构建系统中调用的外部可执行程序一定要能够通过 PATH 环境变量找到。请参考 构建系统常见问题 章节来了解有关如何正确设置 PATH 环境变量的更多信息。

文件格式

构建系统是以 .sublime-build 作为文件扩展名的JSON文件。

示例

下面是构建系统的一个小例子:

{
    "cmd": ["python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}
cmd

必填内容。这个选项的内容是实际执行的命令行语句:

python -u /path/to/current/file.ext
file_regex
存放一段用于捕获外部程序输出的错误信息的Perl风格的正则表达式。这部分信息用于帮助你在不同 的错误实例之间使用 F4 快捷键进行跳转。
selector
如果你勾选了 Tools | Build System | Automatic 选项,Sublime Text会自动从构建 系统中通过 selector 选项找到适合当前文件的构建方式。

除了这些选项,在构建系统中还可以使用一些变量,例如在前面使用的 $file 变量,就能自动扩充为 当前缓冲区对应的文件名。

构建系统存储在哪里

构建系统必须被放在 Packages 文件夹下面的某个位置(例如 Packages/User)。许多包都含有它们自己 的构建系统。

运行构建系统

可以使用 F7 快捷键来运行构建系统,也可以从 Tools | Build 菜单中运行。

参考

构建系统参考手册
包含所有可用选项、变量。

文件导航与文件管理

任意跳转

Use Goto Anything to navigate your project’s files swiftly. (More about projects later.)

To open Goto Anything, press Ctrl+P. As you type into the input area, all file names of files open within the editor (and of files in added folders too) will be searched, and a preview of the best match will be shown. This preview is transient; that is, it won’t become the actual active view until you perform some operation on it. Transient views go away when you press Esc. You will see transient views in other situations too.

But Goto Anything lives up to its name—there’s more to it than searching files:

To perform a fuzzy text search using Goto Anything, append # and keep typing, like this:

isl#trsr

This makes Sublime Text perform a fuzzy search for trsr in files whose name loosely matches isl. For example, you could find the word treasure inside a file named island.

To perform a fuzzy search in the current view, press Ctrl+;.

Fuzzy searches can detect transposed characters for clumsy fingers.

And there’s more:

To search symbols in the current view, press Ctrl+R. As in the case of #, the @ operator can be used after file names too.

To go to a line number, press Ctrl+G. Again, the operator : can be used after file names, just as # and @.

Searching for symbols will only work if the active file type has symbols defined for it. Symbols are defined in .tmLanguage files.

侧边栏

侧边栏可以提供一个项目的概览视图。添加到侧边栏的文件和目录均可以通过“任意跳转”功能访问,同时也适用于项目范围的操作(比如项目范围内的搜索)。项目与侧边栏是密切相关的。不管以显式或是隐式的方式,总是有一个项目存在于侧边栏中。

可以通过组合键:kbd:`Ctrl+K, Ctrl+B`来打开或关闭侧边栏。

在侧边栏可以使用方向键来在文件间切换,但是首先需要通过按组合键:kbd:Ctrl+0 使其获得**输入焦点**。 如果希望缓冲区重新获得输入焦点,则需要按 :kbd:`Esc`键。同样,你也可以使用鼠标达到同样的效果。

Files opened from the sidebar create semi-transient views. Unlike transient views, semi-transient views show up as a new tab. You will be able to tell semi-transient views from other views because their tab text is shown in italics. When a new semi-transient view is opnened, any existing semi- transient view in the same pane gets automatically closed.

侧边栏可以通过菜单的方式提供基本的文件管理操作。

项目

Projects group sets of files and folders to keep your work organized. Set up a project by adding folders in a way that suits you, and then save your new configuration.

To save a project, go to Project | Save Project As....

To switch projects quickly, press Ctrl+Alt+P.

Project data is stored in JSON files with a .sublime-project extension. Wherever there’s a .sublime-project file, you may find one or more .sublime-workspace files. Workspaces are explained later.

Project files can define settings specific to that project. More information in the official documentation.

You can open a project from the command line by passing the .sublime- project file as an argument to the Sublime Text executable.

Workspaces

Workspaces can be seen as different views into the same project. For example, you may want to have only a selected few files open while working on Feature A. Or perhaps you use a different pane layout when you’re writing tests, etc. Workspaces help in these situations.

**Workspaces behave very much like projects. To create a new workspace, select **Project | New Workspace for Project. To save the current workspace, select **Project | Save Workspace As....

Workspaces data is stored in JSON files with the .sublime-workspace extension.

Contrary to .sublime-project files, .sublime-workspace files are not meant to be shared or edited manually. Never commit .sublime-workspace files into a source code repository.

To switch between different workspaces, use Ctrl+Alt+P, exactly as you do with projects.

As with projects, you can open a workspace from the command line by passing the desired .sublime-workspace file as an argument to the Sublime Text executable.

Panes

Panes are groups of Views. In Sublime Text you can have multiple panes open at the same time.

To create a new pane, press Ctrl+K, Ctrl+Up. To destroy a pane, press Ctrl+K, Ctrl+Down.

To find further pane management commands, look under View | Layout and related submenus.

定制Sublime Text

Sublime Text是高度可定制的。在接下来的几节中,我们将向你介绍如何根据自己的需要和偏好来定制它。

配置

Sublime Text把配置信息保存在 .sublime-settings 文件中。为了拥有较好的灵活性,作为代价, 需要一个略显繁琐的系统来管理配置项。我们先来说一条基本原则吧:

个人定义的配置项文件一定要保存到 Packages/User 目录下,这样就能保证在发生冲突的时候,你定 义的文件拥有较高的优先级。

那咱们就来揭开配置项工作的具体原理了,从而满足部分喜欢受虐读者的需求。

格式

配置项文件是以 .sublime-settings 作为扩展名的的JSON文件。

配置文件的类型

可以通过 .sublime-settings 文件的名字看出它的用途。这些文件的名字可能具有一定的描述性(例如 Preferences (Windows).sublime-settings 或者 Minimap.sublime-settings),亦或是跟 它所控制的内容有关联。以控制文件类型的配置项文件为例,命名时要求必须有与之对应的 .tmLanguage 语法定义文件。因此,对于 .py 文件类型,它的语法定义信息存放在 Python.tmLanguage 文件中, 那么对应的文件类型配置项文件就该被叫做 Python.sublime-settings

除此之外,某些配置文件只能作用于某个特定的平台。可以通过文件名进行推断,例如: Preferences (Windows).sublime-settingsPreferences (Linux).sublime-settings

有一点特别 重要 :存放在 Packages/User 目录中的平台相关的配置文件将被忽略。通过这种方式, 就可以保证单个配置文件内容可以覆盖其他所有配置文件的内容了。

如何访问并修改公共的配置文件

除非你对配置项有非常精确的掌控力,否则,你只需要通过 Preferences | Settings - UserPreferences | Settings - More 菜单项来访问主要的配置文件。编辑 Preferences - Settings Default 这个文件并不是一件明智的事情,因为每次版本升级这些修改都 将被重置。不过,你确实可以把这些文件当作一个不错的参考资料:默认配置项文件里面包含了解释所有能 为你所用的全局配置项和文件类型配置项的说明注释。

.sublime-settings 文件的优先级顺序

名字相同的配置项文件(例如,都叫 Python.sublime-settings 的文件)可以在多个位置出现。以相同 名称命名的配置项文件中的内容都将按预定义的规则进行合并或者覆盖。请参考 合并与优先级顺序 这一小节以了解更多信息。

再说明一次,在 Packages/User 目录下的配置项文件拥有最高优先级,并且最终会覆盖其他同名配置项 文件中的相同内容。

除了配置项文件以外,Sublime Text还维护 会话 数据 —— 一些针对正在编辑的文件集所应用的配置项。 会话数据是在你编辑文件的过程中发生变化的,所以,无论你通过何种方式调整了一个特定文件的配置项 (主要是通过API调用的方式),这些配置项的变更将被记录在当前的会话中,并且将拥有比所有符合条件的 .sublime-settings 文件更高的优先级。

如果想要检查针对特定文件当前正在发挥作用的配置项的值,可以在控制台中输入 view.settings().get(<配置项名称>) 命令。

最后需要注意的是,某些配置项的值可能会被系统自动进行调整。请记住这一点,这样一来你就能够解释某 些令你困惑的配置项内容了。举例来说,在查看某些与空格相关的配置项的值,以及某些 语法 配置项 内容的时候,就有可能遇到这种问题。

接下来你将看到Sublime Text是如何处理Windows平台上Python相关的配置项文件的,这里的配置项文件 目录结构是虚构的:

  • Packages/Default/Preferences.sublime-settings
  • Packages/Default/Preferences (Windows).sublime-settings
  • Packages/User/Preferences.sublime-settings
  • Packages/Python/Python.sublime-settings
  • Packages/User/Python.sublime-settings
  • 当前文件的会话数据
  • 由系统自动调整的配置项内容

(译者注:分析下优先级,可以得到结论:全局默认项 < 平台默认项 < 用户配置项 < 语言相关的配置 < 由用户指定的语言相关的配置 < 会话数据 < 系统调整的数据)

全局编辑器配置以及全局文件配置

这类全局配置项内容一般被保存在名为 Preferences.sublime-settingsPreferences (<platform>).sublime-settings 的文件中。默认的全局配置项存放在 Packages/Default 目录中。

上面所说的 <platform> 可能是 Linux, OSX, 或者 Windows.

文件类型配置

如果你想针对某个特定的文件类型进行一些配置,那请根据这个文件类型的语法定义文件名称来对应的命名 .sublime-settings 文件。举例来说,如果我们的语法定义文件叫 Python.tmLanguage ,那么 配置项文件的名称就应该叫 Python.sublime-settings

通常情况下,某个特定文件类型的配置项信息一般存放在包组文件夹的一个目录中,例如 Packages/Python, 但是,与同一个文件类型相关的多个配置项文件也有可能被存放在不同的位置。

与全局配置项类似,也可以为文件类型配置项信息创建平台相关的内容。例如只有在Linux平台下,保存在 Python (Linux).sublime-settings 中的配置项内容才会被系统考虑。

需要特别指出的一点是,在 Packages/User 目录下,只有 Python.sublime-settings 文件会被 加载,所有以 Python (<platform>).sublime-settings 命名的平台相关的变种都不会被考虑。

不管文件类型配置项信息保存在哪里,它拥有比保存在全局配置项文件中的、影响文件类型的配置项都高的 优先级。

用户配置信息应该保存到哪里

无论何时,当你想要保存一些配置的时候,尤其是那些在软件升级前后应该被保留的配置,就把它们保存在 Packages/User 目录下的对应 .sublime-settings 文件中吧。

缩进

参考

官方Sublime Text文档 缩进

键盘绑定

键盘绑定使得你能够将按键与动作进行映射。

文件格式

键盘绑定是以 .sublime-keymap 作为扩展名的JSON文件。为了让键盘能够更好的与各平台融合,系统为 Linux,OSX以及Windows平台分别提供了不同的文件。只有与当前系统相符的键盘映射文件才会生效。

示例

下面这段代码是从Windows平台默认的按键映射文件中截取出来的:

[
        { "keys": ["ctrl+shift+n"], "command": "new_window" },
        { "keys": ["ctrl+o"], "command": "prompt_open_file" }
]

定义与重载键盘绑定

Sublime Text自带一套默认的键盘绑定(一般对应这个文件: Packages/Default/Default (Windows).sublime-keymap))。如果你想重载其中的部分键盘 或者添加新的键盘绑定,你可以在具有更高文件优先级的位置重新存储一个文件,例如 Packages/User/Default (Windows).sublime-keymap

请参考 合并与优先级顺序 来了解Sublime Text中关于文件优先级以及文件合并的更多信息

高级键盘绑定

对于简单的键盘绑定,就是一个键盘组合对应一个命令。除此之外,还有一些传递参数和上下文信息的复杂语法。

参数传递

通过 args 键可以指定需要的参数:

{ "keys": ["shift+enter"], "command": "insert", "args": {"characters": "\n"} }

在这个例子中当你按下 Shift+Enter 的时候, \n 将会作为参数传递给 insert 命令

上下文

利用上下文,可以通过插入符的位置及其他状态信息来决定某种键盘组合是否可以发挥作用。

{ "keys": ["escape"], "command": "clear_fields", "context":
        [
                { "key": "has_next_field", "operator": "equal", "operand": true }
        ]
}

这段代码的作用是 当有下一个可用域的时候就清空当前代码片段,并返回正常编辑模式 。因此,当你 没有在代码域中循环切换的时候,按下 ESC 键就 不会 触发这个按键绑定(然而,如果 ESC 恰巧与另外的上下文进行了绑定,那么那个动作仍然会被触发——事实上,对于 ESC 来说,这种情况 并不少见)。

菜单栏

关于这个主题没有任何可用文档。

但是,可以参考 李小龙的嘶吼

Extending Sublime Text

As can be seen from the long list of topics below, Sublime Text is a very extensible editor.

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 editor’s core, but many of them are provided as Python plugins. Every command can be called from a Python plugin.

Command Dispatching

Normally, commands are bound to the application object, a window object or a view object. Window objects, however, will dispatch commands based on input focus, so you can issue a view command from a window object and the correct view instance will be found for you.

Anatomy of a Command

Commands have a name separated by underscores (snake_case) like hot_exit, and can take a dictionary of arguments whose keys must be strings and whose values must be JSON types. Here are a few examples of commands run from the Python console:

view.run_command("goto_line", {"line": 10})
view.run_command('insert_snippet', {"contents": "<$SELECTION>"})
view.window().run_command("prompt_select_project")

See also

Reference for commands
Command reference.

Macros

Macros are a basic automation facility comprising 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.

How to Record Macros

To start recording a macro, press Ctrl+q and subsequently execute the desired steps one by one. When you’re done, press Ctrl+q again to stop the macro recorder. Your new macro won’t be saved to a file, but kept in the macro buffer instead. Now you will be able to run the recorded macro by pressing Ctrl+Shift+q, or save it to a file by selecting Tools | Save macro...

Note that the macro buffer will remember only the latest recorded macro. Also, macros only record commands sent to the buffer: window-level commands, such creating a new file, will be ignored.

How to Edit Macros

As an alternative to recording a macro, you can edit it by hand. Just save a new file with the extension .sublime-macro under PackagesUser and add commands to it. Macro files have this format:

[
    {"command": "move_to", "args": {"to": "hardeol"}},
    {"command": "insert", "args": {"characters": "\n"}}
]

See the ../core/commands section for more information on commands.

If you’re editing a macro by hand, you need to escape quotation marks, blank spaces and backslashes by preceding them with \.

Where to Store Macros

Macro files can be stored in any package folder, and then will show up under Tools | Macros | <PackageName>.

Snippets

Whether you are coding or writing the next vampire best-seller, you’re 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, adapting it to their context.

To create a new snippet, select Tools | New Snippet... Sublime Text will present you with an skeleton for it.

Snippets can be stored under any package’s folder, but to keep it simple while you’re learning, you can save them to your Packages/User folder.

Snippets File Format

Snippets typically live in a Sublime Text package. They are simplified XML files with the extension sublime-snippet. For instance, you could have a greeting.sublime-snippet inside an Email package.

The structure of a typical snippet is as follows (including the default hints Sublime Text inserts for your convenience):

<snippet>
    <content><![CDATA[Type your snippet here]]></content>
    <!-- Optional: Tab trigger to activate the snippet -->
    <tabTrigger>xyzzy</tabTrigger>
    <!-- Optional: Scope the tab trigger will be active in -->
    <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 and when. Let’s see all of these parts in turn.

content

The actual snippet. Snippets can range from simple to fairly complex templates. We’ll look at examples of both later.

Keep the following in mind when writing your own snippets:

  • If you want to get a literal $, you have to escape it like this: \$.
  • When writing a snippet that contains indentation, always use tabs. When the snippet is inserted, the tabs will be transformed into spaces if the option translateTabsToSpaces is true.
  • The content must be included in a <![CDATA[...]]> section. Snippets won’t work if you don’t do this!
  • The content of your snippet must not contain ]]> because this string of characters will prematurely close the <![CDATA[…]]> section, resulting in an XML error. To work around this pitfall, you can insert an undefined variable into the string like this: ]]$NOT_DEFINED>. This modified string passes through the XML parser without closing the content element’s <![CDATA[…]]> section, but Sublime Text will replace $NOT_DEFINED with an empty string before inserting the snippet into your document. In other words, ]]$NOT_DEFINED> in your snippet file content will be written as ]]> when you trigger the snippet.
tabTrigger

Defines the sequence of keys that must be pressed to insert this snippet. After typing this sequence, the snippet will kick in as soon as you hit the Tab key.

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 for displaying the snippet in the Snippets menu. If unavailable, 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, we’re only including the content element’s text in examples unless otherwise noted.

Snippet Features

Environment Variables

Snippets have access to contextual information in the form of environment variables. Sublime Text automatically sets the values of the variables listed below.

You can also add your own variables to provide extra information. These custom variables are defined in .sublime-options files.

Let’s see a simple example of a snippet using variables:

====================================
USER NAME:          $TM_FULLNAME
FILE NAME:          $TM_FILENAME
 TAB SIZE:          $TM_TAB_SIZE
SOFT TABS:          $TM_SOFT_TABS
====================================

# Output:
====================================
USER NAME:          guillermo
FILE NAME:          test.txt
 TAB SIZE:          4
SOFT TABS:          YES
====================================
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 after it’s 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 snippet’s content, enabling you to 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 in real time with the same value.

First Name: $1
Second Name: $2
Address: $3
User name: $1

In this example, “User name” will be filled out with the same value as “First Name”.

Placeholders

By expanding the field syntax a little bit, you can define default values for a field. Placeholders are useful whenever there’s a general case for your snippet, but still you still want to keep it customizable.

#####.. code-block:: perl

First Name: ${1:Guillermo} Second Name: ${2:López} Address: ${3:Main Street 1234} User name: $1

Variables can be used as placeholders:

#####.. code-block:: perl

First Name: ${1:Guillermo} Second Name: ${2:López} Address: ${3:Main Street 1234} User name: ${4:$TM_FULLNAME}

And you can nest placeholders within other placeholders too:

#####.. code-block:: perl

Test: ${1:Nested ${2:Placeholder}}
Substitutions

Warning

This section is a draft and may contain inaccurate information.

In addition to the placeholder 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
Don’t ignore newlines in the string.

With substitutions you can, for instance, underline text effortlessly:

      Original: ${1:Hey, Joe!}
Transformation: ${1/./=/g}

# Output:

      Original: Hey, Joe!
Transformation: =========

Completions

See also

Reference for completions
Complete documentation on all available options.
Sublime Text Documentation
Official documentation on this topic.

In the spirit of IDEs, completions suggest terms and insert snippets. Completions work through the completions list or, optionally, by pressing Tab.

Note that, in the broader sense of words that Sublime Text will look up and insert for you, completions aren’t limited to completions files, because other sources contribute to the list of words to be completed, namely:

  • Snippets
  • API-injected completions
  • Buffer contents

However, the most explicit way Sublime Text provides you to feed it completions is by means of .sublime-completions files. This topic deals with the creation of a .sublime-completions file as well as with the interactions among all sources for completions.

File Format

Completions are JSON files with the .sublime-completions extension. Entries in completions files can contain either snippets or plain strings.

Example

Here’s an excerpt from Sublime Text’s HTML completions:

{
        "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>" }
        ]
}
scope
Determines when the completions list will be populated with this list of completions. See Scopes for more information.

In the example above, we’ve only used trigger-based completions, but completions files support simple completions too. Simple completions are just plain strings. Expanding our example with a few simple completions results in a list like this:

{
        "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"
        ]
}

Sources for Completions

Completions not only originate in .sublime-completions files. Here is the exhaustive list of sources for completions:

  • Snippets
  • API-injected completions
  • .sublime-completions files
  • Words in buffer
Priority of Sources for Completions

This is the order in which completions are prioritized:

  • Snippets
  • API-injected completions
  • .sublime-completions files
  • Words in the buffer

Snippets will always win if the current prefix matches their tab trigger exactly. For the rest of the completion sources, a fuzzy match is performed. Furthermore, snippets always lose with fuzzy matches.

But this is relevant only when the completion is inserted automatically. When a list of completions is shown, snippets will still be listed alongside the other items, even if the prefix only partially matches the snippets’ tab triggers.

How to Use Completions

There are two methods for using completions. Even though, when screening them, the priority given to completions always stays the same, the two methods produce different results, as explained next.

Completions can be inserted in two ways:

  • Through the completions list (Ctrl+spacebar).
  • By pressing Tab.
The Completions List

The completions list (Ctrl+spacebar) does its work in two ways: by bringing up a list of suggested words to be completed, or by inserting the best match directly.

If the choice of best completion is ambiguous, an interactive list will be presented to the user, who then will have to select an item himself. Unlike other items, snippets in this list are displayed in the format: <tab_trigger> : <name>, where <tab_trigger> and <name> are variable.

Using Ctrl+spacebar, the completion choice will be automatic only if the list of completion candidates can be narrowed down to one unambiguous choice, given the current prefix.

Tab-Completed Completions

If you want to be able to tab-complete completions, the setting tab_completion must be true, which is the default. Snippets’ tab-completion is unaffected by this setting: they always will be completed, or not, according to their tab trigger.

With tab_completion enabled, completion of items is always automatic. This means, unlike the case of the completions list, that Sublime Text will always make the decision for you. The rules for selecting the best completion are the same as described above, but in case of ambiguity, Sublime Text will insert the item it deems most suitable.

Inserting a Literal Tab Character

When tab_completion is enabled, you can press Shift+Tab to insert a literal tab character.

Command Palette

See also

Reference for Command Palette
Complete documentation on the command palette options.

Overview

The command palette bound to Ctrl+Shift+P is an interactive list whose purpose is to execute commands. The command palette is fed by entries in .sublime-commands files. Usually, commands that don’t warrant creating a key binding of their own are good candidates for inclusion in a .sublime- commands files.

File Format (Commands Files)

Commands files use JSON and have the .sublime-commands extension.

Here’s an excerpt from Packages/Default/Default.sublime-commands:

[
    { "caption": "Project: Save As", "command": "save_project_as" },
    { "caption": "Project: Close", "command": "close_project" },
    { "caption": "Project: Add Folder", "command": "prompt_add_folder" },

    { "caption": "Preferences: Default File Settings", "command": "open_file", "args": {"file": "${packages}/Default/Base File.sublime-settings"} },
    { "caption": "Preferences: User File Settings", "command": "open_file", "args": {"file": "${packages}/User/Base File.sublime-settings"} },
    { "caption": "Preferences: Default Global Settings", "command": "open_file", "args": {"file": "${packages}/Default/Global.sublime-settings"} },
    { "caption": "Preferences: User Global Settings", "command": "open_file", "args": {"file": "${packages}/User/Global.sublime-settings"} },
    { "caption": "Preferences: Browse Packages", "command": "open_dir", "args": {"dir": "$packages"} }
]
caption
Text for display in the command palette.
command
Command to be executed.
args
Arguments to pass to command.

How to Use the Command Palette

  1. Press Ctrl+Shift+P
  2. Select command

The command palette filters entries by context. This means that whenever you open it, you won’t always see all the commands defined in every .sublime-commands file.

Syntax Definitions

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 named regions. Several editing features in Sublime Text make extensive use of this fine-grained contextual information.

Essentially, syntax definitions consist of regular expressions used to find text, as well as more or less arbitrary, dot-separated strings called scopes or scope names. For every occurrence of a given regular expression, Sublime Text gives the matching text its corresponding scope name.

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. It lives in a public Mercurial repository at Bitbucket.

Download the latest .sublime-package file and install it as described in Installation of .sublime-package Files.

File format

Sublime Text uses property list (Plist) files to store syntax definitions. However, because editing XML files is a cumbersome task, we’ll use JSON instead, and convert it to Plist format afterwards. This is where the AAAPackageDev package (mentioned above) comes in.

Note

If you experience unexpected errors during this tutorial, chances are AAAPackageDev is to blame. Don’t immediately think your problem is due to a bug in Sublime Text.

By all means, do edit the Plist files by hand if you prefer to work in XML, but always keep in mind their differing needs in regards to escape sequences, etc.

Scopes

Scopes are a key concept in Sublime Text. Essentially, they are named text regions in a buffer. They don’t 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 bound to the snippet and looks at the caret’s position in the file. If the caret’s current position matches the snippet’s scope selector, Sublime Text fires it off. Otherwise, nothing happens.

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 inherits the idea of scopes from Textmate, a text editor for Mac. Textmate’s online manual contains further information about scope selectors that’s useful for Sublime Text users too.

How Syntax Definitions Work

At their core, syntax definitions are arrays of regular expressions paired with scope names. Sublime Text will try to match these patterns against a buffer’s text and attach the corresponding scope name to all occurrences. These pairs of regular expressions and scope names are known as rules.

Rules are applied in order, one line at a time. Each rule consumes the matched text region, which therefore will be excluded from the next rule’s matching attempt (save for a few exceptions). In practical terms, this means that you should take care to go from more specific rules to more general ones when you create a new syntax definition. Otherwise, a greedy regular expression might swallow parts you’d like to have styled differently.

Syntax definitions from separate files can be combined, and they can be recursively applied too.

Your First Syntax Definition

By way of example, let’s create a syntax definition for Sublime Text snippets. We’ll be styling the actual snippet content, not the .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 file into scopes. Keep in mind, however, that colors are a different thing from syntax definitions and that scopes have many more uses besides syntax highlighting.

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 ($, <...)

Note

Before continuing, make sure you’ve installed the AAAPackageDev package as explained above.

Creating A New Syntax Definition

To create a new syntax definition, follow these steps:

  • Go to Tools | Packages | Package Development | New Syntax Definition
  • Save the new file in your Packages/User folder as a .JSON-tmLanguage file.

You now should see a file like this:

{ "name": "Syntax Name",
  "scopeName": "source.syntax_name",
  "fileTypes": [""],
  "patterns": [
  ],
  "uuid": "ca03e751-04ef-4330-9a6b-9b99aae1c418"
}

Let’s examine now the key elements.

uuid
Located at the end, this is a unique identifier for this syntax definition. Each new syntax definition gets its own uuid. Don’t modify them.
name
The name that Sublime Text will display in the syntax definition drop-down list. Use a short, descriptive name. Typically, you will use the name of the programming language you are creating the syntax definition for.
scopeName
The top level scope for this syntax definition. It takes the form source.<lang_name> or text.<lang_name>. For programming languages, use source. For markup and everything else, use text.
fileTypes
This is a list of file extensions. When opening files of these types, Sublime Text will automatically activate this syntax definition for them.
patterns
A container for your patterns.

For our example, fill the template with the following information:

{   "name": "Sublime Snippet (Raw)",
    "scopeName": "source.ssraw",
    "fileTypes": ["ssraw"],
    "patterns": [
    ],
    "uuid": "ca03e751-04ef-4330-9a6b-9b99aae1c418"
}

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. We’ll explain later how to convert a syntax definition in JSON to Plist.

Analyzing Patterns

The patterns array can contain several types of elements. We’ll look at some of them in the following sections. If you want to learn more about patterns, refer to Textmate’s online manual.

Matches

Matches 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 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. Make it look like this:

{ "name": "Sublime Snippet (Raw)",
  "scopeName": "source.ssraw",
  "fileTypes": ["ssraw"],
  "patterns": [
  ],
  "uuid": "ca03e751-04ef-4330-9a6b-9b99aae1c418"
}

That is, make sure the patterns array is empty.

Now we can begin to add our rules for Sublime snippets. Let’s start with simple fields. These could be matched with a regex like so:

\$[0-9]+
# or...
\$\d+

However, because we’re writing our regex in JSON, we need to factor in JSON’s 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..."
}

And we can add it to our syntax definition too:

{   "name": "Sublime Snippet (Raw)",
    "scopeName": "source.ssraw",
    "fileTypes": ["ssraw"],
    "patterns": [
        { "match": "\\$\\d+",
          "name": "keyword.source.ssraw",
          "comment": "Tab stops like $1, $2..."
        }
    ],
    "uuid": "ca03e751-04ef-4330-9a6b-9b99aae1c418"
}

We’re now ready to convert our file to .tmLanguage. Syntax definitions use Textmate’s .tmLanguage extension for compatibility reasons. As explained above, they are simply XML files, but in 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 buffer’s 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.

Let’s 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 above steps to update the .tmLanguage file, and restart Sublime Text.

Fine Tuning Matches

You might have noticed, for instance, that the entire text in $PARAM1 is styled the same way. Depending on your needs or your personal preferences, you may want the $ to stand out. That’s where captures come in. Using captures, you can break a pattern down into components to target them individually.

Let’s rewrite one of our previous patterns to use captures:

{ "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, you’d want the other scope to be visually consistent with this one. Go ahead and change it too.

Begin-End Rules

Up to now we’ve been using a simple rule. Although we’ve seen how to dissect patterns into smaller components, sometimes you’ll want to target a larger portion of your source code that is clearly delimited by start and end marks.

Literal strings enclosed by quotation marks or other delimiting constructs are better dealt with by begin-end rules. This is a skeleton for one of these rules:

{ "name": "",
  "begin": "",
  "end": ""
}

Well, at least in their simplest version. Let’s take a look at one that includes 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. Let’s 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). Effectively, this will create nested scopes for beginCaptures, endCaptures and patterns defined within this rule. Optional.
patterns
An array of patterns to match only against the begin-end’s content—they aren’t matched against the text consumed by begin or end themselves.

We’ll 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 we’ll 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 their appearance here.

We’ve seen above that fields can be nested. In order to account for this, we need to style nested fields recursively. That’s what the include rule does when we furnish it the $self value: it recursively applies our entire syntax definition the text captured by our begin-end rule. This portion excludes the text individually consumed by the regexes for begin and end.

Remember, matched text is consumed; thus, it is excluded from the next match attempt.

To finish off complex fields, we’ll style placeholders as strings. Since we’ve 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, let’s style escape sequences and illegal sequences, and then we can 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 you’re familiar with regular expressions.

However, you must take care to place the second rule after any others matching the $ character, since otherwise you may not get the desired results.

Also, even after adding these two additional rules, note that our recursive begin-end rule from above continues to work as expected.

At long last, here’s the final syntax definition:

{   "name": "Sublime Snippet (Raw)",
    "scopeName": "source.ssraw",
    "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.

Plugins

See also

API Reference
More information on the Python API.
Plugins Reference
More information about plugins.

Sublime Text is programmable with Python scripts. Plugins reuse existing commands or create new ones to build a feature. Plugins are a logical entity, rather than a physical one.

Prerequisites

In order to write plugins, you must be able to program in Python.

Where to Store Plugins

Sublime Text will look for plugins directly in these places:

  • Packages
  • Packages/<pkg_name>/

Consequently, any plugin nested deeper in Packages won’t be loaded.

Keeping plugins just under Packages is discouraged, because Sublime Text sorts packages in a predefined way before loading them. So, you might get confusing results if your plugins live outside a package.

Your First Plugin

Let’s write a “Hello, World!” plugin for Sublime Text:

  1. Select Tools | New Plugin... in the menu.
  2. Save to Packages/User/hello_world.py.

You’ve just written your first plugin! Let’s put it to use:

  1. Create a new buffer (Ctrl+n).
  2. Open the Python console (Ctrl+`).
  3. Type: view.run_command("example") and press enter.

You should see the text “Hello, World!” in your new buffer.

Analyzing Your First Plugin

The plugin created in the previous section should look roughly like this:

import sublime, sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.insert(edit, 0, "Hello, World!")

Both the sublime and sublime_plugin modules are provided by Sublime Text.

All new commands derive from the *Command classes defined in sublime_plugin (more on this later).

The rest of the code is concerned with the particulars of TextCommand or with the API. We’ll discuss those topics in later sections.

Before moving on, though, we’ll look at how we invoked the new command. First we opened the Python console, and then we issued a call to view.run_command(). This is rather an inconvenient way of using plugins, but it’s often useful when you’re in the development phase of a plugin. For now, keep in mind that your commands can be accessed both through key bindings and by other means, just like other commands.

Conventions for Command Names

You might have noticed that our command is defined with the name ExampleCommand, but we pass the string example to the API call instead. This is necessary because Sublime Text normalizes command names, stripping the Command suffix and separating CamelCasedPhrases with underscores, like this: snake_cased_phrases.

New commands should follow the CamelCase pattern for class names.

Types of Commands

You can create the following types of commands:

  • Application commands (ApplicationCommand)
  • Window commands (WindowCommand)
  • Text commands (TextCommand)

When writing plugins, consider your goal and choose the appropriate type of commands for your plugin.

Shared Traits of Commands

All commands need to implement a .run() method in order to work. Additionally, they can receive an arbitrarily long number of keyword parameters.

Application Commands

Application commands derive from sublime_plugin.ApplicationCommand and can be executed with sublime.run_command().

Window Commands

Window commands operate at the window level. This doesn’t mean you can’t manipulate views from window commands, but rather that you don’t need views in order for window commands to be available. For instance, the built-in command new_file is defined as a WindowCommand so it works, even when no view is open. Requiring a view to exist in that case wouldn’t make sense.

Window command instances have a .window attribute to point to the window instance that created them.

The .run() method of a window command needn’t be passed any positional arguments.

Text Commands

Text commands operate at the buffer level, so they require a buffer to exist in order to be available.

View command instances have a .view attribute pointing to the view instance that created them.

The .run() method of a text command needs to accept an edit instance as the first positional argument.

Text Commands and the edit Object

The edit object groups any modifications to the view so as to enable undo and macros to work sensibly.

You are responsible for creating and closing edit objects. To do so, you can call view.begin_edit() and edit.end_edit(). For convenience, the currently open edit object gets passed to text commands’ run method automatically. Additionally, many View methods require an edit object.

Responding to Events

Any command deriving from EventListener will be able to respond to events.

Another Plugin Example: Feeding the Completions List

Let’s create a plugin that fetches data from Google’s Autocomplete service and then feeds it to the Sublime Text completions list. Please note that, as ideas for plugins go, this a very bad one.

import sublime, sublime_plugin

from xml.etree import ElementTree as ET
from urllib import urlopen

GOOGLE_AC = r"http://google.com/complete/search?output=toolbar&q=%s"

class GoogleAutocomplete(sublime_plugin.EventListener):
    def on_query_completions(self, view, prefix, locations):
        elements = ET.parse(
                        urlopen(GOOGLE_AC % prefix)
                    ).getroot().findall("./CompleteSuggestion/suggestion")

        sugs = [(x.attrib["data"],) * 2 for x in elements]

        return sugs

Note

Make sure you don’t keep this plugin around after trying it or it will interfere with Sublime Text’s autocompletion.

Learning the API

In order to create plugins, you need to get acquainted with the Sublime Text API and the available commands. Documentation on both is scarce at the time of this writing, but you can read existing code and learn from it too. In particular, the Packages/Default folder contains many examples of undocumented commands and API calls.

Packages

Packages are simply folders under Packages. They exist mainly for organizational purposes, but Sublime Text follows a few rules when dealing with them. More on this later.

Here’s a list of the typical resources living inside packages:

  • build systems (.sublime-build)
  • key maps (.sublime-keymap)
  • 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.

Types of Packages

In this guide, in order to talk about packages, we divide them into groups. This division is artificial, and just useful for clarity when discussing this topic. Sublime Text doesn’t use this division in any way.

core packages
Sublime Text requires these packages in order to work.
shipped packages
Sublime Text includes these packages in every installation, though technically they are not required. These shipped packages enhance Sublime Text out of the box. They may have been contributed by users or third parties.
user packages
Packages installed by the user to extend Sublime Text’s functionaility. They are not part of any Sublime Text installation, and always are contributed by users or third parties.
installed packages
Any package that, if deleted, Sublime Text will be able to restore.

Let’s emphasize again that you don’t need to memorize this classification.

Also, it’s worth noting that by third party we mainly refer to users of other editors, such as Textmate.

Installation of Packages

There are two main ways to install packages:

  • .sublime-package files
  • version control systems

Ultimately, installing a package is simply a matter of copying a folder containing Sublime Text resources thato Packages. The only thing that changes from one system to another is how you copy these files.

Installation of .sublime-package Files

Copy the .sublime-package file to the Installed Packages folder and restart Sublime Text. If the Installed Packages folder doesn’t exist, you can create it.

Note that .sublime-package files simply are .zip archives with a custom file extension.

Installation of Packages from a Version Control System

Explaining how to use version control systems (VCSs) is outside the scope of this guide, but there are many user packages available free of charge on public repositories like Google Code, GitHub and Bitbucket.

Also, a Sublime Text organization at GitHub is open to contributors.

Packages and Magic

Sublime Text deals with packages quite simply, without much hidden magic. There are two notable exceptions: Macros defined in any package automatically appear under Tools | Macros | <Your Package>, and snippets from any package appear under Tools | Snippets | <Your Package>.

However, as mentioned at the beginning, Sublime Text follows some rules for packages. For instance, Package/User will never be clobbered during updates to the software.

Merging and Order of Precedence

Packages/Default and Packages/User also receive special treatment when merging files (e.g. .sublime-keymap and .sublime-settings files). Before merging can take place, the files have to be arranged in some order. To that end, Sublime Text sorts them alphabetically by name, with the exception of the folders Default and User. Files contained in Default will always go to the front of the list and, those in User, to the end.

Restoring Packages

Sublime Text keeps a copy of all installed packages so it can recreate them as needed. This means it can reinstall core packages, shipped packages and, potentially, user packages alike. However, only user packages installed as sublime-packages are added to its registry of installed packages. Packages installed in alternative ways will be lost completely if you delete them.

Reverting Sublime Text to Its Default Configuration

To revert Sublime Text to its default configuration, delete the data directory and restart the editor. Keep in mind, though, that the Installed Packages folder will be deleted too, so you’ll lose all your installed packages.

Always make sure to back up your data before taking an extreme measure like this one.

The Installed Packages Directory

You will find this folder in the data directory. It contains a copy of every sublime-package installed. It is used to restore Packages.

The Pristine Packages Directory

You will find this folder in the data directory. It contains a copy of every shipped and core package. It is used to restore Packages.

命令行用法

Reference

In this section you will find concise information about many aspects of Sublime Text.

If you’re looking for a slow-paced introduction to any of these topics, try the general index.

代码片段

与Textmate的兼容性

Sublime Text的代码片段与Textmate的代码片段基本兼容。

File Format

代码片段文件是有 sublime-snippet 后缀的XML文件。

<snippet>
    <content><![CDATA[]]></content>
    <tabTrigger></tabTrigger>
    <scope></scope>
    <description></description>
</snippet>
content
实际的代码片段内容。
tabTrigger
与这段代码片段关联的隐式按键绑定。最后一个(隐式的)按键式 TAB
scope
适用于这段代码片段的作用域选择器
description
为了菜单项准备的用户友好的说明性文字。

转义序列

\$
常量 $.

环境变量

$PARAM1 .. $PARAMn 传递给 insertSnippet 命令的各个参数。
$SELECTION 代码片段被触发的时候选中的文本内容
$TM_CURRENT_LINE 代码片段被触发的时候光标所在行的内容。
$TM_CURRENT_WORD 代码片段被触发的时候光标所在的单词。
$TM_FILENAME 正在编辑的文件名称,包含文件扩展名。
$TM_FILEPATH 正在编辑的文件的文件路径。
$TM_FULLNAME 用户的用户名。
$TM_LINE_INDEX 插入代码片段的列的位置,位置是从0开始计数的。
$TM_LINE_NUMBER 插入代码片段的行的位置,位置是从1开始计数的。
$TM_SELECTED_TEXT $SELECTION 是等价的。
$TM_SOFT_TABS translateTabsToSpaces 选项是真的时候,值是 YES ,否则为 NO
$TM_TAB_SIZE tab对应的空格数(受 tabSize 选项的控制)。

字域

标记代码片段中可以通过 TABSHIFT + TAB 循环的各个位置。

语法: $1 .. $n

$0
退出标记。当循环到这个标记的时候,编辑器应该返回至正常的编辑模式。默认情况下,Sublime Text在 content 元素内容的结尾位置隐式的添加这个标记。

有相同名字的字域互相映射。

站位符

带有默认值的字域。

语法:: ${1:PLACE_HOLDER} .. ${n:PLACE_HOLDER}

字域和站位符可以遇其他的站位符进行组合和嵌套。

替换

语法::

  • ${var_name/regex/format_string/}
  • ${var_name/regex/format_string/options}
var_name
需要替换的区域:1,2,3……
regex
Perl风格的正则表达式:关于`正则表达式 <http://www.boost.org/doc/libs/1_44_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html>`_ ,请参考Boost库的文档。
format_string
参考Boost库文档的 格式字符串 内容。
options
可选的。可以选择下面的任何一个:
i
忽略大小写敏感的正则。
g
替换所有匹配 regex 的内容。
m
在字符串中不要忽略换行符。

语法定义

警告:
这部分内容仍处于草稿阶段,并可能包含错误信息。

与Textmate的兼容性

Sublime Text的语法定义内容基本上与Textmate的语法定义文件是相互兼容的。.

文件格式

语法定义文件是以 tmLanguage 作为扩展名的Plist(属性列表)文件。然而,在本文档中,我们将使用 JSON文件来进行讲解,然后再将JSON文件转换为Plist文件。

{ "name": "Sublime Snippet (Raw)",
  "scopeName": "source.ssraw",
  "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.control.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"
}
name
所定义语法的描述性名称。这个名称显示在Sublime Text界面右下角的下拉菜单中。通常情况下, name 表示的是 编程语言或其他标记语言的名称。
scopeName
语法定义文件起效的顶级坐拥域名称。这个名称一般是 source.<语言名称> 或者 text.<语言名称> 。 如果是在定义编程语言的语法,那么就使用 source 这个名称,否则使用 text 作为名称。
fileTypes
记录适用于这个语法文件的文件扩展名的数组。数组中的每项是去掉”.”的文件扩展名称。
uuid
这个语法定义的唯一标示符。目前被忽略。
foldingStartMarker
目前被忽略,用于标示折叠内容的开始。
foldingStopMarker
目前被忽略,用于标示折叠内容的结束。
patterns
记录与缓冲区中的文字进行匹配的模式的数组。
repository
从模式元素中抽象出来的数组。定义这个数组一方面有助于保持语法定义文件整洁,另一方面也能为像 递归模式这样的功能服务。这个内容是可选的。

模式数组

patterns 数组中包含的元素。

match

包含下列原素:

match 用于搜索的模式。
name 设置被 match 匹配到的内容所具有的作用域。
comment 可选。只是为了提供信息。
captures 可选。是对 match 的精炼。见下文解释

captures` 内容可以包含 组下面要说明的元素对::

0..n 分组的索引。
name 组内元素具有的作用域。

示例::

// 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

在仓库中包含其他的语法定义内容或者当前定义的内容。

References:

$self 当前的语法定义。
#itemName 仓库中名为 “itemName” 的内容。
source.js 外部的语法定义。

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" }
begin..end

定义一个可以跨多行的作用域。

包含下面的一些元素:

begin 模式的开始标志。
end 模式的终止标志。
name 整个区域的作用域名称。
beginCaptures begin 准备的 captures。请参考 captures
endCaptures end 准备的 captures。请参考 captures
patterns 与正文内容进行配对的 patterns
contentName 除掉标志符之后的内容的作用域名称。

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": "\\}"
}

仓库

include 元素中,既可以从 patterns 中引用,也可以从自身引用。请参考 include 章节来了解更多信息。

仓库可以包含下列元素:

  • Simple elements:

    "elementName": {
      "match":  "some regexp",
      "name":   "some.scope.somelang"
    }
    
  • Complex elements:

    "elementName": {
      "patterns": [
        { "match":  "some regexp",
          "name":   "some.scope.somelang"
        },
        { "match":  "other regexp",
          "name":   "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" }
    ]
  },
}

转义序列

请确保对JSON/XML序列内容进行正确的转义。

构建系统

构建系统可以让你通过外部程序来运行文件并且在Sublime Text中看到输出结果。

构建系统包括两个必要部分和第三个可选部分:

  • JSON格式的配置数据(*.sublime-build*文件)
  • 一个Sublime Text命令来驱动构建过程
  • 可选,外部可执行文件(脚本,二进制文件)

从本质上讲,*.sublime-build*文件即是外部程序的配置数据也是前面提到的Sublime Text命令的配置。在其中,需要指定开关,选项,和要传入的环境配置信息。

然后Sublime Text命令从*.sublime-build*文件读取数据。此时,就可以做任何需要*构建*文件的事情了。默认情况下,构建系统会使用``exec``命令,由*Packages/Default/exec.py*中实现。 下面会提到,你可以重写此命令。

最后,外部程序可能是一个你写好的处理文件的shell脚本,或者一些著名的工具,比如``make``或者``tidy``。 通常,这些可执行文件都要接受文件或者目录路径, 开关和选项一起运行。

需要注意的是除非其它原因构建系统不需要调用外部程序;你完全可以通过Sublime Text command来实现一个构建系统。

文件格式

.build-system JSON文件。下面是一个简单的示例:

{
    "cmd": ["python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

选项(Options)

cmd

包含需要运行的命令和其参数的数组。如果不指定绝对路径,外部程序会从`PATH`环境变量中搜索。

Windows下GUI会被抑制。

file_regex
可选。获取``cmd``错误输出的正则表达式(Perl风格)。参看下一部分。
line_regex
可选。If file_regex doesn’t 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
可选。当**Tools | Build System | Automatic** 设为``true``时使用。 Sublime Text在此范围内为当前的view选择合适的构建系统。
working_dir
可选。 运行``cmd``前需要切换的当前目录。之后会恢复到原来目录。
encoding
可选。cmd``输出的编码。必须是有效的python编码字符。 默认``UTF-8
target

可选。 需要运行的Sublime Text命令。默认是``exec`` (Packages/Default/exec.py)。 这个命令接受*.build-system*文件的配置数据。

如果需要覆盖默认的命令来构建,需要在*.sublime-build*文件中指定你特有的变量。

env

可选。 执行``cmd``需要合并进来的环境变量。

可以使用它在不修改系统设置的情况下来添加或者修改环境变量。

shell
可选。如果是``true``, cmd``会通过shell来运行(``cmd.exe, bash…)。
path

可选。这个字符串在运行``cmd``前会替换系统变量:PATH。之后会把`PATH`恢复原值。

可以使用这个选项在不修改系统设置的情况下,添加目录到`PATH`变量中。

variants
可选。 字典列表,用于覆盖主构件系统的选项。Variant的``name`会显示在构建系统选择时命令面板上。
name
只在variant内有效 (参看``variants``)。标识variant构建系统。如果``name``是*Run*,这个variant将显示在**Tools | Build System**菜单下,并且绑定到*Ctrl + Shift + B*上。
使用``file_regex``获取错误输出

``file_regex``选项使用正则表达式来获取构建程序输出的错误信息的4个域,分别为:file name, line number, column numbererror message。 可以通过匹配分组来获取这些信息。*file name*和*line number*是必须的。

当捕获到错误信息时,可通过``F4``和``Shift+F4``导航到项目文件的错误实例位置。如果有的话,error message 会显示在状态栏。

特定平台选项

可以使用``windows``, ``osx``和 ``linux``来指定特定平台的配置数据。下面是示例:

{
    "cmd": ["ant"],
    "file_regex": "^ *\\[javac\\] (.+):([0-9]+):() (.*)$",
    "working_dir": "${project_path:${folder}}",
    "selector": "source.java",

    "windows":
    {
        "cmd": ["ant.bat"]
    }
}

示例中,ant``会在所有除了Windows之外的所有平台下执行,windows下则会执行``ant.bat

Variants

下面是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"
        }
    ]
}

上面这些配置,Ctrl + B 将运行*date*命令,*Crtl + Shift + B*将运行Python解析器并且其它的variants将在激活构建系统时出现在命令面板上。

构建系统变量

构建系统会在*.sublime-build*文件中扩展下面这些变量:

$file_path 当前文件目录,比如,C:Files.
$file 当前文件完整路径,比如,C:FilesChapter1.txt.
$file_name 当前文件的完整文件名,比如,Chapter1.txt.
$file_extension 当前文件的扩展名,比如,txt.
$file_base_name 当前文件的名称,比如,Document.
$packages *Packages*目录的完整路径。
$project 当前project文件完整路径.
$project_path 当前porject文件所在的完整目录。
$project_name project文件的完整文件名。
$project_extension 当前project文件的扩展名。
$project_base_name 当前project文件的基本文件名。
变量占位符

可以像下面这样使用这些变量:

${project_name:Default}

如果有的话将使用当前项目文件名,如果没有则使用``默认``。

${file/\.php/\.txt/}

把当前文正文件路径中*.php*替换成*.txt*。

运行构建系统

从**Tools | Build System**选择期望的构建系统,然后选择**Tools | Build**或者``F7``。

构建系统故障排除

构建系统会在系统变量`PATH`路径下搜寻可执行文件,除非你指定了特定的可执行目录。所以,`PATH`系统变量要配置正确。

有些系统中,`PATH`变量的值在终端中与图形应用中会有不同。所有,尽管你在命令行中使用的构建命令运行正常,但也有可能在Sublime Text运行不正常。这跟用户的shell配置有关。

要解决这个问题,所有要确保你设定的`PATH`是期望的,让Sublime Text这种图形界面程序可以找到。参考下面的连接获取更多信息。

另外,也可以使用*.sublime-build*文件中的``path``配置项来指定`PATH`,不过这只在构建系统运行期间有效,运行完之后会恢复系统原来的值。

按键绑定

按键绑定为按键与动作建立了映射关系。

文件格式

对于按键绑定的配置存储于后缀为 .sublime-keymap 的文件中,文件中记录的是JSON内容。所有按键绑定 配置文件都需要按照如下模式命名: Default (<platform>).sublime-keymap 。否则,Sublime Text 将忽略这些文件。

平台相关的键位设置

每一个平台都有它自己的按键配置文件:

  • Default (Windows).sublime-keymap
  • Default (OSX).sublime-keymap
  • Default (Linux).sublime-keymap

也有针对不同的硬件提供商指定的按键配置文件 HCI guidelines.

一个按键绑定项的结构

键位表是一个按键绑定项的数组。接下来将要解释的是按键绑定中的有效构成元素:

keys
一组大小写敏感的按键组合。可以用 + 指定修饰符。向数组中添加元素可以设置组合键,例如: ["ctrl+k","ctrl+j"]
command
要执行的命令的名称。
args
传递给 command 命令的参数字典。字典中键的名称是 command 命令的参数名称。
context
选择性控制按键绑定是否起效的上下文内容数组。只有当所有上下文都为真时,按键绑定才能被触发。 请参考下面的 上下文的结构 内容来了解更多内容。

下面是一个说明上面提到的大部分特性的例子:

{ "keys": ["shift+enter"], "command": "insert_snippet", "args": {"contents": "\n\t$0\n"}, "context":
        [
                { "key": "setting.auto_indent", "operator": "equal", "operand": true },
                { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
                { "key": "preceding_text", "operator": "regex_contains", "operand": "\\{$", "match_all": true },
                { "key": "following_text", "operator": "regex_contains", "operand": "^\\}", "match_all": true }
        ]
}
上下文的结构
key
要请求的上下文操作符的名称.
operator
key 进行测试的类型。
operand
key 的结果进行测试的值。
match_all
需要多所有选择都进行测试。默认值为 false
上下文操作数
auto_complete_visible
如果自动不全列表可见就返回 true
has_next_field
当下一个代码片段域可用时返回 true
has_prev_field
当上一个代码片段域可用时返回 true
num_selections
返回当前选中的数目。
overlay_visible
当覆盖控件可见时返回 true
panel_visible
当有面板可见时返回 true
following_text
限制测试只对脱字号后的文本进行。
preceding_text
限制测试只对脱字号前的文本进行。
selection_empty
当没有选中内容的时候返回 true
setting.x
返回 x 设置项的值。 x 可以为任意字符串。
text
限制测试只对选中的文本有效。
selector
返回当前作用域。
panel_has_focus
如果当前焦点是在一个面板的话返回``true``
panel
如果指定的面板可用于作为操作数的话返回``true``
上下文操作符
equal, not_equal
测试是否相等。
regex_match, not_regex_match
与一个正则表达式进行匹配。
regex_contains, not_regex_contains
与一个正则表达式进行匹配(检测是否包含)。

命令模式

Sublime Text提供一个称为 command_mode (命令模式)的设置项,启用这个设置可以阻止按键内容 被送往缓冲区。这个设置项在模拟Vim的模式功能的时候很有用处。

可绑定的按键

按键可以通过字面值或者名字来指定。你可以在下面找到一个有效名称的列表:

  • up
  • down
  • right
  • left
  • 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
  • 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
修饰符
  • shift
  • ctrl
  • alt
  • super (Windows key, Command key...)
关于可绑定按键的警告

如果你正在开发一个包,请谨记下面几点:

  • Ctrl+Alt+<alphanum> 在Windows平台上,不要使用 Ctrl+Alt+<alphanum> 进行任何键位绑定。
  • Option+<alphanum> 在OS X平台上,不要使用 Option+<alphanum> 进行任何键位绑定

在以上两种情况下,用户都将在插入非ascii字符时遇到问题。

如果你是终端用户,你可以随意重新映射这些按键组合。

让按键映射井井有条

Sublime Text自带的按键组合存放在 Packages/Default 目录下。其他包组可以包含它们特有的按键 映射文件。对于你自己的键位映射设置而言,推荐的文件存放地址是 Packages/User 目录。

请参考 排序与优先级顺序 以了解关于Sublime Text排序文件并进行合并的更多信息

国际化键盘

根据Sublime Text将按键名称与物理按键进行映射的方式,此二者在不同平台上可能有不同的配对。

常见问题解答

使用 sublime.log_commands(flag) 开启命令日志。这对于调试按键映射有所帮助。

设置项(参考内容)

全局设置项

Target file: Global.sublime-settings. 对应文件: Global.sublime-settings

theme
系统使用的主题文件。接受主题文件的名称(例如: Default.sublime-theme )。
remember_open_files
设置Sublime Text启动时是否需要打开上次关闭时打开了的缓冲区。
folder_exclude_patterns
与匹配模式相符的目录将不会出现在侧边栏、快速跳转面板等位置。
file_exclude_patterns
与匹配模式相符的文件将不会出现在侧边栏、快速跳转面板等位置。
scroll_speed
如果把值设为 0 ,将禁止平滑滚动。取 01 之间的数值将使滑动变的比较缓慢,取大于 1 的值使得滑动更加迅速。
show_tab_close_buttons
如果设置为 false ,通常情况下就不会显示标签页的关闭按钮,只有当鼠标移动到标签上时才显示。
mouse_wheel_switches_tabs
如果设置为 true ,在标签区域滑动鼠标滚轮会触发标签页之间的切换。
open_files_in_new_window
仅在OS X平台有效。当用户从Finder中开打文件,或者把文件拖拽到dock面板的图标上,这个设置项将决定 是否需要创建一个新窗口。

文件设置项

Target files: Base File.sublime-settings, <file_type>.sublime-settings. 对应文件: Base File.sublime-settings<file_type>.sublime-settings

空格与缩进
auto_indent
开/关自动缩进选项。
tab_size
设置tab键对应的空格数。
translate_tabs_to_spaces
设置当用户按下 Tab 键时,是否需要用 tab_size 选项所指定数目的空格进行替换。
use_tab_stops
如果 translate_tabs_to_spaces 选项为 true ,设置这个选项就使得每次按下 TabBackspace 键时,将插入/删除 tab_size 选项所指定数目的空格。
trim_automatic_white_space
开/关对由 auto_indent 选项自动添加的只有空格的行的检测。
detect_indentation
如果设置为 false ,当系统加在缓冲区内容的时候,就会停止对tab与空格的检测。如果设置为 true 则会自动修改 translate_tabs_to_spaces 以及 tab_size 的值。
draw_white_space
有效值: noneselectionall
trim_trailing_white_space_on_save
将这个选项设置为 true 就会在文件保存时候自动去处行为的空格。
显示设置项
color_scheme
设置文本高亮的配色方案。接受从数据目录开始的相对路径(例如: Packages/Color Scheme - Default/Monokai Bright.tmTheme)。
font_face
设置可编辑文本的字体样式。
font_size
设置可编辑字体的字体大小。
font_options
有效值:bolditalicno_antialiasgray_antialiassubpixel_antialiasdirectwrite (对Windows平台有效)。
gutter
开/关侧边栏选项。
rulers
(e. g. [79, 89, 99] or a single numeric value (e. g. 79). 设置标尺所在的列坐标。接受一个数字值的列表(例如 [79, 89, 99] 或者一个单一的数字值 79)。
draw_minimap_border
如果将这个值设置为 true ,就将根据视图当前可见文本的内容在迷你地图区域画一个边框。当前选中的 配色方案中的 minimapBorder 键对应的值用于控制边框的颜色。
highlight_line
将这个值设置为 false 来阻止高亮当前光标所在行。
line_padding_top
每行文字与上一行的额外距离,以像素为单位。
line_padding_bottom
每行文字与下一行的额外距离,以像素为单位。
scroll_past_end
设置为 false 以关闭超出缓冲区的滚动。如果设置为 true ,Sublime Text将在文本的最后一行 与窗口下边界之间添加一大块空白区域。
line_numbers
开/关对行号的显示。
word_wrap
如果设置为 false 那么对于内容很多的行,文本将被截取,而不会自动换行。在水平方向拖动滚动条可以 查看被截取的文字。
wrap_width
如果这个值大于 0 , 系统就会在这个指定的列进行换行切分;否则会根据屏幕的宽度进行换行。这个值 只有在 wrap_width 设置为 true 的时候才有效果。
indent_subsequent_lines
如果这个值设置为 false ,被转换的行就不会进行缩进。只有在 wrap_widthtrue 时 才有效。
draw_centered
如果设置为 true ,文本将居中对齐,否则为左对齐。
match_brackets
当值设置为 false 时,光标放在括号周围的时候就不会显示下划线。
match_brackets_content
设置光标在括号周围时,是否要高亮括号中的内容。
match_brackets_square
如果设置项值为 false ,就停止对方括号的配对显示。只有在 match_brackets 值为 true 时有效。
match_bracktets_braces
如果设置项值为 false ,就停止对花括号的配对显示。只有在 match_brackets 值为 true 时有效。
match_bracktets_angle
如果设置项值为 false ,就停止对尖括号的配对显示。只有在 match_brackets 值为 true 时有效。
自动行为设置项
auto_match_enabled
开/关自动配对引号、括号等符号。
save_on_focus_lost
如果这个值为真,那么当用户切换到一个不同的文件,或不同的应用程序时,文件的内容将会自动保存。
find_selected_text
如果设置为 true ,那么当打开搜索面板时,当前选中的文字会被自动的复制到搜索面板中。
word_separators
设置在动作中用于分割单词的字符,例如光标跨单词移动的时候来界定单词的分隔符。这个单词分隔符并 不用于所有需要区分单词的情况(例如:换行时不切分单词)。在这种情况下,文本是基于其他标准来界 定的(例如:语法定义规则)。
ensure_newline_at_eof_on_save
如果文本末尾没有空行,那么当保存文件的时候,会自动在文件末尾添加一个空行。
系统与其他设置项
is_widget
当缓冲区为输入对话框中的输入域的时候,返回 true
spell_check
开/关拼写检查选项。
dictionary
拼写检查器可选的单词列表。接受从数据目录开始的一个路径(例如: Packages/Language - English/en_US.dic )。 你也可以 添加更多目录
fallback_encoding
控制当无法自动判断编码的时候选用的默认编码。系统可以自动检测的编码包括ASCII,UTF-8以及UTF-16.
default_line_ending
控制系统使用的换行符的字符。有效选项: system (OS相关), windows (即 CRLF )以及 unixLF )。
tab_completion
控制按下 Tab 时是否进行补全。
构建与错误导航设置项
result_file_regex
用于过滤视图或输出面板中的错误信息的正则表达式。这里的正则表达式遵循与构建系统中的错误捕获相同的规则。
result_line_regex
用于过滤视图或输出面板中的错误信息的正则表达式。这里的正则表达式遵循与构建系统中的错误捕获相同的规则。
result_base_dir
设置基于 result_file_regex 以及 result_line_regex 抽取出来的信息开始搜索的文件路径。
build_env
默认添加到构建系统中的路径列表。
文件与目录设置项
default_dir
设置视图对应的默认保存路径。
输入设置项

command_mode

如果将这个值设为 true ,则缓冲区将忽略用户按键。这对模拟Vim很有帮助。

命令面板

命令面板由 .sublime-commands 文件中的各项组成.

文件格式 (.sublime-commands 文件)

如下是来自 Packages/Default/Default.sublime-commands 的实例:

[
    { "caption": "Project: Save As", "command": "save_project_as" },
    { "caption": "Project: Close", "command": "close_project" },
    { "caption": "Project: Add Folder", "command": "prompt_add_folder" },

    { "caption": "Preferences: Default File Settings", "command": "open_file", "args": {"file": "${packages}/Default/Base File.sublime-settings"} },
    { "caption": "Preferences: User File Settings", "command": "open_file", "args": {"file": "${packages}/User/Base File.sublime-settings"} },
    { "caption": "Preferences: Default Global Settings", "command": "open_file", "args": {"file": "${packages}/Default/Global.sublime-settings"} },
    { "caption": "Preferences: User Global Settings", "command": "open_file", "args": {"file": "${packages}/User/Global.sublime-settings"} },
    { "caption": "Preferences: Browse Packages", "command": "open_dir", "args": {"dir": "$packages"} }
]
caption
显示在命令面板中的标题.
command
执行的命令.
args
传给 command 的参数。 需要注意的是,要定位包所在目录,需要使用 ${packages} 或 $packages。由于底层的实现不同,这与在编辑器的其他区域的用法略有不同。

如何使用命令面板

  1. Press Ctrl+Shift+P
  2. 选择命令

显示的选项会根据上下文不同有所区别,并不是在任何时候都会显示所有选项。

自动完成

自动完成提供了像IDE那样的使用补全列表或者 Tab 键插入动态内容的功能。

文件格式

补全信息是以 .sublime-completions 作为扩展名的JSON文件。

补全列表的结构

scope
控制补全是否应该在这个文件中发挥作用。参考 作用域与作用域选择子 来了解更多信息。
completions
补全的数组。

下面是从html补全列表中截取出来的一部分:

{
        "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 的内容与 contents 的内容完全一样的时候,纯文本字符串与这个补全项 是等价的

“foo”

# 等价于::

{ “trigger”: “foo”, “contents”: “foo” }

基于触发内容的补全
trigger
在补全列表中显示的文本,在被确认后,对应的 contents 内容被插入到缓冲区中。
contents
要插入到缓冲区中的文本。可以使用代码片段的特性。

补全的来源

用户可以控制的补全来源包括:

  • .sublime-completions
  • EventListener.on_query_completions()

除此之外,其他在最终补全列表中可以显示的内容包括:

  • Snippets
  • Words in the buffer
补全来源的优先级
  • 代码片段
  • 使用API插入的补全内容
  • .sublime-completions 文件
  • 缓冲区中的单词

代码片段只有在与设置的tab触发器精确匹配时才会被插入。其他类型的补全则是使用大小写不敏感的模糊 搜索进行匹配。

补全列表

要使用补全列表需要:

  • Press Ctrl+spacebar 来打开补全列表
  • Optionally, 再次 press Ctrl+spacebar 来选择下一个候选项
  • Press Enter or Tab 来确认选择

Note

补全列表中被选中的当前项可以用任何没有被绑定到代码片段触发器中的标点符号来确认插入。

代码片段以如下形式出现在补全列表中:<tab_trigger> : <name> 。对于其他补全项,你只能看到要被 插入的文本。

当补全列表被缩减到只有一个候选项时,系统就会绕开自动补全对话框,根据之前介绍的优先级,对应内容 会被直接插入。

为补全列表启用或禁用Tab补全

tab_completion 选项默认是 true 。如果你想停止 Tab 键对最可能选项的索引功能, 就把这个值设置为 false 。这个设置项对定义在 .sublime-snippet 文件中的触发器没有效果, 因此按下 Tab 时,代码片段一定会被插入。

tab_completion 选项开启的时候,上面介绍的优先级顺序仍然有效,但是,与补全列表不同的是,

插入一个Tab(缩进)字符

如果 tab_completion 值为 true ,你可以使用 Shift+Tab 来插入一个缩进字符

插件

更多信息请参考:

API参考文档
有关Python API的更详细的信息。

插件是实现了 sublime_plugin 模块中 *Command 类的Python脚本。

插件放到哪里

Sublime Text 2在以下这些目录中寻找可用插件:

  • Packages
  • Packages/<pkg_name>

存放在 Packages 更深层次的目录结构中的插件不会被加载。

任何插件都应该又自己单独的目录,而不应该直接放在 Packages 目录下。

命令名称的命名规则

Sublime Text 遵循 CamelCasedPhrases 命名规则来定义命令类,同时用 Command 作为后缀。

然而,Sublime Text将类名从 CamelCasedPhrases 形式自动转换成 camel_cased_phrases 。 举例来说, ExampleCommand 将被转换为 example ,而 AnotherExampleCommand 将 转换为 another_example

对于类定义名称,可以使用 CamelCasedPhrasesCommand 命名方式;要从API中调用一个命令,请使用 标准化后的名称( snake_cased_phrases )。

命令类型

  • sublime_plugin.ApplicationCommand
  • sublime_plugin.WindowCommand
  • sublime_plugin.TextCommand
  • sublime_plugin.EventListener

WindowCommand 类的实例都有一个 .window 属性,指向创建他们的那个窗口实例。于此类似, TextCommand 类的实例拥有 .view 属性。

命令之间的共享特性

所有命令都必须实现一个 .run() 方法。 所有命令都可以接受任意长度的关键字参数,但是这些参数一定要是有效的JSON类型。

如何利用API调用命令

根据命令的类型来选择对 ViewWindow 或者 sublime 的引用,然后通过 object.run_command('command_name') 来调用。 除此之外, 你可以用字典作为参数,字典中的键就是要传给 command_name 的参数名称:

window.run_command("echo", {"Tempus": "Irreparabile", "Fugit": "."})

命令的参数

用户提供给命令的所有参数都必须是有效的JSON类型。只有Sublime Text可以给命令传递其他类型的参数
(例如修改对象,视图实例等等)。

Text Commands 和 edit 对象

文本命令的两个较为重要的API是 view.begin_edit()view.end_edit() 。 其中 view.begin_edit() 可以接受一个可选的命令名称和可选的参数字典;而 view.end_edit() 用来结束编辑过程。

在修改过程中发生的所有动作都被整合成一个单一的撤销动作。当编辑过程结束的时候,类似与 on_modifiedon_selection_modified() 的回调函数会被触发。

有一点非常重要,每次调用 view.begin_edit() 之后必须调用 view.end_edit() 方法,否则 缓冲将处于一种不一致状态。在不匹配发生时,系统将尝试自动进行修正,但是这种自动修正的发生频率并 没有你想象的那么多,同时会在控制台输出一条警告信息。换句话说,你应该始终使用 try..finally 来包裹代码快。

传递给 begin_edit() 的命令名称用于重复、宏录制以及撤销/重复过程中的动作描述。如果你在 TextCommand 外面做修改,你就不该指定命令名称。

你可以在开始的时候创建一个修改对象,然后调用了一个方法又创建了另外的一个修改对象:只有当最外层 的修改对象执行了 end_edit() 方法之后,系统才认为整个修改都完成了。

与群组修改类似,你也可以使用修改对象把对选中文本做的修改组合成一个群组,对它们的修改只要一步就 能撤销。

对事件的响应

任何 EventListener 的子类都能够响应事件。对于任何一个类,不能同时继承 EventListener 和其他任何的命令类。

Python和标准库

Sublime Text集成了一个精简版的标准库。被裁剪掉的模块包括 Tkintermultiprocessing 以及 sqlite3

自动插件重载

当你对插件做修改的时候(比如你正在修改一个 .py 文件),Sublime Text会自动加载包中的顶级 Python模块。值得注意的是Python的子模块不会被自动重新加载;这一点在插件开发中可能会产生一些挺 奇葩的问题。一般来说,当你对插件文件做修改之后,最好重启以下Sublime Text,这样能保证你做的修 改能发挥作用。

多线程

只有 .set_timeout() 方法可以安全的从其他线程调用。

Python API

Exploring the API

快速查看API的方法:

  1. Packages\Default (Preferences | Browse Packages…) 添加到你的项目中.
  2. 按下组合键 CTRL + SHIFT + F
  3. In Files: 栏中输入 *.py
  4. 检查 Use Buffer 选项
  5. 搜索 API 名字
  6. F4
  7. 学习相关的源代码

命令

概述

命令列表的整理仍在进行中。

关于命令参数中的路径

有些命令把路径作为参数。这些命令中,有些支持代码片段那样的语法,有些则不支持。第一中类型的命令 可以接受类似 ${packages}/SomeDir/SomeFile.Ext 这样的参数,而第二种类型的命令可以接受类似 Packages/SomeDir/SomeFile.Ext 这样的参数。

大体上来说,较新引入的命令支持类似代码片段的语法。

通常情况下,认为命令参数中的相对路径是相对与 Data 目录来说的。

参数中路径包含的变量

构建系统中使用的变量在参数中也可以使用。参考 构建系统 来了解更多信息。

命令列表

build

运行某个构件系统。

  • variant [String]: 可选参数。要运行配置的名称
run_macro_file

运行一个 .sublime-macro 文件。

  • file [String]: 宏文件路径。
insert_snippet

从字符串或者 .sublime-snippet 文件中插入一个代码片段。

  • contents [String]: 要插入的代码片段的字符串内容。
  • name [String]: 要插入的 .sublime-snippet 文件的路径。
insert

插入一个字符串。

  • characters [String]: 要插入的字符串内容。
move

根据指定的单位移动光标。

  • by [Enum]: 可选值: characters, words, word_ends, subwords, subword_ends, lines, pages, stops.
  • forward [Bool]: 在缓冲区中向前或向后移动。
  • word_begin [Bool]
  • empty_line [Bool]
  • punct_begin [Bool]
  • separators [Bool]
move_to

将光标移动到指定位置。

  • to [Enum]: 可选值: bol, eol, bof, eof, brackets.
  • extend [Bool]: 是否扩展选择内容。默认值是 false
new_window
打开一个新的窗口。
close_window
关闭当前活跃窗口。
switch_file

在有相同文件名、不同扩展名的两个文件之间进行切换。

  • extensions [[String]]: 切换可以发生的文件扩展名(不包括点号)。
close
关闭当前视图。
close_file
关闭当前视图,在某些情况下关闭整个应用程序。 XXX Sounds kinda wrong.
save
保存当前激活的文件。
prompt_save_as
提示输入新的文件名称并保存。
toggle_sidebar
开启或关闭侧边栏。
toggle_full_screen
开启或退出全屏模式。
toggle_distraction_free
开启或退出免打扰模式。
left_delete
删除光标前的那个字符
right_delete
删除光标后的那个字符。
undo
撤销上次操作。
redo
重做上次撤销的操作。
redo_or_repeat
再次执行上次的动作。
soft_undo
先移动到编辑位置再进行撤销操作。
soft_redo
先移动到编辑位置再进行重做操作。
cut
把当前选中的文字从缓冲区中移除,并送到系统剪贴板中。换句话说,执行剪切操作。
copy
把当前选中的文字送到系统剪贴板中。
paste
把剪贴板中的内容插入到光标后。
paste_and_indent
把剪贴板中的内容插入到光标后同时根据上下文进行缩进。
select_lines

在当前选择的内容中添加一行。

  • forward [Bool]: 添加下一行还是上一行。默认值是 true
scroll_lines

在视图中滚动行。

  • amount [Float]: 正值向下滚动,负值向上滚动。
prev_view
切换到上一个视图。
next_view
切换到下一个视图。
next_view_in_stack
切换到最近的活跃视图。
previous_view_in_stack
切换到最近活跃视图的前一个活跃视图。我不认为这种说法非常确切,这么说甚至是不正确的。
select_all
选择视图的全部内容。
split_selection_into_lines
不出所料的,把当前的选择切散成不同行。
single_selection
把多重选择整合成单一选择。
clear_fields
跳出活跃代码片段域的选择。
hide_panel

隐藏当前活跃面板。

  • cancel [Bool]: 当面板打开的时候恢复它之前选择的内容。(仅对增量搜索面板有效。)
hide_overlay
隐藏覆盖控件。使用 show_overlay 命令打开覆盖控件。
hide_auto_complete
隐藏自动补全列表。
insert_best_completion

插入根据当前上下文能推断出的最佳补全内容。 XXX 可能没什么用

  • default [String]: 插入根据当前上下文能推断出的最佳补全内容。 XXX 可能没什么用
replace_completion_with_next_completion
XXX 对用户来说没什么用。 XXX
reindent
XXX ??? XXX 译者注:重新进行缩进操作,常用于整理文件缩进。)
indent
增加缩进。
next_field
将光标移动到下一个代码片段中的可修改区域。
prev_field
将光标移动到上一个代码片段中的可修改区域。
commit_completion
向缓冲区中插入自动补全列表中当前选中项的内容。 XXX 对用户来说没很么用。
unindent
取消缩进。
toggle_overwrite
开启关闭覆盖插入选项。
expand_selection

将选择内容扩展到预定义的边界。

  • to [Enum]: 可选值: bol, hardbol, eol, hardeol, bof, eof, brackets, line.
find_under_expand
根据当前选中的内容增加一个新的选择或者把选择项扩展到当前单词。
close_tag
为当前内部文本添加适当的标签。
toggle_record_macro
开始或关闭宏录制器。
run_macro
运行宏缓冲区中存储的宏脚本。
show_overlay

显示请求的覆盖控件。使用 hide_overlay 命令来隐藏覆盖控件。

show_panel

显示面板。

  • panel [Enum]: 可选值: incremental_find, find, replace, find_in_files, console
  • reverse [Bool]: 在缓冲区中是否后向搜索内容。
  • toggle [Bool]: 当面板已经可见时,是否隐藏面板。
find_next
找到当前搜索内容的下一个匹配项。
find_prev
找到当前搜索内容的上一个匹配项。
find_under
找到与当前选中内容或光标所在位置档次匹配的下一个内容。
find_under_prev
找到与当前选中内容或光标所在位置档次匹配的上一个内容。
find_all_under
选中与当前选择内容或光标所在位置单词匹配的所有内容。
slurp_find_string
复制当前选中内容或当前单词到搜索面板中的 “find” 域。
slurp_replace_string
复制当前选中内容或当前单词到搜索域替换面板中的 “replace” 域。
next_result
移动到下一个搜索到的结果。
prev_result
移动到上一个搜索到的结果。
toggle_setting

修改布尔型设置项的值。

  • setting [String]: 要修改的设置项的名称。
next_misspelling
移动到下一个错误拼写的单词的位置。
prev_misspelling
移动到上一个错误拼写的单词的位置。
swap_line_down
交换当前行与下一行。
swap_line_up
交换当前行与上一行。
toggle_comment

为当前行添加或取消注释。

  • block [Bool]: 为当前行添加或取消注释。
join_lines
把当前行与下一行连接起来。
duplicate_line
重复当前行内容。
auto_complete
打开自动补全列表。
replace_completion_with_auto_complete
XXX 对用户来说没什么用。 XXX
show_scope_name
在状态栏中显示光标所在作用域的名称。
exec

异步运行一个外部进程。

XXX 为所有选项添加文档。

transpose
移动内容。
sort_lines

对行进行排序。

  • case_sensitive [Bool]: 对行进行排序。
set_layout
XXX
focus_group
XXX
move_to_group
XXX
select_by_index
XXX
next_bookmark
选择下一个被标记的区域。
prev_bookmark
选择上一个被书签标记的区域。
toggle_bookmark
对活跃区域设置书签或取消书签。(在区域API中使用 "bookmarks" 作为键可以访问书签内容。)
clear_bookmarks
清楚所有书签。
select_all_bookmarks
选择所有被书签标记过的区域。
wrap_lines

环绕行。默认情况下,在第一个标尺所在的列进行环绕。

  • width [Int]: 设置环绕开始的列坐标。
upper_case
把选择的内容改成大写。
lower_case
把选择的内容改成小写。
title_case
把选择区的首字母大写,其它的字母都小写。
swap_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
放大字体。
decrease_font_size
缩小字体。
fold
XXX
unfold
XXX
fold_by_level
XXX
context_menu
显示上下文菜单。

Windows/Linux平台快捷键

编辑

Keypress Command
Ctrl + X Delete line
Ctrl + ↩ Insert line after
Ctrl + ⇧ + ↩ Insert line before
Ctrl + ⇧ + ↑ Move line/selection up
Ctrl + ⇧ + ↓ Move line/selection down
Ctrl + L Select line - Repeat to select next lines
Ctrl + D Select word - Repeat select others occurrences
Ctrl + M Jump to closing parentheses Repeat to jump to opening parentheses
Ctrl + ⇧ + M Select all contents of the current parentheses
Ctrl + KK Delete from cursor to end of line
Ctrl + K + ⌫ Delete from cursor to start of line
Ctrl + ] Indent current line(s)
Ctrl + [ Un-indent current line(s)
Ctrl + ⇧ + D Duplicate line(s)
Ctrl + J Join line below to the end of the current line
Ctrl + / Comment/un-comment current line
Ctrl + ⇧ + / Block comment current selection
Ctrl + Y Redo, or repeat last keyboard shortcut command
Ctrl + ⇧ + V Paste and indent correctly
Ctrl + Space Select next auto-complete suggestion
Ctrl + U soft undo; jumps to your last change before undoing change when repeated
Windows
Ctrl + Alt + Up Column selection up
Ctrl + Alt + Down Column selection down
Linux
Alt + ⇧ + Up Column selection up
Alt + ⇧ + Down Column selection up

导航/快速跳转

Keypress Command
Ctrl + P Quick-open files by name
Ctrl + R Goto symbol
Ctrl + ; Goto word in current file
Ctrl + G Goto line in current file

通用快捷键

Keypress Command
Ctrl + ⇧ + P Command prompt
Ctrl + KB Toggle side bar
Ctrl + ⇧ + Alt + P Show scope in status bar

查找/替换

Keypress Command
Ctrl + F Find
Ctrl + H Replace
Ctrl + ⇧ + F Find in files

标签页(Tabs)

Keypress Command
Ctrl + ⇧ + t Open last closed tab
Ctrl + PgUp Cycle up through tabs
Ctrl + PgDn Cycle down through tabs
Ctrl + ⇆ Find in files
Alt + [NUM] Switch to tab number [NUM] where [NUM] <= number of tabs

分割窗口

Keypress Command
Alt + ⇧ + 2 Split view into two columns
Alt + ⇧ + 1 Revert view to single column
Alt + ⇧ + 5 Set view to grid (4 groups)
Ctrl + [NUM] Jump to group where num is 1-4
Ctrl + ⇧ + [NUM] Move file to specified group where num is 1-4

书签

Keypress Command
Ctrl + F2 Toggle bookmark
F2 Next bookmark
⇧ + F2 Previous bookmark
Ctrl + ⇧ + F2 Clear bookmarks

文本操作

Keypress Command
Ctrl + KU Transform to Uppercase
Ctrl + KL Transform to Lowercase

OSX平台快捷键

编辑

Keypress Command
⌘ + X Delete line
⌘ + ↩ Insert line after
⌘ + ⇧ + ↩ Insert line before
⌘ + ⌃ + ↑ Move line/selection up
⌘ + ⌃ + ↓ Move line/selection down
⌘ + L Select line - Repeat to select next lines
⌘ + D Select word - Repeat select others occurrences
⌃ + M Jump to closing parentheses Repeat to jump to opening parentheses
⌃ + ⇧ + M Select all contents of the current parentheses
⌘ + K, ⌘ + K Delete from cursor to end of line
⌘ + K + ⌫ Delete from cursor to start of line
⌘ + ] Indent current line(s)
⌘ + [ Un-indent current line(s)
⌘ + ⇧ + D Duplicate line(s)
⌘ + J Join line below to the end of the current line
⌘ + / Comment/un-comment current line
⌘ + ⌥ + / Block comment current selection
⌘ + Y Redo, or repeat last keyboard shortcut command
⌘ + ⇧ + V Paste and indent correctly
⌃ + Space Select next auto-complete suggestion
⌃ + U Soft undo; jumps to your last change before undoing change when repeated
⌃ + ⇧ + Up Column selection up
⌃ + ⇧ + Down Column selection down

导航/快速跳转

Keypress Command
⌘ + P Quick-open files by name
⌘ + R Goto symbol
  Goto word in current file
⌃ + G Goto line in current file

通用快捷键

Keypress Command
⌘ + ⇧ + P Command prompt
⌘ + K, ⌘ + B Toggle side bar
⌃ + ⇧ + P Show scope in status bar

查找/替换

Keypress Command
⌘ + F Find
⌘ + ⌥ + F Replace
⌘ + ⇧ + F Find in files

标签页(Tabs)

Keypress Command
⌘ + ⇧ + t Open last closed tab
^ + Tab Cycle up through tabs
⇧ + ^ + Tab Cycle down through tabs
  Find in files

分割窗口

Keypress Command
⌘ + ⌥ + 2 Split view into two columns
⌘ + ⌥ + 1 Revert view to single column
⌘ + ⌥ + 5 Set view to grid (4 groups)
⌃ + [NUM] Jump to group where num is 1-4
⌃ + ⇧ + [NUM] Move file to specified group where num is 1-4

书签

Keypress Command
⌘ + F2 Toggle bookmark
F2 Next bookmark
⇧ + F2 Previous bookmark
⇧ + ⌘ + F2 Clear bookmarks

文本操作

Keypress Command
⌘ + K, ⌘ + U Transform to Uppercase
⌘ + K, ⌘ + L Transform to Lowercase

词汇表

buffer(缓冲区)
存放已经加载文件的内容以及文件元数据的区域称为缓冲区。缓冲区一般与一个或多个视图相关联。 缓冲区视图 只有一些细节上的差别。大多数情况下这两个术语是可以混用的。
视图(view)
显示缓冲区内容的图形区域。多个不同的视图可以显示同一块缓冲区内容。
plugin(插件)
使用Python实现的一个功能称为插件。它可以包含一个或多个命令。它可以由一个或多个 .py
文件组成。
package(包)
在Sublime Text中这个术语的意义有点模糊,它可以指一个Python包(这种用法很少),或者 是 Packages 目录下的一个文件夹,亦或是一个 .sublime-package 文件。大多数情况下, 包指的是 Packages 目录下的一个文件夹,这个文件夹中包含为某个特性或者某种语言服务的各 种资源。 译者注: Packages 目录保存在Sublime Text的安装目录中
panel(面板)
像搜索或者输出这样的,用于进行输入/输出的窗体控件称为面板。
overlay(覆盖层控件)
一种特殊的输入控件。快速跳转就是一种覆盖层控件