Completed
Pull Request — master (#179)
by Björn
02:42
created

neovim.api.Nvim.run_loop()   A

Complexity

Conditions 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119
Metric Value
cc 4
dl 0
loc 20
ccs 10
cts 11
cp 0.9091
crap 4.0119
rs 9.2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A neovim.api.Nvim.filter_notification_cb() 0 2 1
A neovim.api.Nvim.filter_request_cb() 0 4 1
1
"""Main Nvim interface."""
2 6
import functools
3 6
import os
4 6
import sys
5
6 6
from traceback import format_exc, format_stack
7
8 6
from msgpack import ExtType
0 ignored issues
show
Configuration introduced by
The import msgpack could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
9
10 6
from .buffer import Buffer
11 6
from .common import (DecodeHook, Remote, RemoteApi,
12
                     RemoteMap, RemoteSequence, walk)
13 6
from .tabpage import Tabpage
14 6
from .window import Window
15 6
from ..compat import IS_PYTHON3
16
17
18 6
__all__ = ('Nvim')
19
20
21 6
os_chdir = os.chdir
22
23
24 6
class Nvim(object):
25
26
    """Class that represents a remote Nvim instance.
27
28
    This class is main entry point to Nvim remote API, it is a wrapper
29
    around Session instances.
30
31
    The constructor of this class must not be called directly. Instead, the
32
    `from_session` class method should be used to create the first instance
33
    from a raw `Session` instance.
34
35
    Subsequent instances for the same session can be created by calling the
36
    `with_decodehook` instance method to change the decoding behavior or
37
    `SubClass.from_nvim(nvim)` where `SubClass` is a subclass of `Nvim`, which
38
    is useful for having multiple `Nvim` objects that behave differently
39
    without one affecting the other.
40
    """
41
42 6
    @classmethod
43
    def from_session(cls, session):
44
        """Create a new Nvim instance for a Session instance.
45
46
        This method must be called to create the first Nvim instance, since it
47
        queries Nvim metadata for type information and sets a SessionHook for
48
        creating specialized objects from Nvim remote handles.
49
        """
50 6
        session.error_wrapper = lambda e: NvimError(e[1])
51 6
        channel_id, metadata = session.request(b'vim_get_api_info')
52
53 6
        if IS_PYTHON3:
54
            # decode all metadata strings for python3
55 3
            metadata = DecodeHook().walk(metadata)
56
57 6
        types = {
58
            metadata['types']['Buffer']['id']: Buffer,
59
            metadata['types']['Window']['id']: Window,
60
            metadata['types']['Tabpage']['id']: Tabpage,
61
        }
62
63 6
        return cls(session, channel_id, metadata, types)
64
65 6
    @classmethod
66
    def from_nvim(cls, nvim):
67
        """Create a new Nvim instance from an existing instance."""
68
        return cls(nvim._session, nvim.channel_id, nvim.metadata,
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _session was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
69
                   nvim.types, nvim._decodehook, nvim._err_cb)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _decodehook was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
Coding Style Best Practice introduced by
It seems like _err_cb was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
70
71 6
    def __init__(self, session, channel_id, metadata, types,
72
                 decodehook=None, err_cb=None):
73
        """Initialize a new Nvim instance. This method is module-private."""
74 6
        self._session = session
75 6
        self.channel_id = channel_id
76 6
        self.metadata = metadata
77 6
        self.types = types
78 6
        self.api = RemoteApi(self, 'vim_')
79 6
        self.vars = RemoteMap(self, 'vim_get_var', 'vim_set_var')
80 6
        self.vvars = RemoteMap(self, 'vim_get_vvar', None)
81 6
        self.options = RemoteMap(self, 'vim_get_option', 'vim_set_option')
82 6
        self.buffers = RemoteSequence(self, 'vim_get_buffers')
83 6
        self.windows = RemoteSequence(self, 'vim_get_windows')
84 6
        self.tabpages = RemoteSequence(self, 'vim_get_tabpages')
85 6
        self.current = Current(self)
86 6
        self.funcs = Funcs(self)
87 6
        self.error = NvimError
88 6
        self._decodehook = decodehook
89 6
        self._err_cb = err_cb
90
91 6
    def _from_nvim(self, obj):
92 6
        if type(obj) is ExtType:
93 6
            cls = self.types[obj.code]
94 6
            return cls(self, (obj.code, obj.data))
95 6
        if self._decodehook is not None:
96 3
            obj = self._decodehook.decode_if_bytes(obj)
97 6
        return obj
98
99 6
    def _to_nvim(self, obj):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
100 6
        if isinstance(obj, Remote):
101 6
            return ExtType(*obj.code_data)
102 6
        return obj
103
104 6
    def request(self, name, *args, **kwargs):
105
        """Send an API request or notification to nvim.
106
107
        It is rarely needed to call this function directly, as most API
108
        functions have python wrapper functions. The `api` object can
109
        be also be used to call API functions as methods:
110
111
            vim.api.err_write('ERROR\n', async=True)
112
            vim.current.buffer.api.get_mark('.')
113
114
        is equivalent to
115
116
            vim.request('vim_err_write, 'ERROR\n', async=True)
117
            vim.request('buffer_get_mark', vim.current.buffer, '.')
118
119
120
        Normally a blocking request will be sent.
121
        If the `async` flag is present and True, a asynchronous notification is
122
        sent instead. This will never block, and the return value or error is
123
        ignored.
124
        """
125 6
        args = walk(self._to_nvim, args)
126 6
        res = self._session.request(name, *args, **kwargs)
127 6
        return walk(self._from_nvim, res)
128
129 6
    def next_message(self):
130
        """Block until a message(request or notification) is available.
131
132
        If any messages were previously enqueued, return the first in queue.
133
        If not, run the event loop until one is received.
134
        """
135 6
        msg = self._session.next_message()
136 6
        if msg:
137 6
            return walk(self._from_nvim, msg)
138
139 6
    def run_loop(self, request_cb, notification_cb,
140
                 setup_cb=None, err_cb=None):
141
        """Run the event loop to receive requests and notifications from Nvim.
142
143
        This should not be called from a plugin running in the host, which
144
        already runs the loop and dispatches events to plugins.
145
        """
146 6
        def filter_request_cb(name, args):
147 6
            args = walk(self._from_nvim, args)
148 6
            result = request_cb(self._from_nvim(name), args)
149 6
            return walk(self._to_nvim, result)
150
151 6
        def filter_notification_cb(name, args):
152
            notification_cb(self._from_nvim(name), walk(self._from_nvim, args))
153
154 6
        if err_cb is None:
155 6
            err_cb = sys.stderr.write
156 6
        self._err_cb = err_cb
157
158 6
        self._session.run(filter_request_cb, filter_notification_cb, setup_cb)
159
160 6
    def stop_loop(self):
161
        """Stop the event loop being started with `run_loop`."""
162 6
        self._session.stop()
163
164 6
    def with_decodehook(self, hook):
165
        """Initialize a new Nvim instance."""
166 3
        return Nvim(self._session, self.channel_id,
167
                    self.metadata, self.types, hook, self._err_cb)
168
169 6
    def ui_attach(self, width, height, rgb):
170
        """Register as a remote UI.
171
172
        After this method is called, the client will receive redraw
173
        notifications.
174
        """
175
        return self.request('ui_attach', width, height, rgb)
176
177 6
    def ui_detach(self):
178
        """Unregister as a remote UI."""
179
        return self.request('ui_detach')
180
181 6
    def ui_try_resize(self, width, height):
182
        """Notify nvim that the client window has resized.
183
184
        If possible, nvim will send a redraw request to resize.
185
        """
186
        return self.request('ui_try_resize', width, height)
187
188 6
    def subscribe(self, event):
189
        """Subscribe to a Nvim event."""
190 6
        return self.request('vim_subscribe', event)
191
192 6
    def unsubscribe(self, event):
193
        """Unsubscribe to a Nvim event."""
194 6
        return self.request('vim_unsubscribe', event)
195
196 6
    def command(self, string, async=False):
197
        """Execute a single ex command."""
198 6
        return self.request('vim_command', string, async=async)
199
200 6
    def command_output(self, string):
201
        """Execute a single ex command and return the output."""
202
        return self.request('vim_command_output', string)
203
204 6
    def eval(self, string, async=False):
205
        """Evaluate a vimscript expression."""
206 6
        return self.request('vim_eval', string, async=async)
207
208 6
    def call(self, name, *args, **kwargs):
209
        """Call a vimscript function."""
210 6
        for k in kwargs:
211 6
            if k != "async":
212
                raise TypeError(
213
                    "call() got an unexpected keyword argument '{}'".format(k))
214 6
        return self.request('vim_call_function', name, args, **kwargs)
215
216 6
    def strwidth(self, string):
217
        """Return the number of display cells `string` occupies.
218
219
        Tab is counted as one cell.
220
        """
221 6
        return self.request('vim_strwidth', string)
222
223 6
    def list_runtime_paths(self):
224
        """Return a list of paths contained in the 'runtimepath' option."""
225
        return self.request('vim_list_runtime_paths')
226
227 6
    def foreach_rtp(self, cb):
228
        """Invoke `cb` for each path in 'runtimepath'.
229
230
        Call the given callable for each path in 'runtimepath' until either
231
        callable returns something but None, the exception is raised or there
232
        are no longer paths. If stopped in case callable returned non-None,
233
        vim.foreach_rtp function returns the value returned by callable.
234
        """
235 1
        for path in self.request('vim_list_runtime_paths'):
236 1
            try:
237
                if cb(path) is not None:
238
                    break
239
            except Exception:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
240
                break
241
242 6
    def chdir(self, dir_path):
243
        """Run os.chdir, then all appropriate vim stuff."""
244 6
        os_chdir(dir_path)
245 6
        return self.request('vim_change_directory', dir_path)
246
247 6
    def feedkeys(self, keys, options='', escape_csi=True):
248
        """Push `keys` to Nvim user input buffer.
249
250
        Options can be a string with the following character flags:
251
        - 'm': Remap keys. This is default.
252
        - 'n': Do not remap keys.
253
        - 't': Handle keys as if typed; otherwise they are handled as if coming
254
               from a mapping. This matters for undo, opening folds, etc.
255
        """
256
        return self.request('vim_feedkeys', keys, options, escape_csi)
257
258 6
    def input(self, bytes):
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in bytes.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
259
        """Push `bytes` to Nvim low level input buffer.
260
261
        Unlike `feedkeys()`, this uses the lowest level input buffer and the
262
        call is not deferred. It returns the number of bytes actually
263
        written(which can be less than what was requested if the buffer is
264
        full).
265
        """
266 6
        return self.request('vim_input', bytes)
267
268 6
    def replace_termcodes(self, string, from_part=False, do_lt=True,
269
                          special=True):
270
        r"""Replace any terminal code strings by byte sequences.
271
272
        The returned sequences are Nvim's internal representation of keys,
273
        for example:
274
275
        <esc> -> '\x1b'
276
        <cr>  -> '\r'
277
        <c-l> -> '\x0c'
278
        <up>  -> '\x80ku'
279
280
        The returned sequences can be used as input to `feedkeys`.
281
        """
282
        return self.request('vim_replace_termcodes', string,
283
                            from_part, do_lt, special)
284
285 6
    def out_write(self, msg):
286
        """Print `msg` as a normal message."""
287
        return self.request('vim_out_write', msg)
288
289 6
    def err_write(self, msg, async=False):
290
        """Print `msg` as an error message."""
291
        return self.request('vim_err_write', msg, async=async)
292
293 6
    def quit(self, quit_command='qa!'):
294
        """Send a quit command to Nvim.
295
296
        By default, the quit command is 'qa!' which will make Nvim quit without
297
        saving anything.
298
        """
299
        try:
300 1
            self.command(quit_command)
301 1
        except IOError:
0 ignored issues
show
Unused Code introduced by
This except handler seems to be unused and could be removed.

Except handlers which only contain pass and do not have an else clause can usually simply be removed:

try:
    raises_exception()
except:  # Could be removed
    pass
Loading history...
302
            # sending a quit command will raise an IOError because the
303
            # connection is closed before a response is received. Safe to
304
            # ignore it.
305
            pass
306
307 6
    def new_highlight_source(self):
308
        """Return new src_id for use with Buffer.add_highlight."""
309 4
        return self.current.buffer.add_highlight("", 0, src_id=0)
310
311 6
    def async_call(self, fn, *args, **kwargs):
312
        """Schedule `fn` to be called by the event loop soon.
313
314
        This function is thread-safe, and is the only way code not
315
        on the main thread could interact with nvim api objects.
316
317
        This function can also be called in a synchronous
318
        event handler, just before it returns, to defer execution
319
        that shouldn't block neovim.
320
        """
321 6
        call_point = ''.join(format_stack(None, 5)[:-1])
322
323 6
        def handler():
324 6
            try:
325 6
                fn(*args, **kwargs)
326
            except Exception as err:
327
                msg = ("error caught while executing async callback:\n"
328
                       "{0!r}\n{1}\n \nthe call was requested at\n{2}"
329
                       .format(err, format_exc(5), call_point))
330
                self._err_cb(msg)
331
                raise
332 6
        self._session.threadsafe_call(handler)
333
334
335 6
class Current(object):
336
337
    """Helper class for emulating vim.current from python-vim."""
338
339 6
    def __init__(self, session):
340 6
        self._session = session
341 6
        self.range = None
342
343 6
    @property
344
    def line(self):
345 6
        return self._session.request('vim_get_current_line')
346
347 6
    @line.setter
348
    def line(self, line):
349 6
        return self._session.request('vim_set_current_line', line)
350
351 6
    @property
352
    def buffer(self):
353 6
        return self._session.request('vim_get_current_buffer')
354
355 6
    @buffer.setter
356
    def buffer(self, buffer):
357 6
        return self._session.request('vim_set_current_buffer', buffer)
358
359 6
    @property
360
    def window(self):
361 6
        return self._session.request('vim_get_current_window')
362
363 6
    @window.setter
364
    def window(self, window):
365 6
        return self._session.request('vim_set_current_window', window)
366
367 6
    @property
368
    def tabpage(self):
369 6
        return self._session.request('vim_get_current_tabpage')
370
371 6
    @tabpage.setter
372
    def tabpage(self, tabpage):
373 6
        return self._session.request('vim_set_current_tabpage', tabpage)
374
375
376 6
class Funcs(object):
377
378
    """Helper class for functional vimscript interface."""
379
380 6
    def __init__(self, nvim):
381 6
        self._nvim = nvim
382
383 6
    def __getattr__(self, name):
384 6
        return functools.partial(self._nvim.call, name)
385
386
387 6
class NvimError(Exception):
388
    pass
389