More linting.

This commit is contained in:
Holger Rapp 2014-02-07 10:20:30 +01:00
parent bd132bc379
commit c78a54b158
4 changed files with 120 additions and 117 deletions

View File

@ -526,7 +526,7 @@ class SnippetManager(object):
possible matches. possible matches.
""" """
self._ensure_all_loaded() self._ensure_all_loaded()
filetypes = self._filetypes[_vim.buf.nr][::-1] filetypes = self._filetypes[_vim.buf.number][::-1]
found_snippets = [] found_snippets = []
for ft in filetypes: for ft in filetypes:
@ -624,7 +624,7 @@ class SnippetManager(object):
def primary_filetype(self): def primary_filetype(self):
"""This filetype will be edited when UltiSnipsEdit is called without """This filetype will be edited when UltiSnipsEdit is called without
any arguments.""" any arguments."""
return self._filetypes[_vim.buf.nr][0] return self._filetypes[_vim.buf.number][0]
def file_to_edit(self, ft): # pylint: disable=no-self-use def file_to_edit(self, ft): # pylint: disable=no-self-use
""" Gets a file to edit based on the given filetype. """ Gets a file to edit based on the given filetype.
@ -710,18 +710,18 @@ class SnippetManager(object):
def _ensure_all_loaded(self): def _ensure_all_loaded(self):
"""Make sure that all filetypes fur the current buffer are loaded.""" """Make sure that all filetypes fur the current buffer are loaded."""
for ft in self._filetypes[_vim.buf.nr]: for ft in self._filetypes[_vim.buf.number]:
self._ensure_loaded(ft) self._ensure_loaded(ft)
def reset_buffer_filetypes(self): def reset_buffer_filetypes(self):
"""Reset the filetypes for the current buffer.""" """Reset the filetypes for the current buffer."""
if _vim.buf.nr in self._filetypes: if _vim.buf.number in self._filetypes:
del self._filetypes[_vim.buf.nr] del self._filetypes[_vim.buf.number]
def add_buffer_filetypes(self, ft): def add_buffer_filetypes(self, ft):
"""Checks for changes in the list of snippet files or the contents of """Checks for changes in the list of snippet files or the contents of
the snippet files and reloads them if necessary. """ the snippet files and reloads them if necessary. """
buf_fts = self._filetypes[_vim.buf.nr] buf_fts = self._filetypes[_vim.buf.number]
idx = -1 idx = -1
for ft in ft.split("."): for ft in ft.split("."):
ft = ft.strip() ft = ft.strip()
@ -730,7 +730,7 @@ class SnippetManager(object):
try: try:
idx = buf_fts.index(ft) idx = buf_fts.index(ft)
except ValueError: except ValueError:
self._filetypes[_vim.buf.nr].insert(idx + 1, ft) self._filetypes[_vim.buf.number].insert(idx + 1, ft)
idx += 1 idx += 1
self._ensure_all_loaded() self._ensure_all_loaded()

View File

@ -1,40 +1,43 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # encoding: utf-8
""" """Wrapper functionality around the functions we need from Vim."""
Wrapper functionality around the functions we need from Vim
"""
import re import re
import vim import vim # pylint:disable=import-error
from vim import error from vim import error # pylint:disable=import-error,unused-import
from UltiSnips.geometry import Position from UltiSnips.geometry import Position
from UltiSnips.compatibility import col2byte, byte2col, \ from UltiSnips.compatibility import col2byte, byte2col, \
as_unicode, as_vimencoding as_unicode, as_vimencoding
class VimBuffer(object): class VimBuffer(object):
"""Wrapper around the current Vim buffer."""
def __getitem__(self, idx): def __getitem__(self, idx):
if isinstance(idx, slice): # Py3 if isinstance(idx, slice): # Py3
return self.__getslice__(idx.start, idx.stop) return self.__getslice__(idx.start, idx.stop)
rv = vim.current.buffer[idx] rv = vim.current.buffer[idx]
return as_unicode(rv) return as_unicode(rv)
def __getslice__(self, i, j):
def __getslice__(self, i, j): # pylint:disable=no-self-use
rv = vim.current.buffer[i:j] rv = vim.current.buffer[i:j]
return [ as_unicode(l) for l in rv ] return [as_unicode(l) for l in rv]
def __setitem__(self, idx, text): def __setitem__(self, idx, text):
if isinstance(idx, slice): # Py3 if isinstance(idx, slice): # Py3
return self.__setslice__(idx.start, idx.stop, text) return self.__setslice__(idx.start, idx.stop, text)
vim.current.buffer[idx] = as_vimencoding(text) vim.current.buffer[idx] = as_vimencoding(text)
def __setslice__(self, i, j, text):
vim.current.buffer[i:j] = [ as_vimencoding(l) for l in text ] def __setslice__(self, i, j, text): # pylint:disable=no-self-use
vim.current.buffer[i:j] = [as_vimencoding(l) for l in text]
def __len__(self): def __len__(self):
return len(vim.current.buffer) return len(vim.current.buffer)
@property @property
def line_till_cursor(self): def line_till_cursor(self): # pylint:disable=no-self-use
"""Returns the text before the cursor.""" """Returns the text before the cursor."""
# Note: we want byte position here # Note: we want byte position here
_, col = vim.current.window.cursor _, col = vim.current.window.cursor
@ -43,51 +46,32 @@ class VimBuffer(object):
return before return before
@property @property
def nr(self): def number(self): # pylint:disable=no-self-use
"""The bufnr() of this buffer."""
return int(eval("bufnr('%')")) return int(eval("bufnr('%')"))
def cursor(): @property
def cursor(self): # pylint:disable=no-self-use
""" """
The current windows cursor. Note that this is 0 based in col and 0 The current windows cursor. Note that this is 0 based in col and 0
based in line which is different from Vim's cursor. based in line which is different from Vim's cursor.
""" """
def fget(self):
line, nbyte = vim.current.window.cursor line, nbyte = vim.current.window.cursor
col = byte2col(line, nbyte) col = byte2col(line, nbyte)
return Position(line - 1, col) return Position(line - 1, col)
def fset(self, pos):
@cursor.setter
def cursor(self, pos): # pylint:disable=no-self-use
"""See getter."""
nbyte = col2byte(pos.line + 1, pos.col) nbyte = col2byte(pos.line + 1, pos.col)
vim.current.window.cursor = pos.line + 1, nbyte vim.current.window.cursor = pos.line + 1, nbyte
return locals() buf = VimBuffer() # pylint:disable=invalid-name
cursor = property(**cursor())
buf = VimBuffer()
def text_to_vim(start, end, text):
lines = text.split('\n')
new_end = _calc_end(lines, start)
before = buf[start.line][:start.col]
after = buf[end.line][end.col:]
new_lines = []
if len(lines):
new_lines.append(before + lines[0])
new_lines.extend(lines[1:])
new_lines[-1] += after
buf[start.line:end.line + 1] = new_lines
# Open any folds this might have created
buf.cursor = start
vim.command("normal! zv")
return new_end
def escape(inp): def escape(inp):
""" Creates a vim-friendly string from a group of """Creates a vim-friendly string from a group of
dicts, lists and strings. dicts, lists and strings."""
"""
def conv(obj): def conv(obj):
"""Convert obj."""
if isinstance(obj, list): if isinstance(obj, list):
rv = as_unicode('[' + ','.join(conv(o) for o in obj) + ']') rv = as_unicode('[' + ','.join(conv(o) for o in obj) + ']')
elif isinstance(obj, dict): elif isinstance(obj, dict):
@ -99,18 +83,20 @@ def escape(inp):
return rv return rv
return conv(inp) return conv(inp)
def command(s): def command(cmd):
return as_unicode(vim.command(as_vimencoding(s))) """Wraps vim.command."""
return as_unicode(vim.command(as_vimencoding(cmd)))
def eval(s): def eval(text):
rv = vim.eval(as_vimencoding(s)) """Wraps vim.eval."""
rv = vim.eval(as_vimencoding(text))
if not isinstance(rv, (dict, list)): if not isinstance(rv, (dict, list)):
return as_unicode(rv) return as_unicode(rv)
return rv return rv
def feedkeys(s, mode='n'): def feedkeys(keys, mode='n'):
"""Wrapper around vim's feedkeys function. Mainly for convenience.""" """Wrapper around vim's feedkeys function. Mainly for convenience."""
command(as_unicode(r'call feedkeys("%s", "%s")') % (s, mode)) command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
def new_scratch_buffer(text): def new_scratch_buffer(text):
"""Create a new scratch buffer with the text given""" """Create a new scratch buffer with the text given"""
@ -146,15 +132,14 @@ def select(start, end):
move_cmd += "a" move_cmd += "a"
else: else:
# Case 2a: Non zero length # Case 2a: Non zero length
# If a tabstop immediately starts with a newline, the selection # If a tabstop immediately starts with a newline, the selection must
# must start after the last character in the current line. But if # start after the last character in the current line. But if we are in
# we are in insert mode and <Esc> out of it, we cannot go past the # insert mode and <Esc> out of it, we cannot go past the last character
# last character with move_one_right and therefore cannot # with move_one_right and therefore cannot visual-select this newline.
# visual-select this newline. We have to hack around this by adding # We have to hack around this by adding an extra space which we can
# an extra space which we can select. Note that this problem could # select. Note that this problem could be circumvent by selecting the
# be circumvent by selecting the tab backwards (that is starting # tab backwards (that is starting at the end); one would not need to
# at the end); one would not need to modify the line for this. This creates other # modify the line for this. This creates other trouble though
# trouble though
if col >= len(buf[lineno]): if col >= len(buf[lineno]):
buf[lineno] += " " buf[lineno] += " "
@ -192,14 +177,6 @@ def select(start, end):
feedkeys(move_cmd) feedkeys(move_cmd)
# Helper functions {{{
def _calc_end(lines, start):
if len(lines) == 1:
new_end = start + Position(0,len(lines[0]))
else:
new_end = Position(start.line + len(lines)-1, len(lines[-1]))
return new_end
def _unmap_select_mode_mapping(): def _unmap_select_mode_mapping():
"""This function unmaps select mode mappings if so wished by the user. """This function unmaps select mode mappings if so wished by the user.
Removes select mode mappings that can actually be typed by the user Removes select mode mappings that can actually be typed by the user
@ -215,7 +192,7 @@ def _unmap_select_mode_mapping():
# Check if any mappings where found # Check if any mappings where found
all_maps = list(filter(len, eval(r"_tmp_smaps").splitlines())) all_maps = list(filter(len, eval(r"_tmp_smaps").splitlines()))
if (len(all_maps) == 1 and all_maps[0][0] not in " sv"): if len(all_maps) == 1 and all_maps[0][0] not in " sv":
# "No maps found". String could be localized. Hopefully # "No maps found". String could be localized. Hopefully
# it doesn't start with any of these letters in any # it doesn't start with any of these letters in any
# language # language
@ -225,10 +202,10 @@ def _unmap_select_mode_mapping():
maps = [m for m in all_maps if maps = [m for m in all_maps if
not any(i in m for i in ignores) and len(m.strip())] not any(i in m for i in ignores) and len(m.strip())]
for m in maps: for map in maps:
# The first three chars are the modes, that might be listed. # The first three chars are the modes, that might be listed.
# We are not interested in them here. # We are not interested in them here.
trig = m[3:].split()[0] if len(m[3:].split()) != 0 else None trig = map[3:].split()[0] if len(map[3:].split()) != 0 else None
if trig is None: if trig is None:
continue continue
@ -254,7 +231,7 @@ def _unmap_select_mode_mapping():
# Actually unmap it # Actually unmap it
try: try:
command("silent! sunmap %s %s" % (option, trig)) command("silent! sunmap %s %s" % (option, trig))
except: except: # pylint:disable=bare-except
# Bug 908139: ignore unmaps that fail because of # Bug 908139: ignore unmaps that fail because of
# unprintable characters. This is not ideal because we # unprintable characters. This is not ideal because we
# will not be able to unmap lhs with any unprintable # will not be able to unmap lhs with any unprintable
@ -264,58 +241,54 @@ def _unmap_select_mode_mapping():
# This case should be rare enough to not bother us # This case should be rare enough to not bother us
# though. # though.
pass pass
# End: Helper functions }}}
# Helper classes {{{
class _Real_LangMapTranslator(object):
"""
This carse for the Vim langmap option and basically reverses the mappings. This
was the only solution to get UltiSnips to work nicely with langmap; other stuff
I tried was using inoremap movement commands and caching and restoring the
langmap option.
Note that this will not work if the langmap overwrites a character completely, class _RealLangMapTranslator(object):
for example if 'j' is remapped, but nothing is mapped back to 'j', then moving """This cares for the Vim langmap option and basically reverses the
one line down is no longer possible and UltiSnips will fail. mappings. This was the only solution to get UltiSnips to work nicely with
langmap; other stuff I tried was using inoremap movement commands and
caching and restoring the langmap option.
Note that this will not work if the langmap overwrites a character
completely, for example if 'j' is remapped, but nothing is mapped back to
'j', then moving one line down is no longer possible and UltiSnips will
fail.
""" """
_maps = {} _maps = {}
_SEMICOLONS = re.compile(r"(?<!\\);") _SEMICOLONS = re.compile(r"(?<!\\);")
_COMMA = re.compile(r"(?<!\\),") _COMMA = re.compile(r"(?<!\\),")
def _create_translation(self, langmap): def _create_translation(self, langmap):
"""Create the reverse mapping from 'langmap'."""
from_chars, to_chars = "", "" from_chars, to_chars = "", ""
for c in self._COMMA.split(langmap): for char in self._COMMA.split(langmap):
c = c.replace("\\,", ",") char = char.replace("\\,", ",")
res = self._SEMICOLONS.split(c) res = self._SEMICOLONS.split(char)
if len(res) > 1: if len(res) > 1:
a,b = map(lambda a: a.replace("\\;", ";"), res) from_char, to_char = [a.replace("\\;", ";") for a in res]
from_chars += a from_chars += from_char
to_chars += b to_chars += to_char
else: else:
from_chars += c[::2] from_chars += char[::2]
to_chars += c[1::2] to_chars += char[1::2]
self._maps[langmap] = (from_chars, to_chars) self._maps[langmap] = (from_chars, to_chars)
def translate(self, s): def translate(self, text):
"""Inverse map 'text' through langmap."""
langmap = eval("&langmap").strip() langmap = eval("&langmap").strip()
if langmap == "": if langmap == "":
return s return text
text = as_unicode(text)
s = as_unicode(s)
if langmap not in self._maps: if langmap not in self._maps:
self._create_translation(langmap) self._create_translation(langmap)
for before, after in zip(*self._maps[langmap]):
text = text.replace(before, after)
return text
for f,t in zip(*self._maps[langmap]): class _DummyLangMapTranslator(object):
s = s.replace(f,t) """If vim hasn't got the langmap compiled in, we never have to do anything.
return s Then this class is used. """
class _Dummy_LangMapTranslator(object):
"""
If vim hasn't got the langmap compiled in, we never have to do anything.
Then this class is used.
"""
translate = lambda self, s: s translate = lambda self, s: s
_LangMapTranslator = _Real_LangMapTranslator _LangMapTranslator = _RealLangMapTranslator
if not int(eval('has("langmap")')): if not int(eval('has("langmap")')):
_LangMapTranslator = _Dummy_LangMapTranslator _LangMapTranslator = _DummyLangMapTranslator
# End: Helper classes }}}

View File

@ -1,13 +1,42 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # encoding: utf-8
import vim
import UltiSnips._vim as _vim import UltiSnips._vim as _vim
from UltiSnips.geometry import Position from UltiSnips.geometry import Position
__all__ = ["TextObject", "EditableTextObject", "NoneditableTextObject"] __all__ = ["TextObject", "EditableTextObject", "NoneditableTextObject"]
def _calc_end(lines, start):
if len(lines) == 1:
new_end = start + Position(0,len(lines[0]))
else:
new_end = Position(start.line + len(lines)-1, len(lines[-1]))
return new_end
def _text_to_vim(start, end, text):
"""Copy the given text to the current buffer, overwriting the span 'start'
to 'end'."""
lines = text.split('\n')
new_end = _calc_end(lines, start)
before = _vim.buf[start.line][:start.col]
after = _vim.buf[end.line][end.col:]
new_lines = []
if len(lines):
new_lines.append(before + lines[0])
new_lines.extend(lines[1:])
new_lines[-1] += after
_vim.buf[start.line:end.line + 1] = new_lines
# Open any folds this might have created
_vim.buf.cursor = start
_vim.command("normal! zv")
return new_end
class TextObject(object): class TextObject(object):
""" """
This base class represents any object in the text This base class represents any object in the text
@ -40,7 +69,7 @@ class TextObject(object):
# not want to mess with their positions # not want to mess with their positions
if self.current_text == gtext: return if self.current_text == gtext: return
old_end = self._end old_end = self._end
self._end = _vim.text_to_vim( self._end = _text_to_vim(
self._start, self._end, gtext or self._initial_text) self._start, self._end, gtext or self._initial_text)
if self._parent: if self._parent:
self._parent._child_has_moved( self._parent._child_has_moved(

View File

@ -42,6 +42,7 @@ disable=
too-many-instance-attributes, too-many-instance-attributes,
too-many-public-methods, too-many-public-methods,
too-few-public-methods, too-few-public-methods,
too-many-branches,
[REPORTS] [REPORTS]