[Python-modules-commits] [python-neovim] 01/03: Import python-neovim_0.1.9.orig.tar.gz

Víctor Cuadrado Juan viccuad-guest at moszumanska.debian.org
Sat Jun 18 14:45:58 UTC 2016


This is an automated email from the git hooks/post-receive script.

viccuad-guest pushed a commit to branch master
in repository python-neovim.

commit f0fe3e91fb07d618cd00de8fb962f6c3616eb9e4
Author: Víctor Cuadrado Juan <me at viccuad.me>
Date:   Sat Jun 18 16:36:01 2016 +0200

    Import python-neovim_0.1.9.orig.tar.gz
---
 PKG-INFO                     |  4 ++--
 README.md                    |  2 +-
 neovim.egg-info/PKG-INFO     |  4 ++--
 neovim.egg-info/SOURCES.txt  |  1 +
 neovim/api/buffer.py         |  2 +-
 neovim/api/common.py         |  6 ++---
 neovim/api/nvim.py           | 43 ++++++++++++++++++++++++++++++----
 neovim/plugin/host.py        | 55 ++++++++++++++++++++++++++------------------
 neovim/plugin/script_host.py | 12 ++++++++--
 neovim/util.py               | 12 ++++++++++
 setup.py                     |  4 ++--
 test/test_vim.py             | 24 +++++++++++++++----
 12 files changed, 125 insertions(+), 44 deletions(-)

diff --git a/PKG-INFO b/PKG-INFO
index c6d9758..6703385 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,11 +1,11 @@
 Metadata-Version: 1.1
 Name: neovim
-Version: 0.1.8
+Version: 0.1.9
 Summary: Python client to neovim
 Home-page: http://github.com/neovim/python-client
 Author: Thiago de Arruda
 Author-email: tpadilha84 at gmail.com
 License: Apache
-Download-URL: https://github.com/neovim/python-client/archive/0.1.8.tar.gz
+Download-URL: https://github.com/neovim/python-client/archive/0.1.9.tar.gz
 Description: UNKNOWN
 Platform: UNKNOWN
diff --git a/README.md b/README.md
index ce07b07..fbae2a9 100644
--- a/README.md
+++ b/README.md
@@ -169,7 +169,7 @@ bridge](http://vimdoc.sourceforge.net/htmldoc/if_pyth.html#python-vim)):
 # Create a python API session attached to unix domain socket created above:
 >>> nvim = attach('socket', path='/tmp/nvim')
 # Now do some work. 
->>> buffer = nvim.buffers[0] # Get the first buffer
+>>> buffer = nvim.current.buffer # Get the current buffer
 >>> buffer[0] = 'replace first line'
 >>> buffer[:] = ['replace whole buffer']
 >>> nvim.command('vsplit')
diff --git a/neovim.egg-info/PKG-INFO b/neovim.egg-info/PKG-INFO
index c6d9758..6703385 100644
--- a/neovim.egg-info/PKG-INFO
+++ b/neovim.egg-info/PKG-INFO
@@ -1,11 +1,11 @@
 Metadata-Version: 1.1
 Name: neovim
-Version: 0.1.8
+Version: 0.1.9
 Summary: Python client to neovim
 Home-page: http://github.com/neovim/python-client
 Author: Thiago de Arruda
 Author-email: tpadilha84 at gmail.com
 License: Apache
-Download-URL: https://github.com/neovim/python-client/archive/0.1.8.tar.gz
+Download-URL: https://github.com/neovim/python-client/archive/0.1.9.tar.gz
 Description: UNKNOWN
 Platform: UNKNOWN
diff --git a/neovim.egg-info/SOURCES.txt b/neovim.egg-info/SOURCES.txt
index 910a7da..f841727 100644
--- a/neovim.egg-info/SOURCES.txt
+++ b/neovim.egg-info/SOURCES.txt
@@ -5,6 +5,7 @@ setup.cfg
 setup.py
 neovim/__init__.py
 neovim/compat.py
+neovim/util.py
 neovim.egg-info/PKG-INFO
 neovim.egg-info/SOURCES.txt
 neovim.egg-info/dependency_links.txt
diff --git a/neovim/api/buffer.py b/neovim/api/buffer.py
index ab90b74..d2b2f43 100644
--- a/neovim/api/buffer.py
+++ b/neovim/api/buffer.py
@@ -1,4 +1,4 @@
-"""API for working with Nvim buffers."""
+"""API for working with a Nvim Buffer."""
 from .common import Remote
 from ..compat import IS_PYTHON3
 
diff --git a/neovim/api/common.py b/neovim/api/common.py
index 33244fd..bc6523e 100644
--- a/neovim/api/common.py
+++ b/neovim/api/common.py
@@ -113,9 +113,9 @@ class RemoteSequence(object):
     sequences(of lines, buffers, windows and tabpages) with an API that
     is similar to the one provided by the python-vim interface.
 
-    For example, the 'buffers' property of the `Nvim class is a RemoteSequence
-    sequence instance, and the expression `nvim.buffers[0]` is translated to
-    session.request('vim_get_buffers')[0].
+    For example, the 'windows' property of the `Nvim` class is a RemoteSequence
+    sequence instance, and the expression `nvim.windows[0]` is translated to
+    session.request('vim_get_windows')[0].
 
     It can also receive an optional self_obj that will be passed as first
     argument of the request. For example, `tabpage.windows[0]` is translated
diff --git a/neovim/api/nvim.py b/neovim/api/nvim.py
index 2b68407..8a1641b 100644
--- a/neovim/api/nvim.py
+++ b/neovim/api/nvim.py
@@ -3,7 +3,7 @@ import functools
 import os
 import sys
 
-from traceback import format_exc, format_stack
+from traceback import format_stack
 
 from msgpack import ExtType
 
@@ -13,7 +13,7 @@ from .common import (Remote, RemoteApi, RemoteMap, RemoteSequence,
 from .tabpage import Tabpage
 from .window import Window
 from ..compat import IS_PYTHON3
-
+from ..util import format_exc_skip
 
 __all__ = ('Nvim')
 
@@ -79,7 +79,7 @@ class Nvim(object):
         self.vars = RemoteMap(self, 'vim_get_var', 'vim_set_var')
         self.vvars = RemoteMap(self, 'vim_get_vvar', None)
         self.options = RemoteMap(self, 'vim_get_option', 'vim_set_option')
-        self.buffers = RemoteSequence(self, 'vim_get_buffers')
+        self.buffers = Buffers(self)
         self.windows = RemoteSequence(self, 'vim_get_windows')
         self.tabpages = RemoteSequence(self, 'vim_get_tabpages')
         self.current = Current(self)
@@ -325,12 +325,47 @@ class Nvim(object):
             except Exception as err:
                 msg = ("error caught while executing async callback:\n"
                        "{0!r}\n{1}\n \nthe call was requested at\n{2}"
-                       .format(err, format_exc(5), call_point))
+                       .format(err, format_exc_skip(1, 5), call_point))
                 self._err_cb(msg)
                 raise
         self._session.threadsafe_call(handler)
 
 
+class Buffers(object):
+
+    """Remote NVim buffers.
+
+    Currently the interface for interacting with remote NVim buffers is the
+    `vim_get_buffers` msgpack-rpc function. Most methods fetch the list of
+    buffers from NVim.
+
+    Conforms to *python-buffers*.
+    """
+
+    def __init__(self, nvim):
+        """Initialize a Buffers object with Nvim object `nvim`."""
+        self._fetch_buffers = nvim.api.get_buffers
+
+    def __len__(self):
+        """Return the count of buffers."""
+        return len(self._fetch_buffers())
+
+    def __getitem__(self, number):
+        """Return the Buffer object matching buffer number `number`."""
+        for b in self._fetch_buffers():
+            if b.number == number:
+                return b
+        raise KeyError(number)
+
+    def __contains__(self, b):
+        """Return whether Buffer `b` is a known valid buffer."""
+        return isinstance(b, Buffer) and b.valid
+
+    def __iter__(self):
+        """Return an iterator over the list of buffers."""
+        return iter(self._fetch_buffers())
+
+
 class CompatibilitySession(object):
 
     """Helper class for API compatibility."""
diff --git a/neovim/plugin/host.py b/neovim/plugin/host.py
index 78703a6..f1ee98e 100644
--- a/neovim/plugin/host.py
+++ b/neovim/plugin/host.py
@@ -13,6 +13,7 @@ from . import script_host
 from ..api import decode_if_bytes, walk
 from ..compat import IS_PYTHON3, find_module
 from ..msgpack_rpc import ErrorResponse
+from ..util import format_exc_skip
 
 __all__ = ('Host')
 
@@ -60,6 +61,24 @@ class Host(object):
         self._unload()
         self.nvim.stop_loop()
 
+    def _wrap_function(self, fn, sync, decode, nvim_bind, name, *args):
+        if decode:
+            args = walk(decode_if_bytes, args, decode)
+        if nvim_bind is not None:
+            args.insert(0, nvim_bind)
+        try:
+            return fn(*args)
+        except Exception:
+            if sync:
+                msg = ("error caught in request handler '{} {}':\n{}"
+                       .format(name, args, format_exc_skip(1, 5)))
+                raise ErrorResponse(msg)
+            else:
+                msg = ("error caught in async handler '{} {}'\n{}\n"
+                       .format(name, args, format_exc_skip(1, 5)))
+                self._on_async_err(msg + "\n")
+                raise
+
     def _on_request(self, name, args):
         """Handle a msgpack-rpc request."""
         if IS_PYTHON3:
@@ -87,13 +106,7 @@ class Host(object):
             return
 
         debug('calling notification handler for "%s", args: "%s"', name, args)
-        try:
-            handler(*args)
-        except Exception as err:
-            msg = ("error caught in async handler '{} {}':\n{!r}\n{}\n"
-                   .format(name, args, err, format_exc(5)))
-            self._on_async_err(msg + "\n")
-            raise
+        handler(*args)
 
     def _missing_handler_error(self, name, kind):
         msg = 'no {} handler registered for "{}"'.format(kind, name)
@@ -156,40 +169,36 @@ class Host(object):
         def predicate(o):
             return hasattr(o, '_nvim_rpc_method_name')
 
-        def decoder(fn, decode, *args):
-            return fn(*walk(decode_if_bytes, args, decode))
         specs = []
         objdecode = getattr(obj, '_nvim_decode', self._decode_default)
         for _, fn in inspect.getmembers(obj, predicate):
+            sync = fn._nvim_rpc_sync
             decode = getattr(fn, '_nvim_decode', objdecode)
+            nvim_bind = None
             if fn._nvim_bind:
-                # bind a nvim instance to the handler
-                fn2 = functools.partial(fn, self._configure_nvim_for(fn))
-                # copy _nvim_* attributes from the original function
-                self._copy_attributes(fn, fn2)
-                fn = fn2
-            if decode:
-                fn2 = functools.partial(decoder, fn, decode)
-                self._copy_attributes(fn, fn2)
-                fn = fn2
+                nvim_bind = self._configure_nvim_for(fn)
 
-            # register in the rpc handler dict
             method = fn._nvim_rpc_method_name
             if fn._nvim_prefix_plugin_path:
                 method = '{0}:{1}'.format(plugin_path, method)
-            if fn._nvim_rpc_sync:
+
+            fn_wrapped = functools.partial(self._wrap_function, fn,
+                                           sync, decode, nvim_bind, method)
+            self._copy_attributes(fn, fn_wrapped)
+            # register in the rpc handler dict
+            if sync:
                 if method in self._request_handlers:
                     raise Exception(('Request handler for "{0}" is ' +
                                     'already registered').format(method))
-                self._request_handlers[method] = fn
+                self._request_handlers[method] = fn_wrapped
             else:
                 if method in self._notification_handlers:
                     raise Exception(('Notification handler for "{0}" is ' +
                                     'already registered').format(method))
-                self._notification_handlers[method] = fn
+                self._notification_handlers[method] = fn_wrapped
             if hasattr(fn, '_nvim_rpc_spec'):
                 specs.append(fn._nvim_rpc_spec)
-            handlers.append(fn)
+            handlers.append(fn_wrapped)
         if specs:
             self._specs[plugin_path] = specs
 
diff --git a/neovim/plugin/script_host.py b/neovim/plugin/script_host.py
index 78bed76..c6139ab 100644
--- a/neovim/plugin/script_host.py
+++ b/neovim/plugin/script_host.py
@@ -7,6 +7,8 @@ import sys
 
 from .decorators import plugin, rpc_export
 from ..api import Nvim, walk
+from ..msgpack_rpc import ErrorResponse
+from ..util import format_exc_skip
 
 __all__ = ('ScriptHost',)
 
@@ -72,7 +74,10 @@ class ScriptHost(object):
     def python_execute(self, script, range_start, range_stop):
         """Handle the `python` ex command."""
         self._set_current_range(range_start, range_stop)
-        exec(script, self.module.__dict__)
+        try:
+            exec(script, self.module.__dict__)
+        except Exception:
+            raise ErrorResponse(format_exc_skip(1))
 
     @rpc_export('python_execute_file', sync=True)
     def python_execute_file(self, file_path, range_start, range_stop):
@@ -80,7 +85,10 @@ class ScriptHost(object):
         self._set_current_range(range_start, range_stop)
         with open(file_path) as f:
             script = compile(f.read(), file_path, 'exec')
-            exec(script, self.module.__dict__)
+            try:
+                exec(script, self.module.__dict__)
+            except Exception:
+                raise ErrorResponse(format_exc_skip(1))
 
     @rpc_export('python_do_range', sync=True)
     def python_do_range(self, start, stop, code):
diff --git a/neovim/util.py b/neovim/util.py
new file mode 100644
index 0000000..cd4e009
--- /dev/null
+++ b/neovim/util.py
@@ -0,0 +1,12 @@
+"""Shared utility functions."""
+
+import sys
+from traceback import format_exception
+
+
+def format_exc_skip(skip, limit=None):
+    """Like traceback.format_exc but allow skipping the first frames."""
+    type, val, tb = sys.exc_info()
+    for i in range(skip):
+        tb = tb.tb_next
+    return ('\n'.join(format_exception(type, val, tb, limit))).rstrip()
diff --git a/setup.py b/setup.py
index 1b8e4f4..dccda98 100644
--- a/setup.py
+++ b/setup.py
@@ -19,10 +19,10 @@ if platform.python_implementation() != 'PyPy':
     install_requires.append('greenlet')
 
 setup(name='neovim',
-      version='0.1.8',
+      version='0.1.9',
       description='Python client to neovim',
       url='http://github.com/neovim/python-client',
-      download_url='https://github.com/neovim/python-client/archive/0.1.8.tar.gz',
+      download_url='https://github.com/neovim/python-client/archive/0.1.9.tar.gz',
       author='Thiago de Arruda',
       author_email='tpadilha84 at gmail.com',
       license='Apache',
diff --git a/test/test_vim.py b/test/test_vim.py
index 7a453f0..7618f7b 100644
--- a/test/test_vim.py
+++ b/test/test_vim.py
@@ -92,13 +92,29 @@ def test_options():
 
 @with_setup(setup=cleanup)
 def test_buffers():
+    buffers = []
+
+    # Number of elements
     eq(len(vim.buffers), 1)
-    eq(vim.buffers[0], vim.current.buffer)
+
+    # Indexing (by buffer number)
+    eq(vim.buffers[vim.current.buffer.number], vim.current.buffer)
+
+    buffers.append(vim.current.buffer)
     vim.command('new')
     eq(len(vim.buffers), 2)
-    eq(vim.buffers[1], vim.current.buffer)
-    vim.current.buffer = vim.buffers[0]
-    eq(vim.buffers[0], vim.current.buffer)
+    buffers.append(vim.current.buffer)
+    eq(vim.buffers[vim.current.buffer.number], vim.current.buffer)
+    vim.current.buffer = buffers[0]
+    eq(vim.buffers[vim.current.buffer.number], buffers[0])
+
+    # Membership test
+    ok(buffers[0] in vim.buffers)
+    ok(buffers[1] in vim.buffers)
+    ok({} not in vim.buffers)
+
+    # Iteration
+    eq(buffers, list(vim.buffers))
 
 
 @with_setup(setup=cleanup)

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-neovim.git



More information about the Python-modules-commits mailing list