def vim(): child_argv = os.environ.get('NVIM_CHILD_ARGV') listen_address = os.environ.get('NVIM_LISTEN_ADDRESS') if child_argv is None and listen_address is None: child_argv = '["nvim", "-u", "NONE", "--embed"]' if child_argv is not None: editor = pynvim.attach('child', argv=json.loads(child_argv)) else: editor = pynvim.attach('socket', path=listen_address) return editor
def attach_vim(serveraddr): if len(serveraddr.split(':')) == 2: serveraddr, port = serveraddr.split(':') port = int(port) vim = attach('tcp', address=serveraddr, port=port) else: vim = attach('socket', path=serveraddr) # sync path for path in vim.call( 'globpath', vim.options['runtimepath'], 'rplugin/python3', 1).split('\n'): sys.path.append(path) # Remove current path del sys.path[0] return vim
def execute_command(cmd=''): """Execute command""" if not cmd: return files = glob('/tmp/nvim*/0') for nvim in files: instance = attach('socket', path=nvim) instance.command(cmd)
def rplugin_attach(): """Let's define a basic function to initialize everything.""" global_nvim = pynvim.attach('socket', path=os.environ['NVIM_LISTEN_ADDRESS']) return global_nvim
def get_nvim(name='nvim-qt.exe'): return pynvim.attach('socket', path=get_nvim_address(name))
if hasattr(module_obj, method): getattr(module_obj, method)(*args) else: raise Exception('method %s not found' % method) pass def on_setup(): pass try: # create another connection to avoid synchronization issue? if len(serveraddr.split(':')) == 2: serveraddr, port = serveraddr.split(':') port = int(port) nvim = attach('tcp', address=serveraddr, port=port) else: nvim = attach('socket', path=serveraddr) sys.modules['vim'] = nvim sys.modules['nvim'] = nvim paths = nvim.eval(r'globpath(&rtp,"pythonx",1) . "\n" .' r' globpath(&rtp,"rplugin/python3",1)') for path in paths.split("\n"): if not path: continue if path not in sys.path: sys.path.append(path) module_obj = importlib.import_module(module)
import os import pynvim import sys address = os.environ.get('NVIM') if not address: sys.exit(0) nvim = pynvim.attach("socket", path=address) name = next(filter(lambda item: item != '\n', sys.stdin)).split(maxsplit=1)[0].lower() nvim.command(f'Man {name}')
if Path(executable) != _RT_PY: raise RuntimeError() else: import pynvim import pynvim_pp import std2 import yaml except (ImportError, RuntimeError): msg = """ Please update dependencies using :CHADdeps - - Dependencies will be installed privately inside `chadtree/.vars` `rm -rf chadtree/` will cleanly remove everything """ msg = dedent(msg) print(msg, end="", file=stderr) exit(1) else: from pynvim import attach from pynvim_pp.client import run_client from .client import ChadClient nvim = attach("socket", path=args.socket) code = run_client(nvim, client=ChadClient()) exit(code) else: assert False
def get_nvim(): return attach('socket', path=get_nvim_address())
def vim(): argv = ['nvim', '-u', VIMRC, '--embed', '--headless'] vim = neovim.attach('child', argv=argv) return WrappedVim(vim)
# pylint: disable=all # A basic script to start up a neovim instance and start the plugin running. # This is intended to be used with a debugger, to move through the plugin. import pynvim import os from typing import List from nvim_diary_template.plugin import DiaryTemplatePlugin # Get the current nvim instance. If there are multiple instances, it may be # more reliable to setup a dedicated address, see: # http://pynvim.readthedocs.io/en/latest/development.html#usage-through-the-python-repl PIPES: List[str] = os.listdir("\\\\.\\pipe") CURRENT_PIPE: str = [pipe for pipe in PIPES if pipe.startswith("nvim")][0] NVIM: pynvim.Nvim = pynvim.attach("socket", path=f"\\\\.\\pipe\\{CURRENT_PIPE}") # Initialise the options, then run the required function. plugin: DiaryTemplatePlugin = DiaryTemplatePlugin(NVIM) plugin.check_options() plugin.make_diary_command()
from pynvim import attach import time nvim = attach('socket', path='/tmp/nvim') # Get current buffer # buf = nvim.current.buffer # # Replace line 0 # buf[0] = 'replaced done' # # # Set global var # nvim.vars['global_var'] = [1, 2, 3] # nvim.eval('g:global_var') # # # Get length # length = nvim.request("nvim_buf_line_count", buf) # # # Highlight and clear # ## Create a namespace to manage highlights # nid = nvim.request("nvim_create_namespace", "something") # # # params are curr_buffer, namespace_id, hl_group, row, column start, column end # ## Highlight group can be found from :highlight # ev = nvim.request("nvim_buf_add_highlight", 0, nid, "PMenu", 0, 0, -1) # time.sleep(2) # # # Clear namespace # ev = nvim.request("nvim_buf_clear_namespace", 0, nid, 0, -1) # # # Find and highlight # ## Put some text
if isinstance(lvl, int): level = lvl logging.basicConfig( filename=logfile, level=level, format=( '%(asctime)s [%(levelname)s @ ' '%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s')) setup_logging() from plugin import Plugin if "VIM_NODE_RPC" in os.environ: nvim = attach('socket', path=os.environ['NVIM_LISTEN_ADDRESS']) else: nvim = attach('stdio') plugin = Plugin(nvim) IS_PYTHON3 = sys.version_info >= (3, 0) if IS_PYTHON3: unicode_errors_default = 'surrogateescape' else: unicode_errors_default = 'strict' logger = logging.getLogger(__name__) error, debug, info, warn = ( logger.error,
def start(): # For now, treat all arguments that don't start with - or + as filenames. This # is good enough to recognize '-f' and `+11`, which is all this script really # needs right now. filenames = [ re.sub(" ", r"\ ", os.path.abspath(arg)) for arg in sys.argv[1:] if not arg[0] in ["-", "+"] ] nvim_socket = os.environ.get("NVIM_LISTEN_ADDRESS") if nvim_socket is None: # If we aren't running inside a `:terminal`, just exec nvim. os.execvp("nvim", sys.argv[:]) nvim = pynvim.attach("socket", path=nvim_socket) existing_buffers = get_listed_buffers(nvim) nvim.command("split") nvim.command("args %s" % " ".join(filenames)) new_buffers = get_listed_buffers(nvim).difference(existing_buffers) for arg in sys.argv: if arg[0] == "+": nvim.command(arg[1:]) # The '-f' flag is a signal that we're in a situation like a `git commit` # invocation where we need to block until the user is done with the file(s). if "-f" in sys.argv and len(new_buffers) > 0: # The rule here is that the user is 'done' with the opened files when none # of them are visible onscreen. This allows for use cases like hitting `:q` # on a `git commit` tempfile. However, we can't just poll to see if they're # visible, because using `nvim.windows`, `nvim.eval()`, or `nvim.call()` # will interrupt any multi-key mappings the user may be inputting. The # solution is to set a buffer-local autocmd on each opened buffer so that # we only check for visibility immediately after the user either closes or # hides one of the buffers. channel_id = nvim.channel_id for buffer in new_buffers: nvim.command( ("autocmd BufDelete,BufHidden <buffer=%d> " + 'call rpcnotify(%d, "check_buffers")') % (buffer, channel_id)) stay_open = True while stay_open: # block until `rpcnotify` is called nvim.next_message() open_buffers = [window.buffer.number for window in nvim.windows] stay_open = any([buffer in open_buffers for buffer in new_buffers]) # Now that none of the opened files are visible anymore, we do a few # cleanup steps before ending the script: # * Clear the arg list, since otherwise `:next` would reopen the tempfile # or whatever. # * Clear the autocmds we added, since `bdelete` just hides the buffer and # the autocmds will still be active if the user reopens the file(s). # * Delete each of the buffers we created. nvim.command("argdel *") for buffer in new_buffers: nvim.command("autocmd! BufDelete,BufHidden <buffer=%d>" % buffer) nvim.command("bdelete! %d" % buffer)
#!/usr/bin/env python # neovim-autocd.py import pynvim import os nvim = pynvim.attach('socket', path=os.environ['NVIM_LISTEN_ADDRESS']) nvim.vars['__autocd_cwd'] = os.getcwd() nvim.command('execute "lcd" fnameescape(g:__autocd_cwd)') del nvim.vars['__autocd_cwd']
def main(args): nvim = attach("socket", path=args.socket) fd = ArrowGuy(nvim) fd.move()
def setUp(self): self.nvim = attach('child', argv=[ "/bin/env", "nvim", "--embed", "--headless", "--noplugin", "--clean", "-n" ])
def test(self): from pynvim import attach nvim = attach('socket', path='/tmp/nvim')
# Should never happen -- the only escaped characters should be # '\\', 'e', '"', and 'C' else: raise ValueError escape_next = False else: binding += char position += 1 if __name__ == "__main__": if len(sys.argv) != 5: sys.exit(1) # Just let exceptions raise -- we'll get the information and I can account # for that case. possible_completions = find_command_from_output(sys.argv[1]) list_glob_completions = find_command_from_output(sys.argv[2]) discard_line = find_command_from_output(sys.argv[3]) nvim_socket_path = os.getenv('NVIM') if not nvim_socket_path: nvim_socket_path = os.getenv('NVIM_LISTEN_ADDRESS') nvim = pynvim.attach('socket', path=nvim_socket_path) curbuf = nvim.buffers[int(sys.argv[4])] curbuf.vars['vsh_completions_cmd'] = [ possible_completions, list_glob_completions, discard_line ]
def _reload(instance, colorscheme_file): nvim = attach('socket', path=instance) nvim.command(f'source {colorscheme_file}')
#!/usr/bin/env python3 import os import pynvim NVIM_LISTEN_ADDRESS = os.environ.get('NVIM_LISTEN_ADDRESS') if NVIM_LISTEN_ADDRESS: nvim = pynvim.attach('socket', path=NVIM_LISTEN_ADDRESS) nvim.command(f'cd {os.getcwd()}') nvim.command('lua saveTermCwd()')
'connect to running Nvim to get CocAction("getWorkspaceSymbols", query)') parser.add_argument('socket', help="returned by Nvim's v:servername") parser.add_argument('bufnr', help="Nvim buffer where query should be done") parser.add_argument('query', help="query to pass to CocAction('getWorkspaceSymbols')") parser.add_argument('ansi_typedef', help="ansi code for highlight Typedef") parser.add_argument('ansi_comment', help="ansi code for highlight Comment") parser.add_argument('ansi_ignore', help="ansi code for highlight Ignore") parser.add_argument('symbol_excludes', help="Coc config symbol excludes list") parser.add_argument( '--kind', nargs=1, help='only search for a specific "kind" (class, function, etc)') args = parser.parse_args() nvim = attach('socket', path=args.socket) items = nvim.call('CocAction', 'getWorkspaceSymbols', args.query, int(args.bufnr)) if items is None or len(items) == 0: exit(0) symbol_excludes = eval(args.symbol_excludes) exclude_re_patterns = get_exclude_re_patterns(symbol_excludes) ignored_colon = args.ansi_ignore.replace('STRING', ':') for item in items: lnum = item['location']['range']['start']['line'] + 1 col = item['location']['range']['start']['character'] filename = unquote(item['location']['uri'].replace('file://', ''))
#!/usr/bin/env python3 """ Open a file from inside a Neovim terminal in parent Neovim instance. """ from argparse import ArgumentParser from os import environ, execvp, path from pynvim import attach parser = ArgumentParser(description="Neovim client") parser.add_argument("file", nargs='+', help="file(s) to open") files = [path.abspath(f).replace(' ', "\\ ") for f in parser.parse_args().file] socket = environ.get("NVIM_LISTEN_ADDRESS", None) if socket: nvim = attach("socket", path=socket) nvim.command(f"drop {' '.join(files)}") else: execvp("nvim", ["nvim"] + files)