sublime_lib API Reference

A utility library for Sublime Text providing a variety of convenience features for other packages to use.

For general documentation, see the README.

Most sublime_lib classes and functions rely on the Sublime Text API. As a result, sublime_lib functionality should not be used at import time. Instead, any initialization should be performed in plugin_loaded().

Settings dictionaries

class sublime_lib.SettingsDict(settings)

Wraps a sublime.Settings object settings with a dict-like interface.

There is no way to list or iterate over the keys of a Settings object. As a result, the following methods are not implemented:

  • __len__()

  • __iter__()

  • clear()

  • copy()

  • items()

  • keys()

  • popitem()

  • values()

You can use collections.ChainMap to chain a SettingsDict with other dict-like objects. If you do, calling the above unimplemented methods on the ChainMap will raise an error.

iter(self)

Raise NotImplementedError.

self == other

Return True if self and other are of the same type and refer to the same underlying settings data.

self[key]

Return the setting named key.

If a subclass of SettingsDict defines a method __missing__() and key is not present, the d[key] operation calls that method with key as the argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable.

Raises

KeyError – if there is no setting with the given key and __missing__() is not defined.

self[key] = value

Set self[key] to value.

del self[key]

Remove self[key] from self.

Raises

KeyError – if there us no setting with the given key.

item in self

Return True if self has a setting named key, else False.

get(key, default=None)

Return the value for key if key is in the dictionary, or default otherwise.

If default is not given, it defaults to None, so that this method never raises KeyError.

pop(key, default=SettingsDict.NO_DEFAULT)

Remove the setting self[key] and return its value or default.

Raises

KeyError – if key is not in the dictionary and default is SettingsDict.NO_DEFAULT.

Changed in version 1.2: Added SettingsDict.NO_DEFAULT.

setdefault(key, default=None)

Set self[key] to default if it wasn’t already defined and return self[key].

update(other=[], **kwargs)

Update the dictionary with the key/value pairs from other, overwriting existing keys.

Accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: self.update(red=1, blue=2).

subscribe(selector, callback, default_value=None)

Register a callback to be invoked when the value derived from the settings object changes and return a function that when invoked will unregister the callback.

Instead of passing the SettingsDict to callback, a value derived using selector is passed. If selector is callable, then selector(self) is passed. If selector is a str, then self.get(selector, default_value) is passed. Otherwise, projection(self, selector) is passed.

Changes in the selected value are detected by comparing the last known value to the current value using the equality operator. If you use a selector function, the result must be equatable and should not be mutated.

callback should accept two arguments: the new derived value and the previous derived value.

Changed in version 1.1: Return an unsubscribe callback.

class sublime_lib.NamedSettingsDict(name)

Wraps a sublime.Settings object corresponding to a sublime-settings file.

property file_name: str

The name of the sublime-settings files associated with the NamedSettingsDict.

save()

Flush any in-memory changes to the NamedSettingsDict to disk.

Output streams and panels

class sublime_lib.ViewStream(view, *, force_writes=False, follow_cursor=False)

A TextIOBase encapsulating a View object.

All public methods (except flush()) require that the underlying View object be valid (using View.is_valid()). Otherwise, ValueError will be raised.

The read(), readline(), write(), print(), and tell() methods require that the underlying View have exactly one selection, and that the selection is empty (i.e. a simple cursor). Otherwise, ValueError will be raised.

Parameters
  • force_writes – If True, then write() and print() will write to the view even if it is read-only. Otherwise, those methods will raise ValueError.

  • follow_cursor – If True, then any method that moves the cursor position will scroll the view to ensure that the new position is visible.

Changed in version 1.2: Added the follow_cursor option.

read(size=- 1)

Read and return at most size characters from the stream as a single str.

If size is negative or None, read until EOF.

readline(size=- 1)

Read and return one line from the stream, to a maximum of size characters.

If the stream is already at EOF, return an empty string.

write(s)

Insert the string s into the view immediately before the cursor and return the number of characters inserted.

Because Sublime may convert tabs to spaces, the number of characters inserted may not match the length of the argument.

print(*objects, sep=' ', end='\n')

Shorthand for print() passing this ViewStream as the file argument.

flush()

Do nothing. (The stream is not buffered.)

seek(offset, whence=0)

Move the cursor in the view and return the new offset.

If whence is provided, the behavior is the same as for IOBase. If the cursor would move before the beginning of the view, it will move to the beginning instead, and likewise for the end of the view. If the view had multiple selections, none will be preserved.

Changed in version 1.2: Allow non-zero arguments with any value of whence.

seek_start()

Move the cursor in the view to before the first character.

seek_end()

Move the cursor in the view to after the last character.

tell()

Return the character offset of the cursor.

show_cursor()

Scroll the view to show the position of the cursor.

clear()

Erase all text in the view.

class sublime_lib.Panel(window, panel_name)

An abstraction of a panel, such as the console or an output panel.

Raises

ValueError – if window has no panel called panel_name.

All Panel methods except for exists() will raise a ValueError if the panel does not exist. Descendant classes may override exists() to customize this behavior.

panel_name

The name of the panel as it is listed in sublime.Window.panels().

New in version 1.3.

exists()

Return True if the panel exists, or False otherwise.

This implementation checks sublime.Window.panels(), so it will return False for unlisted panels.

is_visible()

Return True if the panel is currently visible.

show()

Show the panel, hiding any other visible panel.

hide()

Hide the panel.

toggle_visibility()

If the panel is visible, hide it; otherwise, show it.

class sublime_lib.OutputPanel(window, name, *, force_writes=False, follow_cursor=False)

A subclass of ViewStream and Panel wrapping an output panel in the given window with the given name.

Raises

ValueError – if window has no output panel called name.

Changed in version 1.3: Now a subclass of Panel.

classmethod create(window, name, *, force_writes=False, follow_cursor=False, unlisted=False, **kwargs)

Create a new output panel with the given name in the given window.

If kwargs are given, they will be interpreted as for new_view().

property full_name: str

The output panel name, beginning with 'output.'.

Generally, API methods specific to output panels will use name, while methods that work with any panels will use full_name.

exists()

Return True if the panel exists, or False otherwise.

This implementation checks that the encapsulated View is valid, so it will return True even for unlisted panels.

destroy()

Destroy the output panel.

Resource paths

class sublime_lib.ResourcePath(*pathsegments)

A pathlib-inspired representation of a Sublime Text resource path.

Resource paths are similar to filesystem paths in many ways, yet different in other ways. Many features of pathlib.Path objects are not implemented by ResourcePath, and other features may have differerent interpretations.

A resource path consists of one or more parts separated by forward slashes (regardless of platform). The first part is the root. At the present time, the only roots that Sublime uses are 'Packages' and 'Caches'. Resource paths are always absolute; dots in resource paths have no special meaning.

ResourcePath objects are immutable and hashable. The forward slash operator is a shorthand for joinpath(). The string representation of a ResourcePath is the raw resource path in the form that Sublime Text uses.

Some methods accept glob patterns as arguments. Glob patterns are interpreted as in pathlib. Recursive globs (**) are always allowed, even in match(). Leading slashes are not matched literally. A pattern with a leading slash must match the entire path and not merely a suffix of the path.

New in version 1.2.

classmethod glob_resources(pattern)

Find all resources that match the given pattern and return them as ResourcePath objects.

classmethod from_file_path(file_path)

Return a ResourcePath corresponding to the given file path.

If the file path corresponds to a resource inside an installed package, then return the path to that resource.

Raises
  • ValueError – if the given file path does not correspond to any resource path.

  • ValueError – if the given file path is relative.

>>> ResourcePath.from_file_path(
   os.path.join(sublime.packages_path(), 'My Package', 'foo.py')
)
ResourcePath("Packages/My Package/foo.py")

>>> ResourcePath.from_file_path(
   os.path.join(
     sublime.installed_packages_path(),
     'My Package.sublime-package',
     'foo.py'
   )
)
ResourcePath("Packages/My Package/foo.py")
property parts: Tuple[str, ...]

A tuple giving access to the path’s various components.

property parent: sublime_lib.resource_path.ResourcePath

The logical parent of the path. A root path is its own parent.

property parents: Tuple[sublime_lib.resource_path.ResourcePath, ...]

An immutable sequence providing access to the path’s logical ancestors.

property name: str

A string representing the final path component.

property suffix: str

The final component’s last suffix, if any.

property suffixes: List[str]

A list of the final component’s suffixes, if any.

property stem: str

The final path component, minus its last suffix.

property root: str

The first path component (usually 'Packages' or 'Cache').

property package: Optional[str]

The name of the package the path is within, or None if the path is a root path.

match(pattern)

Return True if this path matches the given glob pattern, or False otherwise.

Raises

ValueError – if pattern is invalid.

joinpath(*other)

Combine this path with all of the given strings.

relative_to(*other)

Compute a tuple parts of path components such that self == other.joinpath(*parts).

other will be converted to a ResourcePath.

Raises

ValueError – if this path is not a descendant of other.

New in version 1.3.

with_name(name)

Return a new path with the name changed.

add_suffix(suffix)

Return a new path with the suffix added.

New in version 1.3.

remove_suffix(suffix=None, *, must_remove=True)

Return a new path with the suffix removed.

If suffix is None (the default), then self.suffix will be removed. If suffix is a string, then only that suffix will be removed. Otherwise, if suffix is iterable, then the longest possible item in suffix will be removed.

Raises

ValueError – if must_remove is True (the default) and no suffix can be removed.

New in version 1.3.

with_suffix(suffix)

Return a new path with the suffix changed.

If the original path doesn’t have a suffix, the new suffix is appended instead. If the new suffix is an empty string, the original suffix is removed.

Equivalent to self.remove_suffix(must_remove=False).add_suffix(suffix).

file_path()

Return a Path object representing a filesystem path inside one of Sublime’s data directories.

Even if there is a resource at this path, there may not be a file at that filesystem path. The resource could be in a default package or an installed package.

Raises

ValueError – if the path’s root is not used by Sublime.

exists()

Return True if there is a resource at this path, or False otherwise.

The resource system does not keep track of directories. Even if a path does not point to a resource, there may be resources beneath that path.

read_text()

Load the resource at this path and return it as text.

Raises
read_bytes()

Load the resource at this path and return it as bytes.

Raises

FileNotFoundError – if there is no resource at this path.

glob(pattern)

Glob the given pattern at this path, returning all matching resources.

Raises

ValueError – if pattern is invalid.

rglob(pattern)

Shorthand for path.glob('**/' + pattern).

Raises
children()

Return a list of paths that are direct children of this path and point to a resource at or beneath that path.

copy(target, exist_ok=True)

Copy this resource to the given target.

target should be a string representing a filesystem path or a value convertible to string. If target exists and is a file, and exist_ok is True (the default), it will be silently replaced.

Raises

New in version 1.3.

copytree(target, exist_ok=False)

Copy all resources beneath this path into a directory tree rooted at target.

All missing parent directories of target will be created.

If exist_ok is False (the default), then target must not already exist. If exist_ok is True, then existing files under target will be overwritten.

Raises

FileExistsError – if target already exists and exist_ok is False.

New in version 1.3.

View utilities

sublime_lib.new_view(window, **kwargs)

Open a new view in the given window, returning the View object.

This function takes many optional keyword arguments:

Parameters
  • content – Text to be inserted into the new view. The text will be inserted even if the read_only option is True.

  • encoding – The encoding that the view should use when saving.

  • line_endings – The kind of line endings to use. The given value will be passed to LineEnding.

  • name – The name of the view. This will be shown as the title of the view’s tab.

  • overwrite – If True, the view will be in overwrite mode.

  • read_only – If True, the view will be read-only.

  • scope – A scope name. The view will be assigned a syntax definition that corresponds to the given scope (as determined by get_syntax_for_scope()). Incompatible with the syntax option.

  • scratch – If True, the view will be a scratch buffer. The user will not be prompted to save the view before closing it.

  • settings – A dictionary of names and values that will be applied to the new view’s Settings object.

  • syntax – The resource path of a syntax definition that the view will use. Incompatible with the scope option.

Raises

Changed in version 1.2: Added the line_endings argument.

sublime_lib.close_view(view, *, force=False)

Close the given view, discarding unsaved changes if force is True.

If the view is invalid (e.g. already closed), do nothing.

Raises
  • ValueError – if the view has unsaved changes and force is not True.

  • ValueError – if the view is not closed for any other reason.

class sublime_lib.LineEnding(*args, **kwargs)

An Enum of line endings supported by Sublime Text.

The LineEnding constructor accepts either the case-insensitive name (e.g. 'unix') or the value (e.g. '\n') of a line ending.

Unix = '\n'
Windows = '\r\n'
CR = '\r'

New in version 1.2.

Window utilities

sublime_lib.new_window(*, menu_visible=None, sidebar_visible=None, tabs_visible=None, minimap_visible=None, status_bar_visible=None, project_data=None)

Open a new window, returning the Window object.

This function takes many optional keyword arguments:

Parameters
  • menu_visible – Show the menubar. New windows show the menubar by default. On the Mac OS, this argument has no effect.

  • sidebar_visible – Show the sidebar. The sidebar will only be shown if the window’s project data has at least one folder.

  • tabs_visible – Show the tab bar. If the tab bar is hidden, it will not be shown even if there are multiple tabs.

  • minimap_visible – Show the minimap.

  • status_bar_visible – Show the status bar.

  • project_data – Project data for the window, such as folders. See the .sublime_project documentation for details.

This function currently does not provide a way to associate a window with a .sublime_project file.

Raises

RuntimeError – if the window is not created for any reason.

New in version 1.2.

sublime_lib.close_window(window, *, force=False)

Close the given window, discarding unsaved changes if force is True.

Raises

ValueError – if any view in the window has unsaved changes and force is not True.

New in version 1.2.

sublime_lib.show_selection_panel(window, items, *, flags=0, labels=None, selected=NO_SELECTION, on_select=None, on_cancel=None, on_highlight=None)

Open a quick panel in the given window to select an item from a list.

Parameters
  • window – The sublime.Window in which to show the panel.

  • items – A nonempty Sequence (such as a list) of items to choose from.

Optional keyword arguments:

Parameters
  • flags – A sublime_lib.flags.QuickPanelOption, a value convertible to QuickPanelOption, or an iterable of such values.

  • labels

    A value determining what to show as the label for each item:

    • If labels is None (the default), then use items.

    • If labels is callable, then use map(labels, items).

    • Otherwise, use labels.

    The result should be a Sequence of labels. Every label must be a single item (a string or convertible with str()) or a Sequence of items. In the latter case, each entry in the quick panel will show multiple rows.

  • selected

    The value in items that will be initially selected.

    If selected is sublime_lib.NO_SELECTION (the default), then Sublime will determine the initial selection.

  • on_select – A callback accepting a value from items to be invoked when the user chooses an item.

  • on_cancel – A callback that will be invoked with no arguments if the user closes the panel without choosing an item.

  • on_highlight – A callback accepting a value from items to be invoked every time the user changes the highlighted item in the panel.

Raises

New in version 1.2.

Changed in version 1.3: labels can be a mixture of strings and string sequences of uneven length.

flags can be any value or values convertible to QuickPanelOption.

Syntax utilities

sublime_lib.list_syntaxes()

Return a list of all loaded syntax definitions.

Each item is a namedtuple with the following properties:

path

The resource path to the syntax definition file.

name

The display name of the syntax definition.

scope

The top-level scope of the syntax.

hidden

Whether the syntax will appear in the syntax menus and the command palette.

sublime_lib.get_syntax_for_scope(scope)

Returns the last syntax in load order that matches scope.

Activity indicator

class sublime_lib.ActivityIndicator(target, label=None)

An animated text-based indicator to show that some activity is in progress.

The target argument should be a sublime.View or sublime.Window. The indicator will be shown in the status bar of that view or window. If label is provided, then it will be shown next to the animation.

ActivityIndicator can be used as a context manager.

New in version 1.4.

start()

Start displaying the indicator and animate it.

Raises

ValueError – if the indicator is already running.

stop()

Stop displaying the indicator.

If the indicator is not running, do nothing.

Region manager

class sublime_lib.RegionManager(view, key=None, *, scope=None, icon=None, flags=None)

A manager for regions in a given sublime.View with the same key.

If key is not given, a unique identifier will be used.

If the scope, icon, and flags args are given, then they will be used as default values for set().

When the region manager is garbage-collected, all managed regions will be erased.

New in version 1.4.

set(regions, *, scope=None, icon=None, flags=None)

Replace managed regions with the given regions.

If the scope, icon, and flags arguments are given, then they will be passed to sublime.add_regions(). Otherwise, the defaults specified in the initializer will be used.

get()

Return the list of managed regions.

erase()

Erase all managed regions.

encodings submodule

sublime_lib.encodings.from_sublime(name)

Translate name from a Sublime encoding name to a standard Python encoding name.

Raises

ValueError – if name is not a Sublime encoding.

>>> from_sublime("Western (Windows 1252)")
"cp1252"

Changed in version 1.3: Raise ValueError if name is not a Sublime encoding.

sublime_lib.encodings.to_sublime(name)

Translate name from a standard Python encoding name to a Sublime encoding name.

Raises

ValueError – if name is not a Python encoding.

>>> to_sublime("cp1252")
"Western (Windows 1252)"

Changed in version 1.3: Raise ValueError if name is not a Python encoding.

flags submodule

Python enumerations for use with Sublime API methods.

In addition to the standard behavior, these enumerations’ constructors accept the name of an enumerated value as a string:

>>> DialogResult(sublime.DIALOG_YES)
<DialogResult.YES: 1>
>>> DialogResult("YES")
<DialogResult.YES: 1>

Descendants of IntFlag accept zero or more arguments:

>>> PointClass("WORD_START", "WORD_END")
<PointClass.WORD_END|WORD_START: 3>
>>> PointClass(3)
<PointClass.WORD_END|WORD_START: 3>
>>> PointClass()
<PointClass.0: 0>

Changed in version 1.2: Constructors accept member names and IntFlag constructors accept multiple arguments.

class sublime_lib.flags.DialogResult(value, names=None, *, module=None, qualname=None, type=None, start=1)

An IntEnum for use with sublime.yes_no_cancel_dialog().

CANCEL = sublime.DIALOG_CANCEL
YES = sublime.DIALOG_YES
NO = sublime.DIALOG_NO
class sublime_lib.flags.PointClass(*args, **kwargs)

An IntFlag for use with several methods of sublime.View:

  • classify()

  • find_by_class()

  • expand_by_class()

WORD_START = sublime.CLASS_WORD_START
WORD_END = sublime.CLASS_WORD_END
PUNCTUATION_START = sublime.CLASS_PUNCTUATION_START
PUNCTUATION_END = sublime.CLASS_PUNCTUATION_END
SUB_WORD_START = sublime.CLASS_SUB_WORD_START
SUB_WORD_END = sublime.CLASS_SUB_WORD_END
LINE_START = sublime.CLASS_LINE_START
LINE_END = sublime.CLASS_LINE_END
EMPTY_LINE = sublime.CLASS_EMPTY_LINE
class sublime_lib.flags.FindOption(*args, **kwargs)

An IntFlag for use with several methods of sublime.View:

  • find()

  • find_all()

LITERAL = sublime.LITERAL
IGNORECASE = sublime.IGNORECASE
class sublime_lib.flags.RegionOption(*args, **kwargs)

An IntFlag for use with sublime.View.add_regions().

DRAW_EMPTY = sublime.DRAW_EMPTY
HIDE_ON_MINIMAP = sublime.HIDE_ON_MINIMAP
DRAW_EMPTY_AS_OVERWRITE = sublime.DRAW_EMPTY_AS_OVERWRITE
DRAW_NO_FILL = sublime.DRAW_NO_FILL
DRAW_NO_OUTLINE = sublime.DRAW_NO_OUTLINE
DRAW_SOLID_UNDERLINE = sublime.DRAW_SOLID_UNDERLINE
DRAW_STIPPLED_UNDERLINE = sublime.DRAW_STIPPLED_UNDERLINE
DRAW_SQUIGGLY_UNDERLINE = sublime.DRAW_SQUIGGLY_UNDERLINE
PERSISTENT = sublime.PERSISTENT
HIDDEN = sublime.HIDDEN
class sublime_lib.flags.PopupOption(*args, **kwargs)

An IntFlag for use with sublime.View.show_popup().

COOPERATE_WITH_AUTO_COMPLETE = sublime.COOPERATE_WITH_AUTO_COMPLETE
HIDE_ON_MOUSE_MOVE = sublime.HIDE_ON_MOUSE_MOVE
HIDE_ON_MOUSE_MOVE_AWAY = sublime.HIDE_ON_MOUSE_MOVE_AWAY
class sublime_lib.flags.PhantomLayout(*args, **kwargs)

An IntFlag for use with sublime.Phantom.

INLINE = sublime.LAYOUT_INLINE
BELOW = sublime.LAYOUT_BELOW
BLOCK = sublime.LAYOUT_BLOCK
class sublime_lib.flags.OpenFileOption(*args, **kwargs)

An IntFlag for use with sublime.Window.open_file().

ENCODED_POSITION = sublime.ENCODED_POSITION
TRANSIENT = sublime.TRANSIENT
FORCE_GROUP = sublime.FORCE_GROUP
class sublime_lib.flags.QuickPanelOption(*args, **kwargs)

An IntFlag for use with sublime.Window.show_quick_panel().

MONOSPACE_FONT = sublime.MONOSPACE_FONT
KEEP_OPEN_ON_FOCUS_LOST = sublime.KEEP_OPEN_ON_FOCUS_LOST
class sublime_lib.flags.HoverLocation(value, names=None, *, module=None, qualname=None, type=None, start=1)

An IntEnum for use with sublime_plugin.EventListener.on_hover().

New in version 1.4.

TEXT = sublime.HOVER_TEXT
GUTTER = sublime.HOVER_GUTTER
MARGIN = sublime.HOVER_MARGIN
class sublime_lib.flags.QueryContextOperator(value, names=None, *, module=None, qualname=None, type=None, start=1)

An IntEnum for use with sublime_plugin.EventListener.on_query_context().

New in version 1.4.

apply(value, operand)

Apply the operation to the given values.

For regexp operators, operand should contain the regexp to be tested against the string value.

Example usage:

import sublime_plugin
from sublime_lib.flags import QueryContextOperator

class MyListener(sublime_plugin.EventListener):
    def on_query_context(self, view, key, operator, operand, match_all):
        if key == "my_example_key":
            value = get_some_value()
            return QueryContextOperator(operator).apply(value, operand)
        else:
            return None
EQUAL = sublime.OP_EQUAL
NOT_EQUAL = sublime.OP_NOT_EQUAL
REGEX_MATCH = sublime.OP_REGEX_MATCH
NOT_REGEX_MATCH = sublime.OP_NOT_REGEX_MATCH
REGEX_CONTAINS = sublime.OP_REGEX_CONTAINS
NOT_REGEX_CONTAINS = sublime.OP_NOT_REGEX_CONTAINS
class sublime_lib.flags.CompletionOptions(*args, **kwargs)

An IntFlag for use with sublime_plugin.EventListener.on_query_completions().

New in version 1.4.

INHIBIT_WORD_COMPLETIONS = sublime.INHIBIT_WORD_COMPLETIONS
INHIBIT_EXPLICIT_COMPLETIONS = sublime.INHIBIT_EXPLICIT_COMPLETIONS