コード例 #1
0
ファイル: _python_code.py プロジェクト: guns/haus
    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
コード例 #2
0
ファイル: snippet_manager.py プロジェクト: rendon/ultisnips
    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("'", "''")))
コード例 #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
コード例 #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
コード例 #5
0
ファイル: _python_code.py プロジェクト: joshnuss/dotfiles
    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
コード例 #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)
コード例 #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("'", "''")))
コード例 #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
コード例 #9
0
ファイル: __init__.py プロジェクト: nulpunkt/ultisnips
    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("'", "''")))
コード例 #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])
コード例 #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
コード例 #12
0
ファイル: __init__.py プロジェクト: ivanbrennan/ultisnips
 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
コード例 #13
0
ファイル: buffer_proxy.py プロジェクト: Ryan4021/dotfiles
 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])
コード例 #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
コード例 #15
0
ファイル: _vim.py プロジェクト: zhaocai/ultisnips
    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
コード例 #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
コード例 #17
0
ファイル: _base.py プロジェクト: ackyshake/ultisnips
 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
コード例 #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
コード例 #19
0
ファイル: _vim.py プロジェクト: zhaocai/ultisnips
 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
コード例 #20
0
ファイル: _vim.py プロジェクト: plotnikovanton/dotfiles
 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
コード例 #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
コード例 #22
0
ファイル: _base.py プロジェクト: erkaon23/dotfiles
    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)
コード例 #23
0
ファイル: _base.py プロジェクト: GlebTyazhyolov/vim-linux
    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)
コード例 #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
コード例 #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()
コード例 #26
0
ファイル: __init__.py プロジェクト: MarcWeber/ultisnips
    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
コード例 #27
0
ファイル: _vim.py プロジェクト: roadhouse/dotfiles-1
 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
コード例 #28
0
ファイル: _vim.py プロジェクト: roadhouse/dotfiles-1
def feedkeys(keys, mode='n'):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
コード例 #29
0
ファイル: debug.py プロジェクト: 9diov/UltiSnips
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()
コード例 #30
0
ファイル: snippet_manager.py プロジェクト: alex-vim/ultisnips
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)
コード例 #31
0
ファイル: _vim.py プロジェクト: jn202205/ultisnips
def feedkeys(keys, mode='n'):
    """Wrapper around vim's feedkeys function.

    Mainly for convenience.

    """
    command(as_unicode(r'call feedkeys("%s", "%s")') % (keys, mode))
コード例 #32
0
ファイル: _vim.py プロジェクト: alex-env/dotfiles
 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
コード例 #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
コード例 #34
0
ファイル: debug.py プロジェクト: ZSaberLv0/ultisnips_py2
 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
コード例 #35
0
ファイル: debug.py プロジェクト: 981746/ultisnips
 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
コード例 #36
0
ファイル: debug.py プロジェクト: 9diov/UltiSnips
    def _do_print(to, indent=""):
        debug(indent + as_unicode(to))

        try:
            for c in to._childs:
                _do_print(c, indent=indent + "  ")
        except AttributeError:
            pass
コード例 #37
0
ファイル: snippet_manager.py プロジェクト: nevar/ultisnips
    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
コード例 #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)
コード例 #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("'", "''"),
                    )
                )
コード例 #40
0
ファイル: _vim.py プロジェクト: roadhouse/dotfiles-1
 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
コード例 #41
0
ファイル: _python_code.py プロジェクト: MarcWeber/ultisnips
    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
コード例 #42
0
ファイル: _vim.py プロジェクト: alex-env/dotfiles
 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
コード例 #43
0
ファイル: __init__.py プロジェクト: ivanbrennan/ultisnips
    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("'", "''")))
コード例 #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
コード例 #45
0
ファイル: _vim.py プロジェクト: zhaocai/ultisnips
    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
コード例 #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)
コード例 #47
0
ファイル: snippet_manager.py プロジェクト: gou4shi1/ultisnips
    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
コード例 #48
0
ファイル: _vim.py プロジェクト: plotnikovanton/dotfiles
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))
コード例 #49
0
ファイル: _vim.py プロジェクト: 981746/ultisnips
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))
コード例 #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))
コード例 #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))
コード例 #52
0
ファイル: _shell_code.py プロジェクト: oolong32/dotfiles
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))
コード例 #53
0
ファイル: __init__.py プロジェクト: jumski/ultisnips
    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
コード例 #54
0
ファイル: __init__.py プロジェクト: wb-towa/vimconfig
    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
コード例 #55
0
ファイル: __init__.py プロジェクト: Fake51/work-environment
    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
コード例 #56
0
ファイル: _shell_code.py プロジェクト: 981746/ultisnips
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))
コード例 #57
0
ファイル: snippet_manager.py プロジェクト: blue119/ultisnips
    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
コード例 #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
コード例 #59
0
ファイル: _shell_code.py プロジェクト: 9diov/UltiSnips
    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
コード例 #60
0
ファイル: __init__.py プロジェクト: MarcWeber/ultisnips
    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