API Reference Version:
General Information🔗
Example Plugins🔗
Several pre-made plugins come with Sublime Text, you can find them in the Default package:
Packages/Default/exec.pyUses phantoms to display errors inlinePackages/Default/font.pyShows how to work with settingsPackages/Default/goto_line.pyPrompts the user for input, then updates the selectionPackages/Default/mark.pyUses add_regions() to add an icon to the gutterPackages/Default/show_scope_name.pyUses a popup to show the scope names at the caretPackages/Default/arithmetic.pyAccepts an input from the user when run via the Command Palette
Plugin Lifecycle🔗
At importing time, plugins may not call any API functions, with the exception of:
<4171If a plugin defines a module level functionplugin_loaded(), this will becalled when the API is ready to use. Plugins may also defineplugin_unloaded(), to get notified just before the plugin is unloaded.
Threading🔗
All API functions are thread-safe, however keep in mind that from theperspective of code running in an alternate thread, application state will bechanging while the code is running.
Units and Coordinates🔗
API functions that accept or return coordinates or dimensions do so usingdevice-independent pixel (dip) values. While in some cases these will beequivalent to device pixels, this is often not the case. Per the CSSspecification, minihtml treats the px unit as device-independent.
Types🔗
- sublime.CommandArgs=Optional[dict[str,Value]]🔗
The arguments to a command may be
Noneor adictofstrkeys.
- sublime.Kind=tuple[KindId,str,str]🔗
Metadata about the kind of a symbol,
CompletionItem,QuickPanelItemorListInputItem. Controls the color and letter shown in the “icon” presentedto the left of the item.
- sublime.Event=dict🔗
Contains information about a user’s interaction with a menu, command paletteselection, quick panel selection or HTML document. The follow methods areused to signal that an event
dictis desired:Commands may opt-in to receive an arg named
eventby implementing themethodwant_event(self)and returningTrue.A call to
4096show_quick_panel()may opt-in to receive a second arg to theon_donecallback by specifying the flagQuickPanelFlags.WANT_EVENT.
4096ListInputHandlerclasses may opt-in to receive a second arg to thevalidate()andconfirm()methods by by implementing the methodwant_event()andreturningTrue.
The dict may contain zero or more of the following keys, based on the userinteraction:
- "x":float
The X mouse position when a user clicks on a menu, or in a minihtmldocument.
- "y":float
The Y mouse position when a user clicks on a menu, or in a minihtml document.
- "modifier_keys":dict 4096
Can have zero or more of the following keys:
"primary"- indicatingCtrl (Windows/Linux) orCmd(Mac) was pressed"ctrl"- indicatingCtrl was pressed"alt"- indicatingAlt was pressed"altgr"- indicatingAltGr was pressed (Linux only)"shift"- indicatingShift was pressed"super"- indicatingWin (Windows/Linux) orCmd(Mac) was pressed
Present when the user selects an item from a quick panel, selects an itemfrom a
ListInputHandler, or clicks a link in aminihtmldocument.
- sublime.CompletionValue=str|tuple[str,str]|CompletionItem🔗
Represents an available auto-completion item. completion values may be ofseveral formats. The termtrigger refers to the text matched against theuser input,replacement is what is inserted into the view if the item isselected. Anannotation is a unicode string hint displayed to theright-hand side of the trigger.
str:A string that is both the trigger and the replacement:
["method1()","method2()",]
2-element
tupleorlist:A pair of strings - the trigger and the replacement:
[["me1","method1()"],["me2","method2()"]]
If a t is present in the trigger, all subsequent text is treated as anannotation:
[["me1\tmethod","method1()"],["me2\tmethod","method2()"]]
The replacement text may contain dollar-numeric fields such as a snippet does, e.g.
$0,$1:[["fn","def ${1:name}($2) { $0 }"],["for","for ($1; $2; $3) { $0 }"]]
CompletionItemobjectAn object containing trigger, replacement, annotation, and kind metadata:
[sublime.CompletionItem("fn",annotation="def",completion="def ${1:name}($2) { $0 }",completion_format=sublime.COMPLETION_FORMAT_SNIPPET,kind=sublime.KIND_SNIPPET),sublime.CompletionItem("for",completion="for ($1; $2; $3) { $0 }",completion_format=sublime.COMPLETION_FORMAT_SNIPPET,kind=sublime.KIND_SNIPPET),]
4050
sublime Module🔗
Bases:
IntEnumA zone in an open text sheet where the mouse may hover.
See
EventListener.on_hoverandViewEventListener.on_hover.For backwards compatibility these values are also available outside thisenumeration with a
HOVER_prefix.- TEXT=1🔗
The mouse is hovered over the text.
- GUTTER=2🔗
The mouse is hovered over the gutter.
- MARGIN=3🔗
The mouse is hovered in the white space to the right of a line.
Bases:
IntFlagFlags for creating/opening files in various ways.
See
Window.new_html_sheet,Window.new_fileandWindow.open_file.For backwards compatibility these values are also available outside thisenumeration (without a prefix).
- NONE=0🔗
- ENCODED_POSITION=1🔗
Indicates that the file name should be searched for a
:rowor:row:colsuffix.
- TRANSIENT=4🔗
Open the file as a preview only: it won’t have a tab assigned it untilmodified.
- FORCE_GROUP=8🔗
Don’t select the file if it is open in a different group. Instead make a newclone of that file in the desired group.
- SEMI_TRANSIENT=16🔗 4096
If a sheet is newly created, it will be set to semi-transient.Semi-transient sheets generally replace other semi-transient sheets. Thisis used for the side-bar preview. Only valid with
ADD_TO_SELECTIONorREPLACE_MRU.
- ADD_TO_SELECTION=32🔗 4050
Add the file to the currently selected sheets in the group.
- REPLACE_MRU=64🔗 4096
Causes the sheet to replace the most-recently used sheet in the current sheet selection.
- CLEAR_TO_RIGHT=128🔗 4100
All currently selected sheets to the right of the most-recently used sheetwill be unselected before opening the file. Only valid in combination with
ADD_TO_SELECTION.
- FORCE_CLONE=256🔗
Don’t select the file if it is open. Instead make a new clone of that file in the desiredgroup.
Bases:
IntFlagFlags for use when searching through a
View.See
View.findandView.find_all.For backwards compatibility these values are also available outside thisenumeration (without a prefix).
- NONE=0🔗
- LITERAL=1🔗
Whether the find pattern should be matched literally or as a regex.
- IGNORECASE=2🔗
Whether case should be considered when matching the find pattern.
- WHOLEWORD=4🔗 4149
Whether to only match whole words.
- REVERSE=8🔗 4149
Whether to search backwards.
- WRAP=16🔗 4149
Whether to wrap around once the end is reached.
Bases:
IntFlagFlags for use with popups.
See
View.show_popup.For backwards compatibility these values are also available outside thisenumeration (without a prefix).
- NONE=0🔗
- COOPERATE_WITH_AUTO_COMPLETE=2🔗
Causes the popup to display next to the auto complete menu.
- HIDE_ON_MOUSE_MOVE=4🔗
Causes the popup to hide when the mouse is moved, clicked or scrolled.
- HIDE_ON_MOUSE_MOVE_AWAY=8🔗
Causes the popup to hide when the mouse is moved (unless towards the popup),or when clicked or scrolled.
- KEEP_ON_SELECTION_MODIFIED=16🔗 4057
Prevent the popup from hiding when the selection is modified.
- HIDE_ON_CHARACTER_EVENT=32🔗 4057
Hide the popup when a character is typed.
Bases:
IntFlagFlags for use with added regions. See
View.add_regions.For backwards compatibility these values are also available outside thisenumeration (without a prefix).
- NONE=0🔗
- DRAW_EMPTY=1🔗
Draw empty regions with a vertical bar. By default, they aren’t drawn at all.
- HIDE_ON_MINIMAP=2🔗
Don’t show the regions on the minimap.
- DRAW_EMPTY_AS_OVERWRITE=4🔗
Draw empty regions with a horizontal bar instead of a vertical one.
- PERSISTENT=16🔗
Save the regions in the session.
- DRAW_NO_FILL=32🔗
Disable filling the regions, leaving only the outline.
- HIDDEN=128🔗
Don’t draw the regions.
- DRAW_NO_OUTLINE=256🔗
Disable drawing the outline of the regions.
- DRAW_SOLID_UNDERLINE=512🔗
Draw a solid underline below the regions.
- DRAW_STIPPLED_UNDERLINE=1024🔗
Draw a stippled underline below the regions.
- DRAW_SQUIGGLY_UNDERLINE=2048🔗
Draw a squiggly underline below the regions.
- NO_UNDO=8192🔗
Bases:
IntEnumEnumeration of operators able to be used when querying contexts.
See
EventListener.on_query_contextandViewEventListener.on_query_context.For backwards compatibility these values are also available outside thisenumeration with a
OP_prefix.- EQUAL=0🔗
- NOT_EQUAL=1🔗
- REGEX_MATCH=2🔗
- NOT_REGEX_MATCH=3🔗
- REGEX_CONTAINS=4🔗
- NOT_REGEX_CONTAINS=5🔗
Bases:
IntFlagFlags that identify characteristics about a
Pointin a text sheet. SeeView.classify.For backwards compatibility these values are also available outside thisenumeration with a
CLASS_prefix.- NONE=0🔗
- WORD_START=1🔗
The point is the start of a word.
- WORD_END=2🔗
The point is the end of a word.
- PUNCTUATION_START=4🔗
The point is the start of a sequence of punctuation characters.
- PUNCTUATION_END=8🔗
The point is the end of a sequence of punctuation characters.
- SUB_WORD_START=16🔗
The point is the start of a sub-word.
- SUB_WORD_END=32🔗
The point is the end of a sub-word.
- LINE_START=64🔗
The point is the start of a line.
- LINE_END=128🔗
The point is the end of a line.
- EMPTY_LINE=256🔗
The point is an empty line.
Bases:
IntFlagFlags controlling how asynchronous completions function. See
CompletionList.For backwards compatibility these values are also available outside thisenumeration (without a prefix).
- NONE=0🔗
- INHIBIT_WORD_COMPLETIONS=8🔗
Prevent Sublime Text from showing completions based on the contents of theview.
- INHIBIT_EXPLICIT_COMPLETIONS=16🔗
Prevent Sublime Text from showing completions based on.sublime-completions files.
- DYNAMIC_COMPLETIONS=32🔗 4057
If completions should be re-queried as the user types.
- INHIBIT_REORDER=128🔗 4074
Prevent Sublime Text from changing the completion order.
Bases:
IntEnumThe result from ayes / no / cancel dialog. See
yes_no_cancel_dialog.For backwards compatibility these values are also available outside thisenumeration with a
DIALOG_prefix.- CANCEL=0🔗
- YES=1🔗
- NO=2🔗
Bases:
IntEnumHow a
Phantomshould be positioned. SeePhantomSet.For backwards compatibility these values are also available outside thisenumeration with a
LAYOUT_prefix.- BLOCK=2🔗
The phantom is positioned below the line, left-aligned with the beginning ofthe line.
Bases:
IntEnumFor backwards compatibility these values are also available outside thisenumeration with a
KIND_ID_prefix.- AMBIGUOUS=0🔗
- KEYWORD=1🔗
- TYPE=2🔗
- FUNCTION=3🔗
- NAMESPACE=4🔗
- NAVIGATION=5🔗
- MARKUP=6🔗
- VARIABLE=7🔗
- SNIPPET=8🔗
- COLOR_REDISH=9🔗
- COLOR_ORANGISH=10🔗
- COLOR_YELLOWISH=11🔗
- COLOR_GREENISH=12🔗
- COLOR_CYANISH=13🔗
- COLOR_BLUISH=14🔗
- COLOR_PURPLISH=15🔗
- COLOR_PINKISH=16🔗
- COLOR_DARK=17🔗
- COLOR_LIGHT=18🔗
- sublime.KIND_AMBIGUOUS=(KindId.AMBIGUOUS,'','')🔗 4052
- sublime.KIND_KEYWORD=(KindId.KEYWORD,'','')🔗 4052
- sublime.KIND_TYPE=(KindId.TYPE,'','')🔗 4052
- sublime.KIND_FUNCTION=(KindId.FUNCTION,'','')🔗 4052
- sublime.KIND_NAMESPACE=(KindId.NAMESPACE,'','')🔗 4052
- sublime.KIND_NAVIGATION=(KindId.NAVIGATION,'','')🔗 4052
- sublime.KIND_MARKUP=(KindId.MARKUP,'','')🔗 4052
- sublime.KIND_VARIABLE=(KindId.VARIABLE,'','')🔗 4052
- sublime.KIND_SNIPPET=(KindId.SNIPPET,'s','Snippet')🔗 4052
Bases:
IntEnumFor backwards compatibility these values are also available outside thisenumeration with a
SYMBOL_SOURCE_prefix.- ANY=0🔗 4085
Use any source - both the index and open files.
- INDEX=1🔗 4085
Use the index created when scanning through files in a project folder.
- OPEN_FILES=2🔗 4085
Use the open files, unsaved or otherwise.
Bases:
IntEnumSee
Window.symbol_locationsandView.indexed_symbol_regions.For backwards compatibility these values are also available outside thisenumeration with a
SYMBOL_TYPE_prefix.- ANY=0🔗 4085
Any symbol type - both definitions and references.
- DEFINITION=1🔗 4085
Only definitions.
- REFERENCE=2🔗 4085
Only references.
Bases:
IntEnumThe format completion text can be in. See
CompletionItem.For backwards compatibility these values are also available outside thisenumeration with a
COMPLETION_FORMAT_prefix.- TEXT=0🔗 4050
Plain text, upon completing the text is inserted verbatim.
- SNIPPET=1🔗 4050
A snippet, with
$variables. See alsoCompletionItem.snippet_completion.
- COMMAND=2🔗 4050
A command string, in the format returned by
format_command(). See alsoCompletionItem.command_completion().
- sublime.platform()→Literal['osx','linux','windows']🔗
- Returns
The platform which the plugin is being run on.
- sublime.executable_path()→str🔗
This may be called at import time.
4081- Returns
The path to the main Sublime Text executable.
- sublime.executable_hash()→tuple[str,str,str]🔗
This may be called at import time.
4081- Returns
A tuple uniquely identifying the installation of Sublime Text.
- sublime.packages_path()→str🔗
This may be called at import time.
4081- Returns
The path to the “Packages” folder.
- sublime.installed_packages_path()→str🔗
This may be called at import time.
4081- Returns
The path to the “Installed Packages” folder.
- sublime.cache_path()→str🔗
This may be called at import time.
4081- Returns
The path where Sublime Text stores cache files.
- sublime.ok_cancel_dialog(msg:str,ok_title='',title='')→bool🔗
Show aok / cancel question dialog.
- Parameters
msgThe message to show in the dialog.
ok_titleText to display on theok button.
title4099Title for the dialog. Windows only.
- Returns
Whether the user pressed theok button.
- sublime.yes_no_cancel_dialog(msg:str,yes_title='',no_title='',title='')→DialogResult🔗
Show ayes / no / cancel question dialog.
- Parameters
msgThe message to show in the dialog.
yes_titleText to display on theyes button.
no_titleText to display on theno button.
title4099Title for the dialog. Windows only.
- sublime.open_dialog(callback:Callable[[str|list[str]|None],None],file_types:list[tuple[str,list[str]]]=[],directory:Optional[str]=None,multi_select=False,allow_folders=False)🔗 4075
Show the open file dialog.
- Parameters
callbackCalled with selected path(s) or
Noneonce the dialog is closed.
file_typesA list of allowed file types, consisting of a descriptionand a list of allowed extensions.
directoryThe directory the dialog should start in. Will use thevirtual working directory if not provided.
multi_selectWhether to allow selecting multiple files. When
Truethe callback will be called with a list.
allow_foldersWhether to also allow selecting folders. Only works onmacOS. If you only want to select folders use
select_folder_dialog.
- sublime.save_dialog(callback:Callable[[str|None],None],file_types:list[tuple[str,list[str]]]=[],directory:Optional[str]=None,name:Optional[str]=None,extension:Optional[str]=None)🔗 4075
Show the save file dialog
- Parameters
callbackCalled with selected path or
Noneonce the dialog is closed.
file_typesA list of allowed file types, consisting of a descriptionand a list of allowed extensions.
directoryThe directory the dialog should start in. Will use thevirtual working directory if not provided.
nameThe default name of the file in the save dialog.
extensionThe default extension used in the save dialog.
- sublime.select_folder_dialog(callback:Callable[[str|list[str]|None],None],directory:Optional[str]=None,multi_select=False)🔗 4075
Show the select folder dialog.
- Parameters
callbackCalled with selected path(s) or
Noneonce the dialog is closed.
directoryThe directory the dialog should start in. Will use thevirtual working directory if not provided.
multi_selectWhether to allow selecting multiple files. When
Truethe callback will be called with a list.
Show a dialog for selecting a font.
- Parameters
callbackCalled with the font options, matching the format used insettings (eg.
{"font_face":"monospace"}). May becalled more than once, or will be called withNoneifthe dialog is cancelled.
defaultThe default values to select/return. Same format as theargument passed to
callback.
- sublime.run_command(cmd:str,args:CommandArgs=None)🔗
Run the named
ApplicationCommand.
- sublime.format_command(cmd:str,args:CommandArgs=None)→str🔗 4075
Create a “command string” from a
cmdname andargsarguments. Thisis used when constructing a command-basedCompletionItem.
- sublime.html_format_command(cmd:str,args:CommandArgs=None)→str🔗 4075
- Returns
An escaped “command string” for usage in HTML popups and sheets.
- sublime.command_url(cmd:str,args:CommandArgs=None)→str🔗 4075
- Returns
A HTML embeddable URL for a command.
Get the contents of the clipboard in a callback.
For performance reasons if the size of the clipboard content is bigger than
size_limit, an empty string will be passed to the callback.
- sublime.get_clipboard(size_limit:int=16777216)→str🔗
Get the contents of the clipboard.
For performance reasons if the size of the clipboard content is bigger than
size_limit, an empty string will be returned.- Deprecated
Use
get_clipboard_asyncinstead. 4075
- sublime.log_commands(flag:Optional[bool]=None)🔗
Control whether commands are logged to the console when run.
- Parameters
flagWhether to log.Passing None toggles logging.4099
- sublime.log_input(flag:Optional[bool]=None)🔗
Control whether all key presses will be logged to the console. Use this tofind the names of certain keys on the keyboard.
- Parameters
flagWhether to log.Passing None toggles logging.4099
Control whether rendering timings like frames per second get logged.
- Parameters
flagWhether to log. Pass
Noneto toggle logging.
- sublime.log_result_regex(flag:Optional[bool]=None)🔗
Control whether result regex logging is enabled. Use this to debug
"file_regex"and"line_regex"in build systems.- Parameters
flagWhether to log.Passing None toggles logging.4099
- sublime.log_indexing(flag:Optional[bool]=None)🔗
Control whether indexing logs are printed to the console.
- Parameters
flagWhether to log.Passing None toggles logging.4099
- sublime.log_build_systems(flag:Optional[bool]=None)🔗
Control whether build system logs are printed to the console.
- Parameters
flagWhether to log.Passing None toggles logging.4099
Control whether control tree logging is enabled. When enabled clicking withctrl+alt will log the control tree under the mouse to the console.
- Parameters
flagWhether to log.Passing None toggles logging.4099
- Returns
Information about the user interface including top-level keys
system,themeandcolor_scheme.
- sublime.score_selector(scope_name:str,selector:str)→int🔗
Match the
selectoragainst the givenscope_name, returning a score for how well they match.A score of
0means no match, above0means a match. Differentselectors may be compared against the same scope: a higher score means theselector is a better match for the scope.
- sublime.load_resource(name:str)→str🔗
Loads the given resource. The name should be in the format “Packages/Default/Main.sublime-menu”.
- Raises
FileNotFoundError if resource is not found
- Raises
- sublime.load_binary_resource(name)→bytes🔗
Loads the given resource. The name should be in the format “Packages/Default/Main.sublime-menu”.
- Raises
FileNotFoundError if resource is not found
- Raises
- sublime.find_resources(pattern:str)→list[str]🔗
Finds resources whose file name matches the given glob pattern.
- sublime.encode_value(value:Value,pretty=False,update_text:str=None)→str🔗
Encode a JSON compatible
Valueinto a string representation.- Parameters
prettyWhether the result should include newlines and be indented.
update_text4156Incrementally update the value encoded in this text. Best effort is madeto preserve the contents of
update_text- comments, indentation,etc. This is the same algorithm used to change settings values.Providing this makesprettyhave no effect.
- sublime.decode_value(data:str)→Value🔗
Decode a JSON string into an object. Note that comments and trailing commasare allowed.
- Raises
ValueError If the string is not valid JSON.
- Raises
- sublime.expand_variables(value:Value,variables:dict[str,str])→Value🔗
Expands any variables in
valueusing the variables defined in thedictionaryvariables. value may also be a list or dict, in which case thestructure will be recursively expanded. Strings should use snippet syntax,for example:expand_variables("Hello,${name}",{"name":"Foo"}).
- sublime.load_settings(base_name:str)→Settings🔗
Loads the named settings. The name should include a file name and extension,but not a path. The packages will be searched for files matching thebase_name, and the results will be collated into the settings object.
Subsequent calls to load_settings() with the base_name will return the sameobject, and not load the settings from disk again.
- sublime.save_settings(base_name:str)🔗
Flush any in-memory changes to the named settings object to disk.
- sublime.set_timeout(callback:Callable,delay:int=0)🔗
Run the
callbackin the main thread after the givendelay(in milliseconds). Callbacks with an equal delay will be run in the orderthey were added.
- sublime.set_timeout_async(callback:Callable,delay:int=0)🔗
Runs the callback on an alternate thread after the given delay(in milliseconds).
- sublime.windows()→list[sublime.Window]🔗
- Returns
A list of all the open windows.
- sublime.get_macro()→list[dict]🔗
- Returns
A list of the commands and args that compromise the currentlyrecorded macro. Each
dictwill contain the keys"command"and"args".
- Returns
A list of most recently opened workspaces.Sublime-project files with the same name arelisted in place of sublime-workspace files.
- classsublime.Window🔗
Bases:
object- is_valid()→bool🔗
Check whether this window is still valid. Will return
Falsefor aclosed window, for example.
Construct a sheet with HTML contents rendered usingminihtml Reference.
- Parameters
nameThe name of the sheet to show in the tab.
contentsThe HTML contents of the sheet.
flagsOnly
NewFileFlags.TRANSIENTandNewFileFlags.ADD_TO_SELECTIONare allowed.
groupThe group to add the sheet to.
-1for the active group.
- run_command(cmd:str,args:CommandArgs=None)🔗
Run the named
WindowCommandwith the (optional) given args. Thismethod is able to run any sort of command, dispatching the command viainput focus.
- new_file(flags=NewFileFlags.NONE,syntax='')→View🔗
Create a new empty file.
- Parameters
flagsEither
0,NewFileFlags.TRANSIENTorNewFileFlags.ADD_TO_SELECTION.
syntaxThe name of the syntax to apply to the file.
- Returns
The view for the file.
- open_file(fname:str,flags=NewFileFlags.NONE,group=-1)→View🔗
Open the named file. If the file is already opened, it will be broughtto the front. Note that as file loading is asynchronous, operations onthe returned view won’t be possible until its
is_loading()methodreturnsFalse.- Parameters
fnameThe path to the file to open.
flags
groupThe group to add the sheet to.
-1for the active group.
- find_open_file(fname:str,group=-1)→Optional[View]🔗
Find a opened file by file name.
- Parameters
fnameThe path to the file to open.
groupThe group in which to search for the file.
-1for any group.
- Returns
The
Viewto the file orNoneif the file isn’t open.
- file_history()→list[str]🔗
Get the list of previously opened files. This is the same listasFile > Open Recent.
- select_sheets(sheets:list[sublime.Sheet])🔗 4083
Change the selected sheets for the entire window.
- bring_to_front()🔗
Bring the window in front of any other windows.
- get_sheet_index(sheet:Sheet)→tuple[int,int]🔗
- Returns
The a tuple of the group and index within the group of thegiven
Sheet.
- get_view_index(view:View)→tuple[int,int]🔗
- Returns
The a tuple of the group and index within the group of thegiven
View.
- set_sheet_index(sheet:Sheet,group:int,index:int)🔗
Move the given
Sheetto the givengroupat the givenindex.
- set_view_index(view:View,group:int,index:int)🔗
Move the given
Viewto the givengroupat the givenindex.
- move_sheets_to_group(sheets:list[sublime.Sheet],group:int,insertion_idx=-1,select=True)🔗 4123
Moves all provided sheets to specified group at insertion indexprovided. If an index is not provided defaults to last index of thedestination group.
- Parameters
sheetsThe sheets to move.
groupThe index of the group to move the sheets to.
insertion_idxThe point inside the group at which to insert the sheets.
selectWhether the sheets should be selected after moving them.
- sheets()→list[sublime.Sheet]🔗
- Returns
All open sheets in the window.
- views(*,include_transient=False)→list[sublime.View]🔗
- Parameters
include_transient4081Whether the transient sheet should be included.
- Returns
All open sheets in the window.
- selected_sheets()→list[sublime.Sheet]🔗 4083
- Returns
All selected sheets in the window’s currently selected group.
- selected_sheets_in_group(group:int)→list[sublime.Sheet]🔗 4083
- Returns
All selected sheets in the specified group.
- active_sheet_in_group(group:int)→Optional[Sheet]🔗
- Returns
The currently focused
Sheetin the given group.
- sheets_in_group(group:int)→list[sublime.Sheet]🔗
- Returns
A list of all sheets in the specified group.
- views_in_group(group:int)→list[sublime.View]🔗
- Returns
A list of all views in the specified group.
- transient_sheet_in_group(group:int)→Optional[Sheet]🔗
- Returns
The transient sheet in the specified group.
- create_output_panel(name:str,unlisted=False)→View🔗
Find the
Viewassociated with the named output panel, creating it ifrequired. The output panel can be shown by running theshow_panelwindow command, with thepanelargument set to the name withan"output."prefix.- Parameters
nameThe name of the output panel.
unlistedControl if the output panel should be listed in the panel switcher.
- find_output_panel(name:str)→Optional[View]🔗
- Returns
The
Viewassociated with the named output panel, orNoneifthe output panel does not exist.
- create_io_panel(name:str,on_input:Callable[[str],None],unlisted=False)→Tuple[View,View]🔗
Just like
create_output_panel, find the view(s) associated with thenamed output panel, creating it if required. The output panel willadditionally be configured with an input box. The panel can be shown byrunning theshow_panelwindow command, with thepanelargumentset to the name with an"output."prefix.
- active_panel()→Optional[str]🔗
Returns the name of the currently open panel, or None if no panel isopen. Will return built-in panel names (e.g.
"console","find",etc) in addition to output panels.
- panels()→list[str]🔗
Returns a list of the names of all panels that have not been marked asunlisted. Includes certain built-in panels in addition to outputpanels.
- get_output_panel(name:str)🔗
- Deprecated
Use
create_output_panelinstead.
- show_input_panel(caption:str,initial_text:str,on_done:Optional[Callable[[str],None]],on_change:Optional[Callable[[str],None]],on_cancel:Optional[Callable[[],None]])🔗
Shows the input panel, to collect a line of input from the user.
- Parameters
captionThe label to put next to the input widget.
initial_textThe initial text inside the input widget.
on_doneCalled with the final input when the user presses
enter.
on_changeCalled with the input when it’s changed.
on_cancelCalled when the user cancels input using
esc
- Returns
The
Viewused for the input widget.
- show_quick_panel(items:list[str]|list[list[str]]|list[sublime.QuickPanelItem],on_select:Callable[[int],None],flags=QuickPanelFlags.NONE,selected_index=-1,on_highlight:Optional[Callable[[int],None]]=None,placeholder:Optional[str]=None)🔗
Show a quick panel to select an item in a list. on_select will be calledonce, with the index of the selected item. If the quick panel wascancelled, on_select will be called with an argument of -1.
- Parameters
itemsMay be either a list of strings, or a list of lists of strings wherethe first item is the trigger and all subsequent strings aredetails shown below.
May be a
4083QuickPanelItem.
on_selectCalled with the selected item’s index when the quick panel iscompleted. If the panel was cancelled this is called with
-1.A second
4096Eventargument may be passed when theQuickPanelFlags.WANT_EVENTflag is present.
flagsQuickPanelFlagscontrolling behavior.
selected_indexThe initially selected item.
-1for no selection.
on_highlightCalled every time the highlighted item in the quick panel is changed.
placeholder4081Text displayed in the filter input field before any query is typed.
- Returns
The name of the currently opened workspace file, if any.
- project_data()→Value🔗
- Returns
The project data associated with the current window. The datais in the same format as the contents of a.sublime-project file.
- set_project_data(data:Value)🔗
Updates the project data associated with the current window. If thewindow is associated with a.sublime-project file, the projectfile will be updated on disk, otherwise the window will store the datainternally.
- template_settings()→Settings🔗
- Returns
Per-window settings that are persisted in the session, andduplicated into new windows.
- symbol_locations(sym:str,source=SymbolSource.ANY,type=SymbolType.ANY,kind_id=KindId.AMBIGUOUS,kind_letter='')→list[sublime.SymbolLocation]🔗 4085
Find all locations where the symbol
symis located.
- lookup_symbol_in_index(symbol:str)→list[sublime.SymbolLocation]🔗
- Returns
All locations where the symbol is defined across files in the current project.
- Deprecated
Use
symbol_locations()instead.
- lookup_symbol_in_open_files(symbol:str)→list[sublime.SymbolLocation]🔗
- Returns
All locations where the symbol is defined across open files.
- Deprecated
Use
symbol_locations()instead.
- lookup_references_in_index(symbol:str)→list[sublime.SymbolLocation]🔗
- Returns
All locations where the symbol is referenced across files in the current project.
- Deprecated
Use
symbol_locations()instead.
- lookup_references_in_open_files(symbol:str)→list[sublime.SymbolLocation]🔗
- Returns
All locations where the symbol is referenced across open files.
- Deprecated
Use
symbol_locations()instead.
- extract_variables()→dict[str,str]🔗
Get the
dictof contextual keys of the window.May contain:*
"packages"*"platform"*"file"*"file_path"*"file_name"*"file_base_name"*"file_extension"*"folder"*"project"*"project_path"*"project_name"*"project_base_name"*"project_extension"This
dictis suitable for use withexpand_variables().
- classsublime.Edit🔗
Bases:
objectA grouping of buffer modifications.
Edit objects are passed to
TextCommands, and can not be created by theuser. Using an invalid Edit object, or an Edit object from a differentView, will cause the functions that require them to fail.
- classsublime.Region🔗
Bases:
objectA singular selection region. This region has a order -
bmay be beforeor ata.Also commonly used to represent an area of the text buffer, where orderingand
xposare generally ignored.- b:Point🔗
The second end of the region. In a selection this is the location of thecaret. May be less than
a.
- xpos:DIP🔗
In a selection this is the target horizontal position of the region.This affects behavior when pressing the up or down keys. Use
-1ifundefined.
- contains(x:Point)→bool🔗
Equivalent to
__contains__.
- classsublime.HistoricPosition🔗 4050
Bases:
objectProvides a snapshot of the row and column info for a
Point, before changeswere made to aView. This is primarily useful for replaying changes to adocument.- row:int🔗
The row the
.pywas in when theHistoricPositionwas recorded.
- col:int🔗
The column the
.pywas in when theHistoricPositionwas recorded, in Unicode characters.
- classsublime.TextChange🔗 4050
Bases:
objectRepresents a change that occurred to the text of a
View. This is primarilyuseful for replaying changes to a document.- a:HistoricPosition🔗
The beginning
HistoricPositionof the region that was modified.
- b:HistoricPosition🔗
The ending
HistoricPositionof the region that was modified.
- str:str
A string of thenew contents of the region specified by
.aand.b.
- classsublime.Selection🔗
Bases:
objectMaintains a set of sorted non-overlapping Regions. A selection may beempty.
This is primarily used to represent the textual selection.
- clear()🔗
Remove all regions from the selection.
- add(x:Region|Point)🔗
Add a
RegionorPointto the selection. It will be merged with theexisting regions if intersecting.
- classsublime.Sheet🔗
Bases:
objectRepresents a content container, i.e. a tab, within a window. Sheets maycontain a View, or an image preview.
- window()→Optional[Window]🔗
- Returns
The
Windowcontaining this sheet. May beNoneif thesheet has been closed.
- Returns
The full name of the file associated with the sheet, or
Noneif it doesn’t exist on disk.
- Returns
Whether this sheet is exclusively transient.
Note that a sheet may be both open as a regular file and betransient. In this case
is_transientwill still returnFalse.
- close(on_close=<functionSheet.<lambda>>)🔗 4088
Closes the sheet.
- Parameters
on_close
- classsublime.ContextStackFrame🔗 4127
Bases:
objectRepresents a single stack frame in the syntax highlighting. See
View.context_backtrace.
- classsublime.View🔗
Bases:
objectRepresents a view into a text
Buffer.Note that multiple views may refer to the same
Buffer, but they have theirown unique selection and geometry. A list of these may be gotten usingView.clones()orBuffer.views().- Returns
Nonefor normal views that are part of aSheet. For views thatcomprise part of the UI a string is returned from the followinglist:"console:input"- The console input."goto_anything:input"- The input for the Goto Anything."command_palette:input"- The input for the Command Palette."find:input"- The input for the Find panel."incremental_find:input"- The input for the Incremental Find panel."replace:input:find"- The Find input for the Replace panel."replace:input:replace"- The Replace input for the Replace panel."find_in_files:input:find"- The Find input for the Find in Files panel."find_in_files:input:location"- The Where input for the Find in Files panel."find_in_files:input:replace"- The Replace input for the Find in Files panel."find_in_files:output"- The output panel for Find in Files (buffer or output panel)."input:input"- The input for the Input panel."exec:output"- The output for the exec command."output:output"- A general output panel.
The console output, indexer status output and license input controlsare not accessible via the API.
- is_valid()→bool🔗
Check whether this view is still valid. Will return
Falsefor aclosed view, for example.
- is_primary()→bool🔗
- Returns
Whether view is the primary view into a
Buffer. Will only beFalseif the user has opened multiple views into a file.
- clones()→list[sublime.View]🔗
- file_name()→Optional[str]🔗
- Returns
The full name of the file associated with the sheet, or
Noneif it doesn’t exist on disk.
- reset_reference_document()🔗
Clears the state of theincremental diff for theview.
- set_reference_document(reference:str)🔗
Uses the string reference to calculate the initial diff for theincremental diff.
- is_scratch()→bool🔗
- Returns
Whether the buffer is a scratch buffer. See
set_scratch().
- set_scratch(scratch:bool)🔗
Sets the scratch property on the buffer. When a modified scratch bufferis closed, it will be closed without prompting to save. Scratch buffersnever report as being dirty.
- set_encoding(encoding_name:str)🔗
Applies a new encoding to the file. This will be used when the file issaved.
- insert(edit:Edit,pt:Point,text:str)→int🔗
Insert the given string into the buffer.
- Parameters
editAn
Editobject provided by aTextCommand.
pointThe text point in the view where to insert.
textThe text to insert.
- Returns
The actual number of characters inserted. This may differfrom the provided text due to tab translation.
- Raises
ValueError If the
Editobject is in an invalid state, ie. outside of aTextCommand.
- replace(edit:Edit,region:Region,text:str)🔗
Replaces the contents of the
Regionin the buffer with the provided string.
- change_count()→int🔗
Each time the buffer is modified, the change count is incremented. Thechange count can be used to determine if the buffer has changed sincethe last it was inspected.
- Returns
The current change count.
- change_id()→tuple[int,int,int]🔗
Get a 3-element tuple that can be passed to
transform_region_from()toobtain a region equivalent to a region of the view in the past. This isprimarily useful for plugins providing text modification that mustoperate in an asynchronous fashion and must be able to handle the viewcontents changing between the request and response.
- transform_region_from(region:Region,change_id:tuple[int,int,int])→Region🔗
Transforms a region from a previous point in time to an equivalentregion in the current state of the View. The
change_idmust havebeen obtained fromchange_id()at the point in time the region isfrom.
- run_command(cmd:str,args:CommandArgs=None)🔗
Run the named
TextCommandwith the (optional) givenargs.
- find_all(pattern:str,flags=FindFlags.NONE,fmt:Optional[str]=None,extractions:Optional[list[str]]=None,within:Optional[Union[Region,list[sublime.Region]]]=None)→list[sublime.Region]🔗
- Parameters
patternThe regex or literal pattern to search by.
flagsControls various behaviors of find. See
FindFlags.
fmtWhen not
Noneall matches in theextractionslistwill be formatted with the provided format string.
extractionsAn optionally provided list to place the contents ofthe find results into.
within4181When not
Nonesearching is limited to within the providedregion(s).
- Returns
All (non-overlapping) regions matching the pattern.
- settings()→Settings🔗
- Returns
The view’s
Settingsobject. Any changes to it will beprivate to this view.
- meta_info(key:str,pt:Point)→Value🔗
Look up the preference
keyfor the scope at the providedPointfrom all matching.tmPreferencesfiles.Examples of keys are
TM_COMMENT_STARTandshowInSymbolList.
- extract_tokens_with_scopes(region:Region)→list[tuple[sublime.Region,str]]🔗
- Parameters
regionThe region from which to extract tokens and scopes.
- Returns
A list of pairs containing the
Regionand the scope of each token.
- extract_scope(pt:Point)→Region🔗
- Returns
The extent of the syntax scope name assigned to the characterat the given
Point, narrower syntax scope names included.
- expand_to_scope(pt:Point,selector:str)→Optional[Region]🔗
Expand by the provided scope selector from the
Point.- Parameters
ptThe point from which to expand.
selectorThe scope selector to match.
- Returns
The matched
Region, if any.
- context_backtrace(pt:Point)→list[ContextStackFrame]🔗 4127
Get a backtrace of
ContextStackFrames at the providedPoint.Note this function is particularly slow.
- match_selector(pt:Point,selector:str)→bool🔗
- Returns
Whether the provided scope selector matches the
Point.
- score_selector(pt:Point,selector:str)→int🔗
Equivalent to:
sublime.score_selector(view.scope_name(pt),selector)
- find_by_selector(selector:str)→list[sublime.Region]🔗
Find all regions in the file matching the given selector.
- Returns
The list of matched regions.
See
style_for_scope.- Returns
The global style settings for the view. All colors are normalizedto the six character hex form with a leading hash, e.g.
#ff0000.
- style_for_scope(scope:str)→dict[str,Value]🔗
Accepts a string scope name and returns a
dictof style informationincluding the keys:"foreground":str"selection_foreground":str(only if set)"background":str(only if set)"bold":bool"italic":bool
4063"glow":bool(only if set)
4075"underline":bool(only if set)
4075"stippled_underline":bool(only if set)
4075"squiggly_underline":bool(only if set)"source_line":str"source_column":int"source_file":int
The foreground and background colors are normalized to the six characterhex form with a leading hash, e.g.
#ff0000.
- lines(region:Region)→list[sublime.Region]🔗
- Returns
A list of lines (in sorted order) intersecting the provided
Region.
- split_by_newlines(region:Region)→list[sublime.Region]🔗
Splits the region up such that each
Regionreturned exists on exactlyone line.
- classify(pt:Point)→PointClassification🔗
Classify the provided
Point. SeePointClassification.
- find_by_class(pt:Point,forward:bool,classes:PointClassification,separators='',sub_word_separators='')→Point🔗
Find the next location that matches the provided
PointClassification.- Parameters
ptThe point to start searching from.
forwardWhether to search forward or backwards.
classesThe classification to search for.
separatorsThe word separators to use when classifying.
sub_word_separators4130The sub-word separators to use when classifying.
- Returns
The found point.
- expand_by_class(x:Region|Point,classes:PointClassification,separators='',sub_word_separators='')→Region🔗
Expand the provided
PointorRegionto the left and right until eachside lands on a location that matches the providedPointClassification. Seefind_by_class.- Parameters
classesThe classification to search by.
separatorsThe word separators to use when classifying.
sub_word_separators4130The sub-word separators to use when classifying.
- rowcol(tp:Point)→tuple[int,int]🔗
Calculates the 0-based line and column numbers of the point. Columnnumbers are returned as number of Unicode characters.
Calculates the 0-based line and column numbers of the point. Columnnumbers are returned as UTF-8 code units.
Calculates the 0-based line and column numbers of the point. Columnnumbers are returned as UTF-16 code units.
- text_point(row:int,col:int,*,clamp_column=False)→Point🔗
Calculates the character offset of the given, 0-based,
rowandcol.colis interpreted as the number of Unicode characters toadvance past the beginning of the row.- Parameters
clamp_column4075Whether
colshould be restricted to valid values for the givenrow.
- text_point_utf8(row:int,col:int,*,clamp_column=False)→Point🔗
Calculates the character offset of the given, 0-based,
rowandcol.colis interpreted as the number of UTF-8 code units toadvance past the beginning of the row.- Parameters
clamp_column4075whether
colshould be restricted to valid values for the givenrow.
- text_point_utf16(row:int,col:int,*,clamp_column=False)→Point🔗
Calculates the character offset of the given, 0-based,
rowandcol.colis interpreted as the number of UTF-16 code units toadvance past the beginning of the row.- Parameters
clamp_column4075whether
colshould be restricted to valid values for the givenrow.
Calculates the utf8 code unit offset at the given text point.
- Parameters
tpThe text point up to which code units should be counted. If notprovided the total is returned.
Calculates the utf16 code unit offset at the given text point.
- Parameters
tpThe text point up to which code units should be counted. If notprovided the total is returned.
- show(location:Region|Selection|Point,show_surrounds=True,keep_to_left=False,animate=True)🔗
Scroll the view to show the given location.
- Parameters
show_surroundsWhether to show the surrounding context around the location.
keep_to_left4075Whether the view should be kept to the left, if horizontal scrollingis possible.
animate4075Whether the scrolling should be animated.
- folded_regions()→list[sublime.Region]🔗
- Returns
The list of folded regions.
- fold(x:sublime.Region|list[sublime.Region])→bool🔗
Fold the provided
Region(s).- Returns
Falseif the regions were already folded.
- unfold(x:sublime.Region|list[sublime.Region])→list[sublime.Region]🔗
Unfold all text in the provided
Region(s).- Returns
The unfolded regions.
- add_regions(key:str,regions:list[sublime.Region],scope='',icon='',flags=RegionFlags.NONE,annotations:list[str]=[],annotation_color='',on_navigate:Optional[Callable[[str],None]]=None,on_close:Optional[Callable[[],None]]=None)🔗
Adds visual indicators to regions of text in the view. Indicatorsinclude icons in the gutter, underlines under the text, borders aroundthe text and annotations. Annotations are drawn aligned to theright-hand edge of the view and may contain HTML markup.
- Parameters
keyAn identifier for the collection of regions. If a set of regionsalready exists for this key they will be overridden. See
get_regions.
regionsThe list of regions to add. These should not overlap.
scopeAn optional string used to source a color to draw the regions in.The scope is matched against the color scheme. Examples include:
"invalid"and"string". SeeScope Namingfor a list of common scopes. If the scope is empty, the regionswon’t be drawn.Also supports the following pseudo-scopes, to allow picking theclosest color from the user‘s color scheme:
"region.redish""region.orangish""region.yellowish""region.greenish""region.cyanish""region.bluish""region.purplish""region.pinkish"
iconAn optional string specifying an icon to draw in the gutter next toeach region. The icon will be tinted using the color associatedwith the
scope. Standard icon names are"dot","circle"`and``"bookmark". The icon may also be a full package-relativepath, such as"Packages/Theme-Default/dot.png".
flagsFlags specifying how the region should be drawn, among otherbehavior. See
RegionFlags.
annotations4050An optional collection of strings containing HTML documents todisplay along the right-hand edge of the view. There should be thesame number of annotations as regions. Seeminihtml Reference for supportedHTML.
annotation_color4050An optional string of the CSS color to use when drawing the leftborder of the annotation. Seeminihtml Reference: Colors for supported color formats.
on_navigate4050Called when a link in an annotation is clicked. Will be passed the
hrefof the link.
on_close4050Called when the annotations are closed.
- get_regions(key:str)→list[sublime.Region]🔗
- Returns
The regions associated with the given
key, if any.
- assign_syntax(syntax:str|sublime.Syntax)🔗
Changes the syntax used by the view.
syntaxmay be a packages pathto a syntax file, or ascope:specifier string.
4080syntaxmay be aSyntaxobject.
- set_syntax_file(syntax_file:str)🔗
- Deprecated
Use
assign_syntax()instead.
- symbols()→list[tuple[sublime.Region,str]]🔗
Extract all the symbols defined in the buffer.
- Deprecated
Use
symbol_regions()instead.
- get_symbols()→list[tuple[sublime.Region,str]]🔗
- Deprecated
Use
symbol_regions()instead.
- indexed_symbols()→list[tuple[sublime.Region,str]]🔗 3148
- Returns
A list of the
Regionand name of symbols.- Deprecated
Use
indexed_symbol_regions()instead.
- indexed_references()→list[tuple[sublime.Region,str]]🔗 3148
- Returns
A list of the
Regionand name of symbols.- Deprecated
Use
indexed_symbol_regions()instead.
- symbol_regions()→list[sublime.SymbolRegion]🔗 4085
- Returns
Info about symbols that are part of the view’s symbol list.
- indexed_symbol_regions(type=SymbolType.ANY)→list[sublime.SymbolRegion]🔗 4085
- Parameters
typeThe type of symbol to return.
- Returns
Info about symbols that are indexed.
- set_status(key:str,value:str)🔗
Add the status
keyto the view. Thevaluewill be displayed in thestatus bar, in a comma separated list of all status values, ordered bykey. Setting thevalueto""will clear the status.
- get_status(key:str)→str🔗
- Returns
The previous assigned value associated with the given
key, if any.
See
set_status().
- extract_completions(prefix:str,tp:Point=-1)→list[str]🔗
Get a list of word-completions based on the contents of the view.
- Parameters
prefixThe prefix to filter words by.
tpThe
Pointby which to weigh words. Closer words are preferred.
- command_history(index:int,modifying_only=False)→tuple[str,CommandArgs,int]🔗
Get info on previous run commands stored in the undo/redo stack.
- Parameters
indexThe offset into the undo/redo stack. Positive values for indexindicate to look in the redo stack for commands.
modifying_onlyWhether only commands that modify the text buffer are considered.
- Returns
The command name, command arguments and repeat count for the historyentry. If the undo/redo history doesn’t extend far enough, then
(None,None,0)will be returned.
- overwrite_status()→bool🔗
- Returns
The overwrite status, which the user normally toggles via theinsert key.
- set_overwrite_status(value:bool)🔗
Set the overwrite status. See
overwrite_status().
- show_popup_menu(items:list[str],on_done:Callable[[int],None],flags=0)🔗
Show a popup menu at the caret, for selecting an item in a list.
- Parameters
itemsThe list of entries to show in the list.
on_doneCalled once with the index of the selected item. If thepopup was cancelled
-1is passed instead.
flagsmust be
0, currently unused.
- show_popup(content:str,flags=PopupFlags.NONE,location:Point=-1,max_width:DIP=320,max_height:DIP=240,on_navigate:Optional[Callable[[str],None]]=None,on_hide:Optional[Callable[[],None]]=None)🔗
Show a popup displaying HTML content.
- Parameters
contentThe HTML content to display.
flagsFlags controlling popup behavior. See
PopupFlags.
locationThe
Pointat which to display the popup. If-1the popup is shown at the current postion of the caret.
max_widthThe maximum width of the popup.
max_heightThe maximum height of the popup.
on_navigateCalled when a link is clicked in the popup. Passed the value of the
hrefattribute of the clicked link.
on_hideCalled when the popup is hidden.
- hide_popup()🔗
Hide the current popup.
- export_to_html(regions:Optional[Union[Region,list[sublime.Region]]]=None,minihtml=False,enclosing_tags=False,font_size=True,font_family=True)🔗 4092
Generates an HTML string of the current view contents, including stylingfor syntax highlighting.
- Parameters
regionsThe region(s) to export. By default the whole view is exported.
minihtmlWhether the exported HTML should be compatible withminihtml Reference.
enclosing_tagsWhether a
<div>with base-styling is added. Note thatwithout this no background color is set.
font_sizeWhether to include the font size in the top level styling. Onlyapplies when
enclosing_tagsisTrue.
font_familyWhether to include the font family in the top level styling. Onlyapplies when
enclosing_tagsisTrue.
- clear_undo_stack()🔗 4114
Clear the undo/redo stack.
- classsublime.Settings🔗
Bases:
objectA
dictlike object that a settings hierarchy.Deletes the provided
keyfrom the setting. Note that a parentsetting may also provide this key, thus deleting may not entirelyremove a key.
Returns the value associated with the provided
key. If it’s notpresent the providedvalueis assigned to thekeyand thenreturned.
Update the settings from the provided argument(s).
Accepts:
A
dictor other implementation ofcollections.abc.Mapping.An object with a
keys()method.An object that iterates over key/value pairs
Keyword arguments, ie.
update(**kwargs).
- get(key:str,default:Value=None)→Value🔗
Same as
__getitem__.
- has(key:str)→bool🔗
Same as
__contains__.
- set(key:str,value:Value)🔗
Same as
__setitem__.
- erase(key:str)🔗
Same as
__delitem__.
- add_on_change(tag:str,callback:Callable[[],None])🔗
Register a callback to be run whenever a setting is changed.
- Parameters
tagA string associated with the callback. For use with
clear_on_change.
callbackA callable object to be run when a setting is changed.
- clear_on_change(tag:str)🔗
Remove all callbacks associated with the provided
tag. Seeadd_on_change.
- classsublime.Phantom🔗
Bases:
objectRepresents anminihtml Reference-based decoration to display non-editable contentinterspersed in a
View. Used withPhantomSetto actually add thephantoms to theView. Once aPhantomhas been constructed and added totheView, changes to the attributes will have no effect.- region:Region🔗
The
Regionassociated with the phantom. The phantom is displayed atthe start of theRegion.
- layout:PhantomLayout🔗
How the phantom should be placed relative to the
region.
- classsublime.PhantomSet🔗
Bases:
objectA collection that manages
Phantomobjects and the process of adding them,updating them and removing them from aView.- update(phantoms:Iterable[Phantom])🔗
Update the set of phantoms. If the
Phantom.regionof existing phantomshave changed they will be moved; new phantoms are added and ones notpresent are removed.
- classsublime.Html🔗
Bases:
objectUsed to indicate that a string is formatted as HTML. See
CommandInputHandler.preview().
- classsublime.CompletionList🔗 4050
Bases:
objectRepresents a list of completions, some of which may be in the process ofbeing asynchronously fetched.
- __init__(completions:Optional[list[CompletionValue]]=None,flags=AutoCompleteFlags.NONE)🔗
- Parameters
completionsIf
Noneis passed, the methodset_completions()must be calledbefore the completions will be displayed to the user.
flagsFlags controlling auto-complete behavior. See
AutoCompleteFlags.
- set_completions(completions:list[CompletionValue],flags=AutoCompleteFlags.NONE)🔗
Sets the list of completions, allowing the list to be displayed to theuser.
This function is thread-safe. If you’re generating a lot ofcompletions you’re encouraged to call this function from abackground thread to avoid blocking the UI.
4184
- classsublime.CompletionItem🔗 4050
Bases:
objectRepresents an available auto-completion item.
- completion:str🔗
Text to insert if the completion is specified. If empty the
triggerwill be inserted instead.
- completion_format:CompletionFormat🔗
The format of the completion. See
CompletionFormat.
An optionalminihtml Reference description of the completion, shown in thedetail pane at the bottom of the auto complete window.
- classmethodsnippet_completion(trigger:str,snippet:str,annotation='',kind=(KindId.SNIPPET,'s','Snippet'),details='')→CompletionItem🔗
Specialized constructor for snippet completions. The
completion_formatis alwaysCompletionFormat.SNIPPET.
- classmethodcommand_completion(trigger:str,command:str,args:CommandArgs=None,annotation='',kind=(KindId.AMBIGUOUS,'',''),details='')→CompletionItem🔗
Specialized constructor for command completions. The
completion_formatis alwaysCompletionFormat.COMMAND.
- sublime.list_syntaxes()→list[sublime.Syntax]🔗
list all known syntaxes.
Returns a list of Syntax.
- sublime.syntax_from_path(path:str)→Optional[Syntax]🔗
Get the syntax for a specific path.
Returns a Syntax or None.
- sublime.find_syntax_by_name(name:str)→list[sublime.Syntax]🔗
Find syntaxes with the specified name.
Name must match exactly. Return a list of Syntax.
- sublime.find_syntax_by_scope(scope:str)→list[sublime.Syntax]🔗
Find syntaxes with the specified scope.
Scope must match exactly. Return a list of Syntax.
- sublime.find_syntax_for_file(path,first_line='')→Optional[Syntax]🔗
Find the syntax to use for a path.
Uses the file extension, various application settings and optionally thefirst line of the file to pick the right syntax for the file.
Returns a Syntax.
- classsublime.QuickPanelItem🔗 4083
Bases:
objectRepresents a row in the quick panel, shown via
Window.show_quick_panel().
- classsublime.ListInputItem🔗 4095
Bases:
objectRepresents a row shown via
ListInputHandler.
- classsublime.SymbolRegion🔗 4085
Bases:
objectContains information about a
Regionof aViewthat contains a symbol.- type:SymbolType🔗
The type of the symbol. See
SymbolType.
- classsublime.SymbolLocation🔗 4085
Bases:
objectContains information about a file that contains a symbol.
- type:SymbolType🔗
The type of the symbol. See
SymbolType.
sublime_plugin Module🔗
- classsublime_plugin.CommandInputHandler🔗
Bases:
object- name()→str🔗
The command argument name this input handler is editing. Defaults to
foo_barfor an input handler namedFooBarInputHandler.
- placeholder()→str🔗
Placeholder text is shown in the text entry box before the user hasentered anything. Empty by default.
A list of 2-element tuples, defining the initially selected parts of theinitial text.
- preview(text:str)→str|sublime.Html🔗
Called whenever the user changes the text in the entry box. The returnedvalue (either plain text or HTML) will be shown in the preview area oftheCommand Palette.
- validate(text:str,event:Optional[Event]=None)→bool🔗
Called whenever the user presses enter in the text entry box.Return
Falseto disallow the current value.- Parameters
eventOnly passed when
want_eventreturnsTrue.
- cancel()🔗
Called when the input handler is canceled, either by the user pressingbackspace or escape.
- confirm(text:str,event:Optional[Event]=None)🔗
Called when the input is accepted, after the user has pressed enter andthe text has been validated.
- Parameters
eventOnly passed when
want_eventreturnsTrue.
- next_input(args)→Optional[CommandInputHandler]🔗
Return the next input after the user has completed this one. May return
Noneto indicate no more input is required, orsublime_plugin.BackInputHandler()to indicate that the input handlershould be popped off the stack instead.
Whether the
validate()andconfirm()methods should received asecondEventparameter. ReturnsFalseby default.
- classsublime_plugin.BackInputHandler🔗
Bases:
CommandInputHandler
- classsublime_plugin.TextInputHandler🔗
Bases:
CommandInputHandlerTextInputHandlers can be used to accept textual input in theCommandPalette. Return a subclass of this from
Command.input().For an input handler to be shown to the user, the command returning theinput handler MUST be made available in the Command Palette by adding thecommand to aDefault.sublime-commands file.
- classsublime_plugin.ListInputHandler🔗
Bases:
CommandInputHandlerListInputHandlers can be used to accept a choice input from a list items intheCommand Palette. Return a subclass of this from
Command.input().For an input handler to be shown to the user, the command returning theinput handler MUST be made available in the Command Palette by adding thecommand to aDefault.sublime-commands file.
- list_items()→list[str]|tuple[list[str],int]|list[tuple[str,Value]]|tuple[list[tuple[str,Value]],int]|list[sublime.ListInputItem]|tuple[list[sublime.ListInputItem],int]🔗
This method should return the items to show in the list.
The returned value may be a
listof item, or a 2-elementtuplecontaining a list of items, and anintindex of the item topre-select.The each item in the list may be one of:
A string used for both the row text and the value passed to thecommand
A 2-element tuple containing a string for the row text, and a
Valueto pass to the commandA
4095sublime.ListInputItemobject
- classsublime_plugin.Command🔗
Bases:
object- is_enabled()→bool🔗
Return whether the command is able to be run at this time. Commandarguments are passed as keyword arguments. The default implementationsimply always returns
True.
- is_visible()→bool🔗
Return whether the command should be shown in the menu at this time.Command arguments are passed as keyword arguments. The defaultimplementation always returns
True.
- is_checked()→bool🔗
Return whether a checkbox should be shown next to the menu item. Commandarguments are passed as keyword arguments. The.sublime-menufile must have the
"checkbox"key set totruefor this tobe used.
- description()→Optional[str]🔗
Return a description of the command with the given arguments. Commandarguments are passed as keyword arguments. Used in the menu, if nocaption is provided. Return
Noneto get the default description.
- want_event()→bool🔗
Return whether to receive an
Eventargument when the command istriggered by a mouse action. The event information allows commands todetermine which portion of the view was clicked on. The defaultimplementation returnsFalse.
- input(args:dict)→Optional[CommandInputHandler]🔗 3154
If this returns something other than
None, the user will beprompted for an input before the command is run in theCommandPalette.
Allows a custom name to be show to the left of the cursor in the inputbox, instead of the default one generated from the command name.
- run()🔗
Called when the command is run. Command arguments are passed as keywordarguments.
- classsublime_plugin.WindowCommand🔗
Bases:
CommandA
Commandinstantiated once per window. TheWindowobject may beretrieved viaself.window.
- classsublime_plugin.TextCommand🔗
Bases:
CommandA
Commandinstantiated once perView. TheViewobject may be retrievedviaself.view.
- classsublime_plugin.EventListener🔗
Bases:
objectCalled once with a list of views that were loaded before theEventListener was instantiated
- on_exit()🔗 4050
Called once after the API has shut down, immediately before theplugin_host process exits
- on_new_async(view:View)🔗
Called when a new buffer is created. Runs in a separate thread, and doesnot block the application.
Called when a buffer is associated with a file. buffer will be a Bufferobject.
Called when a buffer is associated with file. Runs in a separate thread,and does not block the application. buffer will be a Buffer object.
- on_clone_async(view:View)🔗
Called when a view is cloned from an existing one. Runs in a separatethread, and does not block the application.
- on_load_async(view:View)🔗
Called when the file is finished loading. Runs in a separate thread, anddoes not block the application.
Called when the View is reloaded. Runs in a separate thread, and doesnot block the application.
Called when the View is reverted. Runs in a separate thread, and doesnot block the application.
Called right before a view is moved between two windows or within awindow. Passed the View object.
Called right after a view is moved between two windows or within awindow. Passed the View object.
Called right after a view is moved between two windows or within awindow. Passed the View object. Runs in a separate thread, and does notblock the application.
- on_pre_close(view:View)🔗
Called when a view is about to be closed. The view will still be in thewindow at this point.
- on_close(view:View)🔗
Called when a view is closed (note, there may still be other views intothe same buffer).
- on_pre_save_async(view:View)🔗
Called just before a view is saved. Runs in a separate thread, and doesnot block the application.
- on_post_save_async(view:View)🔗
Called after a view has been saved. Runs in a separate thread, and doesnot block the application.
- on_modified_async(view:View)🔗
Called after changes have been made to a view. Runs in a separatethread, and does not block the application.
- on_selection_modified_async(view:View)🔗
Called after the selection has been modified in a view. Runs in aseparate thread, and does not block the application.
- on_activated_async(view:View)🔗
Called when a view gains input focus. Runs in a separate thread, anddoes not block the application.
- on_deactivated_async(view:View)🔗
Called when a view loses input focus. Runs in a separate thread, anddoes not block the application.
- on_hover(view:View,point:Point,hover_zone:HoverZone)🔗
Called when the user’s mouse hovers over the view for a short period.
- Parameters
viewThe view
pointThe closest point in the view to the mouse location. The mouse maynot actually be located adjacent based on the value of
hover_zone.
hover_zoneWhich element in Sublime Text the mouse has hovered over.
- on_query_context(view:View,key:str,operator:QueryOperator,operand:str,match_all:bool)→Optional[bool]🔗
Called when determining to trigger a key binding with the given contextkey. If the plugin knows how to respond to the context, it shouldreturn either True of False. If the context is unknown, it shouldreturn None.
- Parameters
keyThe context key to query. This generally refers to specific stateheld by a plugin.
operatorThe operator to check against the operand; whether to checkequality, inequality, etc.
operandThe value against which to check using the
operator.
match_allThis should be used if the context relates to the selections: doesevery selection have to match(
match_all==True), or is atleast one matching enough (match_all==False)?
- Returns
TrueorFalseif the plugin handles this context key and iteither does or doesn’t match. If the context is unknown returnNone.
- on_query_completions(view:View,prefix:str,locations:List[Point])→Union[None,List[CompletionValue],Tuple[List[CompletionValue],AutoCompleteFlags],CompletionList]🔗
Called whenever completions are to be presented to the user.
- Parameters
prefixThe text already typed by the user.
locationsThe list of points being completed. Since this methodis called for all completions no matter the syntax,
self.view.match_selector(point,relevant_scope)should be called to determine if the point isrelevant.
- Returns
A list of completions in one of the valid formats or
Noneif no completions are provided.
- on_text_command(view:View,command_name:str,args:CommandArgs)🔗
Called when a text command is issued. The listener may return a(command, arguments) tuple to rewrite the command, or
Noneto runthe command unmodified.
- on_window_command(window:Window,command_name:str,args:CommandArgs)🔗
Called when a window command is issued. The listener may return a(command, arguments) tuple to rewrite the command, or
Noneto runthe command unmodified.
- on_post_text_command(view:View,command_name:str,args:CommandArgs)🔗
Called after a text command has been executed.
- on_post_window_command(window:Window,command_name:str,args:CommandArgs)🔗
Called after a window command has been executed.
Called when a window is created, passed the Window object. Runs in aseparate thread, and does not block the application.
Called right before a window is closed, passed the Window object.
Called right after a new project is created, passed the Window object.
Called right after a new project is created, passed the Window object.Runs in a separate thread, and does not block the application.
Called right after a project is loaded, passed the Window object.
Called right after a project is loaded, passed the Window object. Runsin a separate thread, and does not block the application.
Called right before a project is saved, passed the Window object.
Called right after a project is saved, passed the Window object.
Called right after a project is saved, passed the Window object. Runs ina separate thread, and does not block the application.
- classsublime_plugin.ViewEventListener🔗
Bases:
objectA class that provides similar event handling to
EventListener, but boundto a specific view. Provides class method-based filtering to control whatviews objects are created for.- on_load()🔗 3155
Called when the file is finished loading.
- on_reload()🔗 4050
Called when the file is reloaded.
- on_revert()🔗 4050
Called when the file is reverted.
- on_pre_move()🔗 4050
Called right before a view is moved between two windows or within awindow.
- on_post_move()🔗 4050
Called right after a view is moved between two windows or within awindow.
- on_post_move_async()🔗 4050
Same as
on_post_movebut runs in a separate thread, not blocking theapplication.
- on_pre_close()🔗 3155
Called when a view is about to be closed. The view will still be in thewindow at this point.
- on_close()🔗 3155
Called when a view is closed (note, there may still be other views intothe same buffer).
- on_pre_save()🔗 3155
Called just before a view is saved.
- on_pre_save_async()🔗 3155
Same as
on_pre_savebut runs in a separate thread, not blocking theapplication.
- on_post_save()🔗 3155
Called after a view has been saved.
- on_post_save_async()🔗 3155
Same as
on_post_savebut runs in a separate thread, not blocking theapplication.
- on_modified()🔗
Called after changes have been made to the view.
- on_modified_async()🔗
Same as
on_modifiedbut runs in a separate thread, not blocking theapplication.
- on_selection_modified()🔗
Called after the selection has been modified in the view.
- on_selection_modified_async()🔗
Called after the selection has been modified in the view. Runs in aseparate thread, and does not block the application.
- on_activated()🔗
Called when a view gains input focus.
- on_activated_async()🔗
Called when the view gains input focus. Runs in a separate thread, anddoes not block the application.
- on_deactivated()🔗
Called when the view loses input focus.
- on_deactivated_async()🔗
Called when the view loses input focus. Runs in a separate thread, anddoes not block the application.
- on_hover(point:Point,hover_zone:HoverZone)🔗
Called when the user’s mouse hovers over the view for a short period.
- Parameters
pointThe closest point in the view to the mouse location. The mouse maynot actually be located adjacent based on the value of
hover_zone.
hover_zoneWhich element in Sublime Text the mouse has hovered over.
- on_query_context(key:str,operator:QueryOperator,operand:str,match_all:bool)→Optional[bool]🔗
Called when determining to trigger a key binding with the given contextkey. If the plugin knows how to respond to the context, it shouldreturn either True of False. If the context is unknown, it shouldreturn None.
- Parameters
keyThe context key to query. This generally refers to specificstate held by a plugin.
operatorThe operator to check against the operand; whether tocheck equality, inequality, etc.
operandThe value against which to check using the
operator.
match_allThis should be used if the context relates to theselections: does every selection have to match(
match_all==True), or is at least one matchingenough (match_all==False)?
- Returns
TrueorFalseif the plugin handles this context keyand it either does or doesn’t match. If the context is unknownreturnNone.
- on_query_completions(prefix:str,locations:List[Point])→Union[None,List[CompletionValue],Tuple[List[CompletionValue],AutoCompleteFlags],CompletionList]🔗
Called whenever completions are to be presented to the user.
- Parameters
prefixThe text already typed by the user.
locationsThe list of points being completed. Since this methodis called for all completions no matter the syntax,
self.view.match_selector(point,relevant_scope)should be called to determine if the point isrelevant.
- Returns
A list of completions in one of the valid formats or
Noneif no completions are provided.
- on_text_command(command_name:str,args:CommandArgs)→Tuple[str,CommandArgs]🔗 3155
Called when a text command is issued. The listener may return a`` (command, arguments)`` tuple to rewrite the command, or
Nonetorun the command unmodified.
- on_post_text_command(command_name:str,args:CommandArgs)🔗
Called after a text command has been executed.
- classsublime_plugin.TextChangeListener🔗 4081
Bases:
objectA class that provides event handling about text changes made to a specificBuffer. Is separate from
ViewEventListenersince multiple views canshare a single buffer.- on_text_changed(changes:List[TextChange])🔗
Called once after changes has been made to a buffer, with detailedinformation about what has changed.
- on_text_changed_async(changes:List[TextChange]):
Same as
on_text_changedbut runs in a separate thread, not blockingthe application.
- on_revert()🔗
Called when the buffer is reverted.
A revert does not trigger text changes. If the contents of the bufferare required here use
View.substr.
- on_reload()🔗
Called when the buffer is reloaded.
A reload does not trigger text changes. If the contents of the bufferare required here use
View.substr.
- classmethodis_applicable(buffer:Buffer)🔗
- Returns
Whether this listener should apply to the provided buffer.
- detach()🔗
Remove this listener from the buffer.
Async callbacks may still be called after this, as they are queuedseparately.
- Raises
ValueError if the listener is not attached.
- Raises
- attach(buffer:Buffer)🔗
Attach this listener to a buffer.
- Raises
ValueError if the listener is already attached.
- Raises