Add docs for all segments

This commit is contained in:
Kim Silkebækken 2013-02-08 17:33:04 +01:00
parent b599761ae6
commit 2caa136f26
7 changed files with 190 additions and 21 deletions

View File

@ -13,6 +13,14 @@ Powerline
fontpatching fontpatching
license-credits license-credits
Segments
========
.. toctree::
segments/common
segments/shell
segments/vim
Indices and tables Indices and tables
================== ==================

View File

@ -0,0 +1,6 @@
***************
Common segments
***************
.. automodule:: powerline.segments.common
:members:

View File

@ -0,0 +1,6 @@
**************
Shell segments
**************
.. automodule:: powerline.segments.shell
:members:

View File

@ -0,0 +1,6 @@
************
Vim segments
************
.. automodule:: powerline.segments.vim
:members:

View File

@ -45,6 +45,11 @@ def _urllib_urlencode(string):
def hostname(only_if_ssh=False): def hostname(only_if_ssh=False):
'''Return the current hostname.
:param bool only_if_ssh:
only return the hostname if currently in an SSH session
'''
import socket import socket
if only_if_ssh and not os.environ.get('SSH_CLIENT'): if only_if_ssh and not os.environ.get('SSH_CLIENT'):
return None return None
@ -52,6 +57,10 @@ def hostname(only_if_ssh=False):
def user(): def user():
'''Return the current user.
Highlights the user with the ``superuser`` if the effective user ID is 0.
'''
user = os.environ.get('USER') user = os.environ.get('USER')
euid = os.geteuid() euid = os.geteuid()
return [{ return [{
@ -61,6 +70,7 @@ def user():
def branch(): def branch():
'''Return the current VCS branch.'''
from powerline.lib.vcs import guess from powerline.lib.vcs import guess
repo = guess(os.path.abspath(os.getcwd())) repo = guess(os.path.abspath(os.getcwd()))
if repo: if repo:
@ -69,6 +79,15 @@ def branch():
def cwd(dir_shorten_len=None, dir_limit_depth=None): def cwd(dir_shorten_len=None, dir_limit_depth=None):
'''Return the current working directory.
Returns a segment list to create a breadcrumb-like effect.
:param int dir_shorten_len:
shorten parent directory names to this length (e.g. :file:`/long/path/to/powerline` :file:`/l/p/t/powerline`)
:param int dir_limit_depth:
limit directory depth to this number (e.g. :file:`/long/path/to/powerline` :file:`/to/powerline`)
'''
import re import re
try: try:
cwd = os.getcwdu() cwd = os.getcwdu()
@ -97,16 +116,40 @@ def cwd(dir_shorten_len=None, dir_limit_depth=None):
def date(format='%Y-%m-%d'): def date(format='%Y-%m-%d'):
'''Return the current date.
:param str format:
strftime-style date format string
'''
from datetime import datetime from datetime import datetime
return datetime.now().strftime(format) return datetime.now().strftime(format)
@memoize(600) @memoize(600)
def external_ip(query_url='http://ipv4.icanhazip.com/'): def external_ip(query_url='http://ipv4.icanhazip.com/'):
'''Return external IP address.
Suggested URIs:
* http://ipv4.icanhazip.com/
* http://ipv6.icanhazip.com/
* http://icanhazip.com/ (returns IPv6 address if available, else IPv4)
:param str query_url:
URI to query for IP address, should return only the IP address as a text string
'''
return _urllib_read(query_url).strip() return _urllib_read(query_url).strip()
def uptime(format='{days:02d}d {hours:02d}h {minutes:02d}m'): def uptime(format='{days:02d}d {hours:02d}h {minutes:02d}m'):
'''Return system uptime.
Uses the ``psutil`` module if available for multi-platform compatibility,
falls back to reading :file:`/proc/uptime`.
:param str format:
format string, will be passed ``days``, ``hours`` and ``minutes`` as arguments
'''
try: try:
import psutil import psutil
from datetime import datetime from datetime import datetime
@ -125,6 +168,20 @@ def uptime(format='{days:02d}d {hours:02d}h {minutes:02d}m'):
@memoize(1800) @memoize(1800)
def weather(unit='c', location_query=None): def weather(unit='c', location_query=None):
'''Return weather from Yahoo! Weather.
Uses GeoIP lookup from http://freegeoip.net/ to automatically determine
your current location. This should be changed if you're in a VPN or if your
IP address is registered at another location.
Returns a list of colorized icon and temperature segments depending on
weather conditions.
:param str unit:
temperature unit, can be one of ``F``, ``C`` or ``K``
:param str location_query:
location query for your current location, e.g. ``oslo, norway``
'''
import json import json
if not location_query: if not location_query:
@ -164,6 +221,19 @@ def weather(unit='c', location_query=None):
def system_load(format='{avg:.1f}', threshold_good=1, threshold_bad=2): def system_load(format='{avg:.1f}', threshold_good=1, threshold_bad=2):
'''Return normalized system load average.
Highlights using ``system_load_good``, ``system_load_bad`` and
``system_load_ugly`` highlighting groups, depending on the thresholds
passed to the function.
:param str format:
format string, receives ``avg`` as an argument
:param float threshold_good:
threshold for "good load" highlighting
:param float threshold_bad:
threshold for "bad load" highlighting
'''
import multiprocessing import multiprocessing
cpu_count = multiprocessing.cpu_count() cpu_count = multiprocessing.cpu_count()
ret = [] ret = []
@ -187,6 +257,13 @@ def system_load(format='{avg:.1f}', threshold_good=1, threshold_bad=2):
def cpu_load_percent(measure_interval=.5): def cpu_load_percent(measure_interval=.5):
'''Return the average CPU load as a percentage.
Requires the ``psutil`` module.
:param float measure_interval:
interval used to measure CPU load (in seconds)
'''
try: try:
import psutil import psutil
except ImportError: except ImportError:
@ -196,6 +273,21 @@ def cpu_load_percent(measure_interval=.5):
def network_load(interface='eth0', measure_interval=1, suffix='B/s', binary_prefix=False): def network_load(interface='eth0', measure_interval=1, suffix='B/s', binary_prefix=False):
'''Return the network load.
Uses the ``psutil`` module if available for multi-platform compatibility,
falls back to reading
:file:`/sys/class/net/{interface}/statistics/{rx,tx}_bytes`.
:param str interface:
network interface to measure
:param float measure_interval:
interval used to measure the network load (in seconds)
:param str suffix:
string appended to each load string
:param bool binary_prefix:
use binary prefix, e.g. MiB instead of MB
'''
import time import time
from powerline.lib import humanize_bytes from powerline.lib import humanize_bytes
@ -229,11 +321,25 @@ def network_load(interface='eth0', measure_interval=1, suffix='B/s', binary_pref
def virtualenv(): def virtualenv():
'''Return the name of the current Python virtualenv.'''
return os.path.basename(os.environ.get('VIRTUAL_ENV', '')) or None return os.path.basename(os.environ.get('VIRTUAL_ENV', '')) or None
@memoize(60) @memoize(60)
def email_imap_alert(username, password, server='imap.gmail.com', port=993, folder='INBOX'): def email_imap_alert(username, password, server='imap.gmail.com', port=993, folder='INBOX'):
'''Return unread e-mail count for IMAP servers.
:param str username:
login username
:param str password:
login password
:param str server:
e-mail server
:param int port:
e-mail server port
:param str folder:
folder to check for e-mails
'''
import imaplib import imaplib
import re import re

View File

@ -2,11 +2,13 @@
def last_status(segment_info): def last_status(segment_info):
'''Return last exit code.'''
return str(segment_info.last_exit_code) if segment_info.last_exit_code else None return str(segment_info.last_exit_code) if segment_info.last_exit_code else None
last_status.requires_powerline_segment_info = True last_status.requires_powerline_segment_info = True
def last_pipe_status(segment_info): def last_pipe_status(segment_info):
'''Return last pipe status.'''
if any(segment_info.last_pipe_status): if any(segment_info.last_pipe_status):
return [{"contents": str(status), "highlight_group": "exit_fail" if status else "exit_success"} return [{"contents": str(status), "highlight_group": "exit_fail" if status else "exit_success"}
for status in segment_info.last_pipe_status] for status in segment_info.last_pipe_status]

View File

@ -51,11 +51,8 @@ mode_translations = {
def mode(override=None): def mode(override=None):
'''Return the current vim mode. '''Return the current vim mode.
This function returns a tuple with the shorthand mode and the mode expanded :param dict override:
into a descriptive string. The longer string can be overridden by providing dict for overriding default mode strings, e.g. ``{ 'n': 'NORM' }``
a dict with the mode and the new string::
mode = mode({ 'n': 'NORM' })
''' '''
mode = vim_funcs['mode']().decode('utf-8') mode = vim_funcs['mode']().decode('utf-8')
mode = mode_translations.get(mode, mode) mode = mode_translations.get(mode, mode)
@ -68,22 +65,38 @@ def mode(override=None):
def modified_indicator(text=u'+'): def modified_indicator(text=u'+'):
'''Return a file modified indicator.''' '''Return a file modified indicator.
:param string text:
text to display if the current buffer is modified
'''
return text if int(vim.eval('&modified')) else None return text if int(vim.eval('&modified')) else None
def paste_indicator(text='PASTE'): def paste_indicator(text='PASTE'):
'''Return a paste mode indicator.''' '''Return a paste mode indicator.
:param string text:
text to display if paste mode is enabled
'''
return text if int(vim.eval('&paste')) else None return text if int(vim.eval('&paste')) else None
def readonly_indicator(text=u''): def readonly_indicator(text=u''):
'''Return a read-only indicator.''' '''Return a read-only indicator.
:param string text:
text to display if the current buffer is read-only
'''
return text if int(vim.eval('&readonly')) else None return text if int(vim.eval('&readonly')) else None
def file_directory(shorten_home=False): def file_directory(shorten_home=False):
'''Return file directory (head component of the file path).''' '''Return file directory (head component of the file path).
:param bool shorten_home:
shorten all directories in :file:`/home/` to :file:`~user/` instead of :file:`/home/user/`.
'''
file_directory = vim_funcs['expand']('%:~:.:h') file_directory = vim_funcs['expand']('%:~:.:h')
if file_directory is None: if file_directory is None:
return None return None
@ -93,7 +106,13 @@ def file_directory(shorten_home=False):
def file_name(display_no_file=False, no_file_text='[No file]'): def file_name(display_no_file=False, no_file_text='[No file]'):
'''Return file name (tail component of the file path).''' '''Return file name (tail component of the file path).
:param bool display_no_file:
display a string if the buffer is missing a file name
:param str no_file_text:
the string to display if the buffer is missing a file name
'''
file_name = vim_funcs['expand']('%:~:.:t') file_name = vim_funcs['expand']('%:~:.:t')
if not file_name and not display_no_file: if not file_name and not display_no_file:
return None return None
@ -109,8 +128,11 @@ def file_name(display_no_file=False, no_file_text='[No file]'):
def file_size(suffix='B', binary_prefix=False): def file_size(suffix='B', binary_prefix=False):
'''Return file size. '''Return file size.
Returns None if the file isn't saved, or if the size is too :param str suffix:
big to fit in a number. string appended to the file size
:param bool binary_prefix:
use binary prefix, e.g. MiB instead of MB
:return: file size or None if the file isn't saved or if the size is too big to fit in a number
''' '''
file_name = vim_funcs['expand']('%') file_name = vim_funcs['expand']('%')
file_size = vim_funcs['getfsize'](file_name) file_size = vim_funcs['getfsize'](file_name)
@ -122,7 +144,7 @@ def file_size(suffix='B', binary_prefix=False):
def file_format(): def file_format():
'''Return file format (i.e. line ending type). '''Return file format (i.e. line ending type).
Returns None for unknown or missing file format. :return: file format or None if unknown or missing file format
''' '''
return vim.eval('&fileformat') or None return vim.eval('&fileformat') or None
@ -130,7 +152,7 @@ def file_format():
def file_encoding(): def file_encoding():
'''Return file encoding/character set. '''Return file encoding/character set.
Returns None for unknown or missing file encoding. :return: file encoding/character set or None if unknown or missing file encoding
''' '''
return vim.eval('&fileencoding') or None return vim.eval('&fileencoding') or None
@ -138,13 +160,17 @@ def file_encoding():
def file_type(): def file_type():
'''Return file type. '''Return file type.
Returns None for unknown file types. :return: file type or None if unknown file type
''' '''
return vim.eval('&filetype') or None return vim.eval('&filetype') or None
def line_percent(gradient=False): def line_percent(gradient=False):
'''Return the cursor position in the file as a percentage.''' '''Return the cursor position in the file as a percentage.
:param bool gradient:
highlight the percentage with a color gradient (by default a green to red gradient)
'''
line_current = vim_funcs['line']('.') line_current = vim_funcs['line']('.')
line_last = vim_funcs['line']('$') line_last = vim_funcs['line']('$')
percentage = int(line_current * 100 // line_last) percentage = int(line_current * 100 // line_last)
@ -164,23 +190,30 @@ def line_current():
def col_current(virtcol=True): def col_current(virtcol=True):
'''Return the current cursor column. '''Return the current cursor column.
If the optional argument is True then returns visual column with concealed :param bool virtcol:
characters ignored (default), else returns byte offset. return visual column with concealed characters ingored
''' '''
return vim_funcs['virtcol' if virtcol else 'col']('.') return vim_funcs['virtcol' if virtcol else 'col']('.')
def modified_buffers(text=u'+'): def modified_buffers(text=u'+', join_str=','):
'''Return a comma-separated list of modified buffers.''' '''Return a comma-separated list of modified buffers.
:param str text:
text to display before the modified buffer list
:param str join_str:
string to use for joining the modified buffer list
'''
buffer_len = int(vim.eval('bufnr("$")')) buffer_len = int(vim.eval('bufnr("$")'))
buffer_mod = [str(bufnr) for bufnr in range(1, buffer_len + 1) if vim.eval('getbufvar({0}, "&mod")'.format(bufnr)) == '1'] buffer_mod = [str(bufnr) for bufnr in range(1, buffer_len + 1) if vim.eval('getbufvar({0}, "&mod")'.format(bufnr)) == '1']
if buffer_mod: if buffer_mod:
return u'{0} {1}'.format(text, ','.join(buffer_mod)) return u'{0} {1}'.format(text, join_str.join(buffer_mod))
return None return None
@memoize(2) @memoize(2)
def branch(): def branch():
'''Return the current working branch.'''
repo = guess(os.path.abspath(vim.current.buffer.name or os.getcwd())) repo = guess(os.path.abspath(vim.current.buffer.name or os.getcwd()))
if repo: if repo:
return repo.branch() return repo.branch()
@ -190,6 +223,7 @@ def branch():
# TODO Drop cache on BufWrite event # TODO Drop cache on BufWrite event
@memoize(2, additional_key=lambda: vim.current.buffer.number) @memoize(2, additional_key=lambda: vim.current.buffer.number)
def file_vcs_status(): def file_vcs_status():
'''Return the VCS status for this buffer.'''
if vim.current.buffer.name and not vim.eval('&buftype'): if vim.current.buffer.name and not vim.eval('&buftype'):
repo = guess(os.path.abspath(vim.current.buffer.name)) repo = guess(os.path.abspath(vim.current.buffer.name))
if repo: if repo:
@ -210,6 +244,7 @@ def file_vcs_status():
@memoize(2) @memoize(2)
def repository_status(): def repository_status():
'''Return the status for the current repo.'''
repo = guess(os.path.abspath(vim.current.buffer.name or os.getcwd())) repo = guess(os.path.abspath(vim.current.buffer.name or os.getcwd()))
if repo: if repo:
return repo.status() return repo.status()