Cleanup Python files to comply better with PEP 8

Removed excessive newlines and comments, and fixed whitespace issues.
This commit is contained in:
Kim Silkebækken 2013-01-15 08:49:40 +01:00
parent 7eb3bfde9c
commit 6d3dea1f0b
20 changed files with 43 additions and 149 deletions

View File

@ -5,12 +5,9 @@ class Colorscheme(object):
DEFAULT_MODE_KEY = '__default__' DEFAULT_MODE_KEY = '__default__'
def __init__(self, colorscheme): def __init__(self, colorscheme):
'''Initialize a colorscheme. '''Initialize a colorscheme.'''
'''
self.colors = {} self.colors = {}
self.modes_groups = { self.modes_groups = {self.DEFAULT_MODE_KEY: {}}
self.DEFAULT_MODE_KEY: {}
}
# Create a dict of color tuples with both a cterm and hex value # Create a dict of color tuples with both a cterm and hex value
for color_name, color in colorscheme['colors'].items(): for color_name, color in colorscheme['colors'].items():
@ -22,36 +19,33 @@ class Colorscheme(object):
# Create highlighting groups for all modes # Create highlighting groups for all modes
for group_name, group_props in colorscheme['groups'].items(): for group_name, group_props in colorscheme['groups'].items():
group_attr_flag = self._get_attr_flag(group_props.get('attr', [])) group_attr_flag = self._get_attr_flag(group_props.get('attr', []))
self.modes_groups[self.DEFAULT_MODE_KEY][group_name] = { self.modes_groups[self.DEFAULT_MODE_KEY][group_name] = {
'fg': self.colors[group_props['fg']], 'fg': self.colors[group_props['fg']],
'bg': self.colors[group_props['bg']], 'bg': self.colors[group_props['bg']],
'attr': group_attr_flag, 'attr': group_attr_flag,
} }
# Create mode-specific highlighting for this group # Create mode-specific highlighting for this group
for mode, translations in colorscheme['mode_translations'].items(): for mode, translations in colorscheme['mode_translations'].items():
if not mode in self.modes_groups: if not mode in self.modes_groups:
self.modes_groups[mode] = {} self.modes_groups[mode] = {}
if group_name in translations.get('groups', {}): if group_name in translations.get('groups', {}):
# Override entire group if present in the translations group dict # Override entire group if present in the translations group dict
self.modes_groups[mode][group_name] = { self.modes_groups[mode][group_name] = {
'fg': self.colors[translations['groups'][group_name]['fg']], 'fg': self.colors[translations['groups'][group_name]['fg']],
'bg': self.colors[translations['groups'][group_name]['bg']], 'bg': self.colors[translations['groups'][group_name]['bg']],
'attr': self._get_attr_flag(translations['groups'][group_name].get('attr', [])), 'attr': self._get_attr_flag(translations['groups'][group_name].get('attr', [])),
} }
else: else:
# Fallback to color translations from the translations colors dict # Fallback to color translations from the translations colors dict
self.modes_groups[mode][group_name] = { self.modes_groups[mode][group_name] = {
'fg': self.colors[translations.get('colors', {}).get(group_props['fg'], group_props['fg'])], 'fg': self.colors[translations.get('colors', {}).get(group_props['fg'], group_props['fg'])],
'bg': self.colors[translations.get('colors', {}).get(group_props['bg'], group_props['bg'])], 'bg': self.colors[translations.get('colors', {}).get(group_props['bg'], group_props['bg'])],
'attr': group_attr_flag, 'attr': group_attr_flag,
} }
def get_group_highlighting(self, group): def get_group_highlighting(self, group):
'''Return highlighting information for all modes of a highlighting group. '''Return highlighting information for all modes of a highlighting group.'''
'''
group_highlighting = {} group_highlighting = {}
for mode, mode_group in self.modes_groups.items(): for mode, mode_group in self.modes_groups.items():
try: try:
@ -74,7 +68,6 @@ class Colorscheme(object):
''' '''
if not mode or mode not in self.modes_groups: if not mode or mode not in self.modes_groups:
mode = self.DEFAULT_MODE_KEY mode = self.DEFAULT_MODE_KEY
try: try:
return self.modes_groups[mode][group] return self.modes_groups[mode][group]
except TypeError: except TypeError:
@ -82,14 +75,11 @@ class Colorscheme(object):
if try_group in self.modes_groups[mode]: if try_group in self.modes_groups[mode]:
return self.modes_groups[mode][try_group] return self.modes_groups[mode][try_group]
raise KeyError('Highlighting groups not found in colorscheme: {0}'.format(group)) raise KeyError('Highlighting groups not found in colorscheme: {0}'.format(group))
return self.modes_groups[mode][group] return self.modes_groups[mode][group]
def _get_attr_flag(self, attributes): def _get_attr_flag(self, attributes):
'''Convert an attribute array to a renderer flag. '''Convert an attribute array to a renderer flag.'''
'''
from powerline.renderer import Renderer from powerline.renderer import Renderer
attr_flag = 0 attr_flag = 0
if 'bold' in attributes: if 'bold' in attributes:
attr_flag |= Renderer.ATTR_BOLD attr_flag |= Renderer.ATTR_BOLD
@ -97,7 +87,6 @@ class Colorscheme(object):
attr_flag |= Renderer.ATTR_ITALIC attr_flag |= Renderer.ATTR_ITALIC
if 'underline' in attributes: if 'underline' in attributes:
attr_flag |= Renderer.ATTR_UNDERLINE attr_flag |= Renderer.ATTR_UNDERLINE
return attr_flag return attr_flag
cterm_to_hex = { cterm_to_hex = {
@ -141,4 +130,4 @@ cterm_to_hex = {
238: 0x444444, 239: 0x4e4e4e, 240: 0x585858, 241: 0x626262, 242: 0x6c6c6c, 243: 0x767676, 238: 0x444444, 239: 0x4e4e4e, 240: 0x585858, 241: 0x626262, 242: 0x6c6c6c, 243: 0x767676,
244: 0x808080, 245: 0x8a8a8a, 246: 0x949494, 247: 0x9e9e9e, 248: 0xa8a8a8, 249: 0xb2b2b2, 244: 0x808080, 245: 0x8a8a8a, 246: 0x949494, 247: 0x9e9e9e, 248: 0xa8a8a8, 249: 0xb2b2b2,
250: 0xbcbcbc, 251: 0xc6c6c6, 252: 0xd0d0d0, 253: 0xdadada, 254: 0xe4e4e4, 255: 0xeeeeee, 250: 0xbcbcbc, 251: 0xc6c6c6, 252: 0xd0d0d0, 253: 0xdadada, 254: 0xe4e4e4, 255: 0xeeeeee,
} }

View File

@ -13,11 +13,9 @@ from matchers import Matchers
class Powerline(object): class Powerline(object):
def __init__(self, ext): def __init__(self, ext):
config_home = os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) config_home = os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
config_path = os.path.join(config_home, 'powerline') config_path = os.path.join(config_home, 'powerline')
plugin_path = os.path.realpath(os.path.dirname(__file__)) plugin_path = os.path.realpath(os.path.dirname(__file__))
self.search_paths = [config_path, plugin_path] self.search_paths = [config_path, plugin_path]
sys.path[:0] = self.search_paths sys.path[:0] = self.search_paths
# Load main config file # Load main config file
@ -31,19 +29,15 @@ class Powerline(object):
# Load and initialize extension theme # Load and initialize extension theme
theme_config = self._load_theme_config(ext, self.config_ext.get('theme', 'default')) theme_config = self._load_theme_config(ext, self.config_ext.get('theme', 'default'))
path = [os.path.expanduser(path) for path in self.config.get('paths', [])] path = [os.path.expanduser(path) for path in self.config.get('paths', [])]
get_segment = Segments(ext, path, colorscheme).get get_segment = Segments(ext, path, colorscheme).get
get_matcher = Matchers(ext, path).get get_matcher = Matchers(ext, path).get
theme_kwargs = { theme_kwargs = {
'ext': ext, 'ext': ext,
'colorscheme': colorscheme, 'colorscheme': colorscheme,
'common_config': self.config, 'common_config': self.config,
'get_segment': get_segment 'get_segment': get_segment,
} }
local_themes = {} local_themes = {}
for key, local_theme_name in self.config_ext.get('local_themes', {}).iteritems(): for key, local_theme_name in self.config_ext.get('local_themes', {}).iteritems():
key = get_matcher(key) key = get_matcher(key)
@ -65,5 +59,4 @@ class Powerline(object):
if os.path.isfile(config_file_path): if os.path.isfile(config_file_path):
with open(config_file_path, 'rb') as config_file_fp: with open(config_file_path, 'rb') as config_file_fp:
return json.load(config_file_fp) return json.load(config_file_fp)
raise IOError('Config file not found in search path: {0}'.format(config_file)) raise IOError('Config file not found in search path: {0}'.format(config_file))

View File

@ -1,14 +1,12 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
'''Powerline terminal prompt example. '''Powerline terminal prompt.'''
'''
try: try:
from powerline.core import Powerline from powerline.core import Powerline
except ImportError: except ImportError:
import os import os
import sys import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
from powerline.core import Powerline from powerline.core import Powerline
pl = Powerline('terminal') pl = Powerline('terminal')

View File

@ -4,8 +4,7 @@ from powerline.renderer import Renderer
class TerminalRenderer(Renderer): class TerminalRenderer(Renderer):
'''Powerline terminal segment renderer. '''Powerline terminal segment renderer.'''
'''
def hl(self, fg=None, bg=None, attr=None): def hl(self, fg=None, bg=None, attr=None):
'''Highlight a segment. '''Highlight a segment.
@ -14,24 +13,20 @@ class TerminalRenderer(Renderer):
is a valid color or attribute, it's added to the ANSI escape code. is a valid color or attribute, it's added to the ANSI escape code.
''' '''
ansi = [] ansi = []
if fg is not None: if fg is not None:
if fg[0] is False: if fg[0] is False:
ansi += [39] ansi += [39]
else: else:
ansi += [38, 5, fg[0]] ansi += [38, 5, fg[0]]
if bg is not None: if bg is not None:
if bg[0] is False: if bg[0] is False:
ansi += [49] ansi += [49]
else: else:
ansi += [48, 5, bg[0]] ansi += [48, 5, bg[0]]
if attr is not None: if attr is not None:
if attr is False: if attr is False:
ansi += [22] ansi += [22]
else: else:
if attr & Renderer.ATTR_BOLD: if attr & Renderer.ATTR_BOLD:
ansi += [1] ansi += [1]
return '[{0}m'.format(';'.join(str(attr) for attr in ansi)) return '[{0}m'.format(';'.join(str(attr) for attr in ansi))

View File

@ -16,11 +16,10 @@ def hostname():
def user(): def user():
user = os.environ.get('USER') user = os.environ.get('USER')
euid = os.geteuid() euid = os.geteuid()
return { return {
'contents': user, 'contents': user,
'highlight': 'user' if euid != 0 else ['superuser', 'user'], 'highlight': 'user' if euid != 0 else ['superuser', 'user'],
} }
def branch(): def branch():
@ -37,12 +36,9 @@ def cwd(dir_shorten_len=None, dir_limit_depth=None):
cwd = re.sub('^' + re.escape(home), '~', cwd, 1) cwd = re.sub('^' + re.escape(home), '~', cwd, 1)
cwd_split = cwd.split(os.sep) cwd_split = cwd.split(os.sep)
cwd_split_len = len(cwd_split) cwd_split_len = len(cwd_split)
if cwd_split_len > dir_limit_depth + 1: if cwd_split_len > dir_limit_depth + 1:
del(cwd_split[0:-dir_limit_depth]) del(cwd_split[0:-dir_limit_depth])
cwd_split.insert(0, u'') cwd_split.insert(0, u'')
cwd = [i[0:dir_shorten_len] if dir_shorten_len and i else i for i in cwd_split[:-1]] + [cwd_split[-1]] cwd = [i[0:dir_shorten_len] if dir_shorten_len and i else i for i in cwd_split[:-1]] + [cwd_split[-1]]
cwd = os.path.join(*cwd) cwd = os.path.join(*cwd)
return cwd return cwd

View File

@ -4,25 +4,20 @@ from powerline.renderer import Renderer
class TmuxRenderer(Renderer): class TmuxRenderer(Renderer):
'''Powerline tmux segment renderer. '''Powerline tmux segment renderer.'''
'''
def hl(self, fg=None, bg=None, attr=None): def hl(self, fg=None, bg=None, attr=None):
'''Highlight a segment. '''Highlight a segment.'''
'''
tmux_attr = [] tmux_attr = []
if fg is not None: if fg is not None:
if fg[0] is False: if fg[0] is False:
tmux_attr += ['fg=default'] tmux_attr += ['fg=default']
else: else:
tmux_attr += ['fg=colour' + str(fg[0])] tmux_attr += ['fg=colour' + str(fg[0])]
if bg is not None: if bg is not None:
if bg[0] is False: if bg[0] is False:
tmux_attr += ['bg=default'] tmux_attr += ['bg=default']
else: else:
tmux_attr += ['bg=colour' + str(bg[0])] tmux_attr += ['bg=colour' + str(bg[0])]
if attr is not None: if attr is not None:
if attr is False: if attr is False:
tmux_attr += ['nobold', 'noitalics', 'nounderscore'] tmux_attr += ['nobold', 'noitalics', 'nounderscore']
@ -39,5 +34,4 @@ class TmuxRenderer(Renderer):
tmux_attr += ['underscore'] tmux_attr += ['underscore']
else: else:
tmux_attr += ['nounderscore'] tmux_attr += ['nounderscore']
return '#[' + ','.join(tmux_attr) + ']' return '#[' + ','.join(tmux_attr) + ']'

View File

@ -8,4 +8,4 @@ def user_name():
return { return {
'contents': user_name, 'contents': user_name,
'highlight': 'user_name' if user_name != 'root' else ['user_name_root', 'user_name'], 'highlight': 'user_name' if user_name != 'root' else ['user_name_root', 'user_name'],
} }

View File

@ -5,7 +5,5 @@ def source_plugin():
import os import os
import vim import vim
from bindings import vim_get_func from bindings import vim_get_func
fnameescape = vim_get_func('fnameescape') fnameescape = vim_get_func('fnameescape')
vim.command('source ' + fnameescape(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'powerline.vim'))) vim.command('source ' + fnameescape(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'powerline.vim')))

View File

@ -6,13 +6,11 @@ try:
_vim_globals = vim.bindeval('g:') _vim_globals = vim.bindeval('g:')
def vim_set_global_var(var, val): def vim_set_global_var(var, val):
'''Set a global var in vim using bindeval(). '''Set a global var in vim using bindeval().'''
'''
_vim_globals[var] = val _vim_globals[var] = val
def vim_get_func(f, rettype=None): def vim_get_func(f, rettype=None):
'''Return a vim function binding. '''Return a vim function binding.'''
'''
try: try:
return vim.bindeval('function("' + f + '")') return vim.bindeval('function("' + f + '")')
except vim.error: except vim.error:

View File

@ -12,8 +12,7 @@ vim_setwinvar = vim_get_func('setwinvar')
class VimRenderer(Renderer): class VimRenderer(Renderer):
'''Powerline vim segment renderer. '''Powerline vim segment renderer.'''
'''
PERCENT_PLACEHOLDER = u'' PERCENT_PLACEHOLDER = u''
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -30,7 +29,6 @@ class VimRenderer(Renderer):
''' '''
window_id = vim_getwinvar(winnr, 'window_id') window_id = vim_getwinvar(winnr, 'window_id')
winwidth = vim_winwidth(winnr) winwidth = vim_winwidth(winnr)
if current: if current:
mode = vim_mode() mode = vim_mode()
theme = self.get_theme() theme = self.get_theme()
@ -39,10 +37,8 @@ class VimRenderer(Renderer):
else: else:
mode = 'nc' mode = 'nc'
theme, segments = self.window_cache.get(window_id, (None, None)) theme, segments = self.window_cache.get(window_id, (None, None))
statusline = super(VimRenderer, self).render(mode, winwidth, theme, segments) statusline = super(VimRenderer, self).render(mode, winwidth, theme, segments)
statusline = statusline.replace(self.PERCENT_PLACEHOLDER, '%%') statusline = statusline.replace(self.PERCENT_PLACEHOLDER, '%%')
return statusline return statusline
def hl(self, fg=None, bg=None, attr=None): def hl(self, fg=None, bg=None, attr=None):
@ -64,16 +60,13 @@ class VimRenderer(Renderer):
'guibg': 'NONE', 'guibg': 'NONE',
'attr': ['NONE'], 'attr': ['NONE'],
'name': '', 'name': '',
} }
if fg is not None and fg is not False: if fg is not None and fg is not False:
hl_group['ctermfg'] = fg[0] hl_group['ctermfg'] = fg[0]
hl_group['guifg'] = fg[1] hl_group['guifg'] = fg[1]
if bg is not None and bg is not False: if bg is not None and bg is not False:
hl_group['ctermbg'] = bg[0] hl_group['ctermbg'] = bg[0]
hl_group['guibg'] = bg[1] hl_group['guibg'] = bg[1]
if attr: if attr:
hl_group['attr'] = [] hl_group['attr'] = []
if attr & self.ATTR_BOLD: if attr & self.ATTR_BOLD:
@ -82,17 +75,13 @@ class VimRenderer(Renderer):
hl_group['attr'].append('italic') hl_group['attr'].append('italic')
if attr & self.ATTR_UNDERLINE: if attr & self.ATTR_UNDERLINE:
hl_group['attr'].append('underline') hl_group['attr'].append('underline')
hl_group['name'] = 'Pl_' + \ hl_group['name'] = 'Pl_' + \
str(hl_group['ctermfg']) + '_' + \ str(hl_group['ctermfg']) + '_' + \
str(hl_group['guifg']) + '_' + \ str(hl_group['guifg']) + '_' + \
str(hl_group['ctermbg']) + '_' + \ str(hl_group['ctermbg']) + '_' + \
str(hl_group['guibg']) + '_' + \ str(hl_group['guibg']) + '_' + \
''.join(hl_group['attr']) ''.join(hl_group['attr'])
self.hl_groups[(fg, bg, attr)] = hl_group self.hl_groups[(fg, bg, attr)] = hl_group
# Create highlighting group in vim
vim.command('hi {group} ctermfg={ctermfg} guifg={guifg} guibg={guibg} ctermbg={ctermbg} cterm={attr} gui={attr}'.format( vim.command('hi {group} ctermfg={ctermfg} guifg={guifg} guibg={guibg} ctermbg={ctermbg} cterm={attr} gui={attr}'.format(
group=hl_group['name'], group=hl_group['name'],
ctermfg=hl_group['ctermfg'], ctermfg=hl_group['ctermfg'],
@ -101,5 +90,4 @@ class VimRenderer(Renderer):
guibg='#{0:06x}'.format(hl_group['guibg']) if hl_group['guibg'] != 'NONE' else 'NONE', guibg='#{0:06x}'.format(hl_group['guibg']) if hl_group['guibg'] != 'NONE' else 'NONE',
attr=','.join(hl_group['attr']), attr=','.join(hl_group['attr']),
)) ))
return '%#' + self.hl_groups[(fg, bg, attr)]['name'] + '#' return '%#' + self.hl_groups[(fg, bg, attr)]['name'] + '#'

View File

@ -47,10 +47,8 @@ def mode(override=None):
mode = mode({ 'n': 'NORM' }) mode = mode({ 'n': 'NORM' })
''' '''
mode = vim_funcs['mode']() mode = vim_funcs['mode']()
if not override: if not override:
return vim_modes[mode] return vim_modes[mode]
try: try:
return override[mode] return override[mode]
except IndexError: except IndexError:
@ -58,44 +56,36 @@ def mode(override=None):
def modified_indicator(text=u'+'): def modified_indicator(text=u'+'):
'''Return a file modified indicator. '''Return a file modified indicator.'''
'''
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.'''
'''
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.'''
'''
return text if int(vim.eval('&readonly')) else None return text if int(vim.eval('&readonly')) else None
def file_directory(): def file_directory():
'''Return file directory (head component of the file path). '''Return file directory (head component of the file path).'''
'''
file_directory = vim_funcs['expand']('%:~:.:h') file_directory = vim_funcs['expand']('%:~:.:h')
return file_directory + os.sep if file_directory else None return file_directory + os.sep if file_directory else None
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).'''
'''
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
if not file_name: if not file_name:
return { return {
'contents': no_file_text, 'contents': no_file_text,
'highlight': ['file_name_no_file', 'file_name'], 'highlight': ['file_name_no_file', 'file_name'],
} }
return file_name return file_name
@ -124,24 +114,20 @@ def file_type():
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.'''
'''
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)
if not gradient: if not gradient:
return percentage return percentage
return { return {
'contents': percentage, 'contents': percentage,
'highlight': ['line_percent_gradient' + str(int(5 * percentage // 100) + 1), 'line_percent'], 'highlight': ['line_percent_gradient' + str(int(5 * percentage // 100) + 1), 'line_percent'],
} }
def line_current(): def line_current():
'''Return the current cursor line. '''Return the current cursor line.'''
'''
return vim_funcs['line']('.') return vim_funcs['line']('.')
@ -175,5 +161,5 @@ def file_vcs_status():
return { return {
'contents': status, 'contents': status,
'highlight': ['file_vcs_status_' + status, 'file_vcs_status'], 'highlight': ['file_vcs_status_' + status, 'file_vcs_status'],
} }
return None return None

View File

@ -9,21 +9,17 @@ try:
import psMat import psMat
except ImportError: except ImportError:
sys.stderr.write('The required FontForge modules could not be loaded.\n\n') sys.stderr.write('The required FontForge modules could not be loaded.\n\n')
if sys.version_info.major > 2: if sys.version_info.major > 2:
sys.stderr.write('FontForge only supports Python 2. Please run this script with the Python 2 executable - e.g. "python2 {0}"\n'.format(sys.argv[0])) sys.stderr.write('FontForge only supports Python 2. Please run this script with the Python 2 executable - e.g. "python2 {0}"\n'.format(sys.argv[0]))
else: else:
sys.stderr.write('You need FontForge with Python bindings for this script to work.\n') sys.stderr.write('You need FontForge with Python bindings for this script to work.\n')
sys.exit(1) sys.exit(1)
# Handle command-line arguments # Handle command-line arguments
parser = argparse.ArgumentParser(description='Font patcher for Powerline. Requires FontForge with Python bindings. Stores the patched font as a new, renamed font file by default.') parser = argparse.ArgumentParser(description='Font patcher for Powerline. Requires FontForge with Python bindings. Stores the patched font as a new, renamed font file by default.')
parser.add_argument('target_fonts', help='font files to patch', metavar='font', nargs='+', type=argparse.FileType('rb')) parser.add_argument('target_fonts', help='font files to patch', metavar='font', nargs='+', type=argparse.FileType('rb'))
parser.add_argument('--no-rename', help='don\'t add " for Powerline" to the font name', default=True, action='store_false', dest='rename_font') parser.add_argument('--no-rename', help='don\'t add " for Powerline" to the font name', default=True, action='store_false', dest='rename_font')
parser.add_argument('--source-font', help='source symbol font', metavar='font', dest='source_font', default='{0}/fontpatcher-symbols.sfd'.format(sys.path[0]), type=argparse.FileType('rb')) parser.add_argument('--source-font', help='source symbol font', metavar='font', dest='source_font', default='{0}/fontpatcher-symbols.sfd'.format(sys.path[0]), type=argparse.FileType('rb'))
args = parser.parse_args() args = parser.parse_args()
@ -36,10 +32,8 @@ class FontPatcher(object):
def patch(self): def patch(self):
for target_font in self.target_fonts: for target_font in self.target_fonts:
source_font = self.source_font source_font = self.source_font
target_font_em_original = target_font.em target_font_em_original = target_font.em
target_font.em = 2048 target_font.em = 2048
target_font.encoding = 'ISO10646' target_font.encoding = 'ISO10646'
# Rename font # Rename font
@ -61,10 +55,8 @@ class FontPatcher(object):
bbox = target_font[cp].boundingBox() bbox = target_font[cp].boundingBox()
except TypeError: except TypeError:
continue continue
if not target_font_width: if not target_font_width:
target_font_width = target_font[cp].width target_font_width = target_font[cp].width
if bbox[0] < target_bb[0]: if bbox[0] < target_bb[0]:
target_bb[0] = bbox[0] target_bb[0] = bbox[0]
if bbox[1] < target_bb[1]: if bbox[1] < target_bb[1]:
@ -83,7 +75,6 @@ class FontPatcher(object):
x_diff = target_bb[0] - source_bb[0] x_diff = target_bb[0] - source_bb[0]
y_diff = target_bb[1] - source_bb[1] y_diff = target_bb[1] - source_bb[1]
translate = psMat.translate(x_diff, y_diff) translate = psMat.translate(x_diff, y_diff)
transform = psMat.compose(scale, translate) transform = psMat.compose(scale, translate)
# Create new glyphs from symbol font # Create new glyphs from symbol font

View File

@ -8,8 +8,7 @@ import time
class memoize(object): class memoize(object):
'''Memoization decorator with timeout. '''Memoization decorator with timeout.'''
'''
_cache = {} _cache = {}
def __init__(self, timeout, additional_key=None, persistent=False, persistent_file=None): def __init__(self, timeout, additional_key=None, persistent=False, persistent_file=None):
@ -25,22 +24,18 @@ class memoize(object):
key = (func.__name__, args, tuple(kwargs.items()), self.additional_key()) key = (func.__name__, args, tuple(kwargs.items()), self.additional_key())
else: else:
key = (func.__name__, args, tuple(kwargs.items())) key = (func.__name__, args, tuple(kwargs.items()))
if self.persistent: if self.persistent:
try: try:
with open(self.persistent_file, 'rb') as fileobj: with open(self.persistent_file, 'rb') as fileobj:
self._cache = pickle.load(fileobj) self._cache = pickle.load(fileobj)
except (IOError, EOFError): except (IOError, EOFError):
pass pass
cached = self._cache.get(key, None) cached = self._cache.get(key, None)
if cached is None or time.time() - cached['time'] > self.timeout: if cached is None or time.time() - cached['time'] > self.timeout:
cached = self._cache[key] = { cached = self._cache[key] = {
'result': func(*args, **kwargs), 'result': func(*args, **kwargs),
'time': time.time(), 'time': time.time(),
} }
if self.persistent: if self.persistent:
try: try:
with open(self.persistent_file, 'wb') as fileobj: with open(self.persistent_file, 'wb') as fileobj:
@ -51,6 +46,5 @@ class memoize(object):
except TypeError: except TypeError:
# Unable to pickle function result # Unable to pickle function result
pass pass
return cached['result'] return cached['result']
return decorated_function return decorated_function

View File

@ -27,7 +27,7 @@ try:
if path: if path:
try: try:
status = self._repo().status_file(path) status = self._repo().status_file(path)
except KeyError, ValueError: except (KeyError, ValueError):
return None return None
if status == git.GIT_STATUS_CURRENT: if status == git.GIT_STATUS_CURRENT:

View File

@ -32,7 +32,6 @@ class Repository(object):
"U"nknown, "I"gnored, (None)Clean. "U"nknown, "I"gnored, (None)Clean.
''' '''
repo = self._repo() repo = self._repo()
if path: if path:
m = match.match(None, None, [path], exact=True) m = match.match(None, None, [path], exact=True)
statuses = repo.status(match=m, unknown=True, ignored=True) statuses = repo.status(match=m, unknown=True, ignored=True)

View File

@ -14,10 +14,8 @@ class Matchers(object):
if not separator: if not separator:
match_module = 'powerline.ext.{0}.matchers'.format(self.ext) match_module = 'powerline.ext.{0}.matchers'.format(self.ext)
match_function = match_name match_function = match_name
oldpath = sys.path oldpath = sys.path
sys.path = self.path + sys.path sys.path = self.path + sys.path
try: try:
return getattr(import_module(match_module), match_function) return getattr(import_module(match_module), match_function)
finally: finally:

View File

@ -39,16 +39,13 @@ class Renderer(object):
# Handle excluded/included segments for the current mode # Handle excluded/included segments for the current mode
segments = [segment for segment in segments\ segments = [segment for segment in segments\
if mode not in segment['exclude_modes'] or (segment['include_modes'] and segment in segment['include_modes'])] if mode not in segment['exclude_modes'] or (segment['include_modes'] and segment in segment['include_modes'])]
rendered_highlighted = self._render_segments(mode, theme, segments) rendered_highlighted = self._render_segments(mode, theme, segments)
if not width: if not width:
# No width specified, so we don't need to crop or pad anything # No width specified, so we don't need to crop or pad anything
return rendered_highlighted return rendered_highlighted
# Create an ordered list of segments that can be dropped # Create an ordered list of segments that can be dropped
segments_priority = [segment for segment in sorted(segments, key=lambda segment: segment['priority'], reverse=True) if segment['priority'] > 0] segments_priority = [segment for segment in sorted(segments, key=lambda segment: segment['priority'], reverse=True) if segment['priority'] > 0]
while self._total_len(segments) > width and len(segments_priority): while self._total_len(segments) > width and len(segments_priority):
segments.remove(segments_priority[0]) segments.remove(segments_priority[0])
segments_priority.pop(0) segments_priority.pop(0)
@ -65,7 +62,6 @@ class Renderer(object):
segment['contents'] = segments_fillers_contents segment['contents'] = segments_fillers_contents
# Add remainder whitespace to the first filler segment # Add remainder whitespace to the first filler segment
segments_fillers[0]['contents'] += ' ' * segments_fillers_remainder segments_fillers[0]['contents'] += ' ' * segments_fillers_remainder
return self._render_segments(mode, theme, segments) return self._render_segments(mode, theme, segments)
def _render_segments(self, mode, theme, segments, render_highlighted=True): def _render_segments(self, mode, theme, segments, render_highlighted=True):
@ -87,19 +83,16 @@ class Renderer(object):
prev_segment = segments[index - 1] if index > 0 else theme.EMPTY_SEGMENT prev_segment = segments[index - 1] if index > 0 else theme.EMPTY_SEGMENT
next_segment = segments[index + 1] if index < segments_len - 1 else theme.EMPTY_SEGMENT next_segment = segments[index + 1] if index < segments_len - 1 else theme.EMPTY_SEGMENT
compare_segment = next_segment if segment['side'] == 'left' else prev_segment compare_segment = next_segment if segment['side'] == 'left' else prev_segment
segment['rendered_raw'] = u'' segment['rendered_raw'] = u''
outer_padding = ' ' if index == 0 or (index == segments_len - 1 and segment['side'] == 'right') else '' outer_padding = ' ' if index == 0 or (index == segments_len - 1 and segment['side'] == 'right') else ''
divider_type = 'soft' if compare_segment['highlight'][mode]['bg'] == segment['highlight'][mode]['bg'] else 'hard' divider_type = 'soft' if compare_segment['highlight'][mode]['bg'] == segment['highlight'][mode]['bg'] else 'hard'
divider = theme.get_divider(segment['side'], divider_type) divider = theme.get_divider(segment['side'], divider_type)
divider_hl = '' divider_hl = ''
segment_hl = '' segment_hl = ''
if render_highlighted: if render_highlighted:
if divider_type == 'hard': if divider_type == 'hard':
divider_hl = self.hl(segment['highlight'][mode]['bg'], compare_segment['highlight'][mode]['bg'], False) divider_hl = self.hl(segment['highlight'][mode]['bg'], compare_segment['highlight'][mode]['bg'], False)
segment_hl = self.hl(**segment['highlight'][mode]) segment_hl = self.hl(**segment['highlight'][mode])
if segment['type'] == 'filler': if segment['type'] == 'filler':
@ -124,7 +117,6 @@ class Renderer(object):
rendered_highlighted += segment_hl + segment['contents'] + outer_padding rendered_highlighted += segment_hl + segment['contents'] + outer_padding
else: else:
raise ValueError('Unknown segment type') raise ValueError('Unknown segment type')
return rendered_highlighted return rendered_highlighted
def _total_len(self, segments): def _total_len(self, segments):

View File

@ -14,7 +14,6 @@ class Segments(object):
oldpath = sys.path oldpath = sys.path
sys.path = self.path + sys.path sys.path = self.path + sys.path
segment_module = str(segment.get('module', 'powerline.ext.{0}.segments'.format(self.ext))) segment_module = str(segment.get('module', 'powerline.ext.{0}.segments'.format(self.ext)))
try: try:
return None, getattr(import_module(segment_module), segment['name']), '{0}.{1}'.format(segment_module, segment['name']) return None, getattr(import_module(segment_module), segment['name']), '{0}.{1}'.format(segment_module, segment['name'])
finally: finally:
@ -30,14 +29,11 @@ class Segments(object):
def get(self, segment, side): def get(self, segment, side):
segment_type = segment.get('type', 'function') segment_type = segment.get('type', 'function')
try: try:
contents, contents_func, key = getattr(self, 'get_{0}'.format(segment_type))(segment) contents, contents_func, key = getattr(self, 'get_{0}'.format(segment_type))(segment)
except AttributeError: except AttributeError:
raise TypeError('Unknown segment type: {0}'.format(segment_type)) raise TypeError('Unknown segment type: {0}'.format(segment_type))
highlighting_group = segment.get('highlight', segment.get('name')) highlighting_group = segment.get('highlight', segment.get('name'))
return { return {
'key': key, 'key': key,
'type': segment_type, 'type': segment_type,
@ -54,4 +50,4 @@ class Segments(object):
'side': side, 'side': side,
'exclude_modes': segment.get('exclude_modes', []), 'exclude_modes': segment.get('exclude_modes', []),
'include_modes': segment.get('include_modes', []), 'include_modes': segment.get('include_modes', []),
} }

View File

@ -8,18 +8,15 @@ class Theme(object):
self.colorscheme = colorscheme self.colorscheme = colorscheme
self.dividers = theme_config.get('dividers', common_config['dividers']) self.dividers = theme_config.get('dividers', common_config['dividers'])
self.segments = [] self.segments = []
self.EMPTY_SEGMENT = { self.EMPTY_SEGMENT = {
'contents': None, 'contents': None,
'highlight': {self.colorscheme.DEFAULT_MODE_KEY: {'fg': (False, False), 'bg': (False, False), 'attr': 0}} 'highlight': {self.colorscheme.DEFAULT_MODE_KEY: {'fg': (False, False), 'bg': (False, False), 'attr': 0}}
} }
for side in ['left', 'right']: for side in ['left', 'right']:
self.segments.extend((get_segment(segment, side) for segment in theme_config['segments'].get(side, []))) self.segments.extend((get_segment(segment, side) for segment in theme_config['segments'].get(side, [])))
def get_divider(self, side='left', type='soft'): def get_divider(self, side='left', type='soft'):
'''Return segment divider. '''Return segment divider.'''
'''
return self.dividers[side][type] return self.dividers[side][type]
def get_segments(self): def get_segments(self):
@ -31,10 +28,8 @@ class Theme(object):
for segment in self.segments: for segment in self.segments:
if segment['type'] == 'function': if segment['type'] == 'function':
contents = segment['contents_func'](**segment['args']) contents = segment['contents_func'](**segment['args'])
if contents is None: if contents is None:
continue continue
try: try:
segment['highlight'] = self.colorscheme.get_group_highlighting(contents['highlight']) segment['highlight'] = self.colorscheme.get_group_highlighting(contents['highlight'])
segment['contents'] = contents['contents'] segment['contents'] = contents['contents']
@ -44,11 +39,9 @@ class Theme(object):
pass pass
else: else:
continue continue
segment['contents'] = unicode(segment['before'] + unicode(segment['contents']) + segment['after'])\ segment['contents'] = unicode(segment['before'] + unicode(segment['contents']) + segment['after'])\
.ljust(segment['ljust'])\ .ljust(segment['ljust'])\
.rjust(segment['rjust']) .rjust(segment['rjust'])
# We need to yield a copy of the segment, or else mode-dependent # We need to yield a copy of the segment, or else mode-dependent
# segment contents can't be cached correctly e.g. when caching # segment contents can't be cached correctly e.g. when caching
# non-current window contents for vim statuslines # non-current window contents for vim statuslines

View File

@ -11,13 +11,6 @@ try:
except IOError: except IOError:
README = '' README = ''
install_requires = []
docs_extras = [
'Sphinx',
'docutils',
]
setup(name='Powerline', setup(name='Powerline',
version='beta', version='beta',
description='The ultimate statusline/prompt utility.', description='The ultimate statusline/prompt utility.',
@ -31,8 +24,11 @@ setup(name='Powerline',
include_package_data=True, include_package_data=True,
zip_safe=False, zip_safe=False,
test_suite='powerline', test_suite='powerline',
install_requires=install_requires, install_requires=[],
extras_require={ extras_require={
'docs': docs_extras, 'docs': [
}, 'Sphinx',
) 'docutils',
],
},
)