[Python-modules-commits] [python-neovim] 01/04: Imported Upstream version 0.1.0
Víctor Cuadrado Juan
viccuad-guest at moszumanska.debian.org
Wed Jan 27 12:02:45 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 190a1fbfc07a540f2a6477487a1dbe2325c0671d
Author: Víctor Cuadrado Juan <me at viccuad.me>
Date: Sat Jan 2 14:35:20 2016 +0100
Imported Upstream version 0.1.0
---
.gitignore | 7 +
.scrutinizer.yml | 134 +++++++
.travis.yml | 44 +++
LICENSE | 201 ++++++++++
README.md | 51 +++
neovim/__init__.py | 105 ++++++
neovim/api/__init__.py | 15 +
neovim/api/buffer.py | 202 ++++++++++
neovim/api/common.py | 265 ++++++++++++++
neovim/api/nvim.py | 297 +++++++++++++++
neovim/api/tabpage.py | 32 ++
neovim/api/window.py | 78 ++++
neovim/compat.py | 36 ++
neovim/msgpack_rpc/__init__.py | 41 +++
neovim/msgpack_rpc/async_session.py | 134 +++++++
neovim/msgpack_rpc/event_loop/__init__.py | 16 +
neovim/msgpack_rpc/event_loop/asyncio.py | 120 ++++++
neovim/msgpack_rpc/event_loop/base.py | 171 +++++++++
neovim/msgpack_rpc/event_loop/uv.py | 122 +++++++
neovim/msgpack_rpc/msgpack_stream.py | 59 +++
neovim/msgpack_rpc/session.py | 204 +++++++++++
neovim/plugin/__init__.py | 9 +
neovim/plugin/decorators.py | 149 ++++++++
neovim/plugin/host.py | 192 ++++++++++
neovim/ui/__init__.py | 1 +
neovim/ui/cli.py | 73 ++++
neovim/ui/gtk_ui.py | 587 ++++++++++++++++++++++++++++++
neovim/ui/screen.py | 134 +++++++
neovim/ui/ui_bridge.py | 101 +++++
scripts/disable_log_statements.sh | 4 +
scripts/enable_log_statements.sh | 4 +
scripts/logging_statement_modifier.py | 341 +++++++++++++++++
scripts/publish.sh | 5 +
setup.cfg | 2 +
setup.py | 51 +++
test/common.py | 67 ++++
test/test_buffer.py | 151 ++++++++
test/test_client_rpc.py | 80 ++++
test/test_concurrency.py | 11 +
test/test_events.py | 52 +++
test/test_tabpage.py | 30 ++
test/test_vim.py | 141 +++++++
test/test_window.py | 96 +++++
43 files changed, 4615 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6ea0120
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+*.egg-info/
+__pycache__
+neovim/ui/screen.c
+neovim/ui/screen.so
+build/
+dist/
+*.pyc
diff --git a/.scrutinizer.yml b/.scrutinizer.yml
new file mode 100644
index 0000000..ab17321
--- /dev/null
+++ b/.scrutinizer.yml
@@ -0,0 +1,134 @@
+checks:
+ python:
+ imports_relative_import: true
+ imports_wildcard_import: true
+ classes_no_self_argument: true
+ classes_bad_mcs_method_argument: true
+ classes_bad_classmethod_argument: true
+ code_rating: true
+ duplicate_code: true
+ variables_unused_variable: true
+ variables_unused_import: true
+ variables_unused_wildcard_import: true
+ variables_unused_argument: true
+ variables_global_variable_not_assigned: true
+ typecheck_redundant_keyword_arg: true
+ imports_import_self: true
+ format_superfluous_parens: true
+ exceptions_pointless_except: true
+ design_interface_not_implemented: true
+ design_abstract_class_not_used: true
+ basic_useless_else_on_loop: true
+ basic_unreachable: true
+ basic_unnecessary_pass: true
+ basic_unnecessary_lambda: true
+ basic_pointless_string_statement: true
+ basic_pointless_statement: true
+ basic_expression_not_assigned: true
+ variables_redefined_outer_name: true
+ variables_redefined_builtin: true
+ variables_redefine_in_handler: true
+ newstyle_bad_super_call: true
+ logging_not_lazy: true
+ exceptions_broad_except: true
+ exceptions_bare_except: true
+ classes_super_init_not_called: true
+ classes_protected_access: true
+ classes_non_parent_init_called: true
+ classes_bad_mcs_classmethod_argument: true
+ classes_attribute_defined_outside_init: true
+ classes_method_hidden: true
+ basic_lost_exception: true
+ basic_function_redefined: true
+ basic_exec_used: true
+ basic_eval_used: true
+ basic_dangerous_default_value: true
+ design_abstract_class_little_used: true
+ imports_deprecated_module: true
+ format_old_ne_operator: true
+ format_backtick: true
+ basic_old_raise_syntax: true
+ variables_used_before_assignment: true
+ variables_unpacking_non_sequence: true
+ variables_undefined_variable: true
+ variables_undefined_loop_variable: true
+ variables_undefined_all_variable: true
+ variables_unbalanced_tuple_unpacking: true
+ variables_no_name_in_module: true
+ variables_invalid_all_object: true
+ variables_global_variable_undefined: true
+ typecheck_unexpected_keyword_arg: true
+ typecheck_not_callable: true
+ typecheck_no_value_for_parameter: true
+ typecheck_no_member: true
+ typecheck_too_many_function_args: true
+ typecheck_missing_kwoa: true
+ typecheck_maybe_no_member: true
+ typecheck_duplicate_keyword_arg: true
+ typecheck_assignment_from_none: true
+ typecheck_assignment_from_no_return: true
+ string_unused_format_string_key: true
+ string_truncated_format_string: true
+ string_too_many_format_args: true
+ string_too_few_format_args: true
+ string_mixed_format_string: true
+ string_missing_format_string_key: true
+ string_format_needs_mapping: true
+ string_constant_anomalous_unicode_escape_in_string: true
+ string_constant_anomalous_backslash_in_string: true
+ string_bad_str_strip_call: true
+ string_bad_format_string_key: true
+ string_bad_format_character: true
+ open_mode_bad_open_mode: true
+ logging_unsupported_format: true
+ logging_too_many_args: true
+ logging_too_few_args: true
+ logging_format_truncated: true
+ imports_reimported: true
+ imports_import_error: true
+ imports_cyclic_import: true
+ exceptions_raising_string: true
+ exceptions_raising_non_exception: true
+ exceptions_raising_bad_type: true
+ exceptions_notimplemented_raised: true
+ exceptions_catching_non_exception: true
+ exceptions_bad_except_order: true
+ classes_valid_slots: true
+ classes_signature_differs: true
+ classes_non_iterator_returned: true
+ classes_no_method_argument: true
+ classes_missing_interface_method: true
+ classes_interface_is_not_class: true
+ classes_bad_staticmethod_argument: true
+ classes_bad_context_manager: true
+ classes_arguments_differ: true
+ classes_access_member_before_definition: true
+ classes_abstract_method: true
+ basic_yield_outside_function: true
+ basic_return_outside_function: true
+ basic_return_in_init: true
+ basic_return_arg_in_generator: true
+ basic_not_in_loop: true
+ basic_nonexistent_operator: true
+ basic_missing_reversed_argument: true
+ basic_missing_module_attribute: true
+ basic_init_is_generator: true
+ basic_duplicate_key: true
+ basic_duplicate_argument_name: true
+ basic_bad_reversed_sequence: true
+ basic_assert_on_tuple: true
+ basic_abstract_class_instantiated: true
+ format_lowercase_l_suffix: true
+ classes_no_self_use: true
+ classes_no_init: true
+ exceptions_binary_op_exception: true
+ variables_global_statement: true
+
+filter:
+ excluded_paths:
+ - test/*
+
+tools:
+ external_code_coverage:
+ timeout: 1200
+ runs: 6
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..b68fb44
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,44 @@
+sudo: false
+language: python
+env:
+ global:
+ - NOSE_NOLOGCAPTURE=true
+ - NOSE_VERBOSE=2
+ - NOSE_WITH_COVERAGE=true
+ - NOSE_COVER_PACKAGE=neovim
+ matrix:
+ - CI_TARGET=tests
+matrix:
+ include:
+ - python: 2.7
+ env: CI_TARGET=flake
+ - python: 3.4
+ env: CI_TARGET=flake
+python:
+ # If the build matrix gets bigger, also update the number of runs
+ # at the bottom of .scrutinizer.yml.
+ - 2.6
+ - 2.7
+ - 3.3
+ - 3.4
+ - 3.5
+ - pypy
+before_install:
+ - if [ $CI_TARGET = tests ]; then
+ eval "$(curl -Ss https://raw.githubusercontent.com/neovim/bot-ci/master/scripts/travis-setup.sh) nightly-x64";
+ pip install -q scrutinizer-ocular;
+ else
+ pip install -q flake8 flake8-import-order flake8-docstrings pep8-naming;
+ fi
+install:
+ - pip install .
+script:
+ - if [ $CI_TARGET = tests ]; then
+ NVIM_CHILD_ARGV='["nvim", "-u", "NONE", "--embed"]' nosetests;
+ else
+ flake8 neovim;
+ fi
+after_script:
+ - if [ $CI_TARGET = tests ]; then
+ ocular;
+ fi
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..9942365
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2014 Thiago Arruda
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fcfa566
--- /dev/null
+++ b/README.md
@@ -0,0 +1,51 @@
+### Python client to [Neovim](https://github.com/neovim/neovim)
+
+[](https://travis-ci.org/neovim/python-client)
+[](https://scrutinizer-ci.com/g/neovim/python-client/?branch=master)
+[](https://scrutinizer-ci.com/g/neovim/python-client/?branch=master)
+
+Library for scripting Nvim processes through its msgpack-rpc API.
+
+#### Installation
+
+```sh
+pip install neovim
+```
+
+#### Usage through the python REPL
+
+A number of different transports are supported, but the simplest way to get
+started is with the python REPL. First, start Nvim with a known address (or
+use the `$NVIM_LISTEN_ADDRESS` of a running instance):
+
+```sh
+$ NVIM_LISTEN_ADDRESS=/tmp/nvim nvim
+```
+
+In another terminal, connect a python REPL to Nvim (note that the API is
+similar to the one exposed by the [python-vim
+bridge](http://vimdoc.sourceforge.net/htmldoc/if_pyth.html#python-vim)):
+
+```python
+>>> from neovim import attach
+# 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[0] = 'replace first line'
+>>> buffer[:] = ['replace whole buffer']
+>>> nvim.command('vsplit')
+>>> nvim.windows[1].width = 10
+>>> nvim.vars['global_var'] = [1, 2, 3]
+>>> nvim.eval('g:global_var')
+[1, 2, 3]
+```
+
+You can embed neovim into your python application instead of binding to a running neovim instance.
+
+```python
+>>> from neovim import attach
+>>> nvim = attach('child', argv=["/bin/env", "nvim", "--embed"])
+```
+
+The tests can be consulted for more examples.
diff --git a/neovim/__init__.py b/neovim/__init__.py
new file mode 100644
index 0000000..b2a0768
--- /dev/null
+++ b/neovim/__init__.py
@@ -0,0 +1,105 @@
+"""Python client for Nvim.
+
+Client library for talking with Nvim processes via it's msgpack-rpc API.
+"""
+import logging
+import os
+import sys
+
+from .api import DecodeHook, Nvim, SessionHook
+from .msgpack_rpc import (child_session, socket_session, stdio_session,
+ tcp_session)
+from .plugin import (Host, autocmd, command, encoding, function, plugin,
+ rpc_export, shutdown_hook)
+
+
+__all__ = ('tcp_session', 'socket_session', 'stdio_session', 'child_session',
+ 'start_host', 'autocmd', 'command', 'encoding', 'function',
+ 'plugin', 'rpc_export', 'Host', 'DecodeHook', 'Nvim',
+ 'SessionHook', 'shutdown_hook', 'attach')
+
+
+def start_host(session=None):
+ """Promote the current process into python plugin host for Nvim.
+
+ Start msgpack-rpc event loop for `session`, listening for Nvim requests
+ and notifications. It registers Nvim commands for loading/unloading
+ python plugins.
+
+ The sys.stdout and sys.stderr streams are redirected to Nvim through
+ `session`. That means print statements probably won't work as expected
+ while this function doesn't return.
+
+ This function is normally called at program startup and could have been
+ defined as a separate executable. It is exposed as a library function for
+ testing purposes only.
+ """
+ plugins = []
+ for arg in sys.argv:
+ _, ext = os.path.splitext(arg)
+ if ext == '.py':
+ plugins.append(arg)
+
+ if not plugins:
+ sys.exit('must specify at least one plugin as argument')
+
+ logger = logging.getLogger(__name__)
+ if 'NVIM_PYTHON_LOG_FILE' in os.environ:
+ logfile = (os.environ['NVIM_PYTHON_LOG_FILE'].strip() +
+ '_' + str(os.getpid()))
+ handler = logging.FileHandler(logfile, 'w')
+ handler.formatter = logging.Formatter(
+ '%(asctime)s [%(levelname)s @ '
+ '%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s')
+ logging.root.addHandler(handler)
+ level = logging.INFO
+ if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
+ l = getattr(logging,
+ os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
+ level)
+ if isinstance(l, int):
+ level = l
+ logger.setLevel(level)
+ if not session:
+ session = stdio_session()
+ host = Host(Nvim.from_session(session))
+ host.start(plugins)
+
+
+def attach(session_type, address=None, port=None, path=None, argv=None):
+ """Provide a nicer interface to create python api sessions.
+
+ Previous machinery to create python api sessions is still there. This only
+ creates a facade function to make things easier for the most usual cases.
+ Thus, instead of:
+ from neovim import socket_session, Nvim
+ session = tcp_session(address=<address>, port=<port>)
+ nvim = Nvim.from_session(session)
+ You can now do:
+ from neovim import attach
+ nvim = attach('tcp', address=<address>, port=<port>)
+ And also:
+ nvim = attach('socket', path=<path>)
+ nvim = attach('child', argv=<argv>)
+ nvim = attach('stdio')
+ """
+ session = (tcp_session(address, port) if session_type == 'tcp' else
+ socket_session(path) if session_type == 'socket' else
+ stdio_session() if session_type == 'stdio' else
+ child_session(argv) if session_type == 'child' else
+ None)
+
+ if not session:
+ raise Exception('Unknown session type "%s"' % session_type)
+
+ return Nvim.from_session(session)
+
+
+# Required for python 2.6
+class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+
+
+if not logging.root.handlers:
+ logging.root.addHandler(NullHandler())
diff --git a/neovim/api/__init__.py b/neovim/api/__init__.py
new file mode 100644
index 0000000..10f2147
--- /dev/null
+++ b/neovim/api/__init__.py
@@ -0,0 +1,15 @@
+"""Nvim API subpackage.
+
+This package implements a higher-level API that wraps msgpack-rpc `Session`
+instances.
+"""
+
+from .buffer import Buffer
+from .common import DecodeHook, SessionHook
+from .nvim import Nvim, NvimError
+from .tabpage import Tabpage
+from .window import Window
+
+
+__all__ = ('Nvim', 'Buffer', 'Window', 'Tabpage', 'NvimError', 'SessionHook',
+ 'DecodeHook')
diff --git a/neovim/api/buffer.py b/neovim/api/buffer.py
new file mode 100644
index 0000000..b3ba292
--- /dev/null
+++ b/neovim/api/buffer.py
@@ -0,0 +1,202 @@
+"""API for working with Nvim buffers."""
+from .common import Remote, RemoteMap
+from ..compat import IS_PYTHON3
+
+
+__all__ = ('Buffer')
+
+
+if IS_PYTHON3:
+ basestring = str
+
+
+class Buffer(Remote):
+
+ """A remote Nvim buffer."""
+
+ def __init__(self, session, code_data):
+ """Initialize from session and code_data immutable object.
+
+ The `code_data` contains serialization information required for
+ msgpack-rpc calls. It must be immutable for Buffer equality to work.
+ """
+ self._session = session
+ self.code_data = code_data
+ self.vars = RemoteMap(session, 'buffer_get_var', 'buffer_set_var',
+ self)
+ self.options = RemoteMap(session, 'buffer_get_option',
+ 'buffer_set_option', self)
+
+ def __len__(self):
+ """Return the number of lines contained in a Buffer."""
+ return self._session.request('buffer_line_count', self)
+
+ def __getitem__(self, idx):
+ """Get a buffer line or slice by integer index.
+
+ Indexes may be negative to specify positions from the end of the
+ buffer. For example, -1 is the last line, -2 is the line before that
+ and so on.
+
+ When retrieving slices, omiting indexes(eg: `buffer[:]`) will bring
+ the whole buffer.
+ """
+ if not isinstance(idx, slice):
+ return self._session.request('buffer_get_line', self, idx)
+ include_end = False
+ start = idx.start
+ end = idx.stop
+ if start is None:
+ start = 0
+ if end is None:
+ end = -1
+ include_end = True
+ return self._session.request('buffer_get_line_slice', self, start, end,
+ True, include_end)
+
+ def __setitem__(self, idx, lines):
+ """Replace a buffer line or slice by integer index.
+
+ Like with `__getitem__`, indexes may be negative.
+
+ When replacing slices, omiting indexes(eg: `buffer[:]`) will replace
+ the whole buffer.
+ """
+ if not isinstance(idx, slice):
+ if lines is None:
+ return self._session.request('buffer_del_line', self, idx)
+ else:
+ return self._session.request('buffer_set_line', self, idx,
+ lines)
+ if lines is None:
+ lines = []
+ include_end = False
+ start = idx.start
+ end = idx.stop
+ if start is None:
+ start = 0
+ if end is None:
+ end = -1
+ include_end = True
+ return self._session.request('buffer_set_line_slice', self, start, end,
+ True, include_end, lines)
+
+ def __iter__(self):
+ """Iterate lines of a buffer.
+
+ This will retrieve all lines locally before iteration starts. This
+ approach is used because for most cases, the gain is much greater by
+ minimizing the number of API calls by transfering all data needed to
+ work.
+ """
+ lines = self[:]
+ for line in lines:
+ yield line
+
+ def __delitem__(self, idx):
+ """Delete line or slice of lines from the buffer.
+
+ This is the same as __setitem__(idx, [])
+ """
+ if not isinstance(idx, slice):
+ self.__setitem__(idx, None)
+ else:
+ self.__setitem__(idx, [])
+
+ def get_line_slice(self, start, stop, start_incl, end_incl):
+ """More flexible wrapper for retrieving slices."""
+ return self._session.request('buffer_get_line_slice', self, start,
+ stop, start_incl, end_incl)
+
+ def set_line_slice(self, start, stop, start_incl, end_incl, lines):
+ """More flexible wrapper for replacing slices."""
+ return self._session.request('buffer_set_line_slice', self, start,
+ stop, start_incl, end_incl, lines)
+
+ def append(self, lines, index=-1):
+ """Append a string or list of lines to the buffer."""
+ if isinstance(lines, basestring):
+ lines = [lines]
+ return self._session.request('buffer_insert', self, index, lines)
+
+ def mark(self, name):
+ """Return (row, col) tuple for a named mark."""
+ return self._session.request('buffer_get_mark', self, name)
+
+ def range(self, start, end):
+ """Return a `Range` object, which represents part of the Buffer."""
+ return Range(self, start, end)
+
+ @property
+ def name(self):
+ """Get the buffer name."""
+ return self._session.request('buffer_get_name', self)
+
+ @name.setter
+ def name(self, value):
+ """Set the buffer name. BufFilePre/BufFilePost are triggered."""
+ return self._session.request('buffer_set_name', self, value)
+
+ @property
+ def valid(self):
+ """Return True if the buffer still exists."""
+ return self._session.request('buffer_is_valid', self)
+
+ @property
+ def number(self):
+ """Get the buffer number."""
+ return self._session.request('buffer_get_number', self)
+
+
+class Range(object):
+ def __init__(self, buffer, start, end):
+ self._buffer = buffer
+ self.start = start - 1
+ self.end = end
+
+ def __len__(self):
+ return self.end - self.start
+
+ def __getitem__(self, idx):
+ if not isinstance(idx, slice):
+ return self._buffer[self._normalize_index(idx)]
+ start = self._normalize_index(idx.start)
+ end = self._normalize_index(idx.stop)
+ if start is None:
+ start = self.start
+ if end is None:
+ end = self.end
+ return self._buffer[start:end]
+
+ def __setitem__(self, idx, lines):
+ if not isinstance(idx, slice):
+ self._buffer[self._normalize_index(idx)] = lines
+ return
+ start = self._normalize_index(idx.start)
+ end = self._normalize_index(idx.stop)
+ if start is None:
+ start = self.start
+ if end is None:
+ end = self.end
+ self._buffer[start:end] = lines
+
+ def __iter__(self):
+ for i in range(self.start, self.end):
+ yield self._buffer[i]
+
+ def append(self, lines, i=None):
+ i = self._normalize_index(i)
+ if i is None:
+ i = self.end
+ self._buffer.append(lines, i)
+
+ def _normalize_index(self, index):
+ if index is None:
+ return None
+ if index < 0:
+ index = self.end - 1
+ else:
+ index += self.start
+ if index >= self.end:
+ index = self.end - 1
+ return index
diff --git a/neovim/api/common.py b/neovim/api/common.py
new file mode 100644
index 0000000..3a456e3
--- /dev/null
+++ b/neovim/api/common.py
@@ -0,0 +1,265 @@
+"""Code shared between the API classes."""
+
+
+class Remote(object):
+
+ """Base class for Nvim objects(buffer/window/tabpage).
+
+ Each type of object has it's own specialized class with API wrappers around
+ the msgpack-rpc session. This implements equality which takes the remote
+ object handle into consideration.
+ """
+
+ def __eq__(self, other):
+ """Return True if `self` and `other` are the same object."""
+ return (hasattr(other, 'code_data') and
+ other.code_data == self.code_data)
+
+ def __hash__(self):
+ """Return hash based on remote object id."""
+ return self.code_data.__hash__()
+
+
+class RemoteMap(object):
+
+ """Represents a string->object map stored in Nvim.
+
+ This is the dict counterpart to the `RemoteSequence` class, but it is used
+ as a generic way of retrieving values from the various map-like data
+ structures present in Nvim.
+
+ It is used to provide a dict-like API to vim variables and options.
+ """
+
+ def __init__(self, session, get_method, set_method, self_obj=None):
+ """Initialize a RemoteMap with session, getter/setter and self_obj."""
+ self._get = _wrap(session, get_method, self_obj)
+ self._set = None
+ if set_method:
+ self._set = _wrap(session, set_method, self_obj)
+
+ def __getitem__(self, key):
+ """Return a map value by key."""
+ return self._get(key)
+
+ def __setitem__(self, key, value):
+ """Set a map value by key(if the setter was provided)."""
+ if not self._set:
+ raise TypeError('This dict is read-only')
+ self._set(key, value)
+
+ def __delitem__(self, key):
+ """Delete a map value by associating None with the key."""
+ if not self._set:
+ raise TypeError('This dict is read-only')
+ return self._set(key, None)
+
+ def __contains__(self, key):
+ """Check if key is present in the map."""
+ try:
+ self._get(key)
+ return True
+ except Exception:
+ return False
+
+ def get(self, key, default=None):
+ """Return value for key if present, else a default value."""
+ try:
+ return self._get(key)
+ except Exception:
+ return default
+
+
+class RemoteSequence(object):
+
+ """Represents a sequence of objects stored in Nvim.
+
+ This class is used to wrap msgapck-rpc functions that work on Nvim
+ 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].
+
+ 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
+ to: session.request('tabpage_get_windows', tabpage_instance)[0].
+
+ One important detail about this class is that all methods will fetch the
+ sequence into a list and perform the necessary manipulation
+ locally(iteration, indexing, counting, etc).
+ """
+
+ def __init__(self, session, method, self_obj=None):
+ """Initialize a RemoteSequence with session, method and self_obj."""
+ self._fetch = _wrap(session, method, self_obj)
+
+ def __len__(self):
+ """Return the length of the remote sequence."""
+ return len(self._fetch())
+
+ def __getitem__(self, idx):
+ """Return a sequence item by index."""
+ if not isinstance(idx, slice):
+ return self._fetch()[idx]
+ return self._fetch()[idx.start:idx.stop]
+
+ def __iter__(self):
+ """Return an iterator for the sequence."""
+ items = self._fetch()
+ for item in items:
+ yield item
+
+ def __contains__(self, item):
+ """Check if an item is present in the sequence."""
+ return item in self._fetch()
+
+
+def _identity(obj, session, method, kind):
+ return obj
+
+
+class SessionHook(object):
+
+ """Pair of functions to filter objects coming/going from/to Nvim.
+
+ Filter functions receive the following arguments:
+
+ - obj: The object to process
+ - session: The current session object
+ - method: The method name
+ - kind: Kind of filter, can be one of:
+ - 'request' for requests coming from Nvim
+ - 'notification' for notifications coming from Nvim
+ - 'out-request' for requests going to Nvim
+
... 3924 lines suppressed ...
--
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