> Sublime Text中文手册 > Sublime Text 3 API参考

基本信息

  • 示例插件
  • 插件生命周期
  • 线程
  • 类型

核心组件

  • sublime 模块
  • View
  • Selection
  • Region
  • Phantom
  • PhantomSet
  • Edit
  • Window
  • Settings

插件扩展点

  • sublime_plugin 模块
  • EventListener
  • ViewEventListener
  • ApplicationCommand
  • WindowCommand
  • TextCommand

基本信息

示例插件

几个预制插件附带Sublime Text,你可以在Default包中找到它们:

  • Packages/Default/delete_word.py 删除光标左侧或右侧的单词
  • Packages/Default/duplicate_line.py 复制当前行
  • Packages/Default/exec.py 使用幻影在线显示错误
  • Packages/Default/font.py 显示如何使用设置
  • Packages/Default/goto_line.py 提示用户输入,然后更新选择
  • Packages/Default/mark.py 使用 add_regions()</ tt>为图层添加图标
  • Packages/Default/show_scope_name.py 使用弹出窗口在插入符号处显示范围名称
  • Packages/Default/trim_trailing_whitespace.py在保存缓冲区之前修改缓冲区

插件生命周期

在导入时,插件可能不会调用任何API函数,除了sublime.version()sublime.platform()sublime.architecture()sublime.channel()
如果插件定义了模块级函数plugin_loaded(),那么当API准备好使用时,将调用它。 插件也可以定义plugin_unloaded(),以便在插件卸载之前得到通知。

线程

所有API函数都是线程安全的,但是请记住,从代码运行在替代线程的角度来看,应用程序状态将在代码运行时改变。

类型

本文档通常指的是简单的Python数据类型。 一些类型名称是本文中记录的类,但也有一些自定义类型名称引用具有特定语义的构造:

  • location: (str, str, (int, int))的元组,其包含关于符号的位置的信息。 第一个字符串是绝对文件路径,第二个是相对于项目的文件路径,第三个元素是行和列的两元素元组。
  • point: 一个 int </ tt>,表示从编辑器缓冲区开始的偏移量。 查看</ tt>方法 text_point()</ tt>和 rowcol()</ tt>允许转换为此格式。
  • value: 任何Python数据类型 bool </ ttttt> int </ tt>, float </ tt>, str </ tt>,列表</ tt> dict </ tt>。
  • vector: 表示 x </ tt>和 y </ tt>坐标的(float,float)</ tt>的元组。

sublime 模块

方法 返回值 描述
set_timeout(callback, delay) None 在给定的callback(以毫秒为单位)后,在主线程中运行delay。 具有相等延迟的回调将按照它们添加的顺序运行。
set_timeout_async(callback, delay) None 在给定的callback;(以毫秒为单位)后,在备用线程上运行delay。
error_message(string) None 向用户显示错误对话框。
message_dialog(string) None 向用户显示消息对话框。
ok_cancel_dialog(string, <ok_title>) bool 向用户显示确定/取消问题对话框。 如果提供 ok_title ,则可以将其用作确定按钮上的文本。 如果用户按下确定按钮,则返回 True 。
yes_no_cancel_dialog(string, <yes_title>, <no_title>) int 向用户显示是/否/取消问题对话框。 如果提供 yes_title 和/或 no_title ,它们将用作某些平台上相应按钮上的文本。 返回 sublime.DIALOG_YES , sublime.DIALOG_NO 或 sublime.DIALOG_CANCEL 。
load_resource(name) str 加载给定资源。 名称应采用格式 Packages/Default/Main.sublime-menu 。
load_binary_resource(name) bytes 加载给定资源。 名称应采用格式 Packages/Default/Main.sublime-menu 。
find_resources(pattern) [str] 查找其文件名匹配给定pattern的资源。
encode_value(value, <pretty>) str json兼容的值编码为字符串表示形式。 如果 pretty 设置为 True ,则字符串将包含换行符和缩进。
decode_value(string) value 将JSON字符串解码为对象。 如果 string 无效,则会抛出 ValueError 。
expand_variables(value, variables) value 使用字典变量中定义的变量扩展字符串 value 中的任何变量。 value 也可以是列表或 dict ,在这种情况下,结构将被递归地展开。 字符串应使用代码段语法,例如: expand_variables("Hello, ${name}", {"name": "Foo"})
load_settings(base_name) Settings 加载指定的设置。 名称应包括文件名和扩展名,而不是路径。 将搜索与 base_name 匹配的文件包,并将结果整理到设置对象中。 随后使用 base_name 调用 load_settings()将返回相同的对象,而不会再次从磁盘加载设置。
save_settings(base_name) None 将任何内存中的更改刷新到磁盘的指定设置对象。
windows() [Window] 返回所有打开的窗口的列表。
active_window() Window 返回最近使用的窗口。
packages_path() str 返回所有用户丢失软件包的路径。
installed_packages_path() str 返回所有用户所在的路径。sublime-package 文件所在的路径。
cache_path() str 返回Sublime Text存储高速缓存文件的路径。
get_clipboard(<size_limit>) str 返回剪贴板的内容。 size_limit 是为了防止不必要的大数据,默认值为16,777,216个字符
set_clipboard(string) None 设置剪贴板的内容。
score_selector(scope, selector) int 将选择器与给定的范围匹配,返回分数。 分数 0 表示无匹配,高于 0 表示匹配。 可以对同一范围比较不同的选择器:较高的分数意味着选择器是范围的更好匹配。
run_command(string, <args>) None 使用给定的 args (可选)运行命名的 ApplicationCommand 。
log_commands(flag) None 控制命令日志。 如果启用,所有命令从键绑定运行,菜单将记录到控制台。
log_input(flag) None 控制输入记录。 如果启用,所有按键将被记录到控制台。
log_result_regex(flag) None 控制结果正则表达式登录。 这对于调试构建系统中使用的正则表达式很有用。
version() str 返回版本号
platform() str 返回平台,其可以是“osx”,“linux”或“windows”
arch() str 返回CPU体系结构,可以是“x 32”或“x64”

sublime.View Class

将视图表示为文本缓冲区。 注意,多个视图可以引用相同的缓冲区,但是它们具有它们自己的唯一选择和几何。

方法 返回值 描述
id() int 返回唯一标识此视图的数字。
buffer_id() int 返回唯一标识此视图下的缓冲区的数字。
is_primary() bool 如果视图是进入文件的主视图。 只有 False ,如果用户已将多个视图打开到文件中。
file_name() str 全名文件与缓冲区关联的文件,或None(如果磁盘上不存在)。
name() str 分配给缓冲区的名称(如果有)
set_name(name) None 为缓冲区分配名称
is_loading() bool 如果缓冲区仍在从磁盘加载,并且未准备好使用,则返回 True 。
is_dirty() bool 如果有任何未保存的缓冲区修改,则返回 True 。
is_read_only() bool 如果缓冲区可能未被修改,则返回 True 。
set_read_only(value) None 设置缓冲区上的只读属性。
is_scratch() bool 如果缓冲区是暂存缓冲区,则返回 True 。 划痕缓冲区从未报告为脏。
set_scratch(value) None 设置缓冲区上的scratch属性。
settings() Settings 返回对视图的设置对象的引用。 对此设置对象的任何更改将对此视图为私有。
window() Window 返回对包含视图的窗口的引用。
run_command(string, <args>) None 使用给定的参数(可选)运行命名的 TextCommand 。
size() int 返回文件中的字符数。
substr(region) str 以字符串形式返回区域的内容。
substr(point) str 返回点右侧的字符。
insert(edit, point, string) int 在指定的点在缓冲区中插入给定的字符串。 返回插入的字符数:如果将标签翻译为当前缓冲区中的空格,则可能会有所不同。
erase(edit, region) None 从缓冲区中删除区域的内容。
replace(edit, region, string) None 用给定的字符串</ tt>替换区域的内容。
sel() Selection 返回对选择的引用。
line(point) Region 返回包含点的行。
line(region) Region 返回 region 的修改副本,使其从一行的开始处开始,并在一行的结尾处结束。 注意,它可以跨越几行。
full_line(point) Region 作为 line(),但是该区域包括尾随换行符(如果有)。
full_line(region) Region 作为 line(),但是该区域包括尾随换行符(如果有)。
lines(region) [Region] 返回与区域相交的线列表(以排序顺序)。
split_by_newlines(region) [Region] 拆分区域,使得返回的每个区域都存在于一条线上。
word(point) Region 返回包含点的单词。
word(region) Region 返回 region 的修改副本,以使其从单词的开头开始,并在单词的结尾处结束。 注意,它可以跨越几个单词。
classify(point) int

分类点,返回这些标志中的零个或多个的按位OR:

  • sublime.CLASS_WORD_START
  • sublime.CLASS_WORD_END
  • sublime.CLASS_PUNCTUATION_START
  • sublime.CLASS_PUNCTUATION_END
  • sublime.CLASS_SUB_WORD_START
  • sublime.CLASS_SUB_WORD_END
  • sublime.CLASS_LINE_START
  • sublime.CLASS_LINE_END
  • sublime.CLASS_EMPTY_LINE
find_by_class(point, forward, classes, <separators>) Region 查找与给定类匹配的点后的下一个位置。 如果 forward 为 False ,则向后搜索而不是向前搜索。 类是 sublime.CLASS_XXX 标志的按位或。 分隔符可以传入,以定义应该考虑哪些字符来分隔单词。
expand_by_class(point, classes, <separators>) Region 向左和向右展开点,直到每个边达到类匹配的位置。 类是 sublime.CLASS_XXX 标志的按位或。 分隔符可以传入,以定义应该考虑什么字符来分隔单词。
expand_by_class(region, classes, <separators>) Region 向左和向右扩展区域,直到每个边达到类匹配的位置。 类是 sublime.CLASS_XXX 标志的按位或。 分隔符可以传入,以定义应该考虑哪些字符来分隔单词。
find(pattern, start_point, <flags>) Region 如果找不到,则从 start_point 或无返回与正则表达式模式匹配的第一个区域。 可选的 flags 参数可以是 sublime.LITERAL , sublime.IGNORECASE 或两个ORed在一起。
find_all(pattern, <flags>, <format>, <extractions>) [区域] 返回与正则表达式模式匹配的所有(非重叠)区域。 可选的 flags 参数可以是 sublime.LITERAL , sublime.IGNORECASE 或两个ORed在一起。 如果给出了格式字符串,则所有匹配都将使用格式化的字符串格式化,并放入提取列表中。
rowcol(point) (int, int) Calculates the 0-based line and column numbers of the point.
text_point(row, col) int 计算给定的,基于0,行和 col 的字符偏移量。 请注意, col 被解释为超过行开头的字符数。
set_syntax_file(syntax_file) None 更改视图使用的语法。 syntax_file 应为 Packages/Python/Python.tmLanguage 的名称。 要检索当前语法,请使用 view.settings()。get('syntax')
extract_scope(point) Region 返回分配给给定点的字符的范围名称的范围。
scope_name(point) str 返回分配给给定点的字符的语法范围名称。
match_selector(point, selector) bool 检查选择器是否符合给定点的范围,如果匹配,则返回布尔值。
score_selector(point, selector) int 使选择器与给定点的范围匹配,返回分数。 分数 0 表示无匹配,高于 0 表示匹配。 可以对同一范围比较不同的选择器:较高的分数意味着选择器是范围的更好匹配。
find_by_selector(selector) [Region] 查找与给定选择器匹配的文件中的所有区域,将它们作为列表返回。
show(location, <show_surrounds>) None 滚动视图以显示给定的位置,可能是点,区域或选择。
show_at_center(location) None 将视图滚动到位置的中心,可能是点或地区。
visible_region() Region 返回视图的当前可见区域。
viewport_position() vector 返回布局坐标中视口的偏移量。
set_viewport_position(vector, <animate<) None 将视口滚动到给定的布局位置。
viewport_extent() vector 返回视口的宽度和高度。
layout_extent() vector 返回布局的宽度和高度。
text_to_layout(point) vector 将文本位置转换为布局位置
layout_to_text(vector) point 将布局位置转换为文本位置
window_to_layout(vector) vector 将窗口位置转换为布局位置
window_to_text(vector) point 将窗口位置转换为文本位置
line_height() float 返回布局中使用的灯光高度
em_width() float 返回布局中使用的典型字符宽度
add_regions(key, [regions], <scope>, <icon>, <flags>) None

向视图中添加一组区域。 如果给定键已存在一组区域,它们将被覆盖。 范围用于提供颜色来绘制区域,应该是范围的名称,例如&quot; comment&quot; 或“string”。 如果 scope 为空,则不会绘制 regions 。

可选的图标名称(如果给出)将在每个区域旁边的水槽中绘制命名的图标。 图标将使用与范围相关联的颜色进行着色。 有效的图标名称为 dot ,圆形,书签和交叉。 图标名称也可以是完整包相对路径,例如 Packages/Theme-Default/dot.png 。

可选的 flags 参数是以下各项的按位组合:

  • sublime.DRAW EMPTY :使用竖线绘制空白区域。 默认情况下,它们不会绘制。
  • sublime.HIDE_ON_MINIMAP:不要在小地图上显示区域。
  • sublime.DRAW_EMPTY_AS_OVERWRITE: 使用水平条而不是垂直条绘制空白区域。
  • sublime.DRAW_NO_FILL:禁用填充区域,只留下轮廓。
  • sublime.DRAW_NO_OUTLINE:禁用绘制区域的轮廓。
  • sublime.DRAW_SOLID_UNDERLINE: 在区域下面绘制一个实线下划线。
  • sublime.DRAW_STIPPLED_UNDERLINE: 在区域下方绘制点状下划线。
  • sublime.DRAW_SQUIGGLY_UNDERLINE: 以下地区波浪下划线。
  • sublime.PERSISTENT: 在会话中保存区域。
  • sublime.HIDDEN: 不要绘制区域。

下划线样式是独占的,应该给出零个或一个。 如果使用下划线,则通常应传入 sublime.DRAW_NO_FILL 和 sublime.DRAW_NO_OUTLINE 。

get_regions(key) [Region] 返回与给定键(如果有)相关联的区域
erase_regions(key) None 删除了命名区域
set_status(key, value) None 将状态键添加到视图。 值将显示在状态栏中,以逗号分隔的所有状态值列表的形式,按键排序。 将值设置为空字符串将清除状态。
get_status(key) str 返回与键(如果有)相关联的先前分配的值。
erase_status(key) None 清除命名状态。
command_history(index, <modifying_only>) (str, dict, int)

返回存储在undo/redo堆栈中的给定历史记录条目的命令名称,命令参数和重复计数。

索引 0 对应于最近的命令, -1 之前的命令,等等。 索引的正值表示在重做堆栈中查找命令。 如果撤消/重做历史记录不足够延伸,则将返回(None,None,0)。

将 modifying_only 设置为 True (默认值为 False )将只返回修改缓冲区的条目。

change_count() int 返回当前更改计数。 每次修改缓冲区时,增量更改计数。 更改计数可用于确定自上次检查后缓冲区是否已更改。
fold([regions]) bool 折叠给定的区域,如果它们已折叠,则返回 False
fold(region) bool 折叠给定的区域,如果它已折叠,则返回 False
unfold(region) [Region] 展开区域中的所有文本,返回展开的区域
unfold([regions]) [Region] 展开地区中的所有文字,返回展开的区域
encoding() str 返回当前与文件关联的编码
set_encoding(encoding) None 对文件应用新的编码。 此编码将在下次保存文件时使用。
line_endings() str 返回当前文件使用的行尾。
set_line_endings(line_endings) None 设置下次保存时将应用的行结束。
overwrite_status() bool 返回覆盖状态,用户通常通过插入键切换。
set_overwrite_status(enabled) None 设置覆盖状态。
symbols() [(Region, str)] 提取在缓冲区中定义的所有符号。
show_popup_menu(items, on_done, <flags>) None

在插入符处显示弹出式菜单,以选择列表中的项目。 on_done 将使用所选项目的索引调用一次。 如果弹出式菜单已取消,将使用参数 -1 调用 on_done 。

items is a list of strings.

flags it currently unused.

show_popup(content, <flags>, <location>, <max_width>, <max_height>, <on_navigate>, <on_hide>) None

显示显示HTML内容的弹出窗口。

标志是以下各项的按位组合:

  • sublime.COOPERATE_WITH_AUTO_COMPLETE. 导致弹出式窗口显示在自动完成菜单旁边
  • sublime.HIDE_ON_MOUSE_MOVE. 当鼠标移动,点击或滚动时,导致弹出窗口隐藏
  • sublime.HIDE_ON_MOUSE_MOVE_AWAY.当鼠标移动(除非朝向弹出窗口),或单击或滚动时,导致弹出窗口隐藏

-1 的默认位置将在光标处显示弹出窗口,否则应传递文本点。

最大宽度和最大高度设置弹出窗口的最大尺寸,之后将显示滚动条。

on_navigate 是一个回调,应该接受用户点击的链接上的 href 属性的字符串内容。

on_hide 在隐藏弹出式窗口时调用。

update_popup(content) None 更新当前可见弹出窗口的内容。
is_popup_visible() bool 如果弹出窗口当前正在显示,则返回。
hide_popup() None 隐藏弹出窗口。
is_auto_complete_visible() bool 目前可以看到自动完成菜单的返回。

sublime.Selection

保持一组区域,确保没有重叠。 区域按照排序顺序保存。

方法 返回值 描述
clear() None 删除所有区域。
add(region) None 添加给定的区域。 它将与已经包含在集合内的任何相交区域合并。
add_all(regions) None 添加给定列表或元组中的所有区域。
subtract(region) None 从集合中的所有区域中减去区域。
contains(region) bool 如果给定的区域是子集,则返回 True 。

sublime.Region

表示缓冲区的面积。空区域,其中 a==b 有效。

构造函数 描述
Region(a, b) 创建具有初始值a和b的区域。
属性 类型 描述
a int 区域的第一端。
b int 区域的第二端。 可能小于a,在这种情况下,该区域是相反的。
xpos int 区域的目标水平位置,如果未定义,则 -1 。 按下向上或向下键时的效果行为。
方法 返回值 描述
begin() int 返回a和b的最小值。
end() int 返回a和b的最大值。
size() int 返回由区域跨越的字符数。 始终&gt; = 0。
empty() bool 返回 True iff begin() == 和()。
cover(region) Region 返回横跨此区域和给定区域的区域。
intersection(region) Region 返回两个区域的集合交集。
intersects(region) bool 返回 Truett> off self == region 或两者包括一个或多个共同位置。
contains(region) bool 如果给定的区域是子集,则返回 True 。
contains(point) bool 返回 True iff begin() <=tt>指向&lt; = 和()。

sublime.Phantom

表示基于HTML的装饰,用于显示散布在视图中的不可编辑内容。 与PhantomSet一起使用实际将幻像添加到视图。 一旦Phantom被构造并添加到视图中,对属性的更改将不起作用。

构造函数 描述
Phantom(region, content, layout, <on_navigate>)

创建附加到区域的幻像</ tt>。 内容</ tt>是要由主html 处理的HTML。

layout must be one of:

  • sublime.LAYOUT_INLINE: Display the phantom in between the region and the point following.
  • sublime.LAYOUT_BELOW: Display the phantom in space below the current line, left-aligned with the region.
  • sublime.LAYOUT_BLOCK: Display the phantom in space below the current line, left-aligned with the beginning of the line.

on_navigate is an optional callback that should accept a single string parameter, that is the href attribute of the link clicked.

sublime.PhantomSet Class

A collection that manages Phantoms and the process of adding them, updating them and removing them from the View.

Constructors Description
PhantomSet(view, <key>) Creates a PhantomSet attached to a view. key is a string to group Phantoms together.
Methods Return Value Description
update(phantoms) None

phantoms should be a list of phantoms.

The .region attribute of each existing phantom in the set will be updated. New phantoms will be added to the view and phantoms not in phantoms list will be deleted.

sublime.Edit Class

Edit objects have no functions, they exist to group buffer modifications.

Edit objects are passed to TextCommands, and can not be created by the user. Using an invalid Edit object, or an Edit object from a different View, will cause the functions that require them to fail.

Methods Return Value Description
(no methods)    

sublime.Window Class

Methods Return Value Description
id() int Returns a number that uniquely identifies this window.
new_file() View Creates a new file. The returned view will be empty, and its is_loaded() method will return True.
open_file(file_name, <flags>) View

Opens the named file, and returns the corresponding view. If the file is already opened, it will be brought to the front. Note that as file loading is asynchronous, operations on the returned view won't be possible until its is_loading() method returns False.

The optional flags parameter is a bitwise combination of:

  • sublime.ENCODED_POSITION: Indicates the file_name should be searched for a :row or :row:col suffix
  • sublime.TRANSIENT: Open the file as a preview only: it won't have a tab assigned it until modified
find_open_file(file_name) View Finds the named file in the list of open files, and returns the corresponding View, or None if no such file is open.
active_view() View Returns the currently edited view.
active_view_in_group(group) View Returns the currently edited view in the given group.
views() [View] Returns all open views in the window.
views_in_group(group) [View] Returns all open views in the given group.
num_groups() int Returns the number of view groups in the window.
active_group() int Returns the index of the currently selected group.
focus_group(group) None Makes the given group active.
focus_view(view) None Switches to the given view.
get_view_index(view) (int, int) Returns the group, and index within the group of the view. Returns -1 if not found.
set_view_index(view, group, index) None Moves the view to the given group and index.
status_message(string) None Show a message in the status bar.
is_menu_visible() bool Returns True if the menu is visible.
set_menu_visible(flag) None Controls if the menu is visible.
is_sidebar_visible() bool Returns True if the sidebar will be shown when contents are available.
set_sidebar_visible(flag) None Sets the sidebar to be shown or hidden when contents are available.
get_tabs_visible() bool Returns True if tabs will be shown for open files.
set_tabs_visible(flag) None Controls if tabs will be shown for open files.
is_minimap_visible() bool Returns True if the minimap is enabled.
set_minimap_visible(flag) None Controls the visibility of the minimap.
is_status_bar_visible() bool Returns True if the status bar will be shown.
set_status_bar_visible(flag) None Controls the visibility of the status bar.
folders() [str] Returns a list of the currently open folders.
project_file_name() str Returns name of the currently opened project file, if any.
project_data() dict Returns the project data associated with the current window. The data is in the same format as the contents of a .sublime-project file.
set_project_data(data) None Updates the project data associated with the current window. If the window is associated with a .sublime-project file, the project file will be updated on disk, otherwise the window will store the data internally.
run_command(string, <args>) None Runs the named WindowCommand with the (optional) given args. This method is able to run any sort of command, dispatching the command via input focus.
show_quick_panel(items, on_done, <flags>, <selected_index>, <on_highlighted>) None

Shows a quick panel, to select an item in a list. on_done will be called once, with the index of the selected item. If the quick panel was cancelled, on_done will be called with an argument of -1.

items may be a list of strings, or a list of string lists. In the latter case, each entry in the quick panel will show multiple rows.

flags is a bitwise OR of sublime.MONOSPACE_FONT and sublime.KEEP_OPEN_ON_FOCUS_LOST

on_highlighted, if given, will be called every time the highlighted item in the quick panel is changed.

show_input_panel(caption, initial_text, on_done, on_change, on_cancel) View Shows the input panel, to collect a line of input from the user. on_done and on_change, if not None, should both be functions that expect a single string argument. on_cancel should be a function that expects no arguments. The view used for the input widget is returned.
create_output_panel(name, <unlisted>) View

Returns the view associated with the named output panel, creating it if required. The output panel can be shown by running the show_panel window command, with the panel argument set to the name with an "output." prefix.

The optional unlisted parameter is a boolean to control if the output panel should be listed in the panel switcher.

find_output_panel(name) View or None Returns the view associated with the named output panel, or None if the output panel does not exist.
destroy_output_panel(name) None Destroys the named output panel, hiding it if currently open.
active_panel() str or None Returns the name of the currently open panel, or None if no panel is open. Will return built-in panel names (e.g. "console", "find", etc) in addition to output panels.
panels() [str] Returns a list of the names of all panels that have not been marked as unlisted. Includes certain built-in panels in addition to output panels.
lookup_symbol_in_index(symbol) [location] Returns all locations where the symbol is defined across files in the current project.
lookup_symbol_in_open_files(symbol) [location] Returns all locations where the symbol is defined across open files.
extract_variables() dict

Returns a dictionary of strings populated with contextual keys:

packages, platform, file, file_path, file_name, file_base_name, file_extension, folder, project, project_path, project_name, project_base_name, project_extension. This dict is suitable for passing to sublime.expand_variables().

sublime.Settings Class

Methods Return Value Description
get(name, <default>) value Returns the named setting, or default if it's not defined. If not passed, default will have a value of None.
set(name, value) None Sets the named setting. Only primitive types, lists, and dicts are accepted.
erase(name) None Removes the named setting. Does not remove it from any parent Settings.
has(name) bool Returns True iff the named option exists in this set of Settings or one of its parents.
add_on_change(key, on_change) None Register a callback to be run whenever a setting in this object is changed.
clear_on_change(key) None Remove all callbacks registered with the given key.

sublime_plugin Module

Methods Return Value Description
(no methods)    

sublime_plugin.EventListener Class

Note that many of these events are triggered by the buffer underlying the view, and thus the method is only called once, with the first view as the parameter.

Methods Return Value Description
on_new(view) None Called when a new buffer is created.
on_new_async(view) None Called when a new buffer is created. Runs in a separate thread, and does not block the application.
on_clone(view) None Called when a view is cloned from an existing one.
on_clone_async(view) None Called when a view is cloned from an existing one. Runs in a separate thread, and does not block the application.
on_load(view) None Called when the file is finished loading.
on_load_async(view) None Called when the file is finished loading. Runs in a separate thread, and does not block the application.
on_pre_close(view) None Called when a view is about to be closed. The view will still be in the window at this point.
on_close(view) None Called when a view is closed (note, there may still be other views into the same buffer).
on_pre_save(view) None Called just before a view is saved.
on_pre_save_async(view) None Called just before a view is saved. Runs in a separate thread, and does not block the application.
on_post_save(view) None Called after a view has been saved.
on_post_save_async(view) None Called after a view has been saved. Runs in a separate thread, and does not block the application.
on_modified(view) None Called after changes have been made to a view.
on_modified_async(view) None Called after changes have been made to a view. Runs in a separate thread, and does not block the application.
on_selection_modified(view) None Called after the selection has been modified in a view.
on_selection_modified_async(view) None Called after the selection has been modified in a view. Runs in a separate thread, and does not block the application.
on_activated(view) None Called when a view gains input focus.
on_activated_async(view) None Called when a view gains input focus. Runs in a separate thread, and does not block the application.
on_deactivated(view) None Called when a view loses input focus.
on_deactivated_async(view) None Called when a view loses input focus. Runs in a separate thread, and does not block the application.
on_hover(view, point, hover_zone) None

Called when the user's mouse hovers over a view for a short period.

point is the closest point in the view to the mouse location. The mouse may not actually be located adjacent based on the value of hover_zone:

  • sublime.HOVER_TEXT: When the mouse is hovered over text.
  • sublime.HOVER_GUTTER: When the mouse is hovered over the gutter.
  • sublime.HOVER_MARGIN: When the mouse is hovered in whitespace to the right of a line.
on_query_context(view, key, operator, operand, match_all) bool or None

Called when determining to trigger a key binding with the given context key. If the plugin knows how to respond to the context, it should return either True of False. If the context is unknown, it should return None.

operator is one of:

  • sublime.OP_EQUAL: Is the value of the context equal to the operand?
  • sublime.OP_NOT_EQUAL: Is the value of the context not equal to the operand?
  • sublime.OP_REGEX_MATCH: Does the value of the context match the regex given in operand?
  • sublime.OP_NOT_REGEX_MATCH: Does the value of the context not match the regex given in operand?
  • sublime.OP_REGEX_CONTAINS: Does the value of the context contain a substring matching the regex given in operand?
  • sublime.OP_NOT_REGEX_CONTAINS: Does the value of the context not contain a substring matching the regex given in operand?

match_all should be used if the context relates to the selections: does every selection have to match (match_all == True), or is at least one matching enough (match_all == False)?

on_query_completions(view, prefix, locations) list, tuple or None

Called whenever completions are to be presented to the user. The prefix is a unicode string of the text to complete.

locations is a list of points. Since this method is called for all completions in every view no matter the syntax, view.match_selector(point, relevant_scope) should be called to determine if the point is relevant.

The return value must be one of the following formats:

  • None: no completions are provided

    return None

  • A list of 2-element lists/tuples. The first element is a unicode string of the completion trigger, the second is the unicode replacement text.

    return [["me1", "method1()"], ["me2", "method2()"]]

    The trigger may contain a tab character (\t) followed by a hint to display in the right-hand side of the completion box.

    return [
        ["me1\tmethod", "method1()"],
        ["me2\tmethod", "method2()"]
    ]

    The replacement text may contain dollar-numeric fields such as a snippet does, e.g. $0, $1.

    return [
        ["fn", "def ${1:name}($2) { $0 }"],
        ["for", "for ($1; $2; $3) { $0 }"]
    ]

  • A 2-element tuple with the first element being the list format documented above, and the second element being bit flags from the following list:

    • sublime.INHIBIT_WORD_COMPLETIONS: prevent Sublime Text from showing completions based on the contents of the view
    • sublime.INHIBIT_EXPLICIT_COMPLETIONS: prevent Sublime Text from showing completions based on .sublime-completions files

    return (
        [
            ["me1", "method1()"],
            ["me2", "method2()"]
        ],
        sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
    )

on_text_command(view, command_name, args) (str, dict) Called when a text command is issued. The listener may return a (command, arguments) tuple to rewrite the command, or None to run the command unmodified.
on_window_command(window, command_name, args) (str, dict) Called when a window command is issued. The listener may return a (command, arguments) tuple to rewrite the command, or None to run the command unmodified.
on_post_text_command(view, command_name, args) None Called after a text command has been executed.
on_post_window_command(window, command_name, args) None Called after a window command has been executed.

sublime_plugin.ViewEventListener Class

A class that provides similar event handling to EventListener, but bound to a specific view. Provides class method-based filtering to control what views objects are created for.

The view is passed as a single parameter to the constructor. The default implementation makes the view available via self.view.

Class Methods Return Value Description
is_applicable(settings) bool A @classmethod that receives a Settings object and should return a bool indicating if this class applies to a view with those settings
applies_to_primary_view_only() bool A @classmethod that should return a bool indicating if this class applies only to the primary view for a file. A view is considered primary if it is the only, or first, view into a file.
Methods Return Value Description
on_modified() None Called after changes have been made to the view.
on_modified_async() None Called after changes have been made to the view. Runs in a separate thread, and does not block the application.
on_selection_modified() None Called after the selection has been modified in the view.
on_selection_modified_async() None Called after the selection has been modified in the view. Runs in a separate thread, and does not block the application.
on_activated() None Called when a view gains input focus.
on_activated_async() None Called when the view gains input focus. Runs in a separate thread, and does not block the application.
on_deactivated() None Called when the view loses input focus.
on_deactivated_async() None Called when the view loses input focus. Runs in a separate thread, and does not block the application.
on_hover(point, hover_zone) None

Called when the user's mouse hovers over the view for a short period.

point is the closest point in the view to the mouse location. The mouse may not actually be located adjacent based on the value of hover_zone:

  • sublime.HOVER_TEXT: When the mouse is hovered over text.
  • sublime.HOVER_GUTTER: When the mouse is hovered over the gutter.
  • sublime.HOVER_MARGIN: When the mouse is hovered in whitespace to the right of a line.
on_query_context(key, operator, operand, match_all) bool or None

Called when determining to trigger a key binding with the given context key. If the plugin knows how to respond to the context, it should return either True of False. If the context is unknown, it should return None.

operator is one of:

  • sublime.OP_EQUAL: Is the value of the context equal to the operand?
  • sublime.OP_NOT_EQUAL: Is the value of the context not equal to the operand?
  • sublime.OP_REGEX_MATCH: Does the value of the context match the regex given in operand?
  • sublime.OP_NOT_REGEX_MATCH: Does the value of the context not match the regex given in operand?
  • sublime.OP_REGEX_CONTAINS: Does the value of the context contain a substring matching the regex given in operand?
  • sublime.OP_NOT_REGEX_CONTAINS: Does the value of the context not contain a substring matching the regex given in operand?

match_all should be used if the context relates to the selections: does every selection have to match (match_all == True), or is at least one matching enough (match_all == False)?

on_query_completions(prefix, locations) list, tuple or None

Called whenever completions are to be presented to the user. The prefix is a unicode string of the text to complete.

locations is a list of points. Since this method is called for all completions no matter the syntax, self.view.match_selector(point, relevant_scope) should be called to determine if the point is relevant.

The return value must be one of the following formats:

  • None: no completions are provided

    return None

  • A list of 2-element lists/tuples. The first element is a unicode string of the completion trigger, the second is the unicode replacement text.

    return [["me1", "method1()"], ["me2", "method2()"]]

    The trigger may contain a tab character (\t) followed by a hint to display in the right-hand side of the completion box.

    return [
        ["me1\tmethod", "method1()"],
        ["me2\tmethod", "method2()"]
    ]

    The replacement text may contain dollar-numeric fields such as a snippet does, e.g. $0, $1.

    return [
        ["fn", "def ${1:name}($2) { $0 }"],
        ["for", "for ($1; $2; $3) { $0 }"]
    ]

  • A 2-element tuple with the first element being the list format documented above, and the second element being bit flags from the following list:

    • sublime.INHIBIT_WORD_COMPLETIONS: prevent Sublime Text from showing completions based on the contents of the view
    • sublime.INHIBIT_EXPLICIT_COMPLETIONS: prevent Sublime Text from showing completions based on .sublime-completions files

    return (
        [
            ["me1", "method1()"],
            ["me2", "method2()"]
        ],
        sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
    )

sublime_plugin.ApplicationCommand Class

Methods Return Value Description
run(<args>) None Called when the command is run.
is_enabled(<args>) bool Returns True if the command is able to be run at this time. The default implementation simply always returns True.
is_visible(<args>) bool Returns True if the command should be shown in the menu at this time. The default implementation always returns True.
is_checked(<args>) bool Returns True if a checkbox should be shown next to the menu item. The .sublime-menu file must have the checkbox attribute set to true for this to be used.
description(<args>) str Returns a description of the command with the given arguments. Used in the menu, if no caption is provided. Return None to get the default description.

sublime_plugin.WindowCommandClass

WindowCommands are instantiated once per window. The Window object may be retrieved via self.window

Methods Return Value Description
run(<args>) None Called when the command is run.
is_enabled(<args>) bool Returns True if the command is able to be run at this time. The default implementation simply always returns True.
is_visible(<args>) bool Returns True if the command should be shown in the menu at this time. The default implementation always returns True.
description(<args>) str Returns a description of the command with the given arguments. Used in the menu, if no caption is provided. Return None to get the default description.

sublime_plugin.TextCommand Class

TextCommands are instantiated once per view. The View object may be retrieved via self.view

Methods Return Value Description
run(edit, <args>) None Called when the command is run.
is_enabled(<args>) bool Returns True if the command is able to be run at this time. The default implementation simply always returns True.
is_visible(<args>) bool Returns True if the command should be shown in the menu at this time. The default implementation always returns True.
description(<args>) str Returns a description of the command with the given arguments. Used in the menus, and for Undo / Redo descriptions. Return None to get the default description.
want_event() bool Return True to receive an event argument when the command is triggered by a mouse action. The event information allows commands to determine which portion of the view was clicked on. The default implementation returns False.