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
Creating a
powerline.Powerlinesubclass 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()andpowerline.Powerline.shutdown()methods and other methods which may be useful for bindings.This subclass must be placed directly in
powerlinedirectory (e.g. inpowerline/vim.py) and named likeVimPowerline(version of the file name without directory and extension and first capital letter +Powerline). There is no technical reason for naming classes like this.Creating a
powerline.renderer.Renderersubclass 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/renderersdirectory (for powerline extensions developed for a set of applications usepowerline/renderers/ext/*.py) and named likeExtRendererorAppPromptRenderer. For technical reasons the class itself must be referenced inrenderermodule attribute thus allowing only one renderer per one module.Creating an extension bindings. These are to be placed in
powerline/bindings/extand 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
extdictionary frompowerline/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 dotpowerline.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 modulefoo(becausefoo(without dot) tries to get renderer from modulepowerline.renderers.foo). When.foo(with leading dot) variant is usedrenderer_modulewill bepowerline.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:
logging.Loggerinstance.PowerlineLoggerinstance.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_mainis True renderer object will be recreated.- Parameters:
load_main (bool) – Determines whether main configuration file (
config.json) should be loaded. If appropriate configuration changes impliesload_colorschemeandload_themeand recreation of renderer object. Won’t trigger recreation if only unrelated configuration changed.load_colors (bool) – Determines whether colors configuration from
colors.jsonshould 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_themeand processable byself.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 overridableinitthan 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
.jsonsuffix.cfg_type (str) – Configuration type. May be one of
main(forconfig.jsonfile),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
setupfunction 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 callsdo_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_eventand callrenderer.shutdownwhich 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 → powerlineby unsubscribing from config_loader events.
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_themesattribute.theme_kwargs (dict) – Keyword arguments for
Themeclass 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
- get_segment_info(segment_info, mode)[source]¶
Get segment information.
Must return a dictionary containing at least
home,environandgetcwdkeys (see documentation forsegment_infoattribute). This implementation mergessegment_infodictionary passed to.render()method with.segment_infoattribute, preferring keys from the former. It also replacesgetcwdkey with function returningsegment_info['environ']['PWD']in casePWDvariable 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
.themeattribute.- Parameters:
matcher_info – Parameter
matcher_infothat.render()method received. Unused.
- hl(contents, fg=None, bg=None, attrs=None, **kwargs)[source]¶
Output highlighted chunk.
This implementation just outputs
hlstyle()joined withcontents.
- 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
Truethen in place of one string this method outputs a pair(colored_string, colorless_string).output_width (bool) – Changes the output: if this parameter is
Truethen in place of one string this method outputs a pair(colored_string, string_width). Returns a three-tuple ifoutput_rawis alsoTrue:(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:environObject containing environment variables. Must define at least the following methods:
.__getitem__(var)that raisesKeyErrorin case requested environment variable is not present,.get(var, default=None)that works likedict.getand be able to be passed toPopen.getcwdFunction that returns current working directory. Will be called without any arguments, should return
unicodeor (in python-2) regular string.homeString containing path to home directory. Should be
unicodeor (in python-2) regular string orNone.
- 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
widthargument to.render()method. Must take east asian width into account.- Parameters:
string (unicode) – String whose width will be calculated.
- Returns:
unsigned integer.