Creating new powerline extension

Powerline extension is a code that tells powerline how to highlight and display segments in some set of applications. Specifically this means

  1. Creating a powerline.Powerline subclass that knows how to obtain local configuration overrides. It also knows how to load local themes, but not when to apply them.

    Instance of this class is the only instance that interacts directly with bindings code, so it has a proxy powerline.Powerline.render() and powerline.Powerline.shutdown() methods and other methods which may be useful for bindings.

    This subclass must be placed directly in powerline directory (e.g. in powerline/vim.py) and named like VimPowerline (version of the file name without directory and extension and first capital letter + Powerline). There is no technical reason for naming classes like this.

  2. Creating a powerline.renderer.Renderer subclass that knows how to highlight a segment or reset highlighting to the default value (only makes sense in prompts). It is also responsible for selecting local themes and computing text width.

    This subclass must be placed directly in powerline/renderers directory (for powerline extensions developed for a set of applications use powerline/renderers/ext/*.py) and named like ExtRenderer or AppPromptRenderer. For technical reasons the class itself must be referenced in renderer module attribute thus allowing only one renderer per one module.

  3. Creating an extension bindings. These are to be placed in powerline/bindings/ext and may contain virtually anything which may be required for powerline to work inside given applications, assuming it does not fit in other places.

Powerline class

class powerline.Powerline(*args, **kwargs)[source]

Main powerline class, entrance point for all powerline uses. Sets powerline up and loads the configuration.

Parameters:
  • ext (str) – extension used. Determines where configuration files will searched and what renderer module will be used. Affected: used ext dictionary from powerline/config.json, location of themes and colorschemes, render module (powerline.renders.{ext}).

  • renderer_module (str) – Overrides renderer module (defaults to ext). Should be the name of the package imported like this: powerline.renderers.{render_module}. If this parameter contains a dot powerline.renderers. is not prepended. There is also a special case for renderers defined in toplevel modules: foo. (note: dot at the end) tries to get renderer from module foo (because foo (without dot) tries to get renderer from module powerline.renderers.foo). When .foo (with leading dot) variant is used renderer_module will be powerline.renderers.{ext}{renderer_module}.

  • run_once (bool) – Determines whether render() method will be run only once during python session.

  • logger (Logger) – If present no new logger will be created and the provided logger will be used.

  • use_daemon_threads (bool) – When creating threads make them daemon ones.

  • shutdown_event (Event) – Use this Event as shutdown_event instead of creating new event.

  • config_loader (ConfigLoader) – Instance of the class that manages (re)loading of the configuration.

create_logger()[source]

Create logger

This function is used to create logger unless it was already specified at initialization.

Returns:

Three objects:

  1. logging.Logger instance.

  2. PowerlineLogger instance.

  3. Function, output of gen_module_attr_getter().

create_renderer(load_main=False, load_colors=False, load_colorscheme=False, load_theme=False)[source]

(Re)create renderer object. Can be used after Powerline object was successfully initialized. If any of the below parameters except load_main is True renderer object will be recreated.

Parameters:
  • load_main (bool) – Determines whether main configuration file (config.json) should be loaded. If appropriate configuration changes implies load_colorscheme and load_theme and recreation of renderer object. Won’t trigger recreation if only unrelated configuration changed.

  • load_colors (bool) – Determines whether colors configuration from colors.json should be (re)loaded.

  • load_colorscheme (bool) – Determines whether colorscheme configuration should be (re)loaded.

  • load_theme (bool) – Determines whether theme configuration should be reloaded.

static do_setup()[source]

Function that does initialization

Should be overridden by subclasses. May accept any number of regular or keyword arguments.

static get_config_paths()[source]

Get configuration paths.

Should be overridden in subclasses in order to provide a way to override used paths.

Returns:

list of paths

static get_encoding()

Get encoding used by the current application

Usually returns encoding of the current locale.

static get_local_themes(local_themes)[source]

Get local themes. No-op here, to be overridden in subclasses if required.

Parameters:

local_themes (dict) – Usually accepts {matcher_name : theme_name}. May also receive None in case there is no local_themes configuration.

Returns:

anything accepted by self.renderer.get_theme and processable by self.renderer.add_local_theme. Renderer module is determined by __init__ arguments, refer to its documentation.

init(ext, renderer_module=None, run_once=False, logger=None, use_daemon_threads=True, shutdown_event=None, config_loader=None)[source]

Do actual initialization.

__init__ function only stores the arguments and runs this function. This function exists for powerline to be able to reload itself: it is easier to make __init__ store arguments and call overridable init than tell developers that each time they override Powerline.__init__ in subclasses they must store actual arguments.

load_colors_config()[source]

Get colorscheme.

Returns:

dictionary with colors configuration.

load_colorscheme_config(name)[source]

Get colorscheme.

Parameters:

name (str) – Name of the colorscheme to load.

Returns:

dictionary with colorscheme configuration.

load_config(cfg_path, cfg_type)[source]

Load configuration and setup watches

Parameters:
  • cfg_path (str) – Path to the configuration file without any powerline configuration directory or .json suffix.

  • cfg_type (str) – Configuration type. May be one of main (for config.json file), colors, colorscheme, theme.

Returns:

dictionary with loaded configuration.

load_main_config()[source]

Get top-level configuration.

Returns:

dictionary with top-level configuration.

load_theme_config(name)[source]

Get theme configuration.

Parameters:

name (str) – Name of the theme to load.

Returns:

dictionary with theme configuration

reload()[source]

Reload powerline after update.

Should handle most (but not all) powerline updates.

Purges out all powerline modules and modules imported by powerline for segment and matcher functions. Requires defining setup function that updates reference to main powerline object.

Warning

Not guaranteed to work properly, use it at your own risk. It may break your python code.

render(*args, **kwargs)[source]

Update/create renderer if needed and pass all arguments further to self.renderer.render().

render_above_lines(*args, **kwargs)[source]

Like .render(), but for self.renderer.render_above_lines()

setup(*args, **kwargs)[source]

Setup the environment to use powerline.

Must not be overridden by subclasses. This one only saves setup arguments for reload() method and calls do_setup().

setup_components(components)[source]

Run component-specific setup

Parameters:

components (set) – Set of the enabled components or None.

Should be overridden by subclasses.

shutdown(set_event=True)[source]

Shut down all background threads.

Parameters:

set_event (bool) –

Set shutdown_event and call renderer.shutdown which should shut down all threads. Set it to False unless you are exiting an application.

If set to False this does nothing more then resolving reference cycle powerline config_loader bound methods powerline by unsubscribing from config_loader events.

update_renderer()[source]

Updates/creates a renderer if needed.

Renderer class

class powerline.renderer.Renderer(theme_config, local_themes, theme_kwargs, pl, ambiwidth=1, **options)[source]

Object that is responsible for generating the highlighted string.

Parameters:
  • theme_config (dict) – Main theme configuration.

  • local_themes – Local themes. Is to be used by subclasses from .get_theme() method, base class only records this parameter to a .local_themes attribute.

  • theme_kwargs (dict) – Keyword arguments for Theme class constructor.

  • pl (PowerlineLogger) – Object used for logging.

  • ambiwidth (int) – Width of the characters with east asian width unicode attribute equal to A (Ambiguous).

  • options (dict) – Various options. Are normally not used by base renderer, but all options are recorded as attributes.

do_render(mode, width, side, line, output_raw, output_width, segment_info, theme, hl_args)[source]

Like Renderer.render(), but accept theme in place of matcher_info

escape(string)[source]

Method that escapes segment contents.

get_segment_info(segment_info, mode)[source]

Get segment information.

Must return a dictionary containing at least home, environ and getcwd keys (see documentation for segment_info attribute). This implementation merges segment_info dictionary passed to .render() method with .segment_info attribute, preferring keys from the former. It also replaces getcwd key with function returning segment_info['environ']['PWD'] in case PWD variable is available.

Parameters:

segment_info (dict) – Segment information that was passed to .render() method.

Returns:

dict with segment information.

get_theme(matcher_info)[source]

Get Theme object.

Is to be overridden by subclasses to support local themes, this variant only returns .theme attribute.

Parameters:

matcher_info – Parameter matcher_info that .render() method received. Unused.

hl(contents, fg=None, bg=None, attrs=None, **kwargs)[source]

Output highlighted chunk.

This implementation just outputs hlstyle() joined with contents.

static hl_join(iterable, /)

Join a list of rendered segments into a resulting string

This method exists to deal with non-string render outputs, so segments may actually be not an iterable with strings.

Parameters:

segments (list) – Iterable containing rendered segments. By “rendered segments” Renderer.hl() output is meant.

Returns:

Results of joining these segments.

hlstyle(bg=None, attrs=None, **kwargs)[source]

Output highlight style string.

Assuming highlighted string looks like {style}{contents} this method should output {style}. If it is called without arguments this method is supposed to reset style to its default.

render(mode=None, width=None, side=None, line=0, output_raw=False, output_width=False, segment_info=None, matcher_info=None, hl_args=None)[source]

Render all segments.

When a width is provided, low-priority segments are dropped one at a time until the line is shorter than the width, or only segments with a negative priority are left. If one or more segments with "width": "auto" are provided they will fill the remaining space until the desired width is reached.

Parameters:
  • mode (str) – Mode string. Affects contents (colors and the set of segments) of rendered string.

  • width (int) – Maximum width text can occupy. May be exceeded if there are too much non-removable segments.

  • side (str) – One of left, right. Determines which side will be rendered. If not present all sides are rendered.

  • line (int) – Line number for which segments should be obtained. Is counted from zero (botmost line).

  • output_raw (bool) – Changes the output: if this parameter is True then in place of one string this method outputs a pair (colored_string, colorless_string).

  • output_width (bool) – Changes the output: if this parameter is True then in place of one string this method outputs a pair (colored_string, string_width). Returns a three-tuple if output_raw is also True: (colored_string, colorless_string, string_width).

  • segment_info (dict) – Segment information. See also get_segment_info() method.

  • matcher_info – Matcher information. Is processed in get_segment_info() method.

  • hl_args (dict) – Additional arguments to pass on the hl() and :py:meth`hlstyle` methods. They are ignored in the default implementation, but renderer-specific overrides can make use of them as run-time “configuration” information.

render_above_lines(**kwargs)[source]

Render all segments in the {theme}/segments/above list

Rendering happens in the reversed order. Parameters are the same as in .render() method.

Yield:

rendered line.

segment_info = {'environ': <environ dictionary>, 'getcwd': <built-in function getcwd>, 'home': <home directory>}

Basic segment info

Is merged with local segment information by get_segment_info() method. Keys:

environ

Object containing environment variables. Must define at least the following methods: .__getitem__(var) that raises KeyError in case requested environment variable is not present, .get(var, default=None) that works like dict.get and be able to be passed to Popen.

getcwd

Function that returns current working directory. Will be called without any arguments, should return unicode or (in python-2) regular string.

home

String containing path to home directory. Should be unicode or (in python-2) regular string or None.

shutdown()[source]

Prepare for interpreter shutdown. The only job it is supposed to do is calling .shutdown() method for all theme objects. Should be overridden by subclasses in case they support local themes.

strwidth(s)

Function that returns string width.

Is used to calculate the place given string occupies when handling width argument to .render() method. Must take east asian width into account.

Parameters:

string (unicode) – String whose width will be calculated.

Returns:

unsigned integer.