def insert_new_line(): cursor = _get_cursor() indent = vim.Function('indent')(cursor[0]) tabwidth = vim.Function('shiftwidth')() in_brackets = _is_cursor_between_brackets() expandtab = int(vim.eval('&expandtab')) if not expandtab: symbol = '\t' shift = indent/tabwidth next_shift = shift if in_brackets: next_shift += 1 else: symbol = ' ' shift = indent next_shift = shift if in_brackets: next_shift += tabwidth if in_brackets and in_brackets[1] == None: _insert_new_line_at_cursor(1, next_shift*symbol) _set_cursor(cursor[0]+1, next_shift) return if not in_brackets: _insert_new_line_at_cursor(1, shift*symbol) _set_cursor(cursor[0]+1, shift) return _insert_new_line_at_cursor(2, shift*symbol) vim.current.buffer[cursor[0]] = (next_shift * symbol) _set_cursor(cursor[0]+1, next_shift)
def getftime(nr): try: bufname = vim.Function('bufname') ftime = vim.Function('getftime') return ftime(bufname(nr)) except vim.error: return -1
def _is_cursor_in_string(cursor): synstack = vim.Function('synstack')(cursor[0], cursor[1] + 1) for syn_id in synstack: syn_name = vim.Function('synIDattr')( vim.Function('synIDtrans')(syn_id), "name", ) if syn_name.lower() == 'string': return True break return False
def get_encoding(nr): try: getbufvar = vim.Function('getbufvar') encoding = getbufvar(nr, '&encoding') except vim.error: encoding = '' return to_unicode(encoding or 'utf-8', 'utf-8')
def vim_func_exists(f): try: vim.Function(f) except ValueError: return False else: return True
def correct_current_pair(open_pair, close_pair): buffer = vim.current.buffer for pair in _current_pairs: corrected = False close_pair_pos = _current_pairs[pair] if len(buffer) < close_pair_pos[0] - 1: continue if len(buffer[close_pair_pos[0] - 1]) <= close_pair_pos[1]: continue if buffer[close_pair_pos[0] - 1][close_pair_pos[1]] != close_pair: continue moved = _delete_at(close_pair_pos, 1) try: with _restore_cursor(): cursor = _get_cursor() line = buffer[cursor[0] - 1] if line[cursor[1] - 1] == close_pair: _set_cursor(cursor[0], cursor[1] - 1) open_pair_pos = vim.Function('searchpairpos')( _escape_open_pair(open_pair), "", close_pair, "nb", ) open_pair_pos = ( int(open_pair_pos[0]), int(open_pair_pos[1]) - 1 ) if open_pair_pos <= (0, 0): continue current_pair = (buffer.number, open_pair_pos, close_pair) if current_pair not in _current_pairs: continue if _current_pairs[current_pair] == close_pair_pos: corrected = True finally: if not corrected: _insert_at(close_pair_pos, close_pair) if moved: _move_cursor_relative(0, 1) else: _insert_at_cursor(close_pair) del _current_pairs[pair] return True return False
def testFuncrefVim(): vim.Function = mock.MagicMock() vim.Function("vim#function#echovim").return_value = b'vim' vim.Function( "vim#function#echovim" ).__repr__ = lambda self: "<vim.Function 'vim#function#echovim'>" func = vim_utils.VimFunctionWrapper("vim#function#echovim") print("\nfuncref:", func) assert '<locals>' not in repr(func) # do we have pretty name? assert 'vim#function#echovim' in repr(func) r = func("hello") assert isinstance(r, str) and r == 'vim' vim.Function.assert_called_with("vim#function#echovim") vim.Function("vim#function#echovim").assert_called_with("hello")
async def progress_task(response_iterator): import vim progress_function = vim.Function("vim_cmake_server#update_progress") error_function = vim.Function("vim_cmake_server#report_error") async for response in response_iterator: response_type = response["type"] if response_type == "message": _message_function(response["message"]) elif response_type == "progress": #with open("output.txt", "a") as output_file: #print('Progress Message', file=output_file) progress_function(response["progressMessage"], response["progressMinimum"], response["progressMaximum"], response["progressCurrent"]) elif response_type == "error": error_function(response["errorMessage"])
def call(cls, func, *args): try: f = cls._func_cache[func] except KeyError: if IS_NVIM: f = cls._func_cache[func] = getattr(vim.funcs, func) else: f = cls._func_cache[func] = vim.Function(func) return f(*args)
def is_comment_or_string(self): """Test current position is in comment or string. :returns: 0 not in comment or string 1 in comment 2 in string 3 in constant """ return vim.Function('completor#utils#in_comment_or_string')()
def cursor_word(self): """Get the word under cursor. :rtype: unicode """ try: return to_unicode( vim.Function('expand')('<cword>'), get_encoding()) except vim.error: return
def _create_vim_function(name: str) -> Optional[_vim.Function]: """Create a wrapped Vim function using _vim.Function. :name: The Vim function name. :return: The wrapped function or ``None`` if the function does not exist in this version of Vim. """ if int(_vim.eval(f'exists("*{name}")')): return _vim.Function(name) return None
def show_location_list(locations): location_list_data = [{ 'filename': shorten_path(location['path']), 'lnum': to_vim_row(location['line']), 'col': to_vim_col(location['column']), 'text': location['text'].strip() } for location in locations] # replace contents of current window's location list vim.Function('setloclist')(0, location_list_data, 'r') # show current window's location list window vim.command('lwindow')
def _vim_popup(text, line_offset): """Create a popup using Vim +popupwin.""" vim.Function("popup_create")( text, { "line": f"cursor{line_offset}", "col": "cursor", "wrap": False, "padding": (0, 1, 0, 1), "highlight": "PathfinderPopup", "time": int(vim.vars["pf_popup_time"]), "zindex": 1000, }, )
def _remove_pair(open_pair, close_pair): pair_pos = vim.Function('searchpairpos')( _escape_open_pair(open_pair), "", close_pair, "n", ) if pair_pos[0] == 0: return pair_pos = (pair_pos[0], pair_pos[1] - 1) _delete_at(pair_pos, 1)
def substitute(self, patttern, string, Range='g'): return_no = 0 myfunc = vim.Function('substitute') new_win = env.curbuf()[:] no = 0 for line in new_win: value = myfunc(line, patttern, string, Range) value = value.decode() new_win[no] = value no += 1 if value != line: return_no += 1 vim.current.buffer[:] = new_win return return_no
def correct_inserted_pair(open_pair, close_pair): buffer= vim.current.buffer cursor = _get_cursor() text = buffer[cursor[0]-1] if cursor[1]-1 > 0: if buffer[cursor[0]-1][cursor[1]-1] == close_pair: return False open_pair_pos = vim.Function('searchpairpos')( _escape_open_pair(open_pair), "", close_pair, "nb", ) if not open_pair_pos or (open_pair_pos[0] == 0 and open_pair_pos[0] == 0): return False close_pair_pos = None with _restore_cursor(): _set_cursor(open_pair_pos[0], open_pair_pos[1]-1) cursor_before = _get_cursor() vim.command('normal! %') cursor_after = _get_cursor() close_pair_pos = _get_cursor() if cursor_before == cursor_after: return False if close_pair_pos[0] == cursor[0]: if close_pair_pos[1] == cursor[1]: return False if close_pair_pos[0] == open_pair_pos[0]: if close_pair_pos[1] == open_pair_pos[1]: return False if not close_pair_pos: return False if close_pair_pos[0] != vim.current.window.cursor[0]: return False moved = _delete_at(close_pair_pos, 1) _insert_at_cursor(close_pair) return True
def parse(self, base): trigger = self.trigger_cache.get(self.ft) if not trigger or not trigger.search(base): return [] try: func_name = vim.current.buffer.options['omnifunc'] if not func_name: return [] omnifunc = vim.Function(func_name) start = omnifunc(1, '') codepoint = self.start_column() if start < 0 or start != codepoint: return [] return omnifunc(0, to_bytes(base, get_encoding())[codepoint:]) except (vim.error, ValueError, KeyboardInterrupt): return []
def show_output(motions): if vim.eval("has('nvim')"): print(compact_motions(motions)) elif vim.eval("has('popupwin')"): output = list(explained_motions(motions)) vim.Function("popup_create")( output, { # 4 lines up from the bottom of the screen "line": vim.options["lines"] - 4, # No "col" option = centered on screen # Make the "line" option relative to the bottom edge "pos": "botleft", "wrap": False, "padding": (0, 1, 0, 1), "time": 3000 + (500 * len(output)), }, ) else: print(compact_motions(motions))
def insertFromCurrentLine(): path_file_temp = vim.vars['quickInsertSampleFile'] expand = vim.Function("expand") cb = vim.current.buffer cw = vim.current.window cword = expand("<cword>").decode('utf-8') tree = ET.parse(path_file_temp) root = tree.getroot() content = [x.text for x in tree.iterfind('content/item[@word="%s"]'%cword)] if not content: return 0 lines = SubData(content[0], path_file_temp).run().splitlines() if not lines[0].strip(): lines.pop(0) if not lines[-1].strip(): lines.pop(len(lines)-1) row_num = cw.cursor[0] vim.current.line = lines[0] if len(lines) > 1: cb.append(lines[1:], row_num)
def search(self, patttern, flag=None): self.normalCommand('gg') no = 0 strings = self.curWinData() return_str = [] lines = len(strings) func = vim.Function('search') if flag is None: flag = 'c' while no <= lines: no += 1 myeval = func(patttern, ) if myeval == 0: break myeval -= 1 if strings[myeval] in return_str: continue return_str.append(strings[myeval]) self.normalCommand('gg') return return_str
def load_cache(): type_index_file = vim.eval("a:type_index_file") cache = [] with open(type_index_file) as f: for t in f.readlines(): t = t.strip() if len(t) == 0: continue components = t.split('\t') name, page = components[0], components[1] entry = vim.Dictionary( word=name, kind='common', source='unitydoc', action__page=page, ) cache.append(entry) p = vim.Function('unite#sources#unitydoc#set_cache', args=[cache]) p()
def offset(self): line, col = vim.current.window.cursor line2byte = vim.Function('line2byte') return line2byte(line) + col - 1
_current_definitions = None """Current definitions to use for highlighting.""" _pending_definitions = {} """Pending definitions for unloaded buffers.""" _placed_definitions_in_buffers = set() """Set of buffers for faster cleanup.""" IS_NVIM = hasattr(vim, 'from_nvim') if IS_NVIM: vim_prop_add = None else: vim_prop_type_added = False try: vim_prop_add = vim.Function("prop_add") except ValueError: vim_prop_add = None else: vim_prop_remove = vim.Function("prop_remove") def clear_usages(): """Clear existing highlights.""" global _current_definitions if _current_definitions is None: return _current_definitions = None if IS_NVIM: for buf in _placed_definitions_in_buffers:
def __init__(self, name: str): self._fn = vim.Function(name)
import sys import os import threading import vim import logging import msgpack import neovim_rpc_server_api_info import neovim_rpc_methods import threading import socket import time import subprocess from neovim.api import common as neovim_common import neovim_rpc_protocol vim_error = vim.Function('neovim_rpc#_error') # protable devnull if sys.version_info.major == 2: DEVNULL = open(os.devnull, 'wb') else: from subprocess import DEVNULL if sys.version_info.major == 2: from Queue import Queue, Empty as QueueEmpty else: from queue import Queue, Empty as QueueEmpty # NVIM_PYTHON_LOG_FILE=nvim.log NVIM_PYTHON_LOG_LEVEL=INFO vim test.md try:
def lfFunction(name): if lfEval("has('nvim')") == '1': func = partial(vim.call, name) else: func = vim.Function(name) return func
def as_vim_function(self): """Create a vim.Function that will route to this callback.""" return _vim.Function('VPE_Call', args=[self.uid])
def tempname(self): """Write buffer content to a temp file and return the file name :rtype: unicode """ return to_unicode(vim.Function('completor#utils#tempname')(), 'utf-8')
def current_directory(self): """Return the directory of the file in current buffer :rtype: unicode """ return to_unicode(vim.Function('expand')('%:p:h'), 'utf-8')