Writing segments¶
Each powerline segment is a callable object. It is supposed to be either
a Python function or powerline.segments.Segment class. As a callable
object it should receive the following arguments:
Note
All received arguments are keyword arguments.
plA
powerline.PowerlineLoggerinstance. It must be used every time something needs to be logged.segment_infoA dictionary. It is only received if callable has
powerline_requires_segment_infoattribute.Refer to segment_info detailed description for further details.
create_watcherFunction that will create filesystem watcher once called. Which watcher will be created exactly is controlled by watcher configuration option.
And also any other argument(s) specified by user in args key (no additional arguments by default).
Note
For powerline-lint to work properly the following things may be needed:
If segment is a
powerline.segments.Segmentinstance and used arguments are scattered over multiple methodspowerline.segments.Segment.argspecobjs()should be overridden in subclass to tell powerline-lint which objects should be inspected for arguments.If segment takes some arguments that are never listed, but accessed via
kwargs.get()or previous function cannot be used for whatever reasonpowerline.segments.Segment.additional_args()should be overridden in subclass.If user is expected to use one name for multiple segments which cannot be linked to the segment function automatically by powerline-lint (e.g. because there are no instances of the segments in question in the default configuration)
powerline.lint.checks.register_common_name()function should be used.
Object representing segment may have the following attributes used by powerline:
powerline_requires_segment_infoThis attribute controls whether segment will receive
segment_infoargument: if it is present argument will be received.powerline_requires_filesystem_watcherThis attribute controls whether segment will receive
create_watcherargument: if it is present argument will be received.powerline_segment_datasThis attribute must be a dictionary containing
top_theme: segment_datamapping wheretop_themeis any theme name (it is expected that all of the names from top-level themes list are present) andsegment_datais a dictionary like the one that is contained inside segment_data dictionary in configuration. This attribute should be used to specify default theme-specific values for third-party segments: powerline theme-specific values go directly to top-level themes.
startupThis attribute must be a callable which accepts the following keyword arguments:
pl:powerline.PowerlineLoggerinstance which is to be used for logging.shutdown_event:Eventobject which will be set when powerline will be shut down.Any arguments found in user configuration for the given segment (i.e. args key).
This function is called at powerline startup when using long-running processes (e.g. powerline in vim, in zsh with libzpython, in ipython or in powerline daemon) and not called when
powerline-renderexecutable is used (more specific: whenpowerline.Powerlineconstructor received truerun_onceargument).
shutdownThis attribute must be a callable that accepts no arguments and shuts down threads and frees any other resources allocated in
startupmethod of the segment in question.This function is not called when
startupmethod is not called.
expandThis attribute must be a callable that accepts the following keyword arguments:
pl:powerline.PowerlineLoggerinstance which is to be used for logging.amount: integer number representing amount of display cells result must occupy.Warning
“Amount of display cells” is not number of Unicode codepoints, string length, or byte count. It is suggested that this function should look something like
return (' ' * amount) + segment['contents']where' 'may be replaced with anything that is known to occupy exactly one display cell.segment: segment dictionary.Any arguments found in user configuration for the given segment (i.e. args key).
It must return new value of contents key.
truncateLike expand function, but for truncating segments. Here
amountmeans the number of display cells which must be freed.This function is called for all segments before powerline starts purging them to free space.
This callable object should may return either a string (unicode in Python2
or str in Python3, not str in Python2 or bytes in Python3) object
or a list of dictionaries. String object is a short form of the following return
value:
[{
'contents': original_return,
'highlight_groups': [segment_name],
}]
Returned list is a list of segments treated independently, except for draw_inner_divider key.
All keys in segments returned by the function override those obtained from configuration and have the same meaning.
Detailed description of used dictionary keys:
contentsText displayed by segment. Should be a
unicode(Python2) orstr(Python3) instance.literal_contentsText that needs to be output literally (i.e. without passing through
powerline.renderer.strwidth()to determine length, throughpowerline.renderer.escape()to escape special characters and throughpowerline.renderer.hl()to highlight it). Should be a tuple(contents_length, contents)wherecontents_lengthis an integer andcontentsis aunicode(Python2) orstr(Python3) instance.If this key is present and its second value is true then other contents keys (contents, after, before) will be ignored.
Note
If target is inclusion of the segment in powerline upstream all segment functions that output only subsegments with
literal_contentskey must contain the following string in documentation:No highlight groups are used (literal segment).
String must be present on the separate line.
draw_hard_divider,draw_soft_divider,draw_inner_dividerDetermines whether given divider should be drawn. All have the same meaning as the similar keys in configuration (draw_inner_divider).
highlight_groupsDetermines segment highlighting. Refer to themes documentation for more details.
Defaults to the name of the segment.
Note
If target is inclusion of the segment in powerline upstream all used highlighting groups must be specified in the segment documentation in the form:
Highlight groups used: ``g1``[ or ``g2``]*[, ``g3`` (gradient)[ or ``g4``]*]*.
I.e. use:
Highlight groups used: ``foo_gradient`` (gradient) or ``foo``, ``bar``.
to specify that the segment uses either
foo_gradientgroup orfoogroup andbargroup meaning thatpowerline-lintwill check that at least one of the first two groups is defined (and iffoo_gradientis defined it must use at least one gradient color) and third group is defined as well.All groups must be specified on one line.
divider_highlight_groupDetermines segment divider highlight group. Only applicable for soft dividers: colors for hard dividers are determined by colors of adjacent segments.
Note
If target is inclusion of the segment in powerline upstream used divider highlight group must be specified in the segment documentation in the form:
Divider highlight group used: ``group``. This text must not wrap and all divider highlight group names are supposed to end with ``:divider``: e.g. ``cwd:divider``.
gradient_levelFirst and the only key that may not be specified in user configuration. It determines which color should be used for this segment when one of the highlighting groups specified by highlight_groups was defined to use the color gradient.
This key may have any value from 0 to 100 inclusive, value is supposed to be an
intorfloatinstance.No error occurs if segment has this key, but no used highlight groups use gradient color.
_*Keys starting with underscore are reserved for powerline and must not be returned.
__*Keys starting with two underscores are reserved for the segment functions, specifically for expand function.
Segment dictionary¶
Segment dictionary contains the following keys:
All keys returned by segment function (if it was used).
All of the following keys:
nameSegment name: value of the name key or function name (last component of the function key). May be
None.typeSegment type. Always represents actual type and is never
None.highlight_groups,divider_highlight_groupUsed highlight groups. May be
None.highlight_group_prefixIf this key is present then given prefix will be prepended to each highlight group (both regular and divider) used by this segment in a form
{prefix}:{group}(note the colon). This key is mostly useful for segment listers.
before,afterValue of before or after configuration options. May be
Noneas well as an empty string.contents_funcFunction used to get segment contents. May be
None.
contentsActual segment contents, excluding dividers and before/after. May be
None.prioritySegment priority. May be
Nonefor no priority (such segments are always shown).draw_soft_divider,draw_hard_divider,draw_inner_dividersideSegment side:
rightorleft.display_conditionContains function that takes three position parameters:
powerline.PowerlineLoggerinstance, segment_info dictionary and current mode and returns eitherTrueorFalseto indicate whether particular segment should be processed.This key is constructed based on exclude_/include_modes keys and exclude_/include_function keys.
width,alignWidth and align options. May be
None.expand,truncatePartially applied expand or truncate function. Accepts
pl,amountandsegmentpositional parameters, keyword parameters from args key were applied.startupPartially applied startup function. Accepts
plandshutdown_eventpositional parameters, keyword parameters from args key were applied.shutdownShutdown function. Accepts no argument.
Segments layout¶
Powerline segments are all located in one of the powerline.segments
submodules. For extension-specific segments powerline.segments.{ext} module
should be used (e.g. powerline.segments.shell), for extension-agnostic there
is powerline.segments.common.
Plugin-specific segments (currently only those that are specific to vim plugins)
should live in powerline.segments.{ext}.plugin.{plugin_name}: e.g.
powerline.segments.vim.plugin.gundo.
Segment information used in various extensions¶
Each segment_info value should be a dictionary with at least the following
keys:
environCurrent environment, may be an alias to
os.environ. Is guaranteed to have__getitem__andgetmethods and nothing more.Warning
os.environmust not ever be used:If segment is run in the daemon this way it will get daemon’s environment which is not correct.
If segment is run in Vim or in zsh with libzpython
os.environwill contain Vim or zsh environ at the moment Python interpreter was loaded.
getcwdFunction that returns current working directory being called with no arguments.
os.getcwdmust not be used for the same reasons the use ofos.environis forbidden, except that current working directory is valid in Vim and zsh (but not in daemon).homeCurrent home directory. May be false.
Vim¶
Vim segment_info argument is a dictionary with the following keys:
windowvim.Windowobject.vim.current.windoworvim.windows[number - 1]may be used to obtain such object. May be a false object, in which case any of this object’s properties must not be used.winnrWindow number. Same as
segment_info['window'].numberassuming Vim is new enough forvim.Windowobject to havenumberattribute.window_idInternal powerline window id, unique for each newly created window. It is safe to assume that this ID is hashable and supports equality comparison, but no other assumptions about it should be used. Currently uses integer numbers incremented each time window is created.
buffervim.Bufferobject. One may be obtained usingvim.current.buffer,segment_info['window'].bufferorvim.buffers[some_number]. Note that in the latter case depending on vim versionsome_numbermay bebufnror the internal Vim buffer index which is not buffer number. For this reason to getvim.Bufferobject other then stored insegment_infodictionary iteration overvim.buffersand checking theirnumberattributes should be performed.bufnrBuffer number.
tabpagevim.Tabpageobject. One may be obtained usingvim.current.tabpageorvim.tabpages[number - 1]. May be a false object, in which case no object’s properties can be used.tabnrTabpage number.
modeCurrent mode.
encodingValue of
&encodingfrom the time when powerline was initialized. It should be used to convert return values.
Note
Segment generally should not assume that it is run for the current window,
current buffer or current tabpage. “Current window” and “current buffer”
restrictions may be ignored if window_cached decorator is used, “current
tabpage” restriction may be safely ignored if segment is not supposed to be
used in tabline.
Warning
Powerline is being tested with vim-7.0.112 (some minor sanity check) and
latest Vim. This means that most of the functionality like
vim.Window.number, vim.*.vars, vim.*.options or even dir(vim
object) should be avoided in segments that want to be included in the
upstream.
Shell¶
argsParsed shell arguments: a
argparse.Namespaceobject. Check outpowerline-render --helpfor the list of all available arguments. Currently it is expected to contain at least the following attributes:last_exit_codeExit code returned by last shell command. Is either one integer,
sig{name}orsig{name}+core(latter two are only seen inrcshell).last_pipe_statusList of exit codes returned by last programs in the pipe or some false object. Only available in
zshandrc. Is a list of either integers,sig{name}orsig{name}+core(latter two are only seen inrcshell).jobnumNumber of background jobs.
renderer_argDictionary containing some keys that are additional arguments used by shell bindings. This attribute must not be used directly: all arguments from this dictionary are merged with
segment_infodictionary. Known to have at least the following keys:client_idIdentifier unique to one shell instance. Is used to record instance state by powerline daemon. In tmux this is the same as pane_id.
It is not guaranteed that existing client ID will not be retaken when old shell with this ID quit: usually process PID is used as a client ID.
It is also not guaranteed that client ID will be process PID, number or something else at all. It is guaranteed though that client ID will be some hashable object which supports equality comparison.
local_themeLocal theme that will be used by shell. One should not rely on the existence of this key.
pane_idIdentifier unique to each tmux pane. Is always an integer, optional. Obtained by using
tmux display -p '#D', then all leading spaces and per cent signs are stripped and the result is converted into an integer.
Other keys, if any, are specific to segments.
Ipython¶
ipythonSome object which has
prompt_countattribute. Currently it is guaranteed to have only this attribute.Attribute
prompt_countcontains the so-called “history count” (equivalent to\Ninin_template).
Pdb¶
pdbCurrently active
pdb.Pdbinstance.curframeFrame which will be run next. Note: due to the existence of
powerline.listers.pdb.frame_lister()one must not usesegment_info['pdb'].curframe.initial_stack_lengthEqual to the length of
pdb.Pdb.stackat the first invocation of the prompt decremented by one.
i3wm¶
modeCurrently active i3 mode (as a string).
outputxrandroutput name currently drawing to. Currently only available in lemonbar bindings.workspacethe i3-ipc workspace object corresponding to this workspace. Contains string attributes
nameandoutput, as well as boolean attributes forvisible,urgentandfocused. Currently onlyprovided by the
powerline.listers.i3wm.workspace_lister()lister.
Segment class¶
- class powerline.segments.Segment[source]¶
Base class for any segment that is not a function
Required for powerline.lint.inspect to work properly: it defines methods for omitting existing or adding new arguments.
Note
Until python-3.4
inspect.getargspecdoes not support querying callable classes for arguments of their__call__method, requiring to use this method directly (i.e. before 3.4 you should writegetargspec(obj.__call__)in place ofgetargspec(obj)).- static additional_args()[source]¶
Returns a list of (additional argument name[, default value]) tuples.
PowerlineLogger class¶
- class powerline.PowerlineLogger(use_daemon_threads, logger, ext)[source]¶
Proxy class for logging.Logger instance
It emits messages in format
{ext}:{prefix}:{message}where{ext}is a used powerline extension (e.g. “vim”, “shell”, “ipython”).
{prefix}is a local prefix, usually a segment name.
{message}is the original message passed to one of the logging methods.
Each of the methods (
critical,exception,info,error,warn,debug) expects to receive message in anstr.formatformat, not in printf-like format.Log is saved to the location specified by user.