File: visual.py

package info (click to toggle)
vim-ultisnips 3.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,924 kB
  • sloc: python: 8,353; sh: 64; makefile: 38
file content (62 lines) | stat: -rw-r--r-- 2,036 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python
# encoding: utf-8

"""A ${VISUAL} placeholder that will use the text that was last visually
selected and insert it here.

If there was no text visually selected, this will be the empty string.

"""

import re
import textwrap

from UltiSnips.indent_util import IndentUtil
from UltiSnips.text_objects.transformation import TextObjectTransformation
from UltiSnips.text_objects.base import NoneditableTextObject

_REPLACE_NON_WS = re.compile(r"[^ \t]")


class Visual(NoneditableTextObject, TextObjectTransformation):

    """See module docstring."""

    def __init__(self, parent, token):
        # Find our containing snippet for visual_content
        snippet = parent
        while snippet:
            try:
                self._text = snippet.visual_content.text
                self._mode = snippet.visual_content.mode
                break
            except AttributeError:
                snippet = snippet._parent  # pylint:disable=protected-access
        if not self._text:
            self._text = token.alternative_text
            self._mode = "v"

        NoneditableTextObject.__init__(self, parent, token)
        TextObjectTransformation.__init__(self, token)

    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