Esempio n. 1
0
File: v.py Progetto: DJMcMayhem/V
    def __init__(self, args):
        self.args = args

        try:
            if args["--debug"]:
                nvim_launcher_thread = threading.Thread(target=self.__call_nvim__) #Launch nvim in new thread so that V doesn't hang
                nvim_launcher_thread.start()
                time.sleep(1)
                socket = os_code.get_socket_path(args)

                try:
                    self.nvim_instance = neovim.attach("socket", path=socket)
                except py33_exceptions.FileNotFoundError:
                    sys.stderr.write("Couldn't connect to nvim. Did you export your NVIM_LIST_ADDRESS?\n\n")
                    sys.exit()

            else:
                args = os_code.get_embedded_nvim_args(args)
                try:
                    self.nvim_instance = neovim.attach("child", argv=args)
                except py33_exceptions.FileNotFoundError:
                    sys.stderr.write("Couldn't find the neovim executable! Is nvim in your $PATH?\n\n")
                    sys.exit()
        except IOError:
            sys.stderr.write("Couldn't find the neovim executable! Is neovim installed?\n\n")
            sys.exit()

        if self.args["--safe"]:
            self.nvim_instance.command("source nvim/safe_mode.vim")

        self.input_mappings = {'\n' : '\r', '<': "<lt>"}
Esempio n. 2
0
    def __init__(self, args):
        self.args = args

        if args["-d"]:
            nvim_launcher_thread = threading.Thread(target=self.__call_nvim__) #Launch nvim in new thread so that V doesn't hang
            nvim_launcher_thread.start()
            time.sleep(1)
            socket = os_code.get_socket_path(args)

            try:
                self.nvim_instance = neovim.attach("socket", path=socket)
            except py33_exceptions.FileNotFoundError:
                sys.stderr.write("Couldn't connect to nvim. Did you export your NVIM_LIST_ADDRESS?\n\n")
                sys.exit()

        else:
            args = os_code.get_embedded_nvim_args(args)
            try:
                self.nvim_instance = neovim.attach("child", argv=args)
            except py33_exceptions.FileNotFoundError:
                sys.stderr.write("Couldn't find the neovim executable! Is nvim in your $PATH?\n\n")
                sys.exit()

        if self.args["--safe"]:
            self.nvim_instance.command("source nvim/safe_mode.vim")

        self.active_reg = "a"
        self.pending_number = ""
        self.pending_command = ""
        self.loop_symbol = ""
        self.loop_num = ""
        self.recorded_text = ""
        self.recording = False
        self.keys_sent = []
Esempio n. 3
0
 def __init__(self):
     """Construct an engine."""
     addr = os.environ.get('NVIM_LISTEN_ADDRESS')
     if addr:
         self.nvim = attach('socket', path=addr)
     else:
         args = ["/usr/bin/env", "nvim", "--embed", "-n", "-u", "init.vim"]
         self.nvim = attach('child', argv=args)
Esempio n. 4
0
def main():

    start_type = sys.argv[1]

    if start_type == 'core':

        # logging setup
        level = logging.INFO
        if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
            # TODO this affects the log file name
            setup_logging('cm_core')
            l = getattr(logging, os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
                        level)
            if isinstance(l, int):
                level = l

        logger = logging.getLogger(__name__)
        logger.setLevel(level)

        try:
            # connect neovim
            nvim = attach('stdio')
            handler = Handler(nvim)
            logger.info('starting core, enter event loop')
            nvim_event_loop(logger, nvim, handler)
        except Exception as ex:
            logger.info('Exception: %s', ex)

    elif start_type == 'channel':

        path = sys.argv[2]
        dir = os.path.dirname(path)
        name = os.path.splitext(os.path.basename(path))[0]

        # logging setup
        level = logging.INFO
        if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
            # TODO this affects the log file name
            setup_logging(name)
            l = getattr(logging, os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
                        level)
            if isinstance(l, int):
                level = l

        # use the module name here
        logger = logging.getLogger(name)
        logger.setLevel(level)

        try:
            # connect neovim
            nvim = attach('stdio')
            sys.path.append(dir)
            m = importlib.import_module(name)
            handler = m.Handler(nvim)
            logger.info('handler created, entering event loop')
            nvim_event_loop(logger, nvim, handler)
        except Exception as ex:
            logger.info('Exception: %s', ex)
Esempio n. 5
0
 def __init__(self):
     addr = os.environ.get('NVIM_LISTEN_ADDRESS')
     if addr:
         self.nvim = attach('socket', path=addr)
     else:
         self.nvim = attach('child',
                            argv=[
                                "/usr/bin/env", "nvim", "--embed", "-n",
                                "-u", "init.vim"
                            ])
Esempio n. 6
0
 def attach(self):
     try:
         if get_address_type(self.address) == 'tcp':
             ip, port = self.address.split(':', 1)
             self.server = neovim.attach('tcp', address=ip, port=int(port))
         else:
             self.server = neovim.attach('socket', path=self.address)
     except OSError:
         # Ignore invalid addresses.
         pass
Esempio n. 7
0
 def __init__(self):
     """Construct an engine."""
     addr = os.environ.get('NVIM_LISTEN_ADDRESS')
     if addr:
         self.nvim = attach('socket', path=addr)
     else:
         args = ["/usr/bin/env", "nvim", "--embed", "--headless", "-n", "-u", "init.vim"]
         self.nvim = attach('child', argv=args)
         # Dummy request to make sure the embedded Nvim proceeds
         # See in neovim bd8d43c6fef868 (startup: wait for embedder before executing)
         self.Eval("0")
Esempio n. 8
0
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 = neovim.attach('child', argv=json.loads(child_argv))
    else:
        editor = neovim.attach('socket', path=listen_address)

    return editor
Esempio n. 9
0
def nvim_instance() -> neovim.Nvim:
    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:
        nvim = neovim.attach('child', argv=json.loads(child_argv))
    else:
        nvim = neovim.attach('socket', path=listen_address)

    yield nvim
Esempio n. 10
0
def setup_neovim(serveraddr):

    logger.info("connecting to neovim server: %s",serveraddr)
    # 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)

    sync_rtp(nvim)
    return nvim
Esempio n. 11
0
def setup_neovim(serveraddr):

    logger.info("connecting to neovim server: %s", serveraddr)
    # 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)

    sync_rtp(nvim)
    return nvim
Esempio n. 12
0
def main(ctx, prog, notify, listen, connect, profile):
    """Entry point."""
    address = connect or listen

    if address:
        import re
        p = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\:\d{1,5})?$')

        if p.match(address):
            args = ('tcp',)
            kwargs = {'address': address}
        else:
            args = ('socket',)
            kwargs = {'path': address}

    if connect:
        # connect to existing instance listening on address
        nvim = attach(*args, **kwargs)
    elif listen:
        # spawn detached instance listening on address and connect to it
        import os
        import time
        from subprocess import Popen
        os.environ['NVIM_LISTEN_ADDRESS'] = address
        nvim_argv = shlex.split(prog or 'nvim --headless') + ctx.args
        # spawn the nvim with stdio redirected to /dev/null.
        dnull = open(os.devnull)
        p = Popen(nvim_argv, stdin=dnull, stdout=dnull, stderr=dnull)
        dnull.close()
        while p.poll() or p.returncode is None:
            try:
                nvim = attach(*args, **kwargs)
                break
            except IOError:
                # socket not ready yet
                time.sleep(0.050)
    else:
        # spawn embedded instance
        nvim_argv = shlex.split(prog or 'nvim --embed') + ctx.args
        nvim = attach('child', argv=nvim_argv)

    if IS_PYTHON3:
        nvim = nvim.with_hook(DecodeHook())

    from gtk_ui import GtkUI
    ui = GtkUI()
    bridge = UIBridge()
    bridge.connect(nvim, ui, profile if profile != 'disable' else None, notify)
Esempio n. 13
0
def main(ctx, prog, notify, listen, connect, profile):
    """Entry point."""
    address = connect or listen

    if address:
        import re
        p = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\:\d{1,5})?$')

        if p.match(address):
            args = ('tcp', )
            kwargs = {'address': address}
        else:
            args = ('socket', )
            kwargs = {'path': address}

    if connect:
        # connect to existing instance listening on address
        nvim = attach(*args, **kwargs)
    elif listen:
        # spawn detached instance listening on address and connect to it
        import os
        import time
        from subprocess import Popen
        os.environ['NVIM_LISTEN_ADDRESS'] = address
        nvim_argv = shlex.split(prog or 'nvim --headless') + ctx.args
        # spawn the nvim with stdio redirected to /dev/null.
        dnull = open(os.devnull)
        p = Popen(nvim_argv, stdin=dnull, stdout=dnull, stderr=dnull)
        dnull.close()
        while p.poll() or p.returncode is None:
            try:
                nvim = attach(*args, **kwargs)
                break
            except IOError:
                # socket not ready yet
                time.sleep(0.050)
    else:
        # spawn embedded instance
        nvim_argv = shlex.split(prog or 'nvim --embed') + ctx.args
        nvim = attach('child', argv=nvim_argv)

    if IS_PYTHON3:
        nvim = nvim.with_hook(DecodeHook())

    from gtk_ui import GtkUI
    ui = GtkUI()
    bridge = UIBridge()
    bridge.connect(nvim, ui, profile if profile != 'disable' else None, notify)
Esempio n. 14
0
def call_neovim(editor, editor_flags, files, nvim_socket_path='/tmp'):
    """Call Neovim with a desired number of flags and files.

    This is in a separate function as neovim has a VERY different way of doing things.

    If a Neovim server is running on this Tmux window, then the files are opened there.
    Else, create a new Neovim instance in the pane.
    Args:
        editor (str): The editor command that should be called.
        editor_flags (str): A list of strings containing extra flags.
        files (str): A list of strings containing the files that should be opened.
        nvim_socket_path (str): The path where socket files should be stored.  """

    # Neovim instances in this script are formattted "/tmp/[email protected]"
    win = subprocess.check_output(["tmux", "display-message", "-p", "#{window_id}"])
    win = win.rstrip().strip().decode('utf-8')
    #socket_path = os.path.join(nvim_socket_path, ''.join(['nvim_omni']))
    socket_path = os.environ.get("NVIM_LISTEN_ADDRESS")

    if os.path.exists(socket_path):
        # socket already associated with this window.
        # so just attach to it and send the commands
        nvim = attach('socket', path=socket_path)
        for file in files:
            nvim.command('e ' + os.path.join(os.path.abspath(os.curdir), file))
    else:
        # no associated socket. So we create a new Neovim instance
        command = [editor] + editor_flags + files

        # run tmux_send_keys, tmux recognises Vim is running, vim-tmux-navigator not break
        tmux_send_keys(command)
Esempio n. 15
0
 def setup(self):
     ribosome.in_vim = False
     super().setup()
     self.logfile = temp_dir('log') / 'proteome_spec'
     self.vimlog = temp_dir('log') / 'vim'
     self.logfile.touch()
     amino.logging.logfile = self.logfile
     amino.logging.amino_file_logging(handler_level=logging.WARN)
     argv = ['nvim', '--embed', '-V{}'.format(self.vimlog), '-u', 'NONE']
     self.neovim = neovim.attach('child', argv=argv)
     NvimFacade.async = _mock_async
     NvimFacade.main_event_loop = _nop_main_loop
     NvimFacade.proxy = property(_mock_proxy)
     NvimFacade.clean = lambda self: True
     self.proteome = ProteomeNvimPlugin(self.neovim)
     self.vim = self.proteome.vim
     self.vim.vars.set_p('config_path', str(self.config))
     self.vim.vars.set_p('base_dirs', List(str(self.base)))
     self.vim.vars.set_p('type_base_dirs', self.type_bases.keymap(str))
     self.vim.vars.set_p('history_base', str(self.history_base))
     self.vim.vars.set_p('plugins', List('proteome.plugins.history',
                                       'proteome.plugins.ctags',
                                       'proteome.plugins.config',
                                       'proteome.plugins.unite',
                                       ))
     self.pros = self.add_projects(
         ('python', 'pro1'), ('python', 'pro2'), ('vim', 'pro3'))
Esempio n. 16
0
    def __init__(self):
        super(EvinceSyncSourceNeovim, self).__init__()

        logging.debug("importing neovim module")
        import neovim
        logging.debug("attaching to neovim through stdio")
        self.nvim = neovim.attach("stdio")
Esempio n. 17
0
def main(ctx, address, send, expr, tab, silent):
    if IP_ADDR.match(address):
        args = ('tcp', )
        kwargs = {'address': address}
    else:
        args = ('socket', )
        kwargs = {'path': address}
    try:
        nvim = attach(*args, **kwargs)
    except Exception as e:
        if not silent:
            print >> sys.stderr, e.message
        sys.exit(1)

    if send:
        nvim.input(send)
    elif expr:
        print nvim.eval(expr)
    else:
        files = ctx.args
        if not files:
            print >> sys.stderr, 'Need at least one file to edit'
            sys.exit(1)
        cmd = 'tabedit' if tab else 'edit'
        for f in files:
            nvim.command('{0} {1}'.format(cmd, f))
Esempio n. 18
0
def main():
    '''main routine'''
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawTextHelpFormatter)
    parser.add_argument('-v',
                        '--verbose',
                        help='echo verbosely',
                        action='store_false')
    args = parser.parse_args()

    path = os.environ.get('NVIM_LISTEN_ADDRESS', None)
    if not path:
        return 1

    try:
        nvim = attach('socket', path=path)
    except ConnectionRefusedError as e:
        print('connection refused: $NVIM_LISTEN_ADDRESS=' + path,
              file=sys.stderr)
        return 1
    pwd = os.getcwd().translate(str.maketrans({'"': r'\"', '\\': r'\\'}))
    nvim.command('let b:__pwd__ = "{}"'.format(pwd))
    if args.verbose:
        nvim.command('echo "b:__pwd__ changed"')
    nvim.close()

    return 0
Esempio n. 19
0
def main(ctx, address, send, expr, tab, silent):
    if IP_ADDR.match(address):
        args = ('tcp',)
        kwargs = {'address': address}
    else:
        args = ('socket',)
        kwargs = {'path': address}
    try:
        nvim = attach(*args, **kwargs)
    except Exception as e:
        if not silent:
            print >> sys.stderr, e.message
        sys.exit(1)

    if send:
        nvim.input(send)
    elif expr:
        print nvim.eval(expr)
    else:
        files = ctx.args
        if not files:
            print >> sys.stderr, 'Need at least one file to edit'
            sys.exit(1)
        cmd = 'tabedit' if tab else 'edit'
        for f in files:
            nvim.command('{0} {1}'.format(cmd, f))
Esempio n. 20
0
def register_plugin(plugin_dir):
    os.environ['NVIM_RPLUGIN_MANIFEST'] = str(plugin_dir.join('rplugin.vim'))
    child_argv = ['nvim', '-u', VIMRC, '--embed']
    vim = neovim.attach('child', argv=child_argv)
    vim.command('UpdateRemotePlugins')
    vim.quit()
    yield
Esempio n. 21
0
def main():
    import neovim
    nvim = neovim.attach('socket', path=os.environ.get('NVIM_LISTEN_ADDRESS'))
    try:
        nvim.command('VoltAttach')
        try:
            import lldb
            host = 'lldb'
        except:
            pass
        try:
            import gdb
            host = 'gdb'

            class VoltQuit(gdb.Command):
                def __init__(self):
                    super(VoltQuit, self).__init__("volt-quit",
                                                   gdb.COMMAND_USER)

                def invoke(self, arg, from_tty):
                    nvim.command('VoltDetach')
                    gdb.execute('quit')

            VoltQuit()
        except ImportError:
            pass
        try:
            import pykd
            host = 'windbg'
        except:
            pass
    except:
        pass
Esempio n. 22
0
def call_neovim(editor, editor_flags, files, nvim_socket_path='/tmp'):
    """Call Neovim with a desired number of flags and files.

    This is done in a separate function as neovim has a VERY different way of doing things.

    If a running Neovim server associated with the current Tmux window is found, then the files are opened there.
    Otherwise, a new Neovim instance is created in the pane where the call to this program was made, with the name in a format that this script knows to recognise.

    Args:
        editor (str): The editor command that should be called.
        editor_flags (str): A list of strings containing extra flags that should be called alongside the editor of choice.
        files (str): A list of strings containing the files that should be opened.
        nvim_socket_path (str): The path where socket files should be stored.
"""

    # all running Neovim instances associated with this script follow the format "/tmp/[email protected]", where n is the number of the associated tmux window.
    tmux_current_window = subprocess.check_output(["tmux", "display-message", "-p", "#{window_id}"]).rstrip()
    socket_path = os.path.join(nvim_socket_path, ''.join(['.nvim-', tmux_current_window.strip().decode('utf-8'), '.omni']))

    if os.path.exists(socket_path):
        # socket already associated with this window.
        # so just attach to it and send the commands
        nvim = attach('socket', path=socket_path)
        for file in files:
            nvim.command('e ' + os.path.join(os.path.abspath(os.curdir), file))
    else:
        # no associated socket. So we create a new Neovim instance following the format specified above.
        command = ['NVIM_LISTEN_ADDRESS=' + socket_path, editor] + editor_flags + files

        # the call needs to be run through tmux_send_keys so that tmux recognises that Vim is currently running. This allows vim-tmux-navigator to not break.
        tmux_send_keys(command)
Esempio n. 23
0
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
Esempio n. 24
0
 def populate_buffers(self, client_path):
     cname = self.get_client_name(client_path + "/")
     nvim = neovim.attach("socket", path=cname)
     for buf in nvim.buffers:
         if isfile(buf.name):
             buf_path = join(client_path, "buffers", str(buf.number))
             self.init_buffer(buf, buf_path)
Esempio n. 25
0
 def populate_windows(self, client_path):
     cname = self.get_client_name(client_path + "/")
     nvim = neovim.attach("socket", path=cname)
     for win in nvim.windows:
         self.wd += 1
         win_path = join(client_path, "windows", str(self.wd))
         self.init_window(win_path, win)
Esempio n. 26
0
 def write(self, path, data, offset=0, fh=None):
     r_len = len(data)
     cname = self.get_client_name(path)
     if cname:
         nvim = neovim.attach("socket", path=cname)
         lines = data.decode(errors="ignore").splitlines()
         if re.match('/clients/\d+/cmd', path):
             for c in lines:
                 nvim.command(c)
         elif re.match('/clients/\d+/eval', path):
             data = self.nvim_eval(nvim, lines)
         elif re.match('/clients/\d+/buffers/new', path):
             for f in lines:
                 nvim.command('drop ' + f)
                 # initialize the buffer tree
                 bufnr = str(nvim.eval('bufnr("%")'))
                 buf_path = join(re.match('/clients/\d+/buffers/', path).group(), bufnr)
                 self.init_buffer(OBuffer(f.encode()), buf_path)
         elif re.match('/clients/\d+/windows/new', path):
             for w in lines:
                 if re.match('((vertical|leftabove|aboveleft|rightbelow|belowright|topleft|botright)\s)*'\
                         'v?(split|new)', w):
                     nvim.command(w)
     else:
         if re.match('/clients/new', path):
             self.init_client(data.decode())
     # save the data
     # TODO: respect file permissions
     self.data[path] = self.data[path][:offset] + data
     self.files[path]['st_size'] = len(self.data[path])
     return r_len
Esempio n. 27
0
    def __init__(self):
        super(EvinceSyncSourceNeovim, self).__init__()

        logging.debug("importing neovim module")
        import neovim
        logging.debug("attaching to neovim through stdio")
        self.nvim = neovim.attach("stdio")
Esempio n. 28
0
    def start(self, nvim_server_name):
        """
        Start the file server
        @type request: str
        """

        server = self

        class HttpHandler(BaseHTTPRequestHandler):
            def do_GET(self):
                try:
                    server.run_GET(self)
                except Exception as ex:
                    logger.exception('exception on FileServer: %s', ex)
                    self.send_response(500)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    message = str(ex)
                    self.wfile.write(bytes(message, "utf8"))

        # create another connection to avoid synchronization issue?
        self._nvim = attach('socket', path=nvim_server_name)

        # Server settings
        # 0 for random port
        server_address = ('127.0.0.1', 0)
        self._httpd = HTTPServer(server_address, HttpHandler)

        Thread.start(self)
Esempio n. 29
0
def main(files=[]):
    neovim = attach('socket', path=os.environ['NVIM_LISTEN_ADDRESS'])

    for file in files:
        neovim.command('tabedit {}'.format(
            os.path.abspath(file)
            ))
Esempio n. 30
0
def open_path(rel_path, patterns):
    import trytond
    new_path = [trytond.__file__, '..', '..'] + [x for x in rel_path]
    new_path = os.path.abspath(os.path.join(*new_path))
    editor = os.environ.get('EDITOR', None)
    if editor is None:
        logging.getLogger().warning('No editor found, feature disabled')
    if editor == 'nvim':
        from neovim import attach
        path = '/tmp/nvim_' + os.path.basename(
            os.environ.get('VIRTUAL_ENV',
                           os.environ.get('NVIM_LISTEN_ADDRESS',
                                          'root'))) + '.sock'
        nvim = attach('socket', path=path)
        nvim.command('tabnew')
        nvim.command('edit %s' % new_path)
        prev_pos = nvim.eval("getpos('.')")[1]
        for pattern_group in patterns:
            for pattern in pattern_group:
                nvim.command("execute search('%s', 'w')" % pattern)
                new_pos = nvim.eval("getpos('.')")[1]
                if new_pos != prev_pos:
                    prev_pos = new_pos
                    break
                prev_pos = new_pos
        try:
            nvim.command('execute "normal zO"')
        except:
            # Vim fails if no folds were found
            pass
    elif editor == 'gvim':
        os.system(editor + ' -c edit ' + new_path + ' &')
    else:
        os.system(editor + ' ' + new_path + ' &')
    return
Esempio n. 31
0
    def _attach(self, attach_type):
        if attach_type == 'child':
            nvim = attach(
                'child',
                argv=["/bin/env", "nvim", "-u", "test/minvimrc", "--embed"])
            nvim.ui_attach(100, 100)
            return nvim

        try:
            nvim = attach('socket', path='/tmp/nvim_tplearn')
        except FileNotFoundError:
            print('\nCould not find NVIM process. Did you start a NVIM '
                  'instance at /tmp/nvim_tplearn?')
            nvim = None

        return nvim
Esempio n. 32
0
def test() -> None:
    vim = neovim.attach('socket', path='/tmp/nvim')
    lpos = Position([0, 1, 1, 0])
    rpos = Position([0, 2, 10, 0])
    box_area(vim.current.buffer,
             Coords(lpos.column - 1, lpos.line - 1),
             Coords(rpos.column - 1, rpos.line - 1))
Esempio n. 33
0
 def populate_windows(self, client_path):
     cname = self.get_client_name(client_path + "/")
     nvim = neovim.attach("socket", path=cname)
     for win in nvim.windows:
         self.wd += 1
         win_path = join(client_path, "windows", str(self.wd))
         self.init_window(win_path, win)
Esempio n. 34
0
 def write(self, path, data, offset=0, fh=None):
     r_len = len(data)
     cname = self.get_client_name(path)
     if cname:
         nvim = neovim.attach("socket", path=cname)
         lines = data.decode(errors="ignore").splitlines()
         if re.match('/clients/\d+/cmd', path):
             for c in lines:
                 nvim.command(c)
         elif re.match('/clients/\d+/eval', path):
             data = self.nvim_eval(nvim, lines)
         elif re.match('/clients/\d+/buffers/new', path):
             for f in lines:
                 nvim.command('drop ' + f)
                 # initialize the buffer tree
                 bufnr = str(nvim.eval('bufnr("%")'))
                 buf_path = join(
                     re.match('/clients/\d+/buffers/', path).group(), bufnr)
                 self.init_buffer(OBuffer(f.encode()), buf_path)
         elif re.match('/clients/\d+/windows/new', path):
             for w in lines:
                 if re.match('((vertical|leftabove|aboveleft|rightbelow|belowright|topleft|botright)\s)*'\
                         'v?(split|new)', w):
                     nvim.command(w)
     else:
         if re.match('/clients/new', path):
             self.init_client(data.decode())
     # save the data
     # TODO: respect file permissions
     self.data[path] = self.data[path][:offset] + data
     self.files[path]['st_size'] = len(self.data[path])
     return r_len
Esempio n. 35
0
 def populate_buffers(self, client_path):
     cname = self.get_client_name(client_path + "/")
     nvim = neovim.attach("socket", path=cname)
     for buf in nvim.buffers:
         if isfile(buf.name):
             buf_path = join(client_path, "buffers", str(buf.number))
             self.init_buffer(buf, buf_path)
Esempio n. 36
0
def call_neovim(files):
    """Call Neovim with a desired number of flags and files.

    This is in a separate function as neovim has a VERY different way of doing things.

    If a Neovim server is running on this Tmux window, then the files are opened there.
    Else, create a new Neovim instance in the pane.
    Args:
        editor (str): The editor command that should be called.
        editor_flags (str): A list of strings containing extra flags.
        files (str): A list of strings containing the files that should be opened.
        nvim_socket_path (str): The path where socket files should be stored.  """

    # Neovim instances in this script are formattted "/tmp/[email protected]"
    socket_path = os.environ.get("NVIM_LISTEN_ADDRESS")

    if os.path.exists(socket_path):
        # socket already associated with this window.
        # so just attach to it and send the commands
        nvim = attach('socket', path=socket_path)
        command = "vertical botright pedit "
        for file in files:
            nvim.command(command +
                         os.path.join(os.path.abspath(os.curdir), file))
    else:
        pass
Esempio n. 37
0
def main(bufnr, commitsha):
    nvim = neovim.attach('stdio')

    buf = nvim.buffers[int(bufnr)]
    repo = git.Repo(buf.name, search_parent_directories=True)

    files = get_files_from_ref(repo, commitsha)
    packages = get_packages_from_files(files)

    # add highlighting for the current commit
    hl_init(nvim)
    hl_add(nvim, 'gitrebaseCurrent', commitsha)

    # get all other refs from the buffer
    refs = set()
    for line in buf:
        m = LINE_RE.match(line)
        if m:
            refs.add(m.group(1))

    for ref in refs:
        if ref != commitsha:
            otherfiles = get_files_from_ref(repo, ref)
            if otherfiles == files:
                hl_add(nvim, 'gitrebaseSameFiles', ref)
            elif otherfiles & files:
                hl_add(nvim, 'gitrebaseCommonFiles', ref)
            else:
                otherpackages = get_packages_from_files(otherfiles)
                if otherpackages & packages:
                    hl_add(nvim, 'gitrebaseCommonPackages', ref)
Esempio n. 38
0
def main(ctx, prog, notify, listen, connect, font, profile):
    """Entry point."""
    address = connect or listen

    if address:
        import re
        p = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\:\d{1,5})?$')

        if p.match(address):
            args = ('tcp', )
            kwargs = {'address': address}
        else:
            args = ('socket', )
            kwargs = {'path': address}

    def find_nvim_pipe_number():
        #Find nvim pipe number. Spawn nvim if it was not launched yet.
        import subprocess
        import os
        spawned = False

        while True:
            pipes = subprocess.check_output("pipelist",
                                            universal_newlines=True)
            address_location = pipes.find("nvim")

            if address_location != -1:
                break

            if not spawned:
                #try to spawn nvim
                print("spawn nvim myself")
                dnull = open(os.devnull)
                subprocess.Popen("nvim",
                                 stdin=dnull,
                                 stdout=dnull,
                                 stderr=dnull)
                spawned = True

        import re
        #for now, we just know that nvim pipe number starts at address_location + 5
        #but we do not know the exact lenght: could be 3, could be 5
        #Assume 5 digits and actually get 3: "716-0" - need to use regex to seperate the
        #first actual pipe address
        return re.findall(r'\d+',
                          pipes[address_location + 5:address_location + 10])[0]

        #return pipes[address_location + 5:address_location + 9]

    pipe = find_nvim_pipe_number()

    nvim = attach('socket', path='\\\\.\\pipe\\nvim-' + pipe + '-0')

    print(nvim.channel_id)

    from gui_interface import GtkUI
    ui = GtkUI(font)
    bridge = UIBridge()
    bridge.connect(nvim, ui)
Esempio n. 39
0
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
Esempio n. 40
0
 def callback(*args):
     """ Callback called only once for connecting to the neovim instance
     and for additional nvim configuration.
     """
     self.terminal.disconnect(once)
     self.nvim = neovim.attach('socket', path=addr)
     logger.info("nvim attached")
     self.emit('nvim-setup', self.nvim)
Esempio n. 41
0
def main(address=None):
    if address:
        nvim = attach('socket', path=address)
    else:
        try:
            address = sys.argv[1]
            nvim = attach('socket', path=address)
        except:
            nvim_binary = find_executable('nvim')
            args = [nvim_binary, '--embed']
            # args.extend(['-u', 'NONE'])
            nvim = attach('child', argv=args)
    ui = NvimFriendly()
    bridge = UIBridge()
    bridge.connect(nvim, ui)
    if len(sys.argv) > 1:
        nvim.command('edit ' + sys.argv[1])
Esempio n. 42
0
def get_nvim():
    addr = os.environ.get("NVIM_LISTEN_ADDRESS", None)
    if not addr:
        print("Not running inside nvim.. exiting")
        sys.exit(1)

    nvim = attach("socket", path=addr)
    return nvim
Esempio n. 43
0
def start():
    import neovim
    vim = neovim.attach('socket', path='/tmp/v')

    input_queue = Queue.Queue()
    output_queue = Queue.Queue()
    project_dir = os.path.abspath(os.path.curdir)
    client = SocketClientThread(vim, input_queue, output_queue, project_dir)
    client.start()
Esempio n. 44
0
    def run(self):
        self.nvim = attach('socket', path=self.path)
        cindex.Config.set_library_file(self.nvim.vars['opvim_libclang_path'])
        self.is_running = True

        while (self.is_running):
            event = self.nvim.next_message()
            if not event:
                continue
Esempio n. 45
0
def attach_socket(path=None):
    '''does it auto'''
    def open_nvim():
        proc = Popen('NVIM_LISTEN_ADDRESS=/tmp/nvim nvim',
                    stdin=PIPE, stdout=PIPE, shell=True)
        proc.communicate()

    # THIS IS DOESNT WORK UNRELIBALE 
    #path = os.environ.get('NVIM_LISTEN_ADDRESS')
    if not path:
        print('threading')
        t = Thread(target=open_nvim)
        t.start()
        #todo make this give a random path
        return attach('socket', path='/tmp/nvim')
    else:
        print('attaching socket')
        return attach('socket', path=path)
Esempio n. 46
0
 def _start_neovim(self):
     ''' start an embedded vim session that loads no init.vim.
     **self.vimlog** is set as log file. aside from being convenient,
     this is crucially necessary, as the first use of the session
     will block if stdout is used for output.
     '''
     argv = ['nvim', '--embed', '-V{}'.format(self.vimlog), '-u', 'NONE']
     self.neovim = neovim.attach('child', argv=argv)
     self.vim = self._nvim_facade(self.neovim)
Esempio n. 47
0
 def Start(self):
   """Starts Neovim"""
   self.process = subprocess.Popen(self.start_command, env=self.env)
   start_time = time.time()
   # Wait at most 5s for the Neovim socket
   while not os.path.exists(self.args.servername) \
           and time.time() - start_time < 5:
     time.sleep(0.01)
   self.nvim = neovim.attach('socket', path=self.args.servername)
Esempio n. 48
0
 def Start(self):
   """Starts Neovim"""
   self.process = subprocess.Popen(self.start_command, env=self.env)
   start_time = time.time()
   # Wait at most 5s for the Neovim socket
   while not os.path.exists(self.args.servername) \
           and time.time() - start_time < 5:
       time.sleep(0.01)
   self.nvim = neovim.attach('socket', path=self.args.servername)
Esempio n. 49
0
 def __init__(self, logfile, run_handler):
     """pass logfile to be opened and handler to flush writing the file"""
     super(MyEventHandler, self).__init__()
     self.run_log = Logger('Runs')
     self.fs_log = Logger('Files')
     socket_path = environ.get("NVIM_LISTEN_ADDRESS")
     self.nvim = attach('socket', path=socket_path)
     self.log_file = logfile
     self.run_handler = run_handler
Esempio n. 50
0
def remote_nvim(filespecs):
    nvim = neovim.attach("socket", path=SOCKET_PATH)
    to_open = parse_filespecs_for_remote(filespecs)
    nvim.command(":tabnew")
    for fullpath, line, column in to_open:
        nvim.command(":e %s" % fullpath)
        nvim.feedkeys("%iG" % line)
        nvim.feedkeys("%i|" % column)
    if os.path.exists(CWD_PATH):
        os.remove(CWD_PATH)
Esempio n. 51
0
def reattach():
    """
    Attach to a running neovim process
    Exposes some global variables for ease of use
    Call again if detached (neovim process restarts)
    """
    nvim = attach('socket', path=os.environ.get("NVIM_LISTEN_ADDRESS", '/tmp/nvimsocket'))
    environment=globals()
    environment["nvim"] = nvim
    environment["buffers"] = nvim.buffers
    environment["current"] = nvim.current
Esempio n. 52
0
 def cmdline(a):
     from neovim import attach
     nvim = attach('socket', path=a)
     type = nvim.eval('&filetype')
     path = nvim.eval("expand('%:p')")
     file = nvim.eval("expand('%')")
     name = nvim.eval("expand('%:r')")
     nvim.command('w')
     if type in dict:
         dict[type](path, file, name)
     else:
         nvim.command("echo 'Sorry, filetype "+type+" not supported'")
     exit(0)
Esempio n. 53
0
def main():
    parser = argparse.ArgumentParser(description='Process Neovim queries.')
    parser.add_argument("-s", dest="socket", required=True,
                        help="Neovim socket", metavar="FILE",
                        type=lambda x: is_valid_socket(parser, x))
    parser.add_argument("-q", dest="query", required=True, type=str)
    parser.add_argument("params", nargs=argparse.REMAINDER)

    args = parser.parse_args()

    # Create a python API session attached to unix domain socket
    nvim = attach('socket', path=args.socket)
    params = args.params

    if args.query == "close_buffer":
        close_buffer(nvim, params)
Esempio n. 54
0
 def read(conn):
     data = conn.recv(1024)
     if data:
         msg = data.decode().split()
         if msg[0] == 'register':
             self.nvim_list.update({
                 int(msg[1]): (neovim.attach('socket', path=msg[2]),
                               msg[2])
             })
         elif msg[0] == 'unregister':
             if int(msg[1]) in self.nvim_list:
                 self.nvim_list.pop(int(msg[1]))
         else:
             try:
                 tree = self.i3.get_tree()
             except BrokenPipeError:
                 self.i3 = i3ipc.Connection()
                 tree = self.i3.get_tree()
             wid = next((x.window for x in tree.leaves()
                         if x.focused and x.window in self.nvim_list),
                        None)
             if wid:
                 nvim, nv_path = self.nvim_list[wid]
                 if not os.path.exists(nv_path):
                     self.nvim_list.pop(wid)
                     nvim = None
             else:
                 nvim = None
         if msg[0] == 'focus':
             if nvim:
                 wn = nvim.eval('winnr()')
                 nvim.command('wincmd ' + WINCMD[msg[1]])
                 if wn == nvim.eval('winnr()'):
                     self.i3.command('focus ' + msg[1])
             else:
                 self.i3.command('focus ' + msg[1])
         elif msg[0] == 'resize':
             if nvim:
                 if ((msg[1] == 'j' or msg[1] == 'k') and (nvim.eval('CountHSplits()') > 1) or (msg[1] == 'h' or msg[1] == 'l') and (nvim.eval('CountVSplits()') > 1)):
                     nvim.command('4wincmd ' + RESIZE_VIM[msg[1]])
                 else:
                     self.i3.command(RESIZE_I3[msg[1]])
             else:
                 self.i3.command(RESIZE_I3[msg[1]])
     elif not data:
         selector.unregister(conn)
         conn.close()
Esempio n. 55
0
def send_nvim_wincmd(path_to_socket, direction):
        log.info("Sending %s to socket %s" % (direction, path_to_socket))
        try:
                # path=os.environ["NVIM_LISTEN_ADDRESS"]
                # https://github.com/neovim/python-client/issues/124
                nvim = attach('socket', path=path_to_socket)
                log.debug("nvim attached")
                nvim.command('let oldwin = winnr()') 
                nvim.command('wincmd ' + direction)
                res = nvim.eval('oldwin != winnr()')
                log.debug("Result of command %d" % res)
                return res
        except Exception as e:
                log.error("Exception %s" % e)
                return False

        return False
Esempio n. 56
0
def main():
    # What file to edit
    curdir = os.getcwd()
    if len(sys.argv) > 1:
        filename = sys.argv[1]
    else:
        filename = ""
    fullpath = os.path.join(curdir, filename)

    # Edit in new vim or parent vim?
    address = os.environ.get("NVIM_LISTEN_ADDRESS", None)
    if address is None:
        if "NVIM_TUI_ENABLE_TRUE_COLOR" in os.environ:
            os.system("nvim \"{0}\"".format(fullpath))
        else:
            os.system("vim \"{0}\"".format(fullpath))
    else:
        nvim = attach('socket', path=os.environ["NVIM_LISTEN_ADDRESS"])
        nvim.input("<ESC><ESC>:e {0}<CR>".format(fullpath))
Esempio n. 57
0
def main(nvim_listen_addr, cmd, *args):
    from neovim import attach
    from neovim.api.nvim import NvimError

    nvim = attach('socket', path=nvim_listen_addr)
    if cmd[0] == '@':
        nvim.command('cd ' + abspath_esc('.'))
        cmd = cmd[1:]
    try:
        if cmd == [ 'bad', 'badd' ]:
            if len(args) == 0:
                _exit("1+")
            for f in args:
                nvim.command('badd ' + abspath_esc(f))
        elif cmd == 'cd':
            if len(args) != 1:
                _exit("1")
            nvim.command(cmd + abspath_esc(args[0]))
        elif cmd in [ 'dr', 'drop', 'e', 'edit' ]:
            if len(args) == 0:
                _exit("1+")
            nvim.command(' '.join(['drop'] + [abspath_esc(f) for f in args]))
        elif cmd in [ 'sp', 'split', 'vs', 'vsp', 'vsplit' ]:
            if len(args) == 0:
                _exit("1+")
            if len(args) == 1:
                nvim.command(cmd + abspath_esc(args[0]))
            else:
                nvim.command('e ' + abspath_esc(args[0]))
                for f in args[1:]:
                    nvim.command(cmd + abspath_esc(f))
        elif cmd == 'diff':
            if len(args) != 2:
                _exit("2")
            nvim.command('tabnew ' + abspath_esc(args[0]))
            nvim.command('diffsplit ' + abspath_esc(args[1]))
        elif cmd != '':
            nvim.command(' '.join((cmd,) + args))
    except NvimError as e:
        print(e)
Esempio n. 58
0
def main():
    arguments = docopt(__doc__)

    address = arguments['--address']

    if address == '$NVIM_LISTEN_ADDRESS':
        address = environ.get('NVIM_LISTEN_ADDRESS')

    if not address:
        exit('No neovim instance found')

    nvim = attach('socket', path=address)
    last_buffer = nvim.current.buffer.number

    command = [arguments['<command>']] + arguments['<args>']

    output = nvim.command_output(' '.join(command))

    if arguments['--wipe-current']:
        nvim.command('bw! %s' % last_buffer)

    return output