Example #1
0
    def filter(self, context):
        if not context['candidates'] or not context['input'] or self.__disabled:
            return context['candidates']

        if not self.__initialized:
            # cpsm installation check
            if globruntime(context['runtimepath'], 'bin/cpsm_py.so'):
                # Add path
                sys.path.append(
                    os.path.dirname(
                        globruntime(context['runtimepath'],
                                    'bin/cpsm_py.so')[0]))
                self.__initialized = True
            else:
                error(
                    self.vim, 'matcher_cpsm: bin/cpsm_py.so' +
                    ' is not found in your runtimepath.')
                error(
                    self.vim, 'matcher_cpsm: You must install/build' +
                    ' Python3 support enabled cpsm.')
                self.__disabled = True
                return []

        import cpsm_py
        cpsm_result = cpsm_py.ctrlp_match(
            (d['word'] for d in context['candidates']),
            context['input'],
            limit=1000,
            highlight_mode='detailed',
            ispath=('action__path' in context['candidates'][0]))[0]
        return [x for x in context['candidates'] if x['word'] in cpsm_result]
Example #2
0
    def filter(self, context):
        if not context['candidates'] or not context['input'] or self.__disabled:
            return context['candidates']

        if not self.__initialized:
            # cpsm installation check
            ext = '.pyd' if context['is_windows'] else '.so'
            if globruntime(context['runtimepath'], 'bin/cpsm_py' + ext):
                # Add path
                sys.path.append(
                    os.path.dirname(
                        globruntime(context['runtimepath'],
                                    'bin/cpsm_py' + ext)[0]))
                self.__initialized = True
            else:
                error(
                    self.vim, 'matcher_cpsm: bin/cpsm_py' + ext +
                    ' is not found in your runtimepath.')
                error(
                    self.vim, 'matcher_cpsm: You must install/build' +
                    ' Python3 support enabled cpsm.')
                self.__disabled = True
                return []

        import cpsm_py
        candidates = context['candidates']
        ispath = (os.path.exists(context['candidates'][0]['word']))
        for pattern in split_input(context['input']):
            cpsm_result = cpsm_py.ctrlp_match((d['word'] for d in candidates),
                                              pattern,
                                              limit=1000,
                                              ispath=ispath)[0]
            candidates = [x for x in candidates if x['word'] in cpsm_result]
        return candidates
Example #3
0
def ctrlp_match():
    # TODO: a:regex is unimplemented.
    try:
        results, regexes = cpsm_py.ctrlp_match(
            vim.eval("a:items"),
            vim.eval("a:str"),
            limit=int(vim.eval("a:limit")),
            mmode=vim.eval("a:mmode"),
            ispath=int(vim.eval("a:ispath")),
            crfile=vim.eval("a:crfile"),
            highlight_mode=vim.eval("g:cpsm_highlight_mode"),
            match_crfile=int(vim.eval("s:match_crfile")),
            max_threads=int(vim.eval("g:cpsm_max_threads")),
            query_inverting_delimiter=vim.eval(
                "g:cpsm_query_inverting_delimiter"),
            unicode=int(vim.eval("g:cpsm_unicode")))
        # Escape backslashes and ".
        vim.command("let s:results = [%s]" %
                    ",".join(map(_escape_and_quote, results)))
        vim.command("let s:regexes = [%s]" %
                    ",".join(map(_escape_and_quote, regexes)))
        for r in regexes:
            print(r)
    except Exception as ex:
        vim.command("let s:results = [%s]" %
                    _escape_and_quote("ERROR: " + str(ex)))
        vim.command("let s:regexes = []")
Example #4
0
def ctrlp_match_with(**kwargs):
    """
    Wrapper for cpsm_py.ctrlp_match() that converts Vim numbers from strings
    back to numbers, and handles exceptions.
    """
    try:
        for key in ("limit", "ispath", "match_crfile", "max_threads",
                    "unicode"):
            kwargs[key] = int(kwargs[key])
        return cpsm_py.ctrlp_match(**kwargs)
    except Exception as ex:
        # Log the exception. Unfortunately something CtrlP causes all messages
        # to be discarded, so this is only visible in Vim verbose logging.
        print("cpsm error:")
        traceback.print_exc(file=sys.stdout)
        # Return a short error message in the results.
        ex_str = str(ex)
        if (sys.exc_info()[0] is TypeError and
            "function takes at most" in ex_str):
            # Most likely due to a new parameter being added to
            # cpsm_py.ctrlp_match.
            ex_str = "rebuild cpsm by running %s: %s" % (
                    os.path.normpath(os.path.join(
                            script_dir, "..", "install.sh")),
                    ex_str)
        return ["ERROR:" + ex_str], []
Example #5
0
def ctrlp_match():
    # TODO: a:regex is unimplemented.
    try:
        results, regexes = cpsm_py.ctrlp_match(
                vim.eval("a:items"), vim.eval("a:str"),
                limit=int(vim.eval("a:limit")), mmode=vim.eval("a:mmode"),
                ispath=int(vim.eval("a:ispath")), crfile=vim.eval("a:crfile"),
                highlight_mode=vim.eval("g:cpsm_highlight_mode"),
                match_crfile=int(vim.eval("s:match_crfile")),
                max_threads=int(vim.eval("g:cpsm_max_threads")),
                query_inverting_delimiter=vim.eval("g:cpsm_query_inverting_delimiter"),
                regex_line_prefix=vim.eval("s:regex_line_prefix"),
                unicode=int(vim.eval("g:cpsm_unicode")))
        # Escape backslashes and ".
        vim.command("let s:results = [%s]" % ",".join(
                map(_escape_and_quote, results)))
        vim.command("let s:regexes = [%s]" % ",".join(
                map(_escape_and_quote, regexes)))
    except Exception as ex:
        ex_str = str(ex)
        if "function takes at most" in ex_str:
            # Most likely due to a new parameter being added to
            # cpsm_py.ctrlp_match.
            ex_str = "rebuild cpsm by running %s: %s" % (
                    os.path.normpath(os.path.join(
                            script_dir, "..", "install.sh")),
                    ex_str)
        vim.command("let s:results = [%s]" % _escape_and_quote(
                "ERROR: " + ex_str))
        vim.command("let s:regexes = []")
Example #6
0
def ctrlp_match():
    # TODO: a:regex is unimplemented.
    try:
        results, regexes = cpsm_py.ctrlp_match(
            vim.eval("a:items"),
            vim.eval("a:str"),
            limit=int(vim.eval("a:limit")),
            mmode=vim.eval("a:mmode"),
            ispath=int(vim.eval("a:ispath")),
            crfile=vim.eval("a:crfile"),
            highlight_mode=vim.eval("g:cpsm_highlight_mode"),
            match_crfile=int(vim.eval("s:match_crfile")),
            max_threads=int(vim.eval("g:cpsm_max_threads")),
            query_inverting_delimiter=vim.eval(
                "g:cpsm_query_inverting_delimiter"),
            regex_line_prefix=vim.eval("s:regex_line_prefix"),
            unicode=int(vim.eval("g:cpsm_unicode")))
        # Escape backslashes and ".
        vim.command("let s:results = [%s]" %
                    ",".join(map(_escape_and_quote, results)))
        vim.command("let s:regexes = [%s]" %
                    ",".join(map(_escape_and_quote, regexes)))
    except Exception as ex:
        ex_str = str(ex)
        if "function takes at most" in ex_str:
            # Most likely due to a new parameter being added to
            # cpsm_py.ctrlp_match.
            ex_str = "rebuild cpsm by running %s: %s" % (os.path.normpath(
                os.path.join(script_dir, "..", "install.sh")), ex_str)
        vim.command("let s:results = [%s]" %
                    _escape_and_quote("ERROR: " + ex_str))
        vim.command("let s:regexes = []")
Example #7
0
 def _get_cpsm_result(self, ispath: bool, candidates: Candidates,
                      pattern: str, bufname: str) -> Candidates:
     import cpsm_py
     return cpsm_py.ctrlp_match(  # type: ignore
         (d['word'] for d in candidates),
         pattern, limit=1000, ispath=ispath,
         crfile=bufname if ispath else '')[0]
Example #8
0
    def filter(self, context):
        if not context['candidates'] or not context[
                'input'] or self.__disabled:
            return context['candidates']

        if not self.__initialized:
            # cpsm installation check
            if globruntime(context['runtimepath'], 'bin/cpsm_py.so'):
                # Add path
                sys.path.append(os.path.dirname(
                    globruntime(context['runtimepath'], 'bin/cpsm_py.so')[0]))
                self.__initialized = True
            else:
                error(self.vim, 'matcher_cpsm: bin/cpsm_py.so' +
                      ' is not found in your runtimepath.')
                error(self.vim, 'matcher_cpsm: You must install/build' +
                      ' Python3 support enabled cpsm.')
                self.__disabled = True
                return []

        import cpsm_py
        candidates = context['candidates']
        max = context['max_candidate_width']
        ispath = (os.path.exists(context['candidates'][0]['word']))
        for pattern in split_input(context['input']):
            cpsm_result = cpsm_py.ctrlp_match(
                (d['word'][:max] for d in candidates),
                pattern, limit=1000, ispath=ispath)[0]
            candidates = [x for x in candidates if x['word'] in cpsm_result]
        return candidates
Example #9
0
File: cpsm.py Project: eapache/cpsm
def ctrlp_match():
    # TODO: a:regex is unimplemented.
    try:
        results, regexes = cpsm_py.ctrlp_match(
                vim.eval("a:items"), vim.eval("a:str"),
                limit=int(vim.eval("a:limit")), mmode=vim.eval("a:mmode"),
                ispath=int(vim.eval("a:ispath")), crfile=vim.eval("a:crfile"),
                highlight_mode=vim.eval("g:cpsm_highlight_mode"),
                match_crfile=int(vim.eval("s:match_crfile")),
                max_threads=int(vim.eval("g:cpsm_max_threads")),
                query_inverting_delimiter=vim.eval("g:cpsm_query_inverting_delimiter"),
                unicode=int(vim.eval("g:cpsm_unicode")))
        # Escape backslashes and ".
        vim.command("let s:results = [%s]" % ",".join(
                map(_escape_and_quote, results)))
        vim.command("let s:regexes = [%s]" % ",".join(
                map(_escape_and_quote, regexes)))
    except Exception as ex:
        vim.command("let s:results = [%s]" % _escape_and_quote(
                "ERROR: " + str(ex)))
        vim.command("let s:regexes = []")
Example #10
0
    def filter(self, context):
        if not context['candidates'] or not context['input']:
            return context['candidates']

        if not self.__initialized:
            # cpsm installation check
            if globruntime(context['runtimepath'], 'bin/cpsm_py.so'):
                # Add path
                sys.path.append(
                    os.path.dirname(
                        globruntime(context['runtimepath'],
                                    'bin/cpsm_py.so')[0]))
                self.__initialized = True
            else:
                return []

        import cpsm_py
        cpsm_result = cpsm_py.ctrlp_match(
            (d['word'] for d in context['candidates']),
            context['input'],
            limit=1000,
            highlight_mode='detailed',
            ispath=('action__path' in context['candidates'][0]))[0]
        return [x for x in context['candidates'] if x['word'] in cpsm_result]
Example #11
0
def ctrlp_match_with(**kwargs):
    """
    Wrapper for cpsm_py.ctrlp_match() that converts Vim numbers from strings
    back to numbers, and handles exceptions.
    """
    try:
        for key in ("limit", "ispath", "match_crfile", "max_threads",
                    "unicode"):
            kwargs[key] = int(kwargs[key])
        return cpsm_py.ctrlp_match(**kwargs)
    except Exception as ex:
        # Log the exception. Unfortunately something CtrlP causes all messages
        # to be discarded, so this is only visible in Vim verbose logging.
        print("cpsm error:")
        traceback.print_exc(file=sys.stdout)
        # Return a short error message in the results.
        ex_str = str(ex)
        if (sys.exc_info()[0] is TypeError
                and "function takes at most" in ex_str):
            # Most likely due to a new parameter being added to
            # cpsm_py.ctrlp_match.
            ex_str = "rebuild cpsm by running %s: %s" % (os.path.normpath(
                os.path.join(script_dir, "..", "install.sh")), ex_str)
        return ["ERROR:" + ex_str], []
Example #12
0
 def _get_cpsm_result(self, ispath, candidates, pattern):
     import cpsm_py
     return cpsm_py.ctrlp_match((d['word'] for d in candidates),
                                pattern, limit=1000, ispath=ispath)[0]
Example #13
0
 def _get_cpsm_result(self, ispath, candidates, pattern, bufname):
     import cpsm_py
     return cpsm_py.ctrlp_match((d['word'] for d in candidates),
                                pattern, limit=1000, ispath=ispath,
                                crfile=bufname if ispath else '')[0]
Example #14
0
from __future__ import print_function

import argparse

import bench
import cpsm_py
import linuxclock

if __name__ == "__main__":
    argp = argparse.ArgumentParser()
    argp.add_argument("-c", "--count", nargs="?", type=int, default=1,
                      help="number of matches to show")
    argp.add_argument("-n", "--iterations", nargs="?", type=int,
                      default=bench.DEFAULT_ITERATIONS,
                      help="number of iterations per query")
    argp.add_argument("-t", "--threads", nargs="?", type=int, default=0,
                      help="number of matcher threads")
    args = argp.parse_args()
    for query in bench.QUERIES:
        times = []
        for _ in xrange(args.iterations):
            start = linuxclock.monotonic()
            results, _ = cpsm_py.ctrlp_match(bench.ITEMS, query.query,
                                             limit=bench.LIMIT, ispath=True,
                                             crfile=query.cur_file,
                                             max_threads=args.threads)
            finish = linuxclock.monotonic()
            times.append(finish - start)
        print("%s: avg time %fs, results: %s" % (
                query, sum(times) / len(times), results[:args.count]))
Example #15
0
                      type=int,
                      default=1,
                      help="number of matches to show")
    argp.add_argument("-n",
                      "--iterations",
                      nargs="?",
                      type=int,
                      default=bench.DEFAULT_ITERATIONS,
                      help="number of iterations per query")
    argp.add_argument("-t",
                      "--threads",
                      nargs="?",
                      type=int,
                      default=0,
                      help="number of matcher threads")
    args = argp.parse_args()
    for query in bench.QUERIES:
        times = []
        for _ in xrange(args.iterations):
            start = linuxclock.monotonic()
            results, _ = cpsm_py.ctrlp_match(bench.ITEMS,
                                             query.query,
                                             limit=bench.LIMIT,
                                             ispath=True,
                                             crfile=query.cur_file,
                                             max_threads=args.threads)
            finish = linuxclock.monotonic()
            times.append(finish - start)
        print("%s: avg time %fs, results: %s" %
              (query, sum(times) / len(times), results[:args.count]))
Example #16
0
 def _get_cpsm_result(self, ispath, candidates, pattern):
     import cpsm_py
     return cpsm_py.ctrlp_match((d['word'] for d in candidates),
                                pattern,
                                limit=1000,
                                ispath=ispath)[0]