API Reference
Ver:
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 function plugin_loaded(), this will be
called when the API is ready to use. Plugins may also define
plugin_unloaded(), to get notified just before the plugin is unloaded.
Threadingπ
All API functions are thread-safe, however keep in mind that from the perspective of code running in an alternate thread, application state will be changing while the code is running.
Units and Coordinatesπ
API functions that accept or return coordinates or dimensions do so using device-independent pixel (dip) values. While in some cases these will be equivalent to device pixels, this is often not the case. Per the CSS specification, minihtml treats the px unit as device-independent.
Typesπ
- sublime.Value = bool | str | int | float | list[Value] | dict[str, Value] | Noneπ
A JSON-equivalent value.
- 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β presented to the left of the item.
- sublime.Event = dictπ
Contains information about a userβs interaction with a menu, command palette selection, quick panel selection or HTML document. The follow methods are used to signal that an event
dictis desired:Commands may opt-in to receive an arg named
eventby implementing the methodwant_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()and returningTrue.
The dict may contain zero or more of the following keys, based on the user interaction:
- "x": float
The X mouse position when a user clicks on a menu, or in a minihtml document.
- "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"- indicating Ctrl (Windows/Linux) or Cmd (Mac) was pressed"ctrl"- indicating Ctrl was pressed"alt"- indicating Alt was pressed"altgr"- indicating AltGr was pressed (Linux only)"shift"- indicating Shift was pressed"super"- indicating Win (Windows/Linux) or Cmd (Mac) was pressed
Present when the user selects an item from a quick panel, selects an item from a
ListInputHandler, or clicks a link in a minihtml document.
- sublime.CompletionValue = str | tuple[str, str] | CompletionItemπ
Represents an available auto-completion item. completion values may be of several formats. The term trigger refers to the text matched against the user input, replacement is what is inserted into the view if the item is selected. An annotation is a unicode string hint displayed to the right-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 an annotation:
[ ["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 this enumeration 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 this enumeration (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 until modified.
- FORCE_GROUP = 8π
Donβt select the file if it is open in a different group. Instead make a new clone 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. This is 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 sheet will 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 desired group.
Bases:
IntFlagFlags for use when searching through a
View.See
View.findandView.find_all.For backwards compatibility these values are also available outside this enumeration (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 a quick panel.
For backwards compatibility these values are also available outside this enumeration (without a prefix).
- NONE = 0π
- MONOSPACE_FONT = 1π
Use a monospace font.
- KEEP_OPEN_ON_FOCUS_LOST = 2π
Keep the quick panel open if the window loses input focus.
Bases:
IntFlagFlags for use with popups.
See
View.show_popup.For backwards compatibility these values are also available outside this enumeration (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 this enumeration (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 this enumeration 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 this enumeration 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 this enumeration (without a prefix).
- NONE = 0π
- INHIBIT_WORD_COMPLETIONS = 8π
Prevent Sublime Text from showing completions based on the contents of the view.
- 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 a yes / no / cancel dialog. See
yes_no_cancel_dialog.For backwards compatibility these values are also available outside this enumeration 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 this enumeration with a
LAYOUT_prefix.- BELOW = 1π
The phantom is positioned below the line, left-aligned with the beginning of its
Region.
- BLOCK = 2π
The phantom is positioned below the line, left-aligned with the beginning of the line.
Bases:
IntEnumFor backwards compatibility these values are also available outside this enumeration 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 this enumeration 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 this enumeration 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 this enumeration 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.channel() Literal['dev', 'stable']π
- Returns
The release channel of this build of Sublime Text.
- 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 a ok / cancel question dialog.
- Parameters
-
msg The message to show in the dialog.
-
ok_title Text to display on the ok button.
-
title
4099 Title for the dialog. Windows only.
-
- Returns
Whether the user pressed the ok button.
- sublime.yes_no_cancel_dialog(msg: str, yes_title='', no_title='', title='') DialogResultπ
Show a yes / no / cancel question dialog.
- Parameters
-
msg The message to show in the dialog.
-
yes_title Text to display on the yes button.
-
no_title Text to display on the no button.
-
title
4099 Title 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
-
callback Called with selected path(s) or
Noneonce the dialog is closed.
-
file_types A list of allowed file types, consisting of a description and a list of allowed extensions.
-
directory The directory the dialog should start in. Will use the virtual working directory if not provided.
-
multi_select Whether to allow selecting multiple files. When
Truethe callback will be called with a list.
-
allow_folders Whether to also allow selecting folders. Only works on macOS. 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
-
callback Called with selected path or
Noneonce the dialog is closed.
-
file_types A list of allowed file types, consisting of a description and a list of allowed extensions.
-
directory The directory the dialog should start in. Will use the virtual working directory if not provided.
-
name The default name of the file in the save dialog.
-
extension The 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
-
callback Called with selected path(s) or
Noneonce the dialog is closed.
-
directory The directory the dialog should start in. Will use the virtual working directory if not provided.
-
multi_select Whether to allow selecting multiple files. When
Truethe callback will be called with a list.
-
- sublime.choose_font_dialog(callback: Callable[[Value], None], default: dict[str, Value] = None)π 4157
Show a dialog for selecting a font.
- Parameters
-
callback Called with the font options, matching the format used in settings (eg.
{ "font_face": "monospace" }). May be called more than once, or will be called withNoneif the dialog is cancelled.
-
default The default values to select/return. Same format as the argument 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. This is 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
-
flag Whether 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 to find the names of certain keys on the keyboard.
- Parameters
-
flag Whether to log. Passing None toggles logging. 4099
-
Control whether rendering timings like frames per second get logged.
- Parameters
-
flag Whether 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
-
flag Whether to log. Passing None toggles logging. 4099
-
- sublime.log_indexing(flag: Optional[bool] = None)π
Control whether indexing logs are printed to the console.
- Parameters
-
flag Whether 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
-
flag Whether to log. Passing None toggles logging. 4099
-
Control whether control tree logging is enabled. When enabled clicking with ctrl+alt will log the control tree under the mouse to the console.
- Parameters
-
flag Whether 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. Different selectors may be compared against the same scope: a higher score means the selector 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
-
pretty Whether the result should include newlines and be indented.
-
update_text
4156 Incrementally update the value encoded in this text. Best effort is made to 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 commas are 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 the dictionaryvariables. value may also be a list or dict, in which case the structure 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 the base_name, and the results will be collated into the settings object.
Subsequent calls to load_settings() with the base_name will return the same object, 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 order they 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 currently recorded macro. Each
dictwill contain the keys"command"and"args".
- Returns
A list of most recently opened workspaces. Sublime-project files with the same name are listed in place of sublime-workspace files.
- Returns
A list of recent folders added to sublime projects
- class sublime.Windowπ
Bases:
object- is_valid() boolπ
Check whether this window is still valid. Will return
Falsefor a closed window, for example.
Construct a sheet with HTML contents rendered using minihtml Reference.
- Parameters
-
name The name of the sheet to show in the tab.
-
contents The HTML contents of the sheet.
-
flags Only
NewFileFlags.TRANSIENTandNewFileFlags.ADD_TO_SELECTIONare allowed.
-
group The 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. This method is able to run any sort of command, dispatching the command via input focus.
- new_file(flags=NewFileFlags.NONE, syntax='') Viewπ
Create a new empty file.
- Parameters
-
flags Either
0,NewFileFlags.TRANSIENTorNewFileFlags.ADD_TO_SELECTION.
-
syntax The 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 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 returnsFalse.- Parameters
-
fname The path to the file to open.
-
flags
-
group The 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
-
fname The path to the file to open.
-
group The 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 list as File > 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 the given
Sheet.
- get_view_index(view: View) tuple[int, int]π
- Returns
The a tuple of the group and index within the group of the given
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 index provided. If an index is not provided defaults to last index of the destination group.
- Parameters
-
sheets The sheets to move.
-
group The index of the group to move the sheets to.
-
insertion_idx The point inside the group at which to insert the sheets.
-
select Whether 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_transient
4081 Whether 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.
- active_view_in_group(group: int) Optional[View]π
- Returns
The currently focused
Viewin 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.
- transient_view_in_group(group: int) Optional[View]π
- Returns
The transient view in the specified group.
- promote_sheet(sheet: Sheet)π
Promote the βSheetβ parameter if semi-transient or transient.
- Since
4135
- create_output_panel(name: str, unlisted=False) Viewπ
Find the
Viewassociated with the named output panel, creating it if required. The output panel can be shown by running theshow_panelwindow command, with thepanelargument set to the name with an"output."prefix.- Parameters
-
name The name of the output panel.
-
unlisted Control 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, orNoneif the 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 the named output panel, creating it if required. The output panel will additionally be configured with an input box. The panel can be shown by running theshow_panelwindow command, with thepanelargument set to the name with an"output."prefix.
- active_panel() Optional[str]π
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() list[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.
- 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
-
caption The label to put next to the input widget.
-
initial_text The initial text inside the input widget.
-
on_done Called with the final input when the user presses
enter.
-
on_change Called with the input when itβs changed.
-
on_cancel Called 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 called once, with the index of the selected item. If the quick panel was cancelled, on_select will be called with an argument of -1.
- Parameters
-
items May be either a list of strings, or a list of lists of strings where the first item is the trigger and all subsequent strings are details shown below.
May be a
4083QuickPanelItem.
-
on_select Called with the selected itemβs index when the quick panel is completed. If the panel was cancelled this is called with
-1.A second
4096Eventargument may be passed when theQuickPanelFlags.WANT_EVENTflag is present.
-
flags QuickPanelFlagscontrolling behavior.
-
selected_index The initially selected item.
-1for no selection.
-
on_highlight Called every time the highlighted item in the quick panel is changed.
-
placeholder
4081 Text displayed in the filter input field before any query is typed.
-
- Returns
Whether the menu is visible.
Hides or shows the menu.
- project_file_name() Optional[str]π
- Returns
The name of the currently opened project file, if any.
- Returns
The name of the currently opened workspace file, if any.
- project_data() Valueπ
- 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: Value)π
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.
- template_settings() Settingsπ
- Returns
Per-window settings that are persisted in the session, and duplicated 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().
- class sublime.Editπ
Bases:
objectA grouping of 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 differentView, will cause the functions that require them to fail.
- class sublime.Regionπ
Bases:
objectA singular selection region. This region has a order -
bmay be before or ata.Also commonly used to represent an area of the text buffer, where ordering and
xposare generally ignored.- b: Pointπ
The second end of the region. In a selection this is the location of the caret. 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
-1if undefined.
- contains(x: Point) boolπ
Equivalent to
__contains__.
- class sublime.HistoricPositionπ 4050
Bases:
objectProvides a snapshot of the row and column info for a
Point, before changes were made to aView. This is primarily useful for replaying changes to a document.- row: intπ
The row the
.pywas in when theHistoricPositionwas recorded.
- col: intπ
The column the
.pywas in when theHistoricPositionwas recorded, in Unicode characters.
- class sublime.TextChangeπ 4050
Bases:
objectRepresents a change that occurred to the text of a
View. This is primarily useful 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 the new contents of the region specified by
.aand.b.
- class sublime.Selectionπ
Bases:
objectMaintains a set of sorted non-overlapping Regions. A selection may be empty.
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 the existing regions if intersecting.
- class sublime.Sheetπ
Bases:
objectRepresents a content container, i.e. a tab, within a window. Sheets may contain a View, or an image preview.
- window() Optional[Window]π
- Returns
The
Windowcontaining this sheet. May beNoneif the sheet 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 be transient. In this case
is_transientwill still returnFalse.
- close(on_close=<function Sheet.<lambda>>)π 4088
Closes the sheet.
- Parameters
-
on_close
-
- class sublime.ContextStackFrameπ 4127
Bases:
objectRepresents a single stack frame in the syntax highlighting. See
View.context_backtrace.
- class sublime.Viewπ
Bases:
objectRepresents a view into a text
Buffer.Note that multiple views may refer to the same
Buffer, but they have their own 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 that comprise part of the UI a string is returned from the following list:"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 controls are not accessible via the API.
- is_valid() boolπ
Check whether this view is still valid. Will return
Falsefor a closed 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 the incremental diff for the view.
- set_reference_document(reference: str)π
Uses the string reference to calculate the initial diff for the incremental 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 buffer is closed, it will be closed without prompting to save. Scratch buffers never report as being dirty.
- set_encoding(encoding_name: str)π
Applies a new encoding to the file. This will be used when the file is saved.
- set_line_endings(line_ending_name: str)π
Sets the line endings that will be applied when next saving.
- insert(edit: Edit, pt: Point, text: str) intπ
Insert the given string into the buffer.
- Parameters
-
edit An
Editobject provided by aTextCommand.
-
point The text point in the view where to insert.
-
text The text to insert.
-
- Returns
The actual number of characters inserted. This may differ from 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. The change count can be used to determine if the buffer has changed since the 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()to obtain a region equivalent to a region of the view in the past. This is primarily useful for plugins providing text modification that must operate in an asynchronous fashion and must be able to handle the view contents 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 equivalent region in the current state of the View. The
change_idmust have been obtained fromchange_id()at the point in time the region is from.
- 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
-
pattern The regex or literal pattern to search by.
-
flags Controls various behaviors of find. See
FindFlags.
-
fmt When not
Noneall matches in theextractionslist will be formatted with the provided format string.
-
extractions An optionally provided list to place the contents of the find results into.
-
within
4181 When not
Nonesearching is limited to within the provided region(s).
-
- Returns
All (non-overlapping) regions matching the pattern.
- settings() Settingsπ
- Returns
The viewβs
Settingsobject. Any changes to it will be private 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
-
region The 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 character at 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
-
pt The point from which to expand.
-
selector The scope selector to match.
-
- Returns
The matched
Region, if any.
- scope_name(pt: Point) strπ
- Returns
The syntax scope name assigned to the character at the given point.
- 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 normalized to 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 information including 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 character hex 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 exactly one 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
-
pt The point to start searching from.
-
forward Whether to search forward or backwards.
-
classes The classification to search for.
-
separators The word separators to use when classifying.
-
sub_word_separators
4130 The 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 each side lands on a location that matches the providedPointClassification. Seefind_by_class.- Parameters
-
classes The classification to search by.
-
separators The word separators to use when classifying.
-
sub_word_separators
4130 The sub-word separators to use when classifying.
-
- rowcol(tp: Point) tuple[int, int]π
Calculates the 0-based line and column numbers of the point. Column numbers are returned as number of Unicode characters.
Calculates the 0-based line and column numbers of the point. Column numbers are returned as UTF-8 code units.
Calculates the 0-based line and column numbers of the point. Column numbers 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 to advance past the beginning of the row.- Parameters
-
clamp_column
4075 Whether
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 to advance past the beginning of the row.- Parameters
-
clamp_column
4075 whether
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 to advance past the beginning of the row.- Parameters
-
clamp_column
4075 whether
colshould be restricted to valid values for the givenrow.
-
Calculates the utf8 code unit offset at the given text point.
- Parameters
-
tp The text point up to which code units should be counted. If not provided the total is returned.
-
Calculates the utf16 code unit offset at the given text point.
- Parameters
-
tp The text point up to which code units should be counted. If not provided 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_surrounds Whether to show the surrounding context around the location.
-
keep_to_left
4075 Whether the view should be kept to the left, if horizontal scrolling is possible.
-
animate
4075 Whether the scrolling should be animated.
-
- show_at_center(location: Region | Point, animate=True)π
Scroll the view to center on the location.
- set_viewport_position(xy: Vector, animate=True)π
Scrolls the viewport to the given layout position.
- 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. Indicators include icons in the gutter, underlines under the text, borders around the text and annotations. Annotations are drawn aligned to the right-hand edge of the view and may contain HTML markup.
- Parameters
-
key An identifier for the collection of regions. If a set of regions already exists for this key they will be overridden. See
get_regions.
-
regions The list of regions to add. These should not overlap.
-
scope An 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". See Scope Naming for a list of common scopes. If the scope is empty, the regions wonβt be drawn.Also supports the following pseudo-scopes, to allow picking the closest color from the userβs color scheme:
"region.redish""region.orangish""region.yellowish""region.greenish""region.cyanish""region.bluish""region.purplish""region.pinkish"
-
icon An optional string specifying an icon to draw in the gutter next to each region. The icon will be tinted using the color associated with the
scope. Standard icon names are"dot","circle"` and ``"bookmark". The icon may also be a full package-relative path, such as"Packages/Theme - Default/dot.png".
-
flags Flags specifying how the region should be drawn, among other behavior. See
RegionFlags.
-
annotations
4050 An optional collection of strings containing HTML documents to display along the right-hand edge of the view. There should be the same number of annotations as regions. See minihtml Reference for supported HTML.
-
annotation_color
4050 An optional string of the CSS color to use when drawing the left border of the annotation. See minihtml Reference: Colors for supported color formats.
-
on_navigate
4050 Called when a link in an annotation is clicked. Will be passed the
hrefof the link.
-
on_close
4050 Called 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 path to 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
-
type The 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 the status bar, in a comma separated list of all status values, ordered by key. 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
-
prefix The prefix to filter words by.
-
tp The
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
-
index The offset into the undo/redo stack. Positive values for index indicate to look in the redo stack for commands.
-
modifying_only Whether only commands that modify the text buffer are considered.
-
- Returns
The command name, command arguments and repeat count for the history entry. 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 the insert key.
- set_overwrite_status(value: bool)π
Set the overwrite status. See
overwrite_status().
Show a popup menu at the caret, for selecting an item in a list.
- Parameters
-
items The list of entries to show in the list.
-
on_done Called once with the index of the selected item. If the popup was cancelled
-1is passed instead.
-
flags must 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
-
content The HTML content to display.
-
flags Flags controlling popup behavior. See
PopupFlags.
-
location The
Pointat which to display the popup. If-1the popup is shown at the current postion of the caret.
-
max_width The maximum width of the popup.
-
max_height The maximum height of the popup.
-
on_navigate Called when a link is clicked in the popup. Passed the value of the
hrefattribute of the clicked link.
-
on_hide Called 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 styling for syntax highlighting.
- Parameters
-
regions The region(s) to export. By default the whole view is exported.
-
minihtml Whether the exported HTML should be compatible with minihtml Reference.
-
enclosing_tags Whether a
<div>with base-styling is added. Note that without this no background color is set.
-
font_size Whether to include the font size in the top level styling. Only applies when
enclosing_tagsisTrue.
-
font_family Whether to include the font family in the top level styling. Only applies when
enclosing_tagsisTrue.
-
- clear_undo_stack()π 4114
Clear the undo/redo stack.
- class sublime.Bufferπ 4081
Bases:
objectRepresents a text buffer. Multiple
Viewobjects may share the same buffer.The full name file the file associated with the buffer, or
Noneif it doesnβt exist on disk.
- views() list[sublime.View]π
Returns a list of all views that are associated with this buffer.
- class sublime.Settingsπ
Bases:
objectA
dictlike object that a settings hierarchy.Deletes the provided
keyfrom the setting. Note that a parent setting may also provide this key, thus deleting may not entirely remove a key.
Returns the value associated with the provided
key. If itβs not present the providedvalueis assigned to thekeyand then returned.
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
-
tag A string associated with the callback. For use with
clear_on_change.
-
callback A 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.
- class sublime.Phantomπ
Bases:
objectRepresents an minihtml Reference-based decoration to display non-editable content interspersed in a
View. Used withPhantomSetto actually add the phantoms to theView. Once aPhantomhas been constructed and added to theView, changes to the attributes will have no effect.- region: Regionπ
The
Regionassociated with the phantom. The phantom is displayed at the start of theRegion.
- layout: PhantomLayoutπ
How the phantom should be placed relative to the
region.
Called when a link in the HTML is clicked. The value of the
hrefattribute is passed.
- to_tuple() tuple[tuple[Point, Point], str, PhantomLayout, Optional[Callable[[str], None]]]π
Returns a tuple of this phantom containing the region, content, layout and callback.
Use this to uniquely identify a phantom in a set or similar. Phantoms canβt be used for that directly as they are mutable.
- class sublime.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 phantoms have changed they will be moved; new phantoms are added and ones not present are removed.
- class sublime.Htmlπ
Bases:
objectUsed to indicate that a string is formatted as HTML. See
CommandInputHandler.preview().
- class sublime.CompletionListπ 4050
Bases:
objectRepresents a list of completions, some of which may be in the process of being asynchronously fetched.
- __init__(completions: Optional[list[CompletionValue]] = None, flags=AutoCompleteFlags.NONE)π
- Parameters
-
completions If
Noneis passed, the methodset_completions()must be called before the completions will be displayed to the user.
-
flags Flags 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 the user.
This function is thread-safe. If youβre generating a lot of completions youβre encouraged to call this function from a background thread to avoid blocking the UI.
4184
- class sublime.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 optional minihtml Reference description of the completion, shown in the detail pane at the bottom of the auto complete window.
- classmethod snippet_completion(trigger: str, snippet: str, annotation='', kind=(KindId.SNIPPET, 's', 'Snippet'), details='') CompletionItemπ
Specialized constructor for snippet completions. The
completion_formatis alwaysCompletionFormat.SNIPPET.
- classmethod command_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 the first line of the file to pick the right syntax for the file.
Returns a Syntax.
- class sublime.QuickPanelItemπ 4083
Bases:
objectRepresents a row in the quick panel, shown via
Window.show_quick_panel().
- class sublime.ListInputItemπ 4095
Bases:
objectRepresents a row shown via
ListInputHandler.
- class sublime.SymbolRegionπ 4085
Bases:
objectContains information about a
Regionof aViewthat contains a symbol.- type: SymbolTypeπ
The type of the symbol. See
SymbolType.
- class sublime.SymbolLocationπ 4085
Bases:
objectContains information about a file that contains a symbol.
- type: SymbolTypeπ
The type of the symbol. See
SymbolType.
sublime_plugin Moduleπ
- class sublime_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 has entered anything. Empty by default.
A list of 2-element tuples, defining the initially selected parts of the initial text.
- preview(text: str) str | sublime.Htmlπ
Called whenever the user changes the text in the entry box. The returned value (either plain text or HTML) will be shown in the preview area of the Command 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
-
event Only passed when
want_eventreturnsTrue.
-
- cancel()π
Called when the input handler is canceled, either by the user pressing backspace or escape.
- confirm(text: str, event: Optional[Event] = None)π
Called when the input is accepted, after the user has pressed enter and the text has been validated.
- Parameters
-
event Only 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 handler should be popped off the stack instead.
Whether the
validate()andconfirm()methods should received a secondEventparameter. ReturnsFalseby default.
- class sublime_plugin.BackInputHandlerπ
Bases:
CommandInputHandler
- class sublime_plugin.TextInputHandlerπ
Bases:
CommandInputHandlerTextInputHandlers can be used to accept textual input in the Command Palette. Return a subclass of this from
Command.input().For an input handler to be shown to the user, the command returning the input handler MUST be made available in the Command Palette by adding the command to a Default.sublime-commands file.
- class sublime_plugin.ListInputHandlerπ
Bases:
CommandInputHandlerListInputHandlers can be used to accept a choice input from a list items in the Command Palette. Return a subclass of this from
Command.input().For an input handler to be shown to the user, the command returning the input handler MUST be made available in the Command Palette by adding the command to a Default.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 to pre-select.The each item in the list may be one of:
A string used for both the row text and the value passed to the command
A 2-element tuple containing a string for the row text, and a
Valueto pass to the commandA
4095sublime.ListInputItemobject
- class sublime_plugin.Commandπ
Bases:
object- name() strπ
Return the name of the command. By default this is derived from the name of the class.
- is_enabled() boolπ
Return whether the command is able to be run at this time. Command arguments are passed as keyword arguments. The default implementation simply 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 default implementation always returns
True.
- is_checked() boolπ
Return whether a checkbox should be shown next to the menu item. Command arguments are passed as keyword arguments. The .sublime-menu file must have the
"checkbox"key set totruefor this to be used.
- description() Optional[str]π
Return a description of the command with the given arguments. Command arguments are passed as keyword arguments. Used in the menu, if no caption is provided. Return
Noneto get the default description.
- want_event() boolπ
Return whether to receive an
Eventargument 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 returnsFalse.
- input(args: dict) Optional[CommandInputHandler]π 3154
If this returns something other than
None, the user will be prompted for an input before the command is run in the Command Palette.
Allows a custom name to be show to the left of the cursor in the input box, instead of the default one generated from the command name.
- run()π
Called when the command is run. Command arguments are passed as keyword arguments.
- class sublime_plugin.WindowCommandπ
Bases:
CommandA
Commandinstantiated once per window. TheWindowobject may be retrieved viaself.window.
- class sublime_plugin.TextCommandπ
Bases:
CommandA
Commandinstantiated once perView. TheViewobject may be retrieved viaself.view.
- class sublime_plugin.EventListenerπ
Bases:
objectCalled once with a list of views that were loaded before the EventListener was instantiated
- on_exit()π 4050
Called once after the API has shut down, immediately before the plugin_host process exits
- on_new_async(view: View)π
Called when a new buffer is created. Runs in a separate thread, and does not block the application.
Called when a buffer is associated with a file. buffer will be a Buffer object.
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 separate thread, and does not block the application.
- on_load_async(view: View)π
Called when the file is finished loading. Runs in a separate thread, and does not block the application.
Called when the View is reloaded. Runs in a separate thread, and does not block the application.
Called when the View is reverted. Runs in a separate thread, and does not block the application.
Called right before a view is moved between two windows or within a window. Passed the View object.
Called right after a view is moved between two windows or within a window. Passed the View object.
Called right after a view is moved between two windows or within a window. Passed the View object. Runs in a separate thread, and does not block the application.
- on_pre_close(view: View)π
Called when a view is about to be closed. The view will still be in the window at this point.
- on_close(view: View)π
Called when a view is closed (note, there may still be other views into the same buffer).
- on_pre_save_async(view: View)π
Called just before a view is saved. Runs in a separate thread, and does not block the application.
- on_post_save_async(view: View)π
Called after a view has been saved. Runs in a separate thread, and does not block the application.
- on_modified_async(view: View)π
Called after changes have been made to a view. Runs in a separate thread, and does not block the application.
- on_selection_modified_async(view: View)π
Called after the selection has been modified in a view. Runs in a separate thread, and does not block the application.
- on_activated_async(view: View)π
Called when a view gains input focus. Runs in a separate thread, and does not block the application.
- on_deactivated_async(view: View)π
Called when a view loses input focus. Runs in a separate thread, and does 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
-
view The view
-
point 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.
-
hover_zone Which 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 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.
- Parameters
-
key The context key to query. This generally refers to specific state held by a plugin.
-
operator The operator to check against the operand; whether to check equality, inequality, etc.
-
operand The value against which to check using the
operator.
-
match_all This 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)?
-
- Returns
TrueorFalseif the plugin handles this context key and it either 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
-
prefix The text already typed by the user.
-
locations The list of points being completed. 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.
-
- 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 run the 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 run the 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 a separate 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. Runs in 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 in a separate thread, and does not block the application.
- class sublime_plugin.ViewEventListenerπ
Bases:
objectA 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.- 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 a window.
- on_post_move()π 4050
Called right after a view is moved between two windows or within a window.
- on_post_move_async()π 4050
Same as
on_post_movebut runs in a separate thread, not blocking the application.
- on_pre_close()π 3155
Called when a view is about to be closed. The view will still be in the window at this point.
- on_close()π 3155
Called when a view is closed (note, there may still be other views into the 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 the application.
- 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 the application.
- 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 the application.
- 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 a separate 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, and does 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, and does 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
-
point 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.
-
hover_zone Which 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 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.
- Parameters
-
key The context key to query. This generally refers to specific state held by a plugin.
-
operator The operator to check against the operand; whether to check equality, inequality, etc.
-
operand The value against which to check using the
operator.
-
match_all This 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)?
-
- Returns
TrueorFalseif the plugin handles this context key and it either does or doesnβt match. If the context is unknown returnNone.
- 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
-
prefix The text already typed by the user.
-
locations The list of points being completed. 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.
-
- 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
Noneto run the command unmodified.
- on_post_text_command(command_name: str, args: CommandArgs)π
Called after a text command has been executed.
- class sublime_plugin.TextChangeListenerπ 4081
Bases:
objectA class that provides event handling about text changes made to a specific Buffer. Is separate from
ViewEventListenersince multiple views can share a single buffer.- on_text_changed(changes: List[TextChange])π
Called once after changes has been made to a buffer, with detailed information about what has changed.
- on_text_changed_async(changes: List[TextChange]):
Same as
on_text_changedbut runs in a separate thread, not blocking the application.
- on_revert()π
Called when the buffer is reverted.
A revert does not trigger text changes. If the contents of the buffer are required here use
View.substr.
- on_revert_async()π
Same as
on_revertbut runs in a separate thread, not blocking the application.
- on_reload()π
Called when the buffer is reloaded.
A reload does not trigger text changes. If the contents of the buffer are required here use
View.substr.
- on_reload_async()π
Same as
on_reloadbut runs in a separate thread, not blocking the application.
- classmethod is_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 queued separately.
- 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