Beispiel #1
0
	def init(self, pyeval='PowerlinePyeval', **kwargs):
		super(VimPowerline, self).init('vim', **kwargs)
		self.last_window_id = 1
		self.pyeval = pyeval
		self.construct_window_statusline = self.create_window_statusline_constructor()
		if all((hasattr(vim.current.window, attr) for attr in ('options', 'vars', 'number'))):
			self.win_idx = self.new_win_idx
		else:
			self.win_idx = self.old_win_idx
			self._vim_getwinvar = vim_get_func('getwinvar', 'bytes')
			self._vim_setwinvar = vim_get_func('setwinvar')
Beispiel #2
0
def watchdogs(pl, err_format='ERR:  {first_line} ({num})'):
	'''Show whether watchdogs has found any errors

	:param str err_format:
		Format string for errors.

	Highlight groups used ``watchdogs:error`` or ``error``.
	'''

	bufnr = int(vim_get_func('bufnr')(''))
	errors = filter(lambda qf: qf['bufnr'] == bufnr, vim_get_func('getqflist')())

	return [] if len(errors) == 0 else [{
		'contents': err_format.format(first_line=errors[0]['lnum'], num=len(errors)),
		'highlight_groups': ['watchdogs:error', 'error']
		}]
def webdevicons(pl, segment_info):
	webdevicons = vim_get_func('WebDevIconsGetFileTypeSymbol')
	name = buffer_name(segment_info)
	return [] if not webdevicons else [{
		'contents': webdevicons(name),
		'highlight_groups': ['webdevicons', 'file_name'],
		}]
Beispiel #4
0
def unite_segment(pl):
	'''Return the unite.vim statusline
	'''
	if int(vim_funcs['exists']('*unite#get_status_string')) > 0:
		unite_stl_func = vim_get_func('unite#get_status_string', rettype=str)
		return str(unite_stl_func())
	else:
		return None
Beispiel #5
0
def syntastic_segment(pl):
	'''Return the syntastic statusline flag
	'''
	if int(vim_funcs['exists']('*SyntasticStatuslineFlag')) > 0:
		syntastic_flag_func = vim_get_func('SyntasticStatuslineFlag', rettype=str)
		return str(syntastic_flag_func())
	else:
		return None
Beispiel #6
0
def parse_status_string():
	status = vim_get_func('unite#get_status_string')()
	try:
		sources, status = re.compile(r' \| ').split(status)
	except ValueError:
		return {}
	return {
			'sources': sources,
			'status':  status,
			}
Beispiel #7
0
def is_active(pl, word='Table'):
	'''Show status for vim-table-mode

	:param str word:
		A string displayed when table-mode is active.

	Highlight groups used ``table_mode`` or ``line_current``.
	'''

	try:
		is_active = int(vim_get_func('tablemode#IsActive')()) == 1
	except:
		is_active = False

	return [] if not is_active else [{
		'contents': word,
		'highlight_groups': ['table_mode', 'paste_indicator'],
		}]
Beispiel #8
0
def is_active(pl, word='Table'):
    '''Show status for vim-table-mode

	:param str word:
		A string displayed when table-mode is active.

	Highlight groups used ``table_mode`` or ``line_current``.
	'''

    try:
        is_active = int(vim_get_func('tablemode#IsActive')()) == 1
    except:
        is_active = False

    return [] if not is_active else [{
        'contents':
        word,
        'highlight_groups': ['table_mode', 'paste_indicator'],
    }]
Beispiel #9
0
def vim_func_segment(pl, func_name, *args):
    if int(vim_funcs['exists']('*' + func_name)) > 0:
        f = vim_get_func(func_name, rettype=str)
        return str(f(*args))
    else:
        return None
Beispiel #10
0
from powerline.lib import add_divider_highlight_group
from powerline.lib.vcs import guess
from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib import wraps_saveargs as wraps
from powerline.segments.common.vcs import BranchSegment
from powerline.segments import with_docstring
from powerline.lib.unicode import string, unicode

try:
	from __builtin__ import xrange as range
except ImportError:
	pass


vim_funcs = {
	'virtcol': vim_get_func('virtcol', rettype='int'),
	'getpos': vim_get_func('getpos'),
	'fnamemodify': vim_get_func('fnamemodify', rettype='bytes'),
	'line2byte': vim_get_func('line2byte', rettype='int'),
	'line': vim_get_func('line', rettype='int'),
}

vim_modes = {
	'n': 'NORMAL',
	'no': 'N-OPER',
	'v': 'VISUAL',
	'V': 'V-LINE',
	'^V': 'V-BLCK',
	's': 'SELECT',
	'S': 'S-LINE',
	'^S': 'S-BLCK',
Beispiel #11
0
from __future__ import absolute_import

import os
try:
	import vim
except ImportError:
	vim = {}  # NOQA

from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.theme import requires_segment_info
from powerline.lib import memoize, humanize_bytes, add_divider_highlight_group
from powerline.lib.vcs import guess
from collections import defaultdict

vim_funcs = {
	'virtcol': vim_get_func('virtcol', rettype=int),
	'fnamemodify': vim_get_func('fnamemodify'),
	'expand': vim_get_func('expand'),
	'bufnr': vim_get_func('bufnr', rettype=int),
}

vim_modes = {
	'n': 'NORMAL',
	'no': 'N·OPER',
	'v': 'VISUAL',
	'V': 'V·LINE',
	'^V': 'V·BLCK',
	's': 'SELECT',
	'S': 'S·LINE',
	'^S': 'S·BLCK',
	'i': 'INSERT',
Beispiel #12
0
def webdevicons_file_format(pl, segment_info):
	webdevicons_file_format = vim_get_func('WebDevIconsGetFileFormatSymbol')
	return [] if not webdevicons_file_format else [{
		'contents': webdevicons_file_format(),
		'highlight_groups': ['webdevicons_file_format', 'file_format'],
		}]
Beispiel #13
0
def plugin_eval(expr):
    global plugin_eval
    plugin_eval = vim_get_func('<SNR>'+sid+'_Eval')
    return plugin_eval(expr)
Beispiel #14
0
class VimPowerline(Powerline):
    def __init__(self, pyeval='PowerlinePyeval'):
        super(VimPowerline, self).__init__('vim')
        self.last_window_id = 1
        self.window_statusline = '%!' + pyeval + '(\'powerline.statusline({0})\')'

    def add_local_theme(self, key, config):
        '''Add local themes at runtime (during vim session).

		:param str key:
			Matcher name (in format ``{matcher_module}.{module_attribute}`` or 
			``{module_attribute}`` if ``{matcher_module}`` is 
			``powerline.matchers.vim``). Function pointed by 
			``{module_attribute}`` should be hashable and accept a dictionary 
			with information about current buffer and return boolean value 
			indicating whether current window matched conditions. See also 
			:ref:`local_themes key description <config-ext-local_themes>`.

		:param dict config:
			:ref:`Theme <config-themes>` dictionary.

		:return:
			``True`` if theme was added successfully and ``False`` if theme with 
			the same matcher already exists.
		'''
        self.update_renderer()
        key = self.get_matcher(key)
        try:
            self.renderer.add_local_theme(key, {'config': config})
        except KeyError:
            return False
        else:
            return True

    def load_main_config(self):
        return _override_from(
            super(VimPowerline, self).load_main_config(),
            'powerline_config_overrides')

    def load_theme_config(self, name):
        # Note: themes with non-[a-zA-Z0-9_] names are impossible to override
        # (though as far as I know exists() won’t throw). Won’t fix, use proper
        # theme names.
        return _override_from(
            super(VimPowerline, self).load_theme_config(name),
            'powerline_theme_overrides__' + name)

    def get_local_themes(self, local_themes):
        if not local_themes:
            return {}

        self.get_matcher = gen_matcher_getter(self.ext, self.import_paths)
        return dict(((self.get_matcher(key), {
            'config': self.load_theme_config(val)
        }) for key, val in local_themes.items()))

    def get_config_paths(self):
        try:
            return [vim_getvar('powerline_config_path')]
        except KeyError:
            return super(VimPowerline, self).get_config_paths()

    @staticmethod
    def get_segment_info():
        return {}

    def reset_highlight(self):
        try:
            self.renderer.reset_highlight()
        except AttributeError:
            # Renderer object appears only after first `.render()` call. Thus if
            # ColorScheme event happens before statusline is drawn for the first
            # time AttributeError will be thrown for the self.renderer. It is
            # fine to ignore it: no renderer == no colors to reset == no need to
            # do anything.
            pass

    if all((hasattr(vim.current.window, attr)
            for attr in ('options', 'vars', 'number'))):

        def win_idx(self, window_id):
            r = None
            for window in vim.windows:
                try:
                    curwindow_id = window.vars['powerline_window_id']
                except KeyError:
                    curwindow_id = self.last_window_id
                    self.last_window_id += 1
                    window.vars['powerline_window_id'] = curwindow_id
                statusline = self.window_statusline.format(curwindow_id)
                if window.options['statusline'] != statusline:
                    window.options['statusline'] = statusline
                if curwindow_id == window_id if window_id else window is vim.current.window:
                    assert r is None, "Non-unique window ID"
                    r = (window, curwindow_id, window.number)
            return r
    else:
        _vim_getwinvar = staticmethod(vim_get_func('getwinvar'))
        _vim_setwinvar = staticmethod(vim_get_func('setwinvar'))

        def win_idx(self, window_id):  # NOQA
            r = None
            for winnr, window in zip(count(1), vim.windows):
                curwindow_id = self._vim_getwinvar(winnr,
                                                   'powerline_window_id')
                if curwindow_id:
                    curwindow_id = int(curwindow_id)
                else:
                    curwindow_id = self.last_window_id
                    self.last_window_id += 1
                    self._vim_setwinvar(winnr, 'powerline_window_id',
                                        curwindow_id)
                statusline = self.window_statusline.format(curwindow_id)
                if self._vim_getwinvar(winnr, '&statusline') != statusline:
                    self._vim_setwinvar(winnr, '&statusline', statusline)
                if curwindow_id == window_id if window_id else window is vim.current.window:
                    assert r is None, "Non-unique window ID"
                    r = (window, curwindow_id, winnr)
            return r

    def statusline(self, window_id):
        window, window_id, winnr = self.win_idx(window_id) or (None, None,
                                                               None)
        if not window:
            return 'No window {0}'.format(window_id)
        return self.render(window, window_id, winnr)

    def new_window(self):
        window, window_id, winnr = self.win_idx(None)
        return self.render(window, window_id, winnr)

    if not hasattr(vim, 'bindeval'):
        # Method for PowerlinePyeval function. Is here to reduce the number of
        # requirements to __main__ globals to just one powerline object
        # (previously it required as well vim and json)
        @staticmethod
        def pyeval():
            import __main__
            vim.command('return ' +
                        json.dumps(eval(vim.eval('a:e'), __main__.__dict__)))
Beispiel #15
0
from __future__ import absolute_import

import os
import re

from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.segments.vim import vim_funcs

vim_funcs['winnr'] = vim_get_func('winnr', rettype=int)
vim_funcs['bufwinnr'] = vim_get_func('bufwinnr', rettype=int)
vim_funcs['getwinvar'] = vim_get_func('getwinvar')


def getbufwinvar(bufnr, var):
    return vim_funcs['getwinvar'](vim_funcs['bufwinnr'](bufnr), var)


# ---------------------------------%<----------------------------------


def tagbar(matcher_info):
    name = matcher_info['buffer'].name
    return name and os.path.basename(name) == '__Tagbar__'


def unite(matcher_info):
    return str(getbufvar(matcher_info['bufnr'], '&filetype')) == 'unite'


def vimfiler(matcher_info):
    return str(getbufvar(matcher_info['bufnr'], '&filetype')) == 'vimfiler'
Beispiel #16
0
# from powerline.bindings.vim import (vim_get_func, getbufvar, vim_getbufoption,
#                                                                         buffer_name, vim_getwinvar)
# from powerline.theme import requires_segment_info, requires_filesystem_watcher
# from powerline.lib import add_divider_highlight_group
# from powerline.lib.vcs import guess, tree_status
# from powerline.lib.humanize_bytes import humanize_bytes
# from powerline.lib import wraps_saveargs as wraps
# from collections import defaultdict

vim_funcs = {
    # 'fnamemodify': vim_get_func('fnamemodify'),
    # 'expand': vim_get_func('expand'),
    # 'bufnr': vim_get_func('bufnr', rettype=int),
    # 'line2byte': vim_get_func('line2byte', rettype=int),
    'virtcol': vim_get_func('virtcol', rettype=int),
    'getline': vim_get_func('getline'),
}

def character_info(pl):
    line_contents = vim_funcs['getline']('.')
    cursor_column = int(vim_funcs['virtcol']('.'))

    if line_contents and cursor_column <= len(line_contents):
        character = line_contents.decode('utf-8')[cursor_column - 1]
        codepoint = ord(character)

        if codepoint <= 255:
            highlight_group = "current_character"
        else:
            highlight_group = "current_character_utf"
Beispiel #17
0
def unite_status_string(pl):
    '''Return status string from unite.vim'''
    return vim_get_func('unite#get_status_string')()
Beispiel #18
0
try:
    import vim
except ImportError:
    vim = {}  # NOQA

from powerline.bindings.vim import vim_get_func, getbufvar, vim_getbufoption, buffer_name, vim_getwinvar
from powerline.theme import requires_segment_info, requires_filesystem_watcher
from powerline.lib import add_divider_highlight_group
from powerline.lib.vcs import guess, tree_status
from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib import wraps_saveargs as wraps
from collections import defaultdict

vim_funcs = {
    "virtcol": vim_get_func("virtcol", rettype=int),
    "getpos": vim_get_func("getpos"),
    "fnamemodify": vim_get_func("fnamemodify"),
    "expand": vim_get_func("expand"),
    "bufnr": vim_get_func("bufnr", rettype=int),
    "line2byte": vim_get_func("line2byte", rettype=int),
    "line": vim_get_func("line", rettype=int),
}

vim_modes = {
    "n": "NORMAL",
    "no": "N·OPER",
    "v": "VISUAL",
    "V": "V·LINE",
    "^V": "V·BLCK",
    "s": "SELECT",
Beispiel #19
0
from powerline.theme import requires_segment_info
from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.lib import add_divider_highlight_group

vim_funcs = {"tabpagebuflist": vim_get_func("tabpagebuflist", rettype=list)}


@requires_segment_info
def current_char(segment_info, **extra):
    try:
        pos = segment_info["window"].cursor
        char = segment_info["buffer"][pos[0] - 1][pos[1]]
        return "0x%02X" % ord(char)
    except Exception:
        return "0x00"


@requires_segment_info
@add_divider_highlight_group("background:divider")
def file_encoding(segment_info, expected=["utf-8"], unknown_text="unknown", **extra):
    """Return file encoding/character set.

    :return: file encoding/character set or None if unknown or missing file encoding

    Divider highlight group used: ``background:divider``.
    """
    enc = getbufvar(segment_info["bufnr"], "&fileencoding")

    if enc in expected:
        return None
    else:
Beispiel #20
0
# vim:fileencoding=utf-8:noet

from __future__ import absolute_import

from powerline.bindings.vim import vim_get_func
from powerline import Powerline
from powerline.lib import mergedicts
from powerline.matcher import gen_matcher_getter
import vim


vim_exists = vim_get_func('exists', rettype=int)


def _override_from(config, override_varname):
	if vim_exists(override_varname):
		# FIXME vim.eval has problem with numeric types, vim.bindeval may be 
		# absent (and requires converting values to python built-in types), 
		# vim.eval with typed call like the one I implemented in frawor is slow. 
		# Maybe eval(vime.eval('string({0})'.format(override_varname)))?
		overrides = vim.eval(override_varname)
		mergedicts(config, overrides)
	return config


class VimPowerline(Powerline):
	def __init__(self):
		super(VimPowerline, self).__init__('vim')

	def add_local_theme(self, key, config):
		'''Add local themes at runtime (during vim session).
Beispiel #21
0
from __future__ import absolute_import

import os
import re

from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.segments.vim import vim_funcs

vim_funcs['winnr'] = vim_get_func('winnr', rettype=int)
vim_funcs['bufwinnr'] = vim_get_func('bufwinnr', rettype=int)
vim_funcs['getwinvar'] = vim_get_func('getwinvar')


def getbufwinvar(bufnr, var):
    return vim_funcs['getwinvar'](vim_funcs['bufwinnr'](bufnr), var)

# ---------------------------------%<----------------------------------


def tagbar(matcher_info):
    name = matcher_info['buffer'].name
    return name and os.path.basename(name) == '__Tagbar__'


def unite(matcher_info):
    return str(getbufvar(matcher_info['bufnr'], '&filetype')) == 'unite'


def vimfiler(matcher_info):
    return str(getbufvar(matcher_info['bufnr'], '&filetype')) == 'vimfiler'
Beispiel #22
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from powerline.bindings.vim import vim_get_func
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE

import vim

vim_mode = vim_get_func('mode')
vim_getwinvar = vim_get_func('getwinvar')
vim_setwinvar = vim_get_func('setwinvar')
mode_translations = {
	chr(ord('V') - 0x40): '^V',
	chr(ord('S') - 0x40): '^S',
}


class VimRenderer(Renderer):
	'''Powerline vim segment renderer.'''

	def __init__(self, *args, **kwargs):
		super(VimRenderer, self).__init__(*args, **kwargs)
		self.hl_groups = {}

	def render(self, window_id, winidx, current):
		'''Render all segments.

		This method handles replacing of the percent placeholder for vim
		statuslines, and it caches segment contents which are retrieved and
Beispiel #23
0
#! /usr/bin/env python -3
# -*- coding: utf-8 -*-

import vim

from subprocess import Popen, PIPE
from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.segments.vim import window_cached, vim_funcs
# from powerline.theme import requires_segment_info
from powerline.lib.threaded import ThreadedSegment, with_docstring

vim_funcs['exists'] = vim_get_func('exists', rettype=int)


sort_indicator = {
    "on": "sort",
    "off": "name"
}

# --------%<--------
# helper functions
# --------%>--------


def vim_func_segment(pl, func_name, *args):
    if int(vim_funcs['exists']('*' + func_name)) > 0:
        f = vim_get_func(func_name, rettype=str)
        return str(f(*args))
    else:
        return None
Beispiel #24
0
class VimPowerline(Powerline):
    def init(self, pyeval='PowerlinePyeval', **kwargs):
        super(VimPowerline, self).init('vim', **kwargs)
        self.last_window_id = 1
        self.pyeval = pyeval
        self.window_statusline = '%!' + pyeval + '(\'powerline.statusline({0})\')'

    default_log_stream = sys.stdout

    def add_local_theme(self, key, config):
        '''Add local themes at runtime (during vim session).

		:param str key:
			Matcher name (in format ``{matcher_module}.{module_attribute}`` or 
			``{module_attribute}`` if ``{matcher_module}`` is 
			``powerline.matchers.vim``). Function pointed by 
			``{module_attribute}`` should be hashable and accept a dictionary 
			with information about current buffer and return boolean value 
			indicating whether current window matched conditions. See also 
			:ref:`local_themes key description <config-ext-local_themes>`.

		:param dict config:
			:ref:`Theme <config-themes>` dictionary.

		:return:
			``True`` if theme was added successfully and ``False`` if theme with 
			the same matcher already exists.
		'''
        self.update_renderer()
        matcher = self.get_matcher(key)
        theme_config = {}
        for cfg_path in self.theme_levels:
            try:
                lvl_config = self.load_config(cfg_path, 'theme')
            except IOError:
                pass
            else:
                mergedicts(theme_config, lvl_config)
        mergedicts(theme_config, config)
        try:
            self.renderer.add_local_theme(matcher, {'config': theme_config})
        except KeyError:
            return False
        else:
            # Hack for local themes support: when reloading modules it is not
            # guaranteed that .add_local_theme will be called once again, so
            # this function arguments will be saved here for calling from
            # .do_setup().
            self.setup_kwargs.setdefault('_local_themes', []).append(
                (key, config))
            return True

    @staticmethod
    def get_encoding():
        return vim.eval('&encoding')

    def load_main_config(self):
        return _override_from(
            super(VimPowerline, self).load_main_config(),
            'powerline_config_overrides')

    def load_theme_config(self, name):
        # Note: themes with non-[a-zA-Z0-9_] names are impossible to override
        # (though as far as I know exists() won’t throw). Won’t fix, use proper
        # theme names.
        return _override_from(
            super(VimPowerline, self).load_theme_config(name),
            'powerline_theme_overrides__' + name)

    def get_local_themes(self, local_themes):
        if not local_themes:
            return {}

        return dict(((matcher, {
            'config': self.load_theme_config(val)
        }) for matcher, key, val in (((
            None if k == '__tabline__' else self.get_matcher(k)), k, v)
                                     for k, v in local_themes.items())
                     if (matcher or key == '__tabline__')))

    def get_matcher(self, match_name):
        match_module, separator, match_function = match_name.rpartition('.')
        if not separator:
            match_module = 'powerline.matchers.{0}'.format(self.ext)
            match_function = match_name
        return self.get_module_attr(match_module,
                                    match_function,
                                    prefix='matcher_generator')

    def get_config_paths(self):
        try:
            return vim_getvar('powerline_config_paths')
        except KeyError:
            return super(VimPowerline, self).get_config_paths()

    def do_setup(self,
                 pyeval=None,
                 pycmd=None,
                 can_replace_pyeval=True,
                 _local_themes=()):
        import __main__
        if not pyeval:
            pyeval = 'pyeval' if sys.version_info < (3, ) else 'py3eval'
            can_replace_pyeval = True
        if not pycmd:
            pycmd = get_default_pycmd()

        set_pycmd(pycmd)

        # pyeval() and vim.bindeval were both introduced in one patch
        if not hasattr(vim, 'bindeval') and can_replace_pyeval:
            vim.command(('''
				function! PowerlinePyeval(e)
					{pycmd} powerline.do_pyeval()
				endfunction
			''').format(pycmd=pycmd))
            pyeval = 'PowerlinePyeval'

        self.pyeval = pyeval
        self.window_statusline = '%!' + pyeval + '(\'powerline.statusline({0})\')'

        self.update_renderer()
        __main__.powerline = self

        if (bool(int(vim.eval("has('gui_running') && argc() == 0")))
                and not vim.current.buffer.name and len(vim.windows) == 1):
            # Hack to show startup screen. Problems in GUI:
            # - Defining local value of &statusline option while computing global
            #   value purges startup screen.
            # - Defining highlight group while computing statusline purges startup
            #   screen.
            # This hack removes the “while computing statusline” part: both things
            # are defined, but they are defined right now.
            #
            # The above condition disables this hack if no GUI is running, Vim did
            # not open any files and there is only one window. Without GUI
            # everything works, in other cases startup screen is not shown.
            self.new_window()

        # Cannot have this in one line due to weird newline handling (in :execute
        # context newline is considered part of the command in just the same cases
        # when bar is considered part of the command (unless defining function
        # inside :execute)). vim.command is :execute equivalent regarding this case.
        vim.command('augroup Powerline')
        vim.command(
            '	autocmd! ColorScheme * :{pycmd} powerline.reset_highlight()'.
            format(pycmd=pycmd))
        vim.command(
            '	autocmd! VimLeavePre * :{pycmd} powerline.shutdown()'.format(
                pycmd=pycmd))
        vim.command('augroup END')

        # Hack for local themes support after reloading.
        for args in _local_themes:
            self.add_local_theme(*args)

    @staticmethod
    def get_segment_info():
        return {}

    def reset_highlight(self):
        try:
            self.renderer.reset_highlight()
        except AttributeError:
            # Renderer object appears only after first `.render()` call. Thus if
            # ColorScheme event happens before statusline is drawn for the first
            # time AttributeError will be thrown for the self.renderer. It is
            # fine to ignore it: no renderer == no colors to reset == no need to
            # do anything.
            pass

    if all((hasattr(vim.current.window, attr)
            for attr in ('options', 'vars', 'number'))):

        def win_idx(self, window_id):
            r = None
            for window in vim.windows:
                try:
                    curwindow_id = window.vars['powerline_window_id']
                    if r is not None and curwindow_id == window_id:
                        raise KeyError
                except KeyError:
                    curwindow_id = self.last_window_id
                    self.last_window_id += 1
                    window.vars['powerline_window_id'] = curwindow_id
                statusline = self.window_statusline.format(curwindow_id)
                if window.options['statusline'] != statusline:
                    window.options['statusline'] = statusline
                if curwindow_id == window_id if window_id else window is vim.current.window:
                    r = (window, curwindow_id, window.number)
            return r
    else:
        _vim_getwinvar = staticmethod(vim_get_func('getwinvar'))
        _vim_setwinvar = staticmethod(vim_get_func('setwinvar'))

        def win_idx(self, window_id):
            r = None
            for winnr, window in zip(count(1), vim.windows):
                curwindow_id = self._vim_getwinvar(winnr,
                                                   'powerline_window_id')
                if curwindow_id and not (r is not None
                                         and curwindow_id == window_id):
                    curwindow_id = int(curwindow_id)
                else:
                    curwindow_id = self.last_window_id
                    self.last_window_id += 1
                    self._vim_setwinvar(winnr, 'powerline_window_id',
                                        curwindow_id)
                statusline = self.window_statusline.format(curwindow_id)
                if self._vim_getwinvar(winnr, '&statusline') != statusline:
                    self._vim_setwinvar(winnr, '&statusline', statusline)
                if curwindow_id == window_id if window_id else window is vim.current.window:
                    r = (window, curwindow_id, winnr)
            return r

    def statusline(self, window_id):
        window, window_id, winnr = self.win_idx(window_id) or (None, None,
                                                               None)
        if not window:
            return FailedUnicode('No window {0}'.format(window_id))
        return self.render(window, window_id, winnr)

    def tabline(self):
        return self.render(*self.win_idx(None), is_tabline=True)

    def new_window(self):
        return self.render(*self.win_idx(None))

    if not hasattr(vim, 'bindeval'):
        # Method for PowerlinePyeval function. Is here to reduce the number of
        # requirements to __main__ globals to just one powerline object
        # (previously it required as well vim and json)
        @staticmethod
        def do_pyeval():
            import __main__
            vim.command('return ' +
                        json.dumps(eval(vim.eval('a:e'), __main__.__dict__)))

    def setup_components(self, components):
        if components is None:
            components = ('statusline', 'tabline')
        if 'statusline' in components:
            # Is immediately changed after new_window function is run. Good for
            # global value.
            vim.command(
                'set statusline=%!{pyeval}(\'powerline.new_window()\')'.format(
                    pyeval=self.pyeval))
        if 'tabline' in components:
            vim.command(
                'set tabline=%!{pyeval}(\'powerline.tabline()\')'.format(
                    pyeval=self.pyeval))
Beispiel #25
0
def vim_func_segment(pl, func_name, *args):
    if int(vim_funcs['exists']('*' + func_name)) > 0:
        f = vim_get_func(func_name, rettype=str)
        return str(f(*args))
    else:
        return None
Beispiel #26
0
# -*- coding: utf-8 -*-

from __future__ import absolute_import

from powerline.bindings.vim import vim_get_func
from powerline import Powerline
from powerline.lib import mergedicts
from powerline.matcher import gen_matcher_getter
import vim


vim_exists = vim_get_func('exists', rettype=int)


def _override_from(config, override_varname):
	if vim_exists(override_varname):
		# FIXME vim.eval has problem with numeric types, vim.bindeval may be 
		# absent (and requires converting values to python built-in types), 
		# vim.eval with typed call like the one I implemented in frawor is slow. 
		# Maybe eval(vime.eval('string({0})'.format(override_varname)))?
		overrides = vim.eval(override_varname)
		mergedicts(config, overrides)
	return config


class VimPowerline(Powerline):
	def __init__(self):
		super(VimPowerline, self).__init__('vim')

	def add_local_theme(self, key, config):
		'''Add local themes at runtime (during vim session).
Beispiel #27
0
# -*- coding: utf-8 -*-
# vim:se fenc=utf8 noet:

import os
import re
try:
	import vim
except ImportError:
	vim = {}

from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.theme import requires_segment_info

vim_funcs = {
		'col': vim_get_func('col', rettype=int),
		'virtcol': vim_get_func('virtcol', rettype=int),
		'getcwd': vim_get_func('getcwd'),
		'fnamemodify': vim_get_func('fnamemodify'),
		}

def _do_ex(command):
	'''Execute Ex command.

	Execute Ex command from args and return results string.
	'''
	vim.command('redir => tmp_do_ex | silent! {0} | redir END'.format(command))
	return vim.eval('tmp_do_ex')

def col_current_virt(pl, gradient=True):
	'''Return the current cursor column.
Beispiel #28
0
try:
    import vim
except ImportError:
    vim = {}  # NOQA

from powerline.bindings.vim import (vim_get_func, getbufvar, vim_getbufoption,
                                    buffer_name, vim_getwinvar)
from powerline.theme import requires_segment_info
from powerline.lib import add_divider_highlight_group
from powerline.lib.vcs import guess, tree_status
from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib import wraps_saveargs as wraps
from collections import defaultdict

vim_funcs = {
    'virtcol': vim_get_func('virtcol', rettype=int),
    'getpos': vim_get_func('getpos'),
    'fnamemodify': vim_get_func('fnamemodify'),
    'expand': vim_get_func('expand'),
    'bufnr': vim_get_func('bufnr', rettype=int),
    'line2byte': vim_get_func('line2byte', rettype=int),
    'line': vim_get_func('line', rettype=int),
}

vim_modes = {
    'n': 'NORMAL',
    'no': 'N·OPER',
    'v': 'VISUAL',
    'V': 'V·LINE',
    '^V': 'V·BLCK',
    's': 'SELECT',
Beispiel #29
0
except ImportError:
	vim = {}  # NOQA

from subprocess import Popen, PIPE
from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.theme import requires_segment_info
from powerline.lib import add_divider_highlight_group
from powerline.lib.vcs import guess, tree_status
from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib.threaded import ThreadedSegment, KwThreadedSegment, with_docstring
from powerline.lib import wraps_saveargs as wraps
from collections import defaultdict


vim_funcs = {
	'virtcol': vim_get_func('virtcol', rettype=int),
	'fnamemodify': vim_get_func('fnamemodify', rettype=str),
	'expand': vim_get_func('expand', rettype=str),
	'bufnr': vim_get_func('bufnr', rettype=int),
	'line2byte': vim_get_func('line2byte', rettype=int),
	'exists': vim_get_func('exists', rettype=int),
}

vim_modes = {
	'n': 'NORMAL',
	'no': 'N·OPER',
	'v': 'VISUAL',
	'V': 'V·LINE',
	'^V': 'V·BLCK',
	's': 'SELECT',
	'S': 'S·LINE',
Beispiel #30
0
from powerline.theme import requires_segment_info
from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.lib import add_divider_highlight_group

vim_funcs = {
    'tabpagebuflist': vim_get_func('tabpagebuflist', rettype=list),
}


@requires_segment_info
def current_char(segment_info, **extra):
    try:
        pos = segment_info['window'].cursor
        char = segment_info['buffer'][pos[0] - 1][pos[1]]
        return "0x%02X" % ord(char)
    except Exception:
        return "0x00"


@requires_segment_info
@add_divider_highlight_group('background:divider')
def file_encoding(segment_info,
                  expected=['utf-8'],
                  unknown_text='unknown',
                  **extra):
    '''Return file encoding/character set.

    :return: file encoding/character set or None if unknown or missing file encoding

    Divider highlight group used: ``background:divider``.
    '''
Beispiel #31
0
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)

import sys

import vim

from powerline.bindings.vim import vim_get_func, vim_getoption, environ, current_tabpage
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from powerline.theme import Theme
from powerline.lib.unicode import unichr, register_strwidth_error


vim_mode = vim_get_func('mode', rettype='unicode')
if int(vim.eval('v:version')) >= 702:
	_vim_mode = vim_mode
	vim_mode = lambda: _vim_mode(1)

mode_translations = {
	unichr(ord('V') - 0x40): '^V',
	unichr(ord('S') - 0x40): '^S',
}


class VimRenderer(Renderer):
	'''Powerline vim segment renderer.'''

	character_translations = Renderer.character_translations.copy()
	character_translations[ord('%')] = '%%'
Beispiel #32
0
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)

import os
import re
import time
try:
    import vim
except ImportError:
    vim = {}

from powerline.bindings.vim import vim_get_func, getbufvar, buffer_name
from powerline.theme import requires_segment_info

vim_funcs = {
    'col': vim_get_func('col', rettype='int'),
    'virtcol': vim_get_func('virtcol', rettype='int'),
    'getcwd': vim_get_func('getcwd'),
    'fnamemodify': vim_get_func('fnamemodify'),
}


def _do_ex(command):
    '''Execute Ex command.

	Execute Ex command from args and return results string.
	'''
    vim.command('redir => tmp_do_ex | silent! {0} | redir END'.format(command))
    return vim.eval('tmp_do_ex').decode('utf-8')

Beispiel #33
0
from powerline.bindings.vim import vim_get_func, environ
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from powerline.theme import Theme

import vim
import sys


try:
	from __builtin__ import unichr as chr
except ImportError:
	pass


vim_mode = vim_get_func('mode', rettype=str)
mode_translations = {
	chr(ord('V') - 0x40): '^V',
	chr(ord('S') - 0x40): '^S',
}


class VimRenderer(Renderer):
	'''Powerline vim segment renderer.'''

	character_translations = Renderer.character_translations.copy()
	character_translations[ord('%')] = '%%'

	segment_info = Renderer.segment_info.copy()
	segment_info.update(environ=environ)
Beispiel #34
0
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)

import sys

import vim

from powerline.bindings.vim import vim_get_func, vim_getoption, environ, current_tabpage, get_vim_encoding
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from powerline.theme import Theme
from powerline.lib.unicode import unichr, register_strwidth_error


vim_mode = vim_get_func('mode', rettype='unicode')
if int(vim.eval('v:version')) >= 702:
	_vim_mode = vim_mode
	vim_mode = lambda: _vim_mode(1)

mode_translations = {
	unichr(ord('V') - 0x40): '^V',
	unichr(ord('S') - 0x40): '^S',
}


class VimRenderer(Renderer):
	'''Powerline vim segment renderer.'''

	character_translations = Renderer.character_translations.copy()
	character_translations[ord('%')] = '%%'
Beispiel #35
0
import os
try:
	import vim
except ImportError:
	vim = {}  # NOQA

from powerline.bindings.vim import vim_get_func, getbufvar, vim_getbufoption
from powerline.theme import requires_segment_info
from powerline.lib import add_divider_highlight_group
from powerline.lib.vcs import guess, tree_status
from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib import wraps_saveargs as wraps
from collections import defaultdict

vim_funcs = {
	'virtcol': vim_get_func('virtcol', rettype=int),
	'fnamemodify': vim_get_func('fnamemodify', rettype=str),
	'expand': vim_get_func('expand', rettype=str),
	'bufnr': vim_get_func('bufnr', rettype=int),
	'line2byte': vim_get_func('line2byte', rettype=int),
}

vim_modes = {
	'n': 'NORMAL',
	'no': 'N·OPER',
	'v': 'VISUAL',
	'V': 'V·LINE',
	'^V': 'V·BLCK',
	's': 'SELECT',
	'S': 'S·LINE',
	'^S': 'S·BLCK',
Beispiel #36
0
# vim:fileencoding=utf-8:noet

from __future__ import absolute_import

from powerline.bindings.vim import vim_get_func
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from powerline.theme import Theme

import vim
import sys

vim_mode = vim_get_func('mode', rettype=str)
mode_translations = {
    chr(ord('V') - 0x40): '^V',
    chr(ord('S') - 0x40): '^S',
}


class VimRenderer(Renderer):
    '''Powerline vim segment renderer.'''
    def __init__(self, *args, **kwargs):
        if not hasattr(vim, 'strwidth'):
            # Hope nobody want to change this at runtime
            if vim.eval('&ambiwidth') == 'double':
                kwargs = dict(**kwargs)
                kwargs['ambigious'] = 2
        super(VimRenderer, self).__init__(*args, **kwargs)
        self.hl_groups = {}

    def shutdown(self):
Beispiel #37
0
from __future__ import (unicode_literals, division, absolute_import, print_function)

from powerline.bindings.vim import (buffer_name, vim_get_func)
from powerline.lib.vcs import guess
from powerline.theme import (requires_filesystem_watcher, requires_segment_info)

import re
import os

try:
	import vim
except ImportError:
	vim = object()

vim_funcs = {
		'fnamemodify': vim_get_func('fnamemodify', rettype='bytes'),
		'getcwd': vim_get_func('getcwd')
		}

SCHEME_RE = re.compile(b'^\\w[\\w\\d+\\-.]*(?=:)')

@requires_filesystem_watcher
@requires_segment_info
def repo_directory(pl, segment_info, create_watcher):
	name = buffer_name(segment_info)
	file_directory = vim_funcs['fnamemodify'](name, ':h')
	if not name:
		return None
	match = SCHEME_RE.match(name)
	if match:
		repo_directory = file_directory
Beispiel #38
0
#! /usr/bin/env python -3
# -*- coding: utf-8 -*-

import vim

from subprocess import Popen, PIPE
from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.segments.vim import window_cached, vim_funcs
# from powerline.theme import requires_segment_info
from powerline.lib.threaded import ThreadedSegment, with_docstring

vim_funcs['exists'] = vim_get_func('exists', rettype=int)


sort_indicator = {
    "on": "sort",
    "off": "name"
}

# --------%<--------
# helper functions
# --------%>--------


def vim_func_segment(pl, func_name, *args):
    if int(vim_funcs['exists']('*' + func_name)) > 0:
        f = vim_get_func(func_name, rettype=str)
        return str(f(*args))
    else:
        return None
Beispiel #39
0
from powerline.theme import requires_segment_info, requires_filesystem_watcher
from powerline.lib import add_divider_highlight_group
from powerline.lib.vcs import guess
from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib import wraps_saveargs as wraps
from powerline.segments.common.vcs import BranchSegment, StashSegment
from powerline.segments import with_docstring
from powerline.lib.unicode import string, unicode

try:
    from __builtin__ import xrange as range
except ImportError:
    pass

vim_funcs = {
    'virtcol': vim_get_func('virtcol', rettype='int'),
    'getpos': vim_get_func('getpos'),
    'fnamemodify': vim_get_func('fnamemodify', rettype='bytes'),
    'line2byte': vim_get_func('line2byte', rettype='int'),
    'line': vim_get_func('line', rettype='int'),
}

vim_modes = {
    'n': 'NORMAL',
    'no': 'N-OPER',
    'v': 'VISUAL',
    'V': 'V-LINE',
    '^V': 'V-BLCK',
    's': 'SELECT',
    'S': 'S-LINE',
    '^S': 'S-BLCK',
Beispiel #40
0
# -*- coding: utf-8 -*-
# vim:se fenc=utf8 noet:

import os
import re
try:
	import vim
except ImportError:
	vim = {}

from powerline.bindings.vim import vim_get_func, getbufvar
from powerline.theme import requires_segment_info

vim_funcs = {
		'col': vim_get_func('col', rettype=int),
		'virtcol': vim_get_func('virtcol', rettype=int),
		'getcwd': vim_get_func('getcwd'),
		}

def _do_ex(command):
	'''Execute Ex command.

	Execute Ex command from args and return results string.
	'''
	vim.command('redir => tmp_do_ex | silent! {0} | redir END'.format(command))
	return vim.eval('tmp_do_ex')

def col_current_virt(pl, gradient=True):
	'''Return the current cursor column.

	Since default 'col_current()' function returns current OR virtual column