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.py Uses phantoms to display errors inline

  • Packages/Default/font.py Shows how to work with settings

  • Packages/Default/goto_line.py Prompts the user for input, then updates the selection

  • Packages/Default/mark.py Uses add_regions() to add an icon to the gutter

  • Packages/Default/show_scope_name.py Uses a popup to show the scope names at the caret

  • Packages/Default/arithmetic.py Accepts 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:

<4171

If 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.DIP = floatπŸ”—

Represents a device-independent pixel position.

sublime.Vector = tuple[DIP, DIP]πŸ”—

Represents a X and Y coordinate.

sublime.Point = intπŸ”—

Represents the offset from the beginning of the editor buffer.

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 None or a dict of str keys.

sublime.Kind = tuple[KindId, str, str]πŸ”—

Metadata about the kind of a symbol, CompletionItem, QuickPanelItem or ListInputItem. 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 dict is desired:

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 tuple or list:

    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 }"]
    ]
    
  • CompletionItem object

    An 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πŸ”—

class sublime.HoverZoneπŸ”—
4132 3.8

Bases: IntEnum

A zone in an open text sheet where the mouse may hover.

See EventListener.on_hover and ViewEventListener.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.

class sublime.NewFileFlagsπŸ”—
4132 3.8

Bases: IntFlag

Flags for creating/opening files in various ways.

See Window.new_html_sheet, Window.new_file and Window.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 :row or :row:col suffix.

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_SELECTION or REPLACE_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.

class sublime.FindFlagsπŸ”—
4132 3.8

Bases: IntFlag

Flags for use when searching through a View.

See View.find and View.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.

class sublime.QuickPanelFlagsπŸ”—
4132 3.8

Bases: IntFlag

Flags for use with a quick panel.

See Window.show_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.

WANT_EVENT = 4πŸ”—
4096

Pass a second parameter to the on_done callback, a Event.

class sublime.PopupFlagsπŸ”—
4132 3.8

Bases: IntFlag

Flags 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.

class sublime.RegionFlagsπŸ”—
4132 3.8

Bases: IntFlag

Flags 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πŸ”—
class sublime.QueryOperatorπŸ”—
4132 3.8

Bases: IntEnum

Enumeration of operators able to be used when querying contexts.

See EventListener.on_query_context and ViewEventListener.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πŸ”—
class sublime.PointClassificationπŸ”—
4132 3.8

Bases: IntFlag

Flags that identify characteristics about a Point in a text sheet. See View.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.

class sublime.AutoCompleteFlagsπŸ”—
4132 3.8

Bases: IntFlag

Flags 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.

class sublime.DialogResultπŸ”—
4132 3.8

Bases: IntEnum

The 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πŸ”—
class sublime.PhantomLayoutπŸ”—
4132 3.8

Bases: IntEnum

How a Phantom should be positioned. See PhantomSet.

For backwards compatibility these values are also available outside this enumeration with a LAYOUT_ prefix.

INLINE = 0πŸ”—

The phantom is positioned inline with the text at the beginning of its Region.

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.

class sublime.KindIdπŸ”—
4132 3.8

Bases: IntEnum

For 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
class sublime.SymbolSourceπŸ”—
4132 3.8

Bases: IntEnum

See Window.symbol_locations.

For 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.

class sublime.SymbolTypeπŸ”—
4132 3.8

Bases: IntEnum

See Window.symbol_locations and View.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.

class sublime.CompletionFormatπŸ”—
4132 3.8

Bases: IntEnum

The 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 also CompletionItem.snippet_completion.

COMMAND = 2πŸ”—
4050

A command string, in the format returned by format_command(). See also CompletionItem.command_completion().

sublime.version() strπŸ”—
Returns

The version number.

sublime.platform() Literal['osx', 'linux', 'windows']πŸ”—
Returns

The platform which the plugin is being run on.

sublime.arch() Literal['x32', 'x64', 'arm64']πŸ”—
Returns

The CPU architecture.

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.status_message(msg: str)πŸ”—

Show a message in the status bar.

sublime.error_message(msg: str)πŸ”—

Display an error dialog.

sublime.message_dialog(msg: str)πŸ”—

Display a message dialog.

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 None once 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 True the 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 None once 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 None once 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 True the 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 with None if 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 cmd name and args arguments. This is used when constructing a command-based CompletionItem.

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.

sublime.get_clipboard_async(callback: Callable[[str], None], size_limit: int = 16777216)πŸ”—
4075

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_async instead.

4075
sublime.set_clipboard(text: str)πŸ”—

Set the contents of the clipboard.

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.get_log_commands() boolπŸ”—
4099

Get whether command logging is enabled.

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

sublime.get_log_input() boolπŸ”—
4099

Get whether input logging is enabled.

sublime.log_fps(flag: Optional[bool] = None)πŸ”—
4099

Control whether rendering timings like frames per second get logged.

Parameters
flag

Whether to log. Pass None to toggle logging.

sublime.get_log_fps() boolπŸ”—
4099

Get whether fps logging is enabled.

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.get_log_result_regex() boolπŸ”—
4099

Get whether result regex logging is enabled.

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.get_log_indexing() boolπŸ”—
4099

Get whether indexing logging is enabled.

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

sublime.get_log_build_systems() boolπŸ”—
4099

Get whether build system logging is enabled.

sublime.log_control_tree(flag: Optional[bool] = None)πŸ”—
4064

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

sublime.get_log_control_tree() boolπŸ”—
4099

Get whether control tree logging is enabled.

sublime.ui_info() dictπŸ”—
4096
Returns

Information about the user interface including top-level keys system, theme and color_scheme.

sublime.score_selector(scope_name: str, selector: str) intπŸ”—

Match the selector against the given scope_name, returning a score for how well they match.

A score of 0 means no match, above 0 means 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

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

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 Value into 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 makes pretty have 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.

sublime.expand_variables(value: Value, variables: dict[str, str]) ValueπŸ”—

Expands any variables in value using the variables defined in the dictionary variables. 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 callback in the main thread after the given delay (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.active_window() WindowπŸ”—
Returns

The most recently used Window.

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 dict will contain the keys "command" and "args".

sublime.project_history() list[str]πŸ”—
4144
Returns

A list of most recently opened workspaces. Sublime-project files with the same name are listed in place of sublime-workspace files.

sublime.folder_history() list[str]πŸ”—
4144
Returns

A list of recent folders added to sublime projects

class sublime.WindowπŸ”—

Bases: object

id() intπŸ”—
Returns

A number that uniquely identifies this window.

is_valid() boolπŸ”—

Check whether this window is still valid. Will return False for a closed window, for example.

hwnd() intπŸ”—
Returns

A platform specific window handle. Windows only.

active_sheet() Optional[Sheet]πŸ”—
Returns

The currently focused Sheet.

active_view() Optional[View]πŸ”—
Returns

The currently edited View.

new_html_sheet(name: str, contents: str, flags=NewFileFlags.NONE, group=- 1) SheetπŸ”—
4065

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.TRANSIENT and NewFileFlags.ADD_TO_SELECTION are allowed.

group

The group to add the sheet to. -1 for the active group.

run_command(cmd: str, args: CommandArgs = None)πŸ”—

Run the named WindowCommand with 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.TRANSIENT or NewFileFlags.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 returns False.

Parameters
fname

The path to the file to open.

flags

NewFileFlags

group

The group to add the sheet to. -1 for 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. -1 for any group.

Returns

The View to the file or None if 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.

num_groups() intπŸ”—
Returns

The number of view groups in the window.

active_group() intπŸ”—
Returns

The index of the currently selected group.

focus_group(idx: int)πŸ”—

Focus the specified group, making it active.

focus_sheet(sheet: Sheet)πŸ”—

Switches to the given Sheet.

focus_view(view: View)πŸ”—

Switches to the given View.

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 Sheet to the given group at the given index.

set_view_index(view: View, group: int, index: int)πŸ”—

Move the given View to the given group at the given index.

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 Sheet in the given group.

active_view_in_group(group: int) Optional[View]πŸ”—
Returns

The currently focused View in 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.

num_sheets_in_group(group: int) intπŸ”—
Returns

The number of sheets in the specified group.

num_views_in_group(group: int) intπŸ”—
Returns

The number of 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

layout() dict[str, Value]πŸ”—

Get the group layout of the window.

get_layout()πŸ”—
Deprecated

Use layout() instead

set_layout(layout: dict[str, Value])πŸ”—

Set the group layout of the window.

create_output_panel(name: str, unlisted=False) ViewπŸ”—

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

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

find_output_panel(name: str) Optional[View]πŸ”—
Returns

The View associated with the named output panel, or None if the output panel does not exist.

destroy_output_panel(name: str)πŸ”—

Destroy the named output panel, hiding it if currently open.

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_panel instead.

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 View used 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 QuickPanelItem.

4083

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 Event argument may be passed when the QuickPanelFlags.WANT_EVENT flag is present.

4096

flags

QuickPanelFlags controlling behavior.

selected_index

The initially selected item. -1 for 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.

is_sidebar_visible() boolπŸ”—
Returns

Whether the sidebar is visible.

set_sidebar_visible(flag: bool, animate=True)πŸ”—

Hides or shows the sidebar.

is_minimap_visible() boolπŸ”—
Returns

Whether the minimap is visible.

set_minimap_visible(flag: bool)πŸ”—

Hides or shows the minimap.

is_status_bar_visible() boolπŸ”—
Returns

Whether the status bar is visible.

set_status_bar_visible(flag: bool)πŸ”—

Hides or shows the status bar.

get_tabs_visible() boolπŸ”—
Returns

Whether the tabs are visible.

set_tabs_visible(flag: bool)πŸ”—

Hides or shows the tabs.

is_menu_visible() boolπŸ”—
Returns

Whether the menu is visible.

set_menu_visible(flag: bool)πŸ”—

Hides or shows the menu.

folders() list[str]πŸ”—
Returns

A list of the currently open folders in this Window.

project_file_name() Optional[str]πŸ”—
Returns

The name of the currently opened project file, if any.

workspace_file_name() Optional[str]πŸ”—
4050
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.

settings() SettingsπŸ”—
Returns

The Settings object for this Window. Any changes to this settings object will be specific to this window.

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 sym is located.

Parameters
sym

The name of the symbol.

source

Sources which should be searched for the symbol.

type

The type of symbol to find

kind_id

The KindId of the symbol.

kind_letter

The letter representing the kind of the symbol. See Kind.

Return

the found symbol locations.

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 dict of 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 dict is suitable for use with expand_variables().

status_message(msg: str)πŸ”—

Show a message in the status bar.

class sublime.EditπŸ”—

Bases: object

A 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 different View, will cause the functions that require them to fail.

class sublime.RegionπŸ”—

Bases: object

A singular selection region. This region has a order - b may be before or at a.

Also commonly used to represent an area of the text buffer, where ordering and xpos are generally ignored.

a: PointπŸ”—

The first end of the region.

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 -1 if undefined.

__len__() intπŸ”—
Returns

The size of the region.

__contains__(v: Region | Point) boolπŸ”—
4023 3.8
Returns

Whether the provided Region or Point is entirely contained within this region.

to_tuple() tuple[Point, Point]πŸ”—
4075
Returns

This region as a tuple (a, b).

empty() boolπŸ”—
Returns

Whether the region is empty, ie. a == b.

begin() PointπŸ”—
Returns

The smaller of a and b.

end() PointπŸ”—
Returns

The larger of a and b.

size() intπŸ”—

Equivalent to __len__.

contains(x: Point) boolπŸ”—

Equivalent to __contains__.

cover(region: Region) RegionπŸ”—
Returns

A Region spanning both regions.

intersection(region: Region) RegionπŸ”—
Returns

A Region covered by both regions.

intersects(region: Region) boolπŸ”—
Returns

Whether the provided region intersects this region.

class sublime.HistoricPositionπŸ”—
4050

Bases: object

Provides a snapshot of the row and column info for a Point, before changes were made to a View. This is primarily useful for replaying changes to a document.

pt: PointπŸ”—

The offset from the beginning of the View.

row: intπŸ”—

The row the .py was in when the HistoricPosition was recorded.

col: intπŸ”—

The column the .py was in when the HistoricPosition was recorded, in Unicode characters.

col_utf16: intπŸ”—
4075

The value of .col, but in UTF-16 code units.

col_utf8: intπŸ”—
4075

The value of .col, but in UTF-8 code units.

class sublime.TextChangeπŸ”—
4050

Bases: object

Represents a change that occurred to the text of a View. This is primarily useful for replaying changes to a document.

a: HistoricPositionπŸ”—

The beginning HistoricPosition of the region that was modified.

b: HistoricPositionπŸ”—

The ending HistoricPosition of the region that was modified.

len_utf16: intπŸ”—
4075

The length of the old contents, in UTF-16 code units.

len_utf8: intπŸ”—
4075

The length of the old contents, in UTF-8 code units.

str: str

A string of the new contents of the region specified by .a and .b.

class sublime.SelectionπŸ”—

Bases: object

Maintains a set of sorted non-overlapping Regions. A selection may be empty.

This is primarily used to represent the textual selection.

__len__() intπŸ”—
Returns

The number of regions in the selection.

__getitem__(index: int) RegionπŸ”—
Returns

The region at the given index.

__delitem__(index: int)πŸ”—

Delete the region at the given index.

is_valid() boolπŸ”—
Returns

Whether this selection is for a valid view.

clear()πŸ”—

Remove all regions from the selection.

add(x: Region | Point)πŸ”—

Add a Region or Point to the selection. It will be merged with the existing regions if intersecting.

add_all(regions: Iterable[Region | Point])πŸ”—

Add all the regions from the given iterable.

subtract(region: Region)πŸ”—

Subtract a region from the selection, such that the whole region is no longer contained within the selection.

contains(region: Region) boolπŸ”—
Returns

Whether the provided region is contained within the selection.

class sublime.SheetπŸ”—

Bases: object

Represents a content container, i.e. a tab, within a window. Sheets may contain a View, or an image preview.

id() intπŸ”—
Returns

A number that uniquely identifies this sheet.

window() Optional[Window]πŸ”—
Returns

The Window containing this sheet. May be None if the sheet has been closed.

view() Optional[View]πŸ”—
Returns

The View contained within the sheet if any.

file_name() Optional[str]πŸ”—
4088
Returns

The full name of the file associated with the sheet, or None if it doesn’t exist on disk.

is_semi_transient() boolπŸ”—
4080
Returns

Whether this sheet is semi-transient.

is_transient() boolπŸ”—
4080
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_transient will still return False.

is_selected() boolπŸ”—
Returns

Whether this sheet is currently selected.

Since

4135

group() Optional[int]πŸ”—
4100
Returns

The (layout) group that the sheet is contained within.

close(on_close=<function Sheet.<lambda>>)πŸ”—
4088

Closes the sheet.

Parameters
on_close

class sublime.TextSheetπŸ”—
4065

Bases: Sheet

Specialization for sheets containing editable text, ie. a View.

set_name(name: str)πŸ”—

Set the name displayed in the tab. Only affects unsaved files.

class sublime.ImageSheetπŸ”—
4065

Bases: Sheet

Specialization for sheets containing an image.

class sublime.HtmlSheetπŸ”—
4065

Bases: Sheet

Specialization for sheets containing HTML.

set_name(name: str)πŸ”—

Set the name displayed in the tab.

set_contents(contents: str)πŸ”—

Set the HTML content of the sheet.

class sublime.ContextStackFrameπŸ”—
4127

Bases: object

Represents a single stack frame in the syntax highlighting. See View.context_backtrace.

context_name: strπŸ”—

The name of the context.

source_file: strπŸ”—

The name of the file the context is defined in.

source_location: tuple[int, int]πŸ”—

The location of the context inside the source file as a pair of row and column. Maybe be (-1, -1) if the location is unclear, like in tmLanguage based syntaxes.

class sublime.ViewπŸ”—

Bases: object

Represents 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 using View.clones() or Buffer.views().

id() intπŸ”—
Returns

A number that uniquely identifies this view.

buffer_id() intπŸ”—
Returns

A number that uniquely identifies this view’s Buffer.

buffer() BufferπŸ”—
Returns

The Buffer for which this is a view.

sheet_id() intπŸ”—
4083
Returns

The ID of the Sheet for this View, or 0 if not part of any sheet.

sheet() Optional[Sheet]πŸ”—
4083
Returns

The Sheet for this view, if displayed in a sheet.

element() Optional[str]πŸ”—
4050
Returns

None for normal views that are part of a Sheet. 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 False for a closed view, for example.

is_primary() boolπŸ”—
Returns

Whether view is the primary view into a Buffer. Will only be False if the user has opened multiple views into a file.

window() Optional[Window]πŸ”—
Returns

A reference to the window containing the view, if any.

clones() list[sublime.View]πŸ”—
Returns

All the other views into the same Buffer. See View.

file_name() Optional[str]πŸ”—
Returns

The full name of the file associated with the sheet, or None if it doesn’t exist on disk.

close(on_close=<function View.<lambda>>) boolπŸ”—

Closes the view.

retarget(new_fname: str)πŸ”—

Change the file path the buffer will save to.

name() strπŸ”—
Returns

The name assigned to the buffer, if any.

set_name(name: str)πŸ”—

Assign a name to the buffer. Displayed as in the tab for unsaved files.

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_loading() boolπŸ”—
Returns

Whether the buffer is still loading from disk, and not ready for use.

is_dirty() boolπŸ”—
Returns

Whether there are any unsaved modifications to the buffer.

is_read_only() boolπŸ”—
Returns

Whether the buffer may not be modified.

set_read_only(read_only: bool)πŸ”—

Set the read only property on the buffer.

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.

encoding() strπŸ”—
Returns

The encoding currently associated with the buffer.

set_encoding(encoding_name: str)πŸ”—

Applies a new encoding to the file. This will be used when the file is saved.

line_endings() strπŸ”—
Returns

The encoding currently associated with the file.

set_line_endings(line_ending_name: str)πŸ”—

Sets the line endings that will be applied when next saving.

size() intπŸ”—
Returns

The number of character in the file.

insert(edit: Edit, pt: Point, text: str) intπŸ”—

Insert the given string into the buffer.

Parameters
edit

An Edit object provided by a TextCommand.

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 Edit object is in an invalid state, ie. outside of a TextCommand.

erase(edit: Edit, region: Region)πŸ”—

Erases the contents of the provided Region from the buffer.

replace(edit: Edit, region: Region, text: str)πŸ”—

Replaces the contents of the Region in 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_id must have been obtained from change_id() at the point in time the region is from.

run_command(cmd: str, args: CommandArgs = None)πŸ”—

Run the named TextCommand with the (optional) given args.

sel() SelectionπŸ”—
Returns

The views Selection.

substr(x: Region | Point) strπŸ”—
Returns

The string at the Point or within the Region provided.

find(pattern: str, start_pt: Point, flags=FindFlags.NONE) RegionπŸ”—
Parameters
pattern

The regex or literal pattern to search by.

start_pt

The Point to start searching from.

flags

Controls various behaviors of find. See FindFlags.

Returns

The first Region matching the provided pattern.

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 None all matches in the extractions list 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 None searching is limited to within the provided region(s).

Returns

All (non-overlapping) regions matching the pattern.

settings() SettingsπŸ”—
Returns

The view’s Settings object. Any changes to it will be private to this view.

meta_info(key: str, pt: Point) ValueπŸ”—

Look up the preference key for the scope at the provided Point from all matching .tmPreferences files.

Examples of keys are TM_COMMENT_START and showInSymbolList.

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 Region and 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 provided Point.

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)

See sublime.score_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.

style() dict[str, str]πŸ”—
3150

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 dict of style information including the keys:

  • "foreground": str

  • "selection_foreground": str (only if set)

  • "background": str (only if set)

  • "bold": bool

  • "italic": bool

  • "glow": bool (only if set)

    4063
  • "underline": bool (only if set)

    4075
  • "stippled_underline": bool (only if set)

    4075
  • "squiggly_underline": bool (only if set)

    4075
  • "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 Region returned exists on exactly one line.

line(x: Region | Point) RegionπŸ”—
Returns

The line that contains the Point or an expanded Region to the beginning/end of lines, excluding the newline character.

full_line(x: Region | Point) RegionπŸ”—
Returns

The line that contains the Point or an expanded Region to the beginning/end of lines, including the newline character.

word(x: Region | Point) RegionπŸ”—
Returns

The word that contains the provided Point. If a Region is provided it’s beginning/end are expanded to word boundaries.

classify(pt: Point) PointClassificationπŸ”—

Classify the provided Point. See PointClassification.

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 Point or Region to the left and right until each side lands on a location that matches the provided PointClassification. See find_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.

rowcol_utf8(tp: Point) tuple[int, int]πŸ”—
4069

Calculates the 0-based line and column numbers of the point. Column numbers are returned as UTF-8 code units.

rowcol_utf16(tp: Point) tuple[int, int]πŸ”—
4069

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, row and col. col is interpreted as the number of Unicode characters to advance past the beginning of the row.

Parameters
clamp_column
4075

Whether col should be restricted to valid values for the given row.

text_point_utf8(row: int, col: int, *, clamp_column=False) PointπŸ”—

Calculates the character offset of the given, 0-based, row and col. col is interpreted as the number of UTF-8 code units to advance past the beginning of the row.

Parameters
clamp_column
4075

whether col should be restricted to valid values for the given row.

text_point_utf16(row: int, col: int, *, clamp_column=False) PointπŸ”—

Calculates the character offset of the given, 0-based, row and col. col is interpreted as the number of UTF-16 code units to advance past the beginning of the row.

Parameters
clamp_column
4075

whether col should be restricted to valid values for the given row.

utf8_code_units(tp: Point = None) intπŸ”—
4173

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.

utf16_code_units(tp: Point = None) intπŸ”—
4173

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.

visible_region() RegionπŸ”—
Returns

The currently visible area of the view.

show(location: Region | Selection | Point, show_surrounds=True, keep_to_left=False, animate=True)πŸ”—

Scroll the view to show the given location.

Parameters
location

The location to scroll the view to. For a Selection only the first Region is shown.

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.

Parameters
location

Which Point or Region to scroll to.

animate
4075

Whether the scrolling should be animated.

viewport_position() VectorπŸ”—
Returns

The offset of the viewport in layout coordinates.

set_viewport_position(xy: Vector, animate=True)πŸ”—

Scrolls the viewport to the given layout position.

viewport_extent() VectorπŸ”—
Returns

The width and height of the viewport.

layout_extent() VectorπŸ”—
Returns

The width and height of the layout.

text_to_layout(tp: Point) VectorπŸ”—

Convert a text point to a layout position.

text_to_window(tp: Point) VectorπŸ”—

Convert a text point to a window position.

layout_to_text(xy: Vector) PointπŸ”—

Convert a layout position to a text point.

layout_to_window(xy: Vector) VectorπŸ”—

Convert a layout position to a window position.

window_to_layout(xy: Vector) VectorπŸ”—

Convert a window position to a layout position.

window_to_text(xy: Vector) PointπŸ”—

Convert a window position to a text point.

line_height() DIPπŸ”—
Returns

The light height used in the layout.

em_width() DIPπŸ”—
Returns

The typical character width used in the layout.

is_folded(region: Region) boolπŸ”—
Returns

Whether the provided Region is folded.

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

False if 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"

3148

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 href of 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.

erase_regions(key: str)πŸ”—

Remove the regions associated with the given key.

assign_syntax(syntax: str | sublime.Syntax)πŸ”—

Changes the syntax used by the view. syntax may be a packages path to a syntax file, or a scope: specifier string.

syntax may be a Syntax object.

4080
set_syntax_file(syntax_file: str)πŸ”—
Deprecated

Use assign_syntax() instead.

syntax() Optional[Syntax]πŸ”—
Returns

The syntax assigned to the buffer.

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 Region and name of symbols.

Deprecated

Use indexed_symbol_regions() instead.

indexed_references() list[tuple[sublime.Region, str]]πŸ”—
3148
Returns

A list of the Region and 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 key to the view. The value will be displayed in the status bar, in a comma separated list of all status values, ordered by key. Setting the value to "" will clear the status.

get_status(key: str) strπŸ”—
Returns

The previous assigned value associated with the given key, if any.

See set_status().

erase_status(key: str)πŸ”—

Clear the status associated with the provided key.

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 Point by 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_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
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 -1 is 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 Point at which to display the popup. If -1 the 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 href attribute of the clicked link.

on_hide

Called when the popup is hidden.

update_popup(content: str)πŸ”—

Update the content of the currently visible popup.

is_popup_visible() boolπŸ”—
Returns

Whether a popup is currently shown.

hide_popup()πŸ”—

Hide the current popup.

is_auto_complete_visible() boolπŸ”—
Returns

Whether the auto-complete menu is currently visible.

preserve_auto_complete_on_focus_lost()πŸ”—
4073

Sets the auto complete popup state to be preserved the next time the View loses focus. When the View regains focus, the auto complete window will be re-shown, with the previously selected entry pre-selected.

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_tags is True.

font_family

Whether to include the font family in the top level styling. Only applies when enclosing_tags is True.

clear_undo_stack()πŸ”—
4114

Clear the undo/redo stack.

class sublime.BufferπŸ”—
4081

Bases: object

Represents a text buffer. Multiple View objects may share the same buffer.

id() intπŸ”—
4083

Returns a number that uniquely identifies this buffer.

file_name() Optional[str]πŸ”—
4083

The full name file the file associated with the buffer, or None if it doesn’t exist on disk.

views() list[sublime.View]πŸ”—

Returns a list of all views that are associated with this buffer.

primary_view() ViewπŸ”—

The primary view associated with this buffer.

class sublime.SettingsπŸ”—

Bases: object

A dict like object that a settings hierarchy.

__getitem__(key: str) ValueπŸ”—
4023 3.8

Returns the named setting.

__setitem__(key: str, value: Value)πŸ”—
4023 3.8

Set the named key to the provided value.

__delitem__(key: str)πŸ”—
4078 3.8

Deletes the provided key from the setting. Note that a parent setting may also provide this key, thus deleting may not entirely remove a key.

__contains__(key: str) boolπŸ”—
4023 3.8

Returns whether the provided key is set.

to_dict() dictπŸ”—
4078 3.8

Return the settings as a dict. This is not very fast.

setdefault(key: str, value: Value)πŸ”—
4023 3.8

Returns the value associated with the provided key. If it’s not present the provided value is assigned to the key and then returned.

update(other=(), /, **kwargs)πŸ”—
4078 3.8

Update the settings from the provided argument(s).

Accepts:

  • A dict or other implementation of collections.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. See add_on_change.

class sublime.PhantomπŸ”—

Bases: object

Represents an minihtml Reference-based decoration to display non-editable content interspersed in a View. Used with PhantomSet to actually add the phantoms to the View. Once a Phantom has been constructed and added to the View, changes to the attributes will have no effect.

region: RegionπŸ”—

The Region associated with the phantom. The phantom is displayed at the start of the Region.

content: strπŸ”—

The HTML content of the phantom.

layout: PhantomLayoutπŸ”—

How the phantom should be placed relative to the region.

on_navigate: Optional[Callable[[str], None]]πŸ”—

Called when a link in the HTML is clicked. The value of the href attribute 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: object

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

__init__(view: View, key='')πŸ”—
view: ViewπŸ”—

The View the phantom set is attached to.

key: strπŸ”—

A string used to group the phantoms together.

update(phantoms: Iterable[Phantom])πŸ”—

Update the set of phantoms. If the Phantom.region of existing phantoms have changed they will be moved; new phantoms are added and ones not present are removed.

class sublime.HtmlπŸ”—

Bases: object

Used to indicate that a string is formatted as HTML. See CommandInputHandler.preview().

class sublime.CompletionListπŸ”—
4050

Bases: object

Represents 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 None is passed, the method set_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: object

Represents an available auto-completion item.

trigger: strπŸ”—

Text to match against the user’s input.

annotation: strπŸ”—

A hint to draw to the right-hand side of the trigger.

completion: strπŸ”—

Text to insert if the completion is specified. If empty the trigger will be inserted instead.

completion_format: CompletionFormatπŸ”—

The format of the completion. See CompletionFormat.

kind: KindπŸ”—

The kind of the completion. See Kind.

details: strπŸ”—
4073

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_format is always CompletionFormat.SNIPPET.

classmethod command_completion(trigger: str, command: str, args: CommandArgs = None, annotation='', kind=(KindId.AMBIGUOUS, '', ''), details='') CompletionItemπŸ”—

Specialized constructor for command completions. The completion_format is always CompletionFormat.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.SyntaxπŸ”—
4081

Bases: object

Contains information about a syntax.

path: strπŸ”—

The packages path to the syntax file.

name: strπŸ”—

The name of the syntax.

hidden: boolπŸ”—

If the syntax is hidden from the user.

scope: strπŸ”—

The base scope name of the syntax.

class sublime.QuickPanelItemπŸ”—
4083

Bases: object

Represents a row in the quick panel, shown via Window.show_quick_panel().

trigger: strπŸ”—

Text to match against user’s input.

details: str | list[str] | tuple[str]πŸ”—

A minihtml Reference string or list of strings displayed below the trigger.

annotation: strπŸ”—

Hint to draw to the right-hand side of the row.

kind: KindπŸ”—

The kind of the item. See Kind.

class sublime.ListInputItemπŸ”—
4095

Bases: object

Represents a row shown via ListInputHandler.

text: strπŸ”—

Text to match against the user’s input.

value: AnyπŸ”—

A Value passed to the command if the row is selected.

details: str | list[str] | tuple[str]πŸ”—

A minihtml Reference string or list of strings displayed below the trigger.

annotation: strπŸ”—

Hint to draw to the right-hand side of the row.

kind: KindπŸ”—

The kind of the item. See Kind.

class sublime.SymbolRegionπŸ”—
4085

Bases: object

Contains information about a Region of a View that contains a symbol.

name: strπŸ”—

The name of the symbol.

region: RegionπŸ”—

The location of the symbol within the View.

syntax: strπŸ”—

The name of the syntax for the symbol.

type: SymbolTypeπŸ”—

The type of the symbol. See SymbolType.

kind: KindπŸ”—

The kind of the symbol. See Kind.

class sublime.SymbolLocationπŸ”—
4085

Bases: object

Contains information about a file that contains a symbol.

path: strπŸ”—

The filesystem path to the file containing the symbol.

display_name: strπŸ”—

The project-relative path to the file containing the symbol.

row: intπŸ”—

The row of the file the symbol is contained on.

col: intπŸ”—

The column of the row that the symbol is contained on.

syntax: strπŸ”—

The name of the syntax for the symbol.

type: SymbolTypeπŸ”—

The type of the symbol. See SymbolType.

kind: KindπŸ”—

The kind of the symbol. See Kind.

sublime_plugin ModuleπŸ”—

class sublime_plugin.CommandInputHandlerπŸ”—

Bases: object

name() strπŸ”—

The command argument name this input handler is editing. Defaults to foo_bar for an input handler named FooBarInputHandler.

placeholder() strπŸ”—

Placeholder text is shown in the text entry box before the user has entered anything. Empty by default.

initial_text() strπŸ”—

Initial text shown in the text entry box. Empty by default.

initial_selection() list[tuple[int, int]]πŸ”—
4081

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) boolπŸ”—

Called whenever the user presses enter in the text entry box. Return False to disallow the current value.

cancel()πŸ”—

Called when the input handler is canceled, either by the user pressing backspace or escape.

confirm(text: str)πŸ”—

Called when the input is accepted, after the user has pressed enter and the text has been validated.

next_input(args) Optional[CommandInputHandler]πŸ”—

Return the next input after the user has completed this one. May return None to indicate no more input is required, or sublime_plugin.BackInputHandler() to indicate that the input handler should be popped off the stack instead.

want_event() boolπŸ”—
4096

Whether the validate() and confirm() methods should received a second Event parameter. Returns False by default.

class sublime_plugin.BackInputHandlerπŸ”—

Bases: CommandInputHandler

class sublime_plugin.TextInputHandlerπŸ”—

Bases: CommandInputHandler

TextInputHandlers 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.

description(text: str) strπŸ”—

The text to show in the Command Palette when this input handler is not at the top of the input handler stack. Defaults to the text the user entered.

class sublime_plugin.ListInputHandlerπŸ”—

Bases: CommandInputHandler

ListInputHandlers 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 list of item, or a 2-element tuple containing a list of items, and an int index 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 Value to pass to the command

  • A sublime.ListInputItem object

    4095
description(value, text: str) strπŸ”—

The text to show in the Command Palette when this input handler is not at the top of the input handler stack. Defaults to the text of the list item the user selected.

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 to true for 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 None to get the default description.

want_event() boolπŸ”—

Return whether to receive an Event argument when the command is triggered by a mouse action. The event information allows commands to determine which portion of the view was clicked on. The default implementation returns False.

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.

input_description() strπŸ”—
3154

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.ApplicationCommandπŸ”—

Bases: Command

A Command instantiated just once.

class sublime_plugin.WindowCommandπŸ”—

Bases: Command

A Command instantiated once per window. The Window object may be retrieved via self.window.

window: WindowπŸ”—

The Window this command is attached to.

class sublime_plugin.TextCommandπŸ”—

Bases: Command

A Command instantiated once per View. The View object may be retrieved via self.view.

view: ViewπŸ”—

The View this command is attached to.

run(edit: Edit)πŸ”—

Called when the command is run. Command arguments are passed as keyword arguments.

class sublime_plugin.EventListenerπŸ”—

Bases: object

on_init(views: List[View])πŸ”—
4050

Called 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(view: View)πŸ”—

Called when a new file is created.

on_new_async(view: View)πŸ”—

Called when a new buffer is created. Runs in a separate thread, and does not block the application.

on_associate_buffer(buffer: View)πŸ”—
4084

Called when a buffer is associated with a file. buffer will be a Buffer object.

on_associate_buffer_async(buffer: View)πŸ”—
4084

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(view: View)πŸ”—

Called when a view is cloned from an existing one.

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(view: View)πŸ”—

Called when the file is finished loading.

on_load_async(view: View)πŸ”—

Called when the file is finished loading. Runs in a separate thread, and does not block the application.

on_reload(view: View)πŸ”—
4050

Called when the View is reloaded.

on_reload_async(view: View)πŸ”—
4050

Called when the View is reloaded. Runs in a separate thread, and does not block the application.

on_revert(view: View)πŸ”—
4050

Called when the View is reverted.

on_revert_async(view: View)πŸ”—
4050

Called when the View is reverted. Runs in a separate thread, and does not block the application.

on_pre_move(view: View)πŸ”—
4050

Called right before a view is moved between two windows or within a window. Passed the View object.

on_post_move(view: View)πŸ”—
4050

Called right after a view is moved between two windows or within a window. Passed the View object.

on_post_move_async(view: View)πŸ”—
4050

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(view: View)πŸ”—

Called just before a view is saved.

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(view: View)πŸ”—

Called after a view has been saved.

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(view: View)πŸ”—

Called after changes have been made to a view.

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(view: View)πŸ”—

Called after the selection has been modified in a view.

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(view: View)πŸ”—

Called when a view gains input focus.

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(view: View)πŸ”—

Called when a view loses input focus.

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

True or False if the plugin handles this context key and it either does or doesn’t match. If the context is unknown return None.

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 None if 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 None to 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 None to 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.

on_new_window(window: Window)πŸ”—
4050

Called when a window is created, passed the Window object.

on_new_window_async(window: Window)πŸ”—
4050

Called when a window is created, passed the Window object. Runs in a separate thread, and does not block the application.

on_pre_close_window(window: Window)πŸ”—
4050

Called right before a window is closed, passed the Window object.

on_new_project(window: Window)πŸ”—
4050

Called right after a new project is created, passed the Window object.

on_new_project_async(window: Window)πŸ”—
4050

Called right after a new project is created, passed the Window object. Runs in a separate thread, and does not block the application.

on_load_project(window: Window)πŸ”—
4050

Called right after a project is loaded, passed the Window object.

on_load_project_async(window: Window)πŸ”—
4050

Called right after a project is loaded, passed the Window object. Runs in a separate thread, and does not block the application.

on_pre_save_project(window: Window)πŸ”—
4050

Called right before a project is saved, passed the Window object.

on_post_save_project(window: Window)πŸ”—
4050

Called right after a project is saved, passed the Window object.

on_post_save_project_async(window: Window)πŸ”—
4050

Called right after a project is saved, passed the Window object. Runs in a separate thread, and does not block the application.

on_pre_close_project(window: Window)πŸ”—

Called right before a project is closed, passed the Window object.

class sublime_plugin.ViewEventListenerπŸ”—

Bases: object

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

on_load()πŸ”—
3155

Called when the file is finished loading.

on_load_async()πŸ”—
3155

Same as on_load but runs in a separate thread, not blocking the application.

on_reload()πŸ”—
4050

Called when the file is reloaded.

on_reload_async()πŸ”—
4050

Same as on_reload but runs in a separate thread, not blocking the application.

on_revert()πŸ”—
4050

Called when the file is reverted.

on_revert_async()πŸ”—
4050

Same as on_revert but runs in a separate thread, not blocking the application.

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_move but 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_save but 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_save but 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_modified but 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

True or False if the plugin handles this context key and it either does or doesn’t match. If the context is unknown return None.

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 None if 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 None to run the command unmodified.

on_post_text_command(command_name: str, args: CommandArgs)πŸ”—

Called after a text command has been executed.

classmethod is_applicable(settings: Settings) boolπŸ”—
Returns

Whether this listener should apply to a view with the given Settings.

classmethod applies_to_primary_view_only() boolπŸ”—
Returns

Whether this listener should apply only to the primary view for a file or all of its clones as well.

class sublime_plugin.TextChangeListenerπŸ”—
4081

Bases: object

A class that provides event handling about text changes made to a specific Buffer. Is separate from ViewEventListener since 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_changed but 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_revert but 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_reload but 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.

attach(buffer: Buffer)πŸ”—

Attach this listener to a buffer.

Raises ValueError

if the listener is already attached.

is_attached() boolπŸ”—
Returns

whether the listener is receiving events from a buffer. May not be called from __init__.