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/ 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 (if you are creating powerline extension 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.

  • 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 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_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.

  • 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.
default_log_stream = <open file '<stdout>', mode 'w' at 0x7f06560ea150>

Default stream for default log handler

Usually it is sys.stderr, but there is sometimes a reason to prefer sys.stdout or a custom file-like object. It is not supposed to be used to write to some file.

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 overriddable init than tell developers that each time they override Powerline.__init__ in subclasses they must store actual arguments.


Get colorscheme.

Returns:dictionary with colors configuration.

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

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

dictionary with loaded configuration.


Get top-level configuration.

Returns:dictionary with top-level configuration.

Get theme configuration.

Parameters:name (str) – Name of the theme to load.
Returns:dictionary with theme configuration

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.


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().


Run component-specific setup

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

Should be overridden by subclasses.


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.


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.

  • 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 (Ambigious).
  • options (dict) – Various options. Are normally not used by base renderer, but all options are recorded as attributes.
character_translations = {}

Character translations for use in escape() function.

See documentation of unicode.translate for details.

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

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


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 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, attr=None)[source]

Output highlighted chunk.

This implementation just outputs .hlstyle() joined with contents.

hlstyle(fg=None, bg=None, attr=None)[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.

np_character_translations = {0: u'^@', 1: u'^A', 2: u'^B', 3: u'^C', 4: u'^D', 5: u'^E', 6: u'^F', 7: u'^G', 8: u'^H', 9: u'^I', 10: u'^J', 11: u'^K', 12: u'^L', 13: u'^M', 14: u'^N', 15: u'^O', 16: u'^P', 17: u'^Q', 18: u'^R', 19: u'^S', 20: u'^T', 21: u'^U', 22: u'^V', 23: u'^W', 24: u'^X', 25: u'^Y', 26: u'^Z', 27: u'^[', 28: u'^\\', 29: u'^]', 30: u'^^', 31: u'^_'}

Non-printable character translations

These are used to transform characters in range 0x00—0x1F into ^@, ^A and so on. Unilke with .escape() method (and character_translations) result is passed to .strwidth() method.

Note: transforms tab into ^I.

render(mode=None, width=None, side=None, line=0, output_raw=False, output_width=False, segment_info=None, matcher_info=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.

  • 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_theme() method.

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 = {u'getcwd': <built-in function getcwdu>, u'environ': {'LESSOPEN': '| /usr/bin/lesspipe %s', 'CELERY_LOG_REDIRECT_LEVEL': 'WARNING', 'NEW_RELIC_CONFIG_FILE': '/home/docs/newrelic.ini', 'SSH_CLIENT': ' 15214 22', 'CELERY_LOG_REDIRECT': '1', 'LOGNAME': 'docs', 'USER': 'docs', 'PATH': '/home/docs/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games', 'HOME': '/home/docs', 'PS1': '(docs)\\[\\e]0;\\u@\\h: \\w\\a\\]${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ ', 'LANG': 'en_US.UTF-8', 'TERM': 'xterm', 'SHELL': '/bin/bash', 'TZ': 'America/Chicago', '_MP_FORK_LOGFORMAT_': '[%(asctime)s: %(levelname)s/%(processName)s] %(message)s', 'SHLVL': '1', 'SUPERVISOR_ENABLED': '1', 'CELERY_LOG_FILE': '/home/docs/log/celery_proc.log', 'DJANGO_PROJECT_DIR': '/home/docs/checkouts/', 'EDITOR': 'vim', 'XDG_RUNTIME_DIR': '/run/user/1001', 'READTHEDOCS': 'True', 'VIRTUAL_ENV': '/home/docs', 'CELERY_LOADER': 'djcelery.loaders.DjangoLoader', '_MP_FORK_LOGLEVEL_': '20', 'SUPERVISOR_SERVER_URL': 'unix:///home/docs/run/supervisord-docs.sock', 'XDG_SESSION_ID': '237', '_': '/home/docs/bin/supervisord', '_MP_FORK_LOGFILE_': '/home/docs/log/celery_proc.log', 'SSH_CONNECTION': ' 15214 22', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'SUPERVISOR_PROCESS_NAME': 'celery', 'SSH_TTY': '/dev/pts/5', 'OLDPWD': '/home/docs', 'PWD': '/var/build/user_builds/powerline/checkouts/1.1/docs/source', 'MAIL': '/var/mail/docs', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:', 'CELERY_LOG_LEVEL': '20', 'SUPERVISOR_GROUP_NAME': 'celery'}, u'home': '/home/docs'}

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

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.
Function that returns current working directory. Will be called without any arguments, should return unicode or (in python-2) regular string.
String containing path to home directory. Should be unicode or (in python-2) regular string or None.

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.


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.