Esempio n. 1
0
    def launch(self, text_before, visual_content, parent, start, end):
        """Launch this snippet, overwriting the text 'start' to 'end' and
        keeping the 'text_before' on the launch line. 'Parent' is the parent
        snippet instance if any."""
        indent = self._INDENT.match(text_before).group(0)
        lines = (self._value + "\n").splitlines()
        ind_util = IndentUtil()

        # Replace leading tabs in the snippet definition via proper indenting
        initial_text = []
        for line_num, line in enumerate(lines):
            if "t" in self._opts:
                tabs = 0
            else:
                tabs = len(self._TABS.match(line).group(0))
            line_ind = ind_util.ntabs_to_proper_indent(tabs)
            if line_num != 0:
                line_ind = indent + line_ind

            initial_text.append(line_ind + line[tabs:])
        initial_text = '\n'.join(initial_text)

        snippet_instance = SnippetInstance(
                self, parent, initial_text, start, end, visual_content,
                last_re=self._last_re, globals=self._globals)
        self.instantiate(snippet_instance, initial_text, indent)

        snippet_instance.update_textobjects()
        return snippet_instance
Esempio n. 2
0
    def launch(self, text_before, visual_content, parent, start, end):
        """Launch this snippet, overwriting the text 'start' to 'end' and
        keeping the 'text_before' on the launch line. 'Parent' is the parent
        snippet instance if any."""
        indent = self._INDENT.match(text_before).group(0)
        lines = (self._value + "\n").splitlines()
        ind_util = IndentUtil()

        # Replace leading tabs in the snippet definition via proper indenting
        snippet_definition = []
        for line_num, line in enumerate(lines):
            if "t" in self._opts:
                tabs = 0
            else:
                tabs = len(self._TABS.match(line).group(0))

            line_ind = ind_util.ntabs_to_proper_indent(tabs)

            if line_num != 0:
                line_ind = indent + line_ind

            snippet_definition.append(line_ind + line[tabs:])
        snippet_definition = '\n'.join(snippet_definition)

        si = SnippetInstance(self, parent, indent, snippet_definition, start,
                end, visual_content, last_re=self._last_re,
                globals=self._globals)

        return si
Esempio n. 3
0
    def launch(self, text_before, visual_content, parent, start, end):
        """Launch this snippet, overwriting the text 'start' to 'end' and
        keeping the 'text_before' on the launch line.

        'Parent' is the parent snippet instance if any.

        """
        indent = self._INDENT.match(text_before).group(0)
        lines = (self._value + '\n').splitlines()
        ind_util = IndentUtil()

        # Replace leading tabs in the snippet definition via proper indenting
        initial_text = []
        for line_num, line in enumerate(lines):
            if 't' in self._opts:
                tabs = 0
            else:
                tabs = len(self._TABS.match(line).group(0))
            line_ind = ind_util.ntabs_to_proper_indent(tabs)
            if line_num != 0:
                line_ind = indent + line_ind

            result_line = line_ind + line[tabs:]
            if 'm' in self._opts:
                result_line = result_line.rstrip()
            initial_text.append(result_line)
        initial_text = '\n'.join(initial_text)

        snippet_instance = SnippetInstance(
            self, parent, initial_text, start, end, visual_content,
            last_re=self._last_re, globals=self._globals)
        self.instantiate(snippet_instance, initial_text, indent)

        snippet_instance.update_textobjects()
        return snippet_instance
Esempio n. 4
0
    def _update(self, done):
        if self._mode == 'v':  # Normal selection.
            if platform.system() == 'Windows':
                # Remove last character for windows in normal selection.
                text = self._text[:-1]
            else:
                text = self._text
        else:  # Block selection or line selection.
            text_before = _vim.buf[self.start.line][:self.start.col]
            indent = _REPLACE_NON_WS.sub(' ', text_before)
            iu = IndentUtil()
            indent = iu.indent_to_spaces(indent)
            indent = iu.spaces_to_indent(indent)
            text = ''
            for idx, line in enumerate(
                    textwrap.dedent(self._text).splitlines(True)):
                if idx != 0:
                    text += indent
                text += line
            text = text[:-1]  # Strip final '\n'

        text = self._transform(text)
        self.overwrite(text)
        self._parent._del_child(self)  # pylint:disable=protected-access

        return True
Esempio n. 5
0
    def _update(self, done):
        if self._mode == 'v':  # Normal selection.
            if platform.system() == 'Windows':
                # Remove last character for windows in normal selection.
                text = self._text[:-1]
            else:
                text = self._text
        else:  # Block selection or line selection.
            text_before = _vim.buf[self.start.line][:self.start.col]
            indent = _REPLACE_NON_WS.sub(' ', text_before)
            iu = IndentUtil()
            indent = iu.indent_to_spaces(indent)
            indent = iu.spaces_to_indent(indent)
            text = ''
            for idx, line in enumerate(textwrap.dedent(
                    self._text).splitlines(True)):
                if idx != 0:
                    text += indent
                text += line
            text = text[:-1]  # Strip final '\n'

        text = self._transform(text)
        self.overwrite(text)
        self._parent._del_child(self)  # pylint:disable=protected-access

        return True
Esempio n. 6
0
 def __init__(self, initial_indent, vmode, vtext, context, parent):
     self._ind = IndentUtil()
     self._visual = _VisualContent(vmode, vtext)
     self._initial_indent = self._ind.indent_to_spaces(initial_indent)
     self._reset('')
     self._context = context
     self._start = parent.start
     self._end = parent.end
     self._parent = parent
Esempio n. 7
0
 def __init__(self, initial_indent, vmode, vtext, context, parent):
     self._ind = IndentUtil()
     self._visual = _VisualContent(vmode, vtext)
     self._initial_indent = self._ind.indent_to_spaces(initial_indent)
     self._reset('')
     self._context = context
     self._start = parent.start
     self._end = parent.end
     self._parent = parent
Esempio n. 8
0
    def _update(self, done, buf):
        if self._mode == "v":  # Normal selection.
            text = self._text
        else:  # Block selection or line selection.
            text_before = buf[self.start.line][: self.start.col]
            indent = _REPLACE_NON_WS.sub(" ", text_before)
            iu = IndentUtil()
            indent = iu.indent_to_spaces(indent)
            indent = iu.spaces_to_indent(indent)
            text = ""
            for idx, line in enumerate(textwrap.dedent(self._text).splitlines(True)):
                if idx != 0:
                    text += indent
                text += line
            text = text[:-1]  # Strip final '\n'

        text = self._transform(text)
        self.overwrite(buf, text)
        self._parent._del_child(self)  # pylint:disable=protected-access

        return True
Esempio n. 9
0
class SnippetUtil(object):

    """Provides easy access to indentation, etc.

    This is the 'snip' object in python code.

    """

    def __init__(self, initial_indent, vmode, vtext, context, parent):
        self._ind = IndentUtil()
        self._visual = _VisualContent(vmode, vtext)
        self._initial_indent = self._ind.indent_to_spaces(initial_indent)
        self._reset('')
        self._context = context
        self._start = parent.start
        self._end = parent.end
        self._parent = parent

    def _reset(self, cur):
        """Gets the snippet ready for another update.

        :cur: the new value for c.

        """
        self._ind.reset()
        self._cur = cur
        self._rv = ''
        self._changed = False
        self.reset_indent()

    def shift(self, amount=1):
        """Shifts the indentation level. Note that this uses the shiftwidth
        because thats what code formatters use.

        :amount: the amount by which to shift.

        """
        self.indent += ' ' * self._ind.shiftwidth * amount

    def unshift(self, amount=1):
        """Unshift the indentation level. Note that this uses the shiftwidth
        because thats what code formatters use.

        :amount: the amount by which to unshift.

        """
        by = -self._ind.shiftwidth * amount
        try:
            self.indent = self.indent[:by]
        except IndexError:
            self.indent = ''

    def mkline(self, line='', indent=None):
        """Creates a properly set up line.

        :line: the text to add
        :indent: the indentation to have at the beginning
                 if None, it uses the default amount

        """
        if indent is None:
            indent = self.indent
            # this deals with the fact that the first line is
            # already properly indented
            if '\n' not in self._rv:
                try:
                    indent = indent[len(self._initial_indent):]
                except IndexError:
                    indent = ''
            indent = self._ind.spaces_to_indent(indent)

        return indent + line

    def reset_indent(self):
        """Clears the indentation."""
        self.indent = self._initial_indent

    # Utility methods
    @property
    def fn(self):  # pylint:disable=no-self-use,invalid-name
        """The filename."""
        return _vim.eval('expand("%:t")') or ''

    @property
    def basename(self):  # pylint:disable=no-self-use
        """The filename without extension."""
        return _vim.eval('expand("%:t:r")') or ''

    @property
    def ft(self):  # pylint:disable=invalid-name
        """The filetype."""
        return self.opt('&filetype', '')

    @property
    def rv(self):  # pylint:disable=invalid-name
        """The return value.

        The text to insert at the location of the placeholder.

        """
        return self._rv

    @rv.setter
    def rv(self, value):  # pylint:disable=invalid-name
        """See getter."""
        self._changed = True
        self._rv = value

    @property
    def _rv_changed(self):
        """True if rv has changed."""
        return self._changed

    @property
    def c(self):  # pylint:disable=invalid-name
        """The current text of the placeholder."""
        return self._cur

    @property
    def v(self):  # pylint:disable=invalid-name
        """Content of visual expansions."""
        return self._visual

    @property
    def p(self):
        if self._parent.current_placeholder:
            return self._parent.current_placeholder
        else:
            return _Placeholder('', 0, 0)

    @property
    def context(self):
        return self._context

    def opt(self, option, default=None):  # pylint:disable=no-self-use
        """Gets a Vim variable."""
        if _vim.eval("exists('%s')" % option) == '1':
            try:
                return _vim.eval(option)
            except _vim.error:
                pass
        return default

    def __add__(self, value):
        """Appends the given line to rv using mkline."""
        self.rv += '\n'  # pylint:disable=invalid-name
        self.rv += self.mkline(value)
        return self

    def __lshift__(self, other):
        """Same as unshift."""
        self.unshift(other)

    def __rshift__(self, other):
        """Same as shift."""
        self.shift(other)

    @property
    def snippet_start(self):
        """
        Returns start of the snippet in format (line, column).
        """
        return self._start

    @property
    def snippet_end(self):
        """
        Returns end of the snippet in format (line, column).
        """
        return self._end

    @property
    def buffer(self):
        return _vim.buf
Esempio n. 10
0
class SnippetUtil(object):

    """Provides easy access to indentation, etc.

    This is the 'snip' object in python code.

    """

    def __init__(self, initial_indent, vmode, vtext, context, parent):
        self._ind = IndentUtil()
        self._visual = _VisualContent(vmode, vtext)
        self._initial_indent = self._ind.indent_to_spaces(initial_indent)
        self._reset('')
        self._context = context
        self._start = parent.start
        self._end = parent.end
        self._parent = parent

    def _reset(self, cur):
        """Gets the snippet ready for another update.

        :cur: the new value for c.

        """
        self._ind.reset()
        self._cur = cur
        self._rv = ''
        self._changed = False
        self.reset_indent()

    def shift(self, amount=1):
        """Shifts the indentation level. Note that this uses the shiftwidth
        because thats what code formatters use.

        :amount: the amount by which to shift.

        """
        self.indent += ' ' * self._ind.shiftwidth * amount

    def unshift(self, amount=1):
        """Unshift the indentation level. Note that this uses the shiftwidth
        because thats what code formatters use.

        :amount: the amount by which to unshift.

        """
        by = -self._ind.shiftwidth * amount
        try:
            self.indent = self.indent[:by]
        except IndexError:
            self.indent = ''

    def mkline(self, line='', indent=None):
        """Creates a properly set up line.

        :line: the text to add
        :indent: the indentation to have at the beginning
                 if None, it uses the default amount

        """
        if indent is None:
            indent = self.indent
            # this deals with the fact that the first line is
            # already properly indented
            if '\n' not in self._rv:
                try:
                    indent = indent[len(self._initial_indent):]
                except IndexError:
                    indent = ''
            indent = self._ind.spaces_to_indent(indent)

        return indent + line

    def reset_indent(self):
        """Clears the indentation."""
        self.indent = self._initial_indent

    # Utility methods
    @property
    def fn(self):  # pylint:disable=no-self-use,invalid-name
        """The filename."""
        return _vim.eval('expand("%:t")') or ''

    @property
    def basename(self):  # pylint:disable=no-self-use
        """The filename without extension."""
        return _vim.eval('expand("%:t:r")') or ''

    @property
    def ft(self):  # pylint:disable=invalid-name
        """The filetype."""
        return self.opt('&filetype', '')

    @property
    def rv(self):  # pylint:disable=invalid-name
        """The return value.

        The text to insert at the location of the placeholder.

        """
        return self._rv

    @rv.setter
    def rv(self, value):  # pylint:disable=invalid-name
        """See getter."""
        self._changed = True
        self._rv = value

    @property
    def _rv_changed(self):
        """True if rv has changed."""
        return self._changed

    @property
    def c(self):  # pylint:disable=invalid-name
        """The current text of the placeholder."""
        return self._cur

    @property
    def v(self):  # pylint:disable=invalid-name
        """Content of visual expansions."""
        return self._visual

    @property
    def p(self):
        if self._parent.current_placeholder:
            return self._parent.current_placeholder
        else:
            return _Placeholder('', 0, 0)

    @property
    def context(self):
        return self._context

    def opt(self, option, default=None):  # pylint:disable=no-self-use
        """Gets a Vim variable."""
        if _vim.eval("exists('%s')" % option) == '1':
            try:
                return _vim.eval(option)
            except _vim.error:
                pass
        return default

    def __add__(self, value):
        """Appends the given line to rv using mkline."""
        self.rv += '\n'  # pylint:disable=invalid-name
        self.rv += self.mkline(value)
        return self

    def __lshift__(self, other):
        """Same as unshift."""
        self.unshift(other)

    def __rshift__(self, other):
        """Same as shift."""
        self.shift(other)

    @property
    def comments(self):
        """ Returns comments list [left, right] if using NERDCommenter """
        if vim.eval("exists('b:NERDCommenterDelims')"):
            left = vim.eval("b:NERDCommenterDelims['left']")
            if left: left += ' '
            right = vim.eval("b:NERDCommenterDelims['right']")
            if right: right = ' ' + right
            return [left, right]
        else:
            return ["", ""]

    def comment(self, index):
        """ Sets instance return value to comments[index] """
        self.rv = self.comments[index]

    @property
    def snippet_start(self):
        """
        Returns start of the snippet in format (line, column).
        """
        return self._start

    @property
    def snippet_end(self):
        """
        Returns end of the snippet in format (line, column).
        """
        return self._end

    @property
    def buffer(self):
        return _vim.buf
Esempio n. 11
0
 def __init__(self, initial_indent, vmode, vtext):
     self._ind = IndentUtil()
     self._visual = _VisualContent(vmode, vtext)
     self._initial_indent = self._ind.indent_to_spaces(initial_indent)
     self._reset("")
Esempio n. 12
0
class SnippetUtil(object):
    """Provides easy access to indentation, etc. This is the 'snip' object in
    python code."""

    def __init__(self, initial_indent, vmode, vtext):
        self._ind = IndentUtil()
        self._visual = _VisualContent(vmode, vtext)
        self._initial_indent = self._ind.indent_to_spaces(initial_indent)
        self._reset("")

    def _reset(self, cur):
        """Gets the snippet ready for another update.
        :cur: the new value for c.
        """
        self._ind.reset()
        self._cur = cur
        self._rv = ""
        self._changed = False
        self.reset_indent()

    def shift(self, amount=1):
        """Shifts the indentation level.
        Note that this uses the shiftwidth because thats what code
        formatters use.

        :amount: the amount by which to shift.
        """
        self.indent += " " * self._ind.shiftwidth * amount

    def unshift(self, amount=1):
        """Unshift the indentation level.
        Note that this uses the shiftwidth because thats what code
        formatters use.

        :amount: the amount by which to unshift.
        """
        by = -self._ind.shiftwidth * amount
        try:
            self.indent = self.indent[:by]
        except IndexError:
            self.indent = ""

    def mkline(self, line="", indent=None):
        """Creates a properly set up line.

        :line: the text to add
        :indent: the indentation to have at the beginning
                 if None, it uses the default amount
        """
        if indent is None:
            indent = self.indent
            # this deals with the fact that the first line is
            # already properly indented
            if '\n' not in self._rv:
                try:
                    indent = indent[len(self._initial_indent):]
                except IndexError:
                    indent = ""
            indent = self._ind.spaces_to_indent(indent)

        return indent + line

    def reset_indent(self):
        """Clears the indentation."""
        self.indent = self._initial_indent

    # Utility methods
    @property
    def fn(self):  # pylint:disable=no-self-use,invalid-name
        """The filename."""
        return _vim.eval('expand("%:t")') or ""

    @property
    def basename(self):  # pylint:disable=no-self-use
        """The filename without extension."""
        return _vim.eval('expand("%:t:r")') or ""

    @property
    def ft(self):  # pylint:disable=invalid-name
        """The filetype."""
        return self.opt("&filetype", "")

    @property
    def rv(self):  # pylint:disable=invalid-name
        """The return value. The text to insert at the location of the
        placeholder."""
        return self._rv

    @rv.setter
    def rv(self, value):  # pylint:disable=invalid-name
        """See getter."""
        self._changed = True
        self._rv = value

    @property
    def _rv_changed(self):
        """True if rv has changed."""
        return self._changed

    @property
    def c(self):  # pylint:disable=invalid-name
        """The current text of the placeholder."""
        return self._cur

    @property
    def v(self):  # pylint:disable=invalid-name
        """Content of visual expansions"""
        return self._visual

    def opt(self, option, default=None):  # pylint:disable=no-self-use
        """Gets a Vim variable."""
        if _vim.eval("exists('%s')" % option) == "1":
            try:
                return _vim.eval(option)
            except _vim.error:
                pass
        return default

    def __add__(self, value):
        """Appends the given line to rv using mkline."""
        self.rv += '\n'  # pylint:disable=invalid-name
        self.rv += self.mkline(value)
        return self

    def __lshift__(self, other):
        """Same as unshift."""
        self.unshift(other)

    def __rshift__(self, other):
        """Same as shift."""
        self.shift(other)
Esempio n. 13
0
 def __init__(self, initial_indent, vmode, vtext):
     self._ind = IndentUtil()
     self._visual = _VisualContent(vmode, vtext)
     self._initial_indent = self._ind.indent_to_spaces(initial_indent)
     self._reset("")
Esempio n. 14
0
class SnippetUtil(object):

    """Provides easy access to indentation, etc.

    This is the 'snip' object in python code.

    """

    def __init__(self, initial_indent, vmode, vtext, context):
        self._ind = IndentUtil()
        self._visual = _VisualContent(vmode, vtext)
        self._initial_indent = self._ind.indent_to_spaces(initial_indent)
        self._reset('')
        self._context = context

    def _reset(self, cur):
        """Gets the snippet ready for another update.

        :cur: the new value for c.

        """
        self._ind.reset()
        self._cur = cur
        self._rv = ''
        self._changed = False
        self._package = None
        self.reset_indent()

    def shift(self, amount=1):
        """Shifts the indentation level. Note that this uses the shiftwidth
        because thats what code formatters use.

        :amount: the amount by which to shift.

        """
        self.indent += ' ' * self._ind.shiftwidth * amount

    def unshift(self, amount=1):
        """Unshift the indentation level. Note that this uses the shiftwidth
        because thats what code formatters use.

        :amount: the amount by which to unshift.

        """
        by = -self._ind.shiftwidth * amount
        try:
            self.indent = self.indent[:by]
        except IndexError:
            self.indent = ''

    def mkline(self, line='', indent=None):
        """Creates a properly set up line.

        :line: the text to add
        :indent: the indentation to have at the beginning
                 if None, it uses the default amount

        """
        if indent is None:
            indent = self.indent
            # this deals with the fact that the first line is
            # already properly indented
            if '\n' not in self._rv:
                try:
                    indent = indent[len(self._initial_indent):]
                except IndexError:
                    indent = ''
            indent = self._ind.spaces_to_indent(indent)

        return indent + line

    def reset_indent(self):
        """Clears the indentation."""
        self.indent = self._initial_indent

    # Utility methods
    @property
    def fn(self):  # pylint:disable=no-self-use,invalid-name
        """The filename."""
        return _vim.eval('expand("%:t")') or ''

    @property
    def basename(self):  # pylint:disable=no-self-use
        """The filename without extension."""
        return _vim.eval('expand("%:t:r")') or ''

    @property
    def dirname(self):  # pylint: disable=no-self-use
        """The filename's directory."""
        return _vim.eval('expand("%:p:h")') or ''

    @property
    def package(self):
        """
        Try our best to detect the python package name where this
        snip is being used.
        """
        if self._package is None:
            package = []
            curdir = self.dirname
            while True:
                if os.path.isfile(os.path.join(curdir, '__init__.py')):
                    package.append(os.path.basename(curdir))
                    curdir = os.path.abspath(os.path.join(curdir, '..'))
                    continue
                break

            if package:
                package.reverse()
                self._package = '.'.join(package)
        return self._package

    @property
    def module(self):
        """
        Try our best to detect the python module name where this snippet
        is being used.
        """
        if not self.package:
            return ''
        if self.basename == '__init__':
            return self.package
        return '{0}.{1}'.format(self.package, self.basename)

    @property
    def ft(self):  # pylint:disable=invalid-name
        """The filetype."""
        return self.opt('&filetype', '')

    @property
    def rv(self):  # pylint:disable=invalid-name
        """The return value.

        The text to insert at the location of the placeholder.

        """
        return self._rv

    @rv.setter
    def rv(self, value):  # pylint:disable=invalid-name
        """See getter."""
        self._changed = True
        self._rv = value

    @property
    def _rv_changed(self):
        """True if rv has changed."""
        return self._changed

    @property
    def c(self):  # pylint:disable=invalid-name
        """The current text of the placeholder."""
        return self._cur

    @property
    def v(self):  # pylint:disable=invalid-name
        """Content of visual expansions."""
        return self._visual

    @property
    def context(self):
        return self._context

    def opt(self, option, default=None):  # pylint:disable=no-self-use
        """Gets a Vim variable."""
        if _vim.eval("exists('%s')" % option) == '1':
            try:
                return _vim.eval(option)
            except _vim.error:
                pass
        return default

    def __add__(self, value):
        """Appends the given line to rv using mkline."""
        self.rv += '\n'  # pylint:disable=invalid-name
        self.rv += self.mkline(value)
        return self

    def __lshift__(self, other):
        """Same as unshift."""
        self.unshift(other)

    def __rshift__(self, other):
        """Same as shift."""
        self.shift(other)