Ejemplo n.º 1
0
    def _update(self, done, buf):
        path = _vim.eval('expand("%")') or ''
        ct = self.current_text
        self._locals.update({
            't': _Tabs(self._parent),
            'fn': os.path.basename(path),
            'path': path,
            'cur': ct,
            'res': ct,
            'snip': self._snip,
        })
        self._snip._reset(ct)  # pylint:disable=protected-access

        for code in self._codes:
            try:
                exec(code, self._locals)  # pylint:disable=exec-used
            except Exception as e:
                e.snippet_code = code
                raise

        rv = as_unicode(
            self._snip.rv if self._snip._rv_changed  # pylint:disable=protected-access
            else as_unicode(self._locals['res'])
        )

        if ct != rv:
            self.overwrite(buf, rv)
            return False
        return True
Ejemplo n.º 2
0
    def snippets_in_current_scope(self):
        """Returns the snippets that could be expanded to Vim as a global
        variable."""
        before = _vim.buf.line_till_cursor
        snippets = self._snips(before, True)

        # Sort snippets alphabetically
        snippets.sort(key=lambda x: x.trigger)
        for snip in snippets:
            description = snip.description[snip.description.find(snip.trigger) +
                len(snip.trigger) + 2:]

            key = as_unicode(snip.trigger)
            description = as_unicode(description)

            # remove surrounding "" or '' in snippet description if it exists
            if len(description) > 2:
                if (description[0] == description[-1] and
                        description[0] in "'\""):
                    description = description[1:-1]

            _vim.command(as_unicode(
                "let g:current_ulti_dict['{key}'] = '{val}'").format(
                    key=key.replace("'", "''"),
                    val=description.replace("'", "''")))
Ejemplo n.º 3
0
    def _update(self, done, not_done):
        path = _vim.eval('expand("%")')
        if path is None:
            path = ""
        fn = os.path.basename(path)

        ct = self.current_text
        self._snip._reset(ct)
        local_d = self._locals

        local_d.update({
            't': _Tabs(self._parent),
            'fn': fn,
            'path': path,
            'cur': ct,
            'res': ct,
            'snip': self._snip,
        })

        compatible_exec(self._code, self._globals, local_d)

        rv = as_unicode(self._snip.rv if self._snip.
                        _rv_changed else as_unicode(local_d['res']))

        if ct != rv:
            self.overwrite(rv)
            return False
        return True
Ejemplo n.º 4
0
    def _update(self, done, buf):
        path = _vim.eval('expand("%")') or ''
        ct = self.current_text
        self._locals.update({
            't': _Tabs(self._parent),
            'fn': os.path.basename(path),
            'path': path,
            'cur': ct,
            'res': ct,
            'snip': self._snip,
        })
        self._snip._reset(ct)  # pylint:disable=protected-access

        for code in self._codes:
            try:
                exec(code, self._locals)  # pylint:disable=exec-used
            except Exception as e:
                e.snippet_code = code
                raise

        rv = as_unicode(
            self._snip.rv if self._snip._rv_changed  # pylint:disable=protected-access
            else as_unicode(self._locals['res'])
        )

        if ct != rv:
            self.overwrite(buf, rv)
            return False
        return True
Ejemplo n.º 5
0
    def _update(self, done, not_done):
        path = _vim.eval('expand("%")')
        if path is None:
            path = ""
        fn = os.path.basename(path)

        ct = self.current_text
        self._snip._reset(ct)
        local_d = self._locals

        local_d.update({
            't': _Tabs(self._parent),
            'fn': fn,
            'path': path,
            'cur': ct,
            'res': ct,
            'i': self._snip.i,
            'snip' : self._snip,
        })

        compatible_exec(self._code, self._globals, local_d)

        rv = as_unicode(self._snip.rv if self._snip._rv_changed
                else as_unicode(local_d['res']))

        if ct != rv:
            self.overwrite(rv)
            return False
        return True
Ejemplo n.º 6
0
    def __init__(
        self,
        priority,
        trigger,
        value,
        description,
        options,
        globals,
        location,
        context,
        actions,
    ):
        self._priority = int(priority)
        self._trigger = as_unicode(trigger)
        self._value = as_unicode(value)
        self._description = as_unicode(description)
        self._opts = options
        self._matched = ""
        self._last_re = None
        self._globals = globals
        self._location = location
        self._context_code = context
        self._context = None
        self._actions = actions

        # Make sure that we actually match our trigger in case we are
        # immediately expanded.
        self.matches(self._trigger)
Ejemplo n.º 7
0
    def snippets_in_current_scope(self):
        """Returns the snippets that could be expanded to Vim as a global
        variable."""
        before = _vim.buf.line_till_cursor
        snippets = self._snips(before, True)

        # Sort snippets alphabetically
        snippets.sort(key=lambda x: x.trigger)
        for snip in snippets:
            description = snip.description[snip.description.find(snip.trigger
                                                                 ) +
                                           len(snip.trigger) + 2:]

            key = as_unicode(snip.trigger)
            description = as_unicode(description)

            # remove surrounding "" or '' in snippet description if it exists
            if len(description) > 2:
                if (description[0] == description[-1]
                        and description[0] in "'\""):
                    description = description[1:-1]

            _vim.command(
                as_unicode(
                    "let g:current_ulti_dict['{key}'] = '{val}'").format(
                        key=key.replace("'", "''"),
                        val=description.replace("'", "''")))
Ejemplo n.º 8
0
    def _update(self, done, buf):
        path = vim_helper.eval('expand("%")') or ""
        ct = self.current_text
        self._locals.update({
            "t": _Tabs(self._parent),
            "fn": os.path.basename(path),
            "path": path,
            "cur": ct,
            "res": ct,
            "snip": self._snip,
        })
        self._snip._reset(ct)  # pylint:disable=protected-access

        for code in self._codes:
            try:
                exec(code, self._locals)  # pylint:disable=exec-used
            except Exception as e:
                e.snippet_code = code
                raise

        rv = as_unicode(self._snip.rv if self._snip._rv_changed  # pylint:disable=protected-access
                        else as_unicode(self._locals["res"]))

        if ct != rv:
            self.overwrite(buf, rv)
            return False
        return True
Ejemplo n.º 9
0
    def list_snippets_dict(self):
        before, after = _vim.buf.current_line_splitted
        snippets = self._snips(before, True)

        # Sort snippets alphabetically
        snippets.sort(key=lambda x: x.trigger)
        for snip in snippets:
            description = snip.description[snip.description.find(snip.trigger
                                                                 ) +
                                           len(snip.trigger) + 2:]

            key = as_unicode(snip.trigger)
            description = as_unicode(description)

            #remove surrounding "" or '' in snippet description if it exists
            if len(description) > 2:
                if description[0] == description[-1] and description[0] in [
                        '"', "'"
                ]:
                    description = description[1:-1]

            _vim.command(
                as_unicode(
                    "let g:current_ulti_dict['{key}'] = '{val}'").format(
                        key=key.replace("'", "''"),
                        val=description.replace("'", "''")))
Ejemplo n.º 10
0
 def __getitem__(self, key):
     """
     Just passing call to the vim.current.window.buffer.__getitem__.
     """
     if isinstance(key, slice):
         return [as_unicode(l) for l in self._buffer[key.start:key.stop]]
     else:
         return as_unicode(self._buffer[key])
Ejemplo n.º 11
0
    def current_line_splitted(self):
        """Returns the text before and after the cursor as a tuple."""
        # Note: we want byte position here
        lineno, col = vim.current.window.cursor

        line = vim.current.line
        before, after = as_unicode(line[:col]), as_unicode(line[col:])
        return before, after
Ejemplo n.º 12
0
 def __init__(self, trigger, value, descr, options, globals):
     self._t = as_unicode(trigger)
     self._v = as_unicode(value)
     self._d = as_unicode(descr)
     self._opts = options
     self._matched = ""
     self._last_re = None
     self._globals = globals
Ejemplo n.º 13
0
 def __getitem__(self, key):
     """
     Just passing call to the vim.current.window.buffer.__getitem__.
     """
     if isinstance(key, slice):
         return [as_unicode(l) for l in self._buffer[key.start:key.stop]]
     else:
         return as_unicode(self._buffer[key])
Ejemplo n.º 14
0
 def __init__(self, trigger, value, descr, options, globals):
     self._t = as_unicode(trigger)
     self._v = as_unicode(value)
     self._d = as_unicode(descr)
     self._opts = options
     self._matched = ""
     self._last_re = None
     self._globals = globals
Ejemplo n.º 15
0
    def current_line_splitted(self):
        """Returns the text before and after the cursor as a tuple."""
        # Note: we want byte position here
        lineno, col = vim.current.window.cursor

        line = vim.current.line
        before, after = as_unicode(line[:col]), as_unicode(line[col:])
        return before, after
Ejemplo n.º 16
0
 def __init__(self, priority, trigger, value, description, options, globals):
     self._priority = priority
     self._trigger = as_unicode(trigger)
     self._value = as_unicode(value)
     self._description = as_unicode(description)
     self._opts = options
     self._matched = ""
     self._last_re = None
     self._globals = globals
Ejemplo n.º 17
0
 def __init__(self, priority, trigger, value, description,
         options, globals):
     self._priority = priority
     self._trigger = as_unicode(trigger)
     self._value = as_unicode(value)
     self._description = as_unicode(description)
     self._opts = options
     self._matched = ""
     self._last_re = None
     self._globals = globals
Ejemplo n.º 18
0
 def conv(obj):
     if isinstance(obj, list):
         rv = as_unicode('[' + ','.join(conv(o) for o in obj) + ']')
     elif isinstance(obj, dict):
         rv = as_unicode('{' + ','.join([
             "%s:%s" % (conv(key), conv(value))
             for key, value in obj.iteritems()]) + '}')
     else:
         rv = as_unicode('"%s"') % as_unicode(obj).replace('"', '\\"')
     return rv
Ejemplo n.º 19
0
 def conv(obj):
     if isinstance(obj, list):
         rv = as_unicode('[' + ','.join(conv(o) for o in obj) + ']')
     elif isinstance(obj, dict):
         rv = as_unicode('{' + ','.join([
             "%s:%s" % (conv(key), conv(value))
             for key, value in obj.iteritems()]) + '}')
     else:
         rv = as_unicode('"%s"') % as_unicode(obj).replace('"', '\\"')
     return rv
Ejemplo n.º 20
0
 def conv(obj):
     """Convert obj."""
     if isinstance(obj, list):
         rv = as_unicode("[" + ",".join(conv(o) for o in obj) + "]")
     elif isinstance(obj, dict):
         rv = as_unicode(
             "{" + ",".join(["%s:%s" % (conv(key), conv(value)) for key, value in obj.iteritems()]) + "}"
         )
     else:
         rv = as_unicode('"%s"') % as_unicode(obj).replace('"', '\\"')
     return rv
Ejemplo n.º 21
0
 def conv(obj):
     """Convert obj."""
     if isinstance(obj, list):
         rv = as_unicode("[" + ",".join(conv(o) for o in obj) + "]")
     elif isinstance(obj, dict):
         rv = as_unicode("{" + ",".join([
             "%s:%s" % (conv(key), conv(value))
             for key, value in obj.iteritems()
         ]) + "}")
     else:
         rv = as_unicode('"%s"') % as_unicode(obj).replace('"', '\\"')
     return rv
Ejemplo n.º 22
0
    def __init__(self, priority, trigger, value, description, options,
                 globals):
        self._priority = priority
        self._trigger = as_unicode(trigger)
        self._value = as_unicode(value)
        self._description = as_unicode(description)
        self._opts = options
        self._matched = ""
        self._last_re = None
        self._globals = globals

        # Make sure that we actually match our trigger in case we are
        # immediately expanded.
        self.matches(self._trigger)
Ejemplo n.º 23
0
    def __init__(self, priority, trigger, value, description,
                 options, globals, location):
        self._priority = int(priority)
        self._trigger = as_unicode(trigger)
        self._value = as_unicode(value)
        self._description = as_unicode(description)
        self._opts = options
        self._matched = ''
        self._last_re = None
        self._globals = globals
        self._location = location

        # Make sure that we actually match our trigger in case we are
        # immediately expanded.
        self.matches(self._trigger)
Ejemplo n.º 24
0
    def _file_to_edit(self, requested_ft, bang):  # pylint: disable=no-self-use
        """Returns a file to be edited for the given requested_ft.

        If 'bang' is
        empty only private files in g:UltiSnipsSnippetsDir are considered,
        otherwise all files are considered and the user gets to choose.

        """
        # This method is not using self, but is called by UltiSnips.vim and is
        # therefore in this class because it is the facade to Vim.
        potentials = set()

        if _vim.eval("exists('g:UltiSnipsSnippetsDir')") == '1':
            snippet_dir = _vim.eval('g:UltiSnipsSnippetsDir')
        else:
            home = _vim.eval('$HOME')
            if platform.system() == 'Windows':
                snippet_dir = os.path.join(home, 'vimfiles', 'UltiSnips')
            elif _vim.eval("has('nvim')") == '1':
                xdg_home_config = _vim.eval(
                    '$XDG_CONFIG_HOME') or os.path.join(home, ".config")
                snippet_dir = os.path.join(xdg_home_config, 'nvim',
                                           'UltiSnips')
            else:
                snippet_dir = os.path.join(home, '.vim', 'UltiSnips')

        filetypes = []
        if requested_ft:
            filetypes.append(requested_ft)
        else:
            if bang:
                filetypes.extend(self._buffer_filetypes[_vim.buf.number])
            else:
                filetypes.append(self._buffer_filetypes[_vim.buf.number][0])

        for ft in filetypes:
            potentials.update(find_snippet_files(ft, snippet_dir))
            potentials.add(os.path.join(snippet_dir, ft + '.snippets'))
            if bang:
                potentials.update(find_all_snippet_files(ft))

        potentials = set(
            os.path.realpath(os.path.expanduser(p)) for p in potentials)

        if len(potentials) > 1:
            files = sorted(potentials)
            formatted = [
                as_unicode('%i: %s') % (i, escape(fn, '\\'))
                for i, fn in enumerate(files, 1)
            ]
            file_to_edit = _ask_user(files, formatted)
            if file_to_edit is None:
                return ''
        else:
            file_to_edit = potentials.pop()

        dirname = os.path.dirname(file_to_edit)
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        return file_to_edit
Ejemplo n.º 25
0
def debug(s):
    s = as_unicode(s)
    fn = "/tmp/file.txt" if not sys.platform.lower().startswith("win") \
            else "C:/windows/temp/ultisnips.txt"
    f = open(fn, "ab")
    f.write((s + '\n').encode("utf-8"))
    f.close()
Ejemplo n.º 26
0
    def _ask_snippets(self, snippets):
        """ Given a list of snippets, ask the user which one they
        want to use, and return it.
        """
        if vim.eval('g:UltiSnips.always_use_first_snippet') == '1':
            vim.command(
                "echom 'UltiSnips: using first snippet due to always_use_first_snippet'"
            )
            return snippets[0]

        # make a python list
        display = [
            as_unicode("%i: %s from:%s") %
            (i + 1, s.description, s.location_hint())
            for i, s in enumerate(snippets)
        ]
        display.append(
            "You can make UltiSnips always pick the first item by setting g:UltiSnips.always_use_first_snippet =1"
        )

        try:
            rv = _vim.eval("inputlist(%s)" % _vim.escape(display))
            if rv is None or rv == '0':
                return None
            rv = int(rv)
            if rv > len(snippets):
                rv = len(snippets)
            return snippets[rv - 1]
        except _vim.error as e:
            # Likely "invalid expression", but might be translated. We have no way
            # of knowing the exact error, therefore, we ignore all errors silently.
            return None
Ejemplo n.º 27
0
 def line_till_cursor(self):  # pylint:disable=no-self-use
     """Returns the text before the cursor."""
     # Note: we want byte position here
     _, col = vim.current.window.cursor
     line = vim.current.line
     before = as_unicode(line[:col])
     return before
Ejemplo n.º 28
0
def feedkeys(keys, mode='n'):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
Ejemplo n.º 29
0
def debug(s):
    s = as_unicode(s)
    fn = "/tmp/file.txt" if not sys.platform.lower().startswith("win") \
            else "C:/windows/temp/ultisnips.txt"
    f = open(fn,"ab")
    f.write((s + '\n').encode("utf-8"))
    f.close()
Ejemplo n.º 30
0
def _ask_snippets(snippets):
    """ Given a list of snippets, ask the user which one they
    want to use, and return it.
    """
    display = [as_unicode("%i: %s (%s)") % (i+1, escape(s.description, '\\'),
        escape(s.location, '\\')) for i, s in enumerate(snippets)]
    return _ask_user(snippets, display)
Ejemplo n.º 31
0
def feedkeys(keys, mode='n'):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
Ejemplo n.º 32
0
 def line_till_cursor(self): # pylint:disable=no-self-use
     """Returns the text before the cursor."""
     # Note: we want byte position here
     _, col = vim.current.window.cursor
     line = vim.current.line
     before = as_unicode(line[:col])
     return before
Ejemplo n.º 33
0
    def _do_print(to, indent=""):
        debug(indent + as_unicode(to))

        try:
            for c in to._childs:
                _do_print(c, indent=indent + "  ")
        except AttributeError:
            pass
Ejemplo n.º 34
0
 def _do_print(text_object, indent=""):
     """prints recursively."""
     debug(indent + as_unicode(text_object))
     try:
         for child in text_object._children:
             _do_print(child, indent=indent + "  ")
     except AttributeError:
         pass
Ejemplo n.º 35
0
 def _do_print(text_object, indent=''):
     """prints recursively."""
     debug(indent + as_unicode(text_object))
     try:
         for child in text_object._children:
             _do_print(child, indent=indent + '  ')
     except AttributeError:
         pass
Ejemplo n.º 36
0
    def _do_print(to, indent=""):
        debug(indent + as_unicode(to))

        try:
            for c in to._childs:
                _do_print(c, indent=indent + "  ")
        except AttributeError:
            pass
Ejemplo n.º 37
0
    def _file_to_edit(self, requested_ft, bang):  # pylint: disable=no-self-use
        """Returns a file to be edited for the given requested_ft.

        If 'bang' is
        empty only private files in g:UltiSnipsSnippetsDir are considered,
        otherwise all files are considered and the user gets to choose.

        """
        # This method is not using self, but is called by UltiSnips.vim and is
        # therefore in this class because it is the facade to Vim.
        potentials = set()

        if _vim.eval("exists('g:UltiSnipsSnippetsDir')") == '1':
            snippet_dir = _vim.eval('g:UltiSnipsSnippetsDir')
        else:
            if platform.system() == 'Windows':
                snippet_dir = os.path.join(_vim.eval('$HOME'),
                                           'vimfiles', 'UltiSnips')
            elif _vim.eval("has('nvim')") == '1':
                snippet_dir = os.path.join(_vim.eval('$HOME'),
                                           '.nvim', 'UltiSnips')
            else:
                snippet_dir = os.path.join(_vim.eval('$HOME'),
                                           '.vim', 'UltiSnips')

        filetypes = []
        if requested_ft:
            filetypes.append(requested_ft)
        else:
            if bang:
                filetypes.extend(self._buffer_filetypes[_vim.buf.number])
            else:
                filetypes.append(self._buffer_filetypes[_vim.buf.number][0])

        for ft in filetypes:
            potentials.update(find_snippet_files(ft, snippet_dir))
            potentials.add(os.path.join(snippet_dir,
                                        ft + '.snippets'))
            if bang:
                potentials.update(find_all_snippet_files(ft))

        potentials = set(os.path.realpath(os.path.expanduser(p))
                         for p in potentials)

        if len(potentials) > 1:
            files = sorted(potentials)
            formatted = [as_unicode('%i: %s') % (i, escape(fn, '\\')) for
                         i, fn in enumerate(files, 1)]
            file_to_edit = _ask_user(files, formatted)
            if file_to_edit is None:
                return ''
        else:
            file_to_edit = potentials.pop()

        dirname = os.path.dirname(file_to_edit)
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        return file_to_edit
Ejemplo n.º 38
0
def _ask_snippets(snippets):
    """Given a list of snippets, ask the user which one they want to use, and
    return it."""
    display = [
        as_unicode("%i: %s (%s)")
        % (i + 1, escape(s.description, "\\"), escape(s.location, "\\"))
        for i, s in enumerate(snippets)
    ]
    return _ask_user(snippets, display)
Ejemplo n.º 39
0
    def snippets_in_current_scope(self, searchAll):
        """Returns the snippets that could be expanded to Vim as a global
        variable."""
        before = "" if searchAll else vim_helper.buf.line_till_cursor
        snippets = self._snips(before, True)

        # Sort snippets alphabetically
        snippets.sort(key=lambda x: x.trigger)
        for snip in snippets:
            description = snip.description[
                snip.description.find(snip.trigger) + len(snip.trigger) + 2 :
            ]

            location = snip.location if snip.location else ""

            key = as_unicode(snip.trigger)
            description = as_unicode(description)

            # remove surrounding "" or '' in snippet description if it exists
            if len(description) > 2:
                if description[0] == description[-1] and description[0] in "'\"":
                    description = description[1:-1]

            vim_helper.command(
                as_unicode("let g:current_ulti_dict['{key}'] = '{val}'").format(
                    key=key.replace("'", "''"), val=description.replace("'", "''")
                )
            )

            if searchAll:
                vim_helper.command(
                    as_unicode(
                        (
                            "let g:current_ulti_dict_info['{key}'] = {{"
                            "'description': '{description}',"
                            "'location': '{location}',"
                            "}}"
                        )
                    ).format(
                        key=key.replace("'", "''"),
                        location=location.replace("'", "''"),
                        description=description.replace("'", "''"),
                    )
                )
Ejemplo n.º 40
0
 def translate(self, text):
     """Inverse map 'text' through langmap."""
     langmap = eval('&langmap').strip()
     if langmap == '':
         return text
     text = as_unicode(text)
     if langmap not in self._maps:
         self._create_translation(langmap)
     for before, after in zip(*self._maps[langmap]):
         text = text.replace(before, after)
     return text
Ejemplo n.º 41
0
    def _update(self, done, not_done):
        path = _vim.eval('expand("%")')
        if path is None:
            path = ""
        fn = os.path.basename(path)

        ct = self.current_text
        self._snip._reset(ct)
        local_d = self._locals

        local_d.update({"t": _Tabs(self._parent), "fn": fn, "path": path, "cur": ct, "res": ct, "snip": self._snip})

        compatible_exec(self._code, self._globals, local_d)

        rv = as_unicode(self._snip.rv if self._snip._rv_changed else as_unicode(local_d["res"]))

        if ct != rv:
            self.overwrite(rv)
            return False
        return True
Ejemplo n.º 42
0
 def translate(self, text):
     """Inverse map 'text' through langmap."""
     langmap = eval("&langmap").strip()
     if langmap == "":
         return text
     text = as_unicode(text)
     if langmap not in self._maps:
         self._create_translation(langmap)
     for before, after in zip(*self._maps[langmap]):
         text = text.replace(before, after)
     return text
Ejemplo n.º 43
0
    def list_snippets_dict(self):
        before, after = _vim.buf.current_line_splitted
        snippets = self._snips(before, True)

        # Sort snippets alphabetically
        snippets.sort(key=lambda x: x.trigger)
        for snip in snippets:
            description = snip.description[snip.description.find(snip.trigger) +
                len(snip.trigger) + 2:]

            key = as_unicode(snip.trigger)
            description = as_unicode(description)

            #remove surrounding "" or '' in snippet description if it exists
            if len(description) > 2:
              if description[0] == description[-1] and description[0] in ['"', "'"]:
                description = description[1:-1]

            _vim.command(as_unicode("let g:current_ulti_dict['{key}'] = '{val}'").format(
              key=key.replace("'", "''"), val=description.replace("'", "''")))
Ejemplo n.º 44
0
    def translate(self, s):
        langmap = eval("&langmap").strip()
        if langmap == "":
            return s

        s = as_unicode(s)
        if langmap not in self._maps:
            self._create_translation(langmap)

        for f, t in zip(*self._maps[langmap]):
            s = s.replace(f, t)
        return s
Ejemplo n.º 45
0
    def translate(self, s):
        langmap = eval("&langmap").strip()
        if langmap == "":
            return s

        s = as_unicode(s)
        if langmap not in self._maps:
            self._create_translation(langmap)

        for f,t in zip(*self._maps[langmap]):
            s = s.replace(f,t)
        return s
Ejemplo n.º 46
0
def _ask_snippets(snippets):
    """Given a list of snippets, ask the user which one they want to use, and
    return it."""
    if _vim.eval("exists('g:UltiSnipsListFormat')") == '1':
        list_format = _vim.eval('g:UltiSnipsListFormat')
    else:
        list_format = "{id}: {description} ({location})"
    display = [
        as_unicode(list_format).format(id=i + 1,
                                       description=escape(s.description, '\\'),
                                       location=escape(s.location, '\\'))
        for i, s in enumerate(snippets)
    ]
    return _ask_user(snippets, display)
Ejemplo n.º 47
0
    def _get_file_to_edit(self,
                          snippet_dir,
                          requested_ft,
                          bang,
                          allow_empty=False):  # pylint: disable=no-self-use
        potentials = set()
        filetypes = []
        if requested_ft:
            filetypes.append(requested_ft)
        else:
            if bang:
                filetypes.extend(self.get_buffer_filetypes())
            else:
                filetypes.append(self.get_buffer_filetypes()[0])

        for ft in filetypes:
            potentials.update(find_snippet_files(ft, snippet_dir))
            potentials.add(os.path.join(snippet_dir, ft + '.snippets'))
            potentials.add(os.path.join('', ft + '.snippets'))
            if bang:
                potentials.update(find_all_snippet_files(ft))

        potentials = set(
            os.path.realpath(os.path.expanduser(p)) for p in potentials)

        if len(potentials) > 1:
            files = sorted(potentials)
            formatted = [
                as_unicode('%i: %s') % (i, escape(fn, '\\'))
                for i, fn in enumerate(files, 1)
            ]
            file_to_edit = _ask_user(files, formatted)
            if file_to_edit is None:
                return ''
        else:
            file_to_edit = potentials.pop()

        if not allow_empty and not os.path.exists(file_to_edit):
            return ''

        dirname = os.path.dirname(file_to_edit)
        if not os.path.exists(dirname):
            os.makedirs(dirname)

        return file_to_edit
Ejemplo n.º 48
0
def feedkeys(keys, mode="n"):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    if eval("mode()") == "n":
        if keys == "a":
            cursor_pos = get_cursor_pos()
            cursor_pos[2] = int(cursor_pos[2]) + 1
            set_cursor_from_pos(cursor_pos)
        if keys in "ai":
            keys = "startinsert"

    if keys == "startinsert":
        command("startinsert")
    else:
        command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
Ejemplo n.º 49
0
def feedkeys(keys, mode='n'):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    if eval('mode()') == 'n':
        if keys == 'a':
            cursor_pos = get_cursor_pos()
            cursor_pos[2] = int(cursor_pos[2]) + 1
            set_cursor_from_pos(cursor_pos)
        if keys in 'ai':
            keys = 'startinsert'

    if keys == 'startinsert':
        command('startinsert')
    else:
        command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
Ejemplo n.º 50
0
def feedkeys(keys, mode="n"):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    if eval("mode()") == "n":
        if keys == "a":
            cursor_pos = get_cursor_pos()
            cursor_pos[2] = int(cursor_pos[2]) + 1
            set_cursor_from_pos(cursor_pos)
        if keys in "ai":
            keys = "startinsert"

    if keys == "startinsert":
        command("startinsert")
    else:
        command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
Ejemplo n.º 51
0
def feedkeys(keys, mode='n'):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    if eval('mode()') == 'n':
        if keys == 'a':
            cursor_pos = get_cursor_pos()
            cursor_pos[2] = int(cursor_pos[2]) + 1
            set_cursor_from_pos(cursor_pos)
        if keys in 'ai':
            keys = 'startinsert'

    if keys == 'startinsert':
        command('startinsert')
    else:
        command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
Ejemplo n.º 52
0
def _run_shell_command(cmd, tmpdir):
    """Write the code to a temporary file"""
    cmdsuf = ''
    if platform.system() == 'Windows':
        # suffix required to run command on windows
        cmdsuf = '.bat'
        # turn echo off
        cmd = '@echo off\r\n' + cmd
    handle, path = tempfile.mkstemp(text=True, dir=tmpdir, suffix=cmdsuf)
    os.write(handle, cmd.encode("utf-8"))
    os.close(handle)
    os.chmod(path, stat.S_IRWXU)

    # Execute the file and read stdout
    proc = Popen(path, shell=True, stdout=PIPE, stderr=PIPE)
    proc.wait()
    stdout, _ = proc.communicate()
    os.unlink(path)
    return _chomp(as_unicode(stdout))
Ejemplo n.º 53
0
    def _ask_snippets(self, snippets):
        """ Given a list of snippets, ask the user which one they
        want to use, and return it.
        """
        # make a python list
        display = [ as_unicode("%i: %s") % (i+1,s.description) for i,s in enumerate(snippets)]

        try:
            rv = _vim.eval("inputlist(%s)" % _vim.escape(display))
            if rv is None or rv == '0':
                return None
            rv = int(rv)
            if rv > len(snippets):
                rv = len(snippets)
            return snippets[rv-1]
        except _vim.error as e:
            if str(e) == 'invalid expression':
                return None
            raise
Ejemplo n.º 54
0
    def _ask_snippets(self, snippets):
        """ Given a list of snippets, ask the user which one they
        want to use, and return it.
        """
        # make a python list
        display = [ as_unicode("%i: %s") % (i+1,s.description) for i,s in enumerate(snippets)]

        try:
            rv = _vim.eval("inputlist(%s)" % _vim.escape(display))
            if rv is None or rv == '0':
                return None
            rv = int(rv)
            if rv > len(snippets):
                rv = len(snippets)
            return snippets[rv-1]
        except _vim.error as e:
            # Likely "invalid expression", but might be translated. We have no way
            # of knowing the exact error, therefore, we ignore all errors silently.
            return None
Ejemplo n.º 55
0
    def _ask_snippets(self, snippets):
        """ Given a list of snippets, ask the user which one they
        want to use, and return it.
        """
        # make a python list
        display = [ as_unicode("%i: %s") % (i+1,s.description) for i,s in enumerate(snippets)]

        try:
            rv = _vim.eval("inputlist(%s)" % _vim.escape(display))
            if rv is None or rv == '0':
                return None
            rv = int(rv)
            if rv > len(snippets):
                rv = len(snippets)
            return snippets[rv-1]
        except _vim.error as e:
            # Likely "invalid expression", but might be translated. We have no way
            # of knowing the exact error, therefore, we ignore all errors silently.
            return None
Ejemplo n.º 56
0
def _run_shell_command(cmd, tmpdir):
    """Write the code to a temporary file."""
    cmdsuf = ''
    if platform.system() == 'Windows':
        # suffix required to run command on windows
        cmdsuf = '.bat'
        # turn echo off
        cmd = '@echo off\r\n' + cmd
    handle, path = tempfile.mkstemp(text=True, dir=tmpdir, suffix=cmdsuf)
    os.write(handle, cmd.encode('utf-8'))
    os.close(handle)
    os.chmod(path, stat.S_IRWXU)

    # Execute the file and read stdout
    proc = Popen(path, shell=True, stdout=PIPE, stderr=PIPE)
    proc.wait()
    stdout, _ = proc.communicate()
    os.unlink(path)
    return _chomp(as_unicode(stdout))
Ejemplo n.º 57
0
    def _file_to_edit(self, ft, bang):  # pylint: disable=no-self-use
        """Returns a file to be edited for the given ft. If 'bang' is empty
        only private files in g:UltiSnipsSnippetsDir are considered, otherwise
        all files are considered and the user gets to choose.
        """
        # This method is not using self, but is called by UltiSnips.vim and is
        # therefore in this class because it is the facade to Vim.
        potentials = set()

        if _vim.eval("exists('g:UltiSnipsSnippetsDir')") == "1":
            snippet_dir = _vim.eval("g:UltiSnipsSnippetsDir")
        else:
            if platform.system() == "Windows":
                snippet_dir = os.path.join(_vim.eval("$HOME"),
                        "_vimfiles", "UltiSnips")
            else:
                snippet_dir = os.path.join(_vim.eval("$HOME"),
                        ".vim", "UltiSnips")
        potentials.update(find_snippet_files(ft, snippet_dir))
        potentials.add(os.path.join(snippet_dir, ft + '.snippets'))

        if bang:
            potentials.update(find_all_snippet_files(ft))

        potentials = set(os.path.realpath(os.path.expanduser(p))
                for p in potentials)

        if len(potentials) > 1:
            files = sorted(potentials)
            formatted = [as_unicode('%i: %s') % (i, fn) for
                    i, fn in enumerate(files, 1)]
            edit = _ask_user(files, formatted)
            if edit is None:
                return ""
        else:
            edit = potentials.pop()

        dirname = os.path.dirname(edit)
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        return edit
Ejemplo n.º 58
0
    def _get_file_to_edit(self, snippet_dir, requested_ft, bang,
                          allow_empty=False): # pylint: disable=no-self-use
        potentials = set()
        filetypes = []
        if requested_ft:
            filetypes.append(requested_ft)
        else:
            if bang:
                filetypes.extend(self.get_buffer_filetypes())
            else:
                filetypes.append(self.get_buffer_filetypes()[0])

        for ft in filetypes:
            potentials.update(find_snippet_files(ft, snippet_dir))
            potentials.add(os.path.join(snippet_dir,
                                        ft + '.snippets'))
            if bang:
                potentials.update(find_all_snippet_files(ft))

        potentials = set(os.path.realpath(os.path.expanduser(p))
                         for p in potentials)

        if len(potentials) > 1:
            files = sorted(potentials)
            formatted = [as_unicode('%i: %s') % (i, escape(fn, '\\')) for
                         i, fn in enumerate(files, 1)]
            file_to_edit = _ask_user(files, formatted)
            if file_to_edit is None:
                return ''
        else:
            file_to_edit = potentials.pop()

        if not allow_empty and not os.path.exists(file_to_edit):
            return ''

        dirname = os.path.dirname(file_to_edit)
        if not os.path.exists(dirname):
            os.makedirs(dirname)

        return file_to_edit
Ejemplo n.º 59
0
    def _update(self, done, not_done):
        # Write the code to a temporary file
        handle, path = tempfile.mkstemp(text=True)
        os.write(handle, self._code.encode("utf-8"))
        os.close(handle)
        os.chmod(path, stat.S_IRWXU)

        # Execute the file and read stdout
        proc = subprocess.Popen(path, shell=True, stdout=subprocess.PIPE)
        proc.wait()
        output = as_unicode(proc.stdout.read())

        if len(output) and output[-1] == '\n':
            output = output[:-1]
        if len(output) and output[-1] == '\r':
            output = output[:-1]

        os.unlink(path)

        self.overwrite(output)
        self._parent._del_child(self)

        return True
Ejemplo n.º 60
0
    def _ask_snippets(self, snippets):
        """ Given a list of snippets, ask the user which one they
        want to use, and return it.
        """
        if vim.eval('g:UltiSnips.always_use_first_snippet') == '1':
            vim.command("echom 'UltiSnips: using first snippet due to always_use_first_snippet'")
            return snippets[0]

        # make a python list
        display = [ as_unicode("%i: %s from:%s") % (i+1, s.description, s.location_hint()) for i,s in enumerate(snippets)]
        display.append("You can make UltiSnips always pick the first item by setting g:UltiSnips.always_use_first_snippet =1")

        try:
            rv = _vim.eval("inputlist(%s)" % _vim.escape(display))
            if rv is None or rv == '0':
                return None
            rv = int(rv)
            if rv > len(snippets):
                rv = len(snippets)
            return snippets[rv-1]
        except _vim.error as e:
            # Likely "invalid expression", but might be translated. We have no way
            # of knowing the exact error, therefore, we ignore all errors silently.
            return None