Esempio n. 1
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. 2
0
def start_channel(source_name, modulename, serveraddr, start_type='channel'):

    # setup logging
    setup_logging(modulename)
    # setup logger for module
    logger = getLogger(modulename)

    logger = getLogger(__name__)

    logger.info("start_channel for %s", modulename)

    # change proccess title
    try:
        import setproctitle
        setproctitle.setproctitle('%s nvim-completion-manager' % modulename)
    except:
        pass

    try:

        # connect neovim and setup python environment
        nvim = setup_neovim(serveraddr)

        if start_type == 'core':

            import cm_core
            nvim.vars['_cm_channel_id'] = nvim.channel_id
            handler = cm_core.CoreHandler(nvim)
            logger.info('starting core, enter event loop')
            run_event_loop('core', logger, nvim, handler)

        elif start_type == 'channel':

            nvim.call('cm#_channel_started', source_name, nvim.channel_id)

            if sys.version_info.major == 2:
                # python2 doesn't support namespace package
                # use load_source as a workaround
                import imp
                file = modulename.replace('.', '/')
                exp = 'globpath(&rtp,"pythonx/%s.py",1)' % file
                path = nvim.eval(exp).strip()
                logger.info('python2 file path: %s, exp: %s', path, exp)
                m = imp.load_source(modulename, path)
            else:
                m = importlib.import_module(modulename)

            handler = m.Source(nvim)
            logger.info('handler created, entering event loop')
            run_event_loop('channel', logger, nvim, handler)

    except Exception as ex:
        logger.exception('Exception when running %s: %s', modulename, ex)
        exit(1)
    finally:
        # terminate here
        exit(0)
Esempio n. 3
0
def main(ctx, prog, notify, listen, connect, font, profile):
    """Entry point."""
    address = connect or listen

    setup_logging("gtk_ui")

    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)

    from .gtk_ui import GtkUI
    ui = GtkUI(font)
    bridge = UIBridge()
    bridge.connect(nvim, ui, profile if profile != 'disable' else None, notify)
Esempio n. 4
0
def main():

    channel_type = sys.argv[1]

    # the default nice is inheriting from parent neovim process.  Increment it
    # so that heavy calculation will not block the ui.
    try:
        os.nice(5)
    except:
        pass

    # psutil ionice
    try:
        import psutil
        p = psutil.Process(os.getpid())
        p.ionice(psutil.IOPRIO_CLASS_IDLE)
    except:
        pass

    if channel_type == 'core':
        source_name = 'cm_core'
        modulename = 'cm_core'
        serveraddr = sys.argv[2]
    else:
        source_name = sys.argv[2]
        modulename = sys.argv[3]
        serveraddr = sys.argv[4]

    setup_logging(modulename)

    logger.info("start_channel for %s", modulename)

    # change proccess title
    try:
        import setproctitle
        setproctitle.setproctitle('%s nvim-completion-manager' % modulename)
    except:
        pass

    try:
        start_and_run_channel(channel_type, serveraddr, source_name, modulename)
    except Exception as ex:
        logger.exception('Exception when running %s: %s', modulename, ex)
        exit(1)
    finally:
        # terminate here
        exit(0)
Esempio n. 5
0
def main():

    channel_type = sys.argv[1]

    # the default nice is inheriting from parent neovim process.  Increment it
    # so that heavy calculation will not block the ui.
    try:
        os.nice(5)
    except:
        pass

    # psutil ionice
    try:
        import psutil
        p = psutil.Process(os.getpid())
        p.ionice(psutil.IOPRIO_CLASS_IDLE)
    except:
        pass

    if channel_type == 'core':
        source_name = 'cm_core'
        modulename = 'cm_core'
        serveraddr = sys.argv[2]
    else:
        source_name = sys.argv[2]
        modulename = sys.argv[3]
        serveraddr = sys.argv[4]

    setup_logging(modulename)

    logger.info("start_channel for %s", modulename)

    # change proccess title
    try:
        import setproctitle
        setproctitle.setproctitle('%s nvim-completion-manager' % modulename)
    except:
        pass

    # Stop Popen from openning console window on Windows system
    if platform.system() == 'Windows':
        try:
            import subprocess
            cls = subprocess.Popen
            class NewPopen(cls):
                def __init__(self, *args, **keys):
                    if 'startupinfo' not in keys:
                        si = subprocess.STARTUPINFO()
                        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                        keys['startupinfo'] = si
                    cls.__init__(self, *args, **keys)
            subprocess.Popen = NewPopen
        except Exception as ex:
            logger.exception('Failed hacking subprocess.Popen for windows platform: %s', ex)

    try:
        start_and_run_channel(channel_type, serveraddr, source_name, modulename)
    except Exception as ex:
        logger.exception('Exception when running %s: %s', modulename, ex)
        exit(1)
    finally:
        # terminate here
        exit(0)
Esempio n. 6
0
from neovim import attach, setup_logging
import sys
import importlib

serveraddr = sys.argv[1]
yarpid = int(sys.argv[2])
module = sys.argv[3]
module_obj = None

setup_logging(module)

# 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)

nvim.call('yarp#core#channel_started', yarpid, nvim.channel_id)
Esempio n. 7
0
import json
import os
import sys

import neovim

from nose.tools import eq_ as eq

neovim.setup_logging()

if 'NVIM_CHILD_ARGV' in os.environ:
    vim = neovim.attach('child', argv=json.loads(os.environ['NVIM_CHILD_ARGV']))
else:
    vim = neovim.attach('socket', path=os.environ['NVIM_LISTEN_ADDRESS'])

if sys.version_info >= (3, 0):
    # For Python3 we decode binary strings as Unicode for compatibility
    # with Python2
    vim = vim.with_decodehook(neovim.DecodeHook())

cleanup_func = ''':function BeforeEachTest()
  set all&
  redir => groups
  silent augroup
  redir END
  for group in split(groups)
    exe 'augroup '.group
    autocmd!
    augroup END
  endfor
  autocmd!
Esempio n. 8
0
def main():

    start_type = sys.argv[1]

    # the default nice is inheriting from parent neovim process.  Increment it
    # so that heavy calculation will not block the ui.
    try:
        os.nice(1)
    except:
        pass

    # psutil ionice
    try:
        import psutil
        p = psutil.Process(os.getpid())
        p.ionice(psutil.IOPRIO_CLASS_IDLE)
    except:
        pass

    if start_type == 'core':

        # use the module name here
        setup_logging('cm_core')
        logger = logging.getLogger(__name__)
        logger.setLevel(get_loglevel())

        # change proccess title
        try:
            import setproctitle
            setproctitle.setproctitle('nvim-completion-manager core')
        except:
            pass

        try:
            # connect neovim
            nvim = nvim_env()
            handler = CoreHandler(nvim)
            logger.info('starting core, enter event loop')
            cm_event_loop('core', logger, nvim, handler)
        except Exception as ex:
            logger.exception('Exception when running channel: %s', ex)
            exit(1)
        finally:
            # terminate here
            exit(0)

    elif start_type == 'channel':

        name = sys.argv[2]

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

        # change proccess title
        try:
            import setproctitle
            setproctitle.setproctitle('nvim-completion-manager %s' % name)
        except:
            pass

        try:
            # connect neovim
            nvim = nvim_env()
            m = importlib.import_module(name)
            handler = m.Source(nvim)
            logger.info('handler created, entering event loop')
            cm_event_loop('channel', logger, nvim, handler)
        except Exception as ex:
            logger.exception('Exception: %s', ex)
            exit(1)
        finally:
            # terminate here
            exit(0)
Esempio n. 9
0
from os import environ

assert __name__ == "__main__"

if "" in sys.path:
    sys.path.remove("")

serveraddr = sys.argv[1]
yarpid = int(sys.argv[2])
module = sys.argv[3]
module_obj = None
nvim = None

environ['NVIM_YARP_MODULE'] = module

setup_logging(module)

def on_request(method, args):
    if hasattr(module_obj, method):
        return getattr(module_obj, method)(*args)
    else:
        raise Exception('method %s not found' % method)


def on_notification(method, args):
    if hasattr(module_obj, method):
        getattr(module_obj, method)(*args)
    else:
        raise Exception('method %s not found' % method)
    pass
Esempio n. 10
0
import json
import os
import sys

import neovim

from nose.tools import eq_ as eq

neovim.setup_logging()

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:
    vim = neovim.attach('child', argv=json.loads(child_argv))
else:
    vim = neovim.attach('socket', path=listen_address)

cleanup_func = ''':function BeforeEachTest()
  set all&
  redir => groups
  silent augroup
  redir END
  for group in split(groups)
    exe 'augroup '.group
    autocmd!
    augroup END
  endfor
  autocmd!
Esempio n. 11
0
def main():

    channel_type = sys.argv[1]

    # the default nice is inheriting from parent neovim process.  Increment it
    # so that heavy calculation will not block the ui.
    try:
        os.nice(5)
    except:
        pass

    # psutil ionice
    try:
        import psutil
        p = psutil.Process(os.getpid())
        p.ionice(psutil.IOPRIO_CLASS_IDLE)
    except:
        pass

    if channel_type == 'core':
        source_name = 'cm_core'
        modulename = 'cm_core'
        serveraddr = sys.argv[2]
    else:
        source_name = sys.argv[2]
        modulename = sys.argv[3]
        serveraddr = sys.argv[4]

    setup_logging(modulename)

    logger.info("start_channel for %s", modulename)

    # change proccess title
    try:
        import setproctitle
        setproctitle.setproctitle('%s nvim-completion-manager' % modulename)
    except:
        pass

    # Stop Popen from openning console window on Windows system
    if platform.system() == 'Windows':
        try:
            import subprocess
            cls = subprocess.Popen

            class NewPopen(cls):
                def __init__(self, *args, **keys):
                    if 'startupinfo' not in keys:
                        si = subprocess.STARTUPINFO()
                        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                        keys['startupinfo'] = si
                    cls.__init__(self, *args, **keys)

            subprocess.Popen = NewPopen
        except Exception as ex:
            logger.exception(
                'Failed hacking subprocess.Popen for windows platform: %s', ex)

    try:
        start_and_run_channel(channel_type, serveraddr, source_name,
                              modulename)
    except Exception as ex:
        logger.exception('Exception when running %s: %s', modulename, ex)
        exit(1)
    finally:
        # terminate here
        exit(0)
Esempio n. 12
0
import json
import os
import textwrap

import neovim
import pytest

neovim.setup_logging("test")


@pytest.fixture(autouse=True)
def cleanup_func(vim):
    fun = textwrap.dedent('''function! BeforeEachTest()
        set all&
        redir => groups
        silent augroup
        redir END
        for group in split(groups)
            exe 'augroup '.group
            autocmd!
            augroup END
        endfor
        autocmd!
        tabnew
        let curbufnum = eval(bufnr('%'))
        redir => buflist
        silent ls!
        redir END
        let bufnums = []
        for buf in split(buflist, '\\n')
            let bufnum = eval(split(buf, '[ u]')[0])
Esempio n. 13
0
import json
import os
import sys

import neovim

from nose.tools import eq_ as eq

neovim.setup_logging("test")

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:
    vim = neovim.attach('child', argv=json.loads(child_argv))
else:
    vim = neovim.attach('socket', path=listen_address)

cleanup_func = ''':function BeforeEachTest()
  set all&
  redir => groups
  silent augroup
  redir END
  for group in split(groups)
    exe 'augroup '.group
    autocmd!
    augroup END
  endfor
  autocmd!