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 []

        ispath = (os.path.exists(context['candidates'][0]['word']))
        cpsm_result = self._get_cpsm_result(
            ispath, context['candidates'], context['input'])
        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
            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 #3
0
 def start(self, args):
     from denite.util import error
     try:
         buffer_name = args[1]['buffer_name']
         if buffer_name not in self.__uis:
             self.__uis[buffer_name] = Default(self.__vim)
         return self.__uis[buffer_name].start(args[0], args[1])
     except Exception:
         for line in traceback.format_exc().splitlines():
             error(self.__vim, line)
         error(self.__vim, 'Please execute :messages command.')
Example #4
0
    def gather_candidates(self, context):
        if not os.access(context['__config'], os.R_OK):
            return []

        candidates = []
        with open(context['__config']) as fp:
            try:
                config = json.loads(fp.read())
                for obj in config:
                    candidates.append({
                        'word': obj['command'],
                        'abbr': '▷ %-12s %s' % (obj['command'], obj['description']),
                        'source__command': obj['command'],
                        'source__args': obj['args'],
                        'source__config': context['__config'],
                        })
            except json.JSONDecodeError:
                util.error(self.vim, 'Decode error for %s' % context['__config'])

        candidates = sorted(candidates, key=itemgetter('source__command'))
        return candidates
Example #5
0
    def _start(self, sources, context):
        self._vim.command('silent! autocmd! denite')

        if re.search(r'\[Command Line\]$', self._vim.current.buffer.name):
            # Ignore command line window.
            return

        if self._initialized and context['resume']:
            # Skip the initialization

            if not self._is_suspend:
                if context['mode']:
                    self._current_mode = context['mode']

                update = ('immediately', 'immediately_1',
                          'cursor_wrap', 'cursor_pos', 'prev_winid')
                for key in update:
                    self._context[key] = context[key]

            if self.check_empty():
                return

            self.init_buffer()
            if context['refresh']:
                self.redraw()
        else:
            if not context['mode']:
                # Default mode
                context['mode'] = 'insert'

            self._context.clear()
            self._context.update(context)
            self._context['sources'] = sources
            self._context['is_redraw'] = False
            self._current_mode = context['mode']
            self._is_multi = len(sources) > 1

            if not sources:
                # Ignore empty sources.
                error(self._vim, 'Empty sources')
                return

            self.init_denite()
            self.gather_candidates()
            self.update_candidates()
            self.init_cursor()

            if self.check_empty():
                return

            self.init_buffer()

        self._is_suspend = False
        self.update_displayed_texts()
        self.change_mode(self._current_mode)
        self.update_buffer()

        # Make sure that the caret position is ok
        self._prompt.caret.locus = self._prompt.caret.tail
        status = self._prompt.start()
        if status == STATUS_INTERRUPT:
            # STATUS_INTERRUPT is returned when user hit <C-c> and the loop has
            # interrupted.
            # In this case, denite cancel any operation and close its window.
            self.quit()
        return
Example #6
0
    def _start(self, sources, context):
        self._vim.command('silent! autocmd! denite')

        if re.search(r'\[Command Line\]$', self._vim.current.buffer.name):
            # Ignore command line window.
            return

        if self._initialized and context['resume']:
            # Skip the initialization

            if not self._is_suspend:
                if context['mode']:
                    self._current_mode = context['mode']

                update = ('immediately', 'immediately_1', 'cursor_wrap',
                          'cursor_pos', 'prev_winid', 'quick_move')
                for key in update:
                    self._context[key] = context[key]

            if self.check_option():
                return

            self.init_buffer()
            if context['refresh']:
                self.redraw()
        else:
            if not context['mode']:
                # Default mode
                context['mode'] = 'insert'

            self._context.clear()
            self._context.update(context)
            self._context['sources'] = sources
            self._context['is_redraw'] = False
            self._current_mode = context['mode']
            self._is_multi = len(sources) > 1

            if not sources:
                # Ignore empty sources.
                error(self._vim, 'Empty sources')
                return

            self.init_denite()
            self.gather_candidates()
            self.update_candidates()
            self.init_cursor()

            if self.check_option():
                return

            self.init_buffer()

        self._is_suspend = False
        self.update_displayed_texts()
        self.change_mode(self._current_mode)
        self.update_buffer()

        if self._context['quick_move'] and self.quick_move():
            return

        # Make sure that the caret position is ok
        self._prompt.caret.locus = self._prompt.caret.tail
        status = self._prompt.start()
        if status == STATUS_INTERRUPT:
            # STATUS_INTERRUPT is returned when user hit <C-c> and the loop has
            # interrupted.
            # In this case, denite cancel any operation and close its window.
            self.quit()
        return
Example #7
0
    def _start(self, sources: typing.List[typing.Any],
               context: UserContext) -> None:
        from denite.ui.map import do_map

        self._vim.command('silent! autocmd! denite')

        if re.search(r'\[Command Line\]$', self._vim.current.buffer.name):
            # Ignore command line window.
            return

        resume = self._initialized and context['resume']
        if resume:
            # Skip the initialization

            update = ('immediately', 'immediately_1',
                      'cursor_pos', 'prev_winid',
                      'start_filter', 'quick_move')
            for key in update:
                self._context[key] = context[key]

            self._check_move_option()
            if self._check_do_option():
                return

            self._init_buffer()
            if context['refresh']:
                self.redraw()
            self._move_to_pos(self._cursor)
        else:
            if self._context != context:
                self._context.clear()
                self._context.update(context)
            self._context['sources'] = sources
            self._context['is_redraw'] = False
            self._is_multi = len(sources) > 1

            if not sources:
                # Ignore empty sources.
                error(self._vim, 'Empty sources')
                return

            self._init_denite()
            self._gather_candidates()
            self._update_candidates()

            self._init_cursor()
            self._check_move_option()
            if self._check_do_option():
                return

            self._init_buffer()

        self._update_displayed_texts()
        self._update_buffer()
        self._move_to_pos(self._cursor)

        if self._context['quick_move'] and do_map(self, 'quick_move', []):
            return

        if self._context['start_filter']:
            do_map(self, 'open_filter_buffer', [])
Example #8
0
 def debug(self, expr: typing.Any) -> None:
     error(self._vim, expr)
Example #9
0
    def _start(self, sources, context):
        if re.search('\[Command Line\]$', self._vim.current.buffer.name):
            # Ignore command line window.
            return

        if self._initialized and context['resume']:
            # Skip the initialization
            if context['mode']:
                self._current_mode = context['mode']
            self._context['immediately'] = context['immediately']
            self._context['cursor_wrap'] = context['cursor_wrap']

            self.init_buffer()

            if context['cursor_pos'] == '+1':
                self.move_to_next_line()
            elif context['cursor_pos'] == '-1':
                self.move_to_prev_line()

            if self.check_empty():
                return

            if context['refresh']:
                self.redraw()
        else:
            if not sources:
                # Ignore empty sources.
                error(self._vim, 'Empty sources')
                return

            if not context['mode']:
                # Default mode
                context['mode'] = 'insert'

            self._context.clear()
            self._context.update(context)
            self._context['sources'] = sources
            self._context['is_redraw'] = False
            self._current_mode = context['mode']
            self._is_multi = len(sources) > 1

            self.init_denite()
            self.gather_candidates()
            self.update_candidates()

            if self.check_empty():
                return

            self.init_buffer()
            self.init_cursor()

        self.update_displayed_texts()
        self.change_mode(self._current_mode)

        if self._context['cursor_pos'].isnumeric():
            self.init_cursor()
            self.move_to_pos(int(self._context['cursor_pos']))

        # Make sure that the caret position is ok
        self._prompt.caret.locus = self._prompt.caret.tail
        status = self._prompt.start()
        if status == STATUS_INTERRUPT:
            # STATUS_INTERRUPT is returned when user hit <C-c> and the loop has
            # interrupted.
            # In this case, denite cancel any operation and close its window.
            self.quit()
        return
Example #10
0
 def _throw_error(self, message):
     message = f'{self.name}: {message}'
     error(self.vim, message)
Example #11
0
 def action_tabopen(self, context):
     target = context['targets'][0]
     if not self.isMac:
         util.error(self.vim, context, 'Tabopen only supported on Mac')
         return
     self.vim.call('denite#extra#iterm_tabopen', target['action__path'])
Example #12
0
    def gather_candidates(self, context):
        package = context['__package']
        if not package:
            util.error(self.vim, 'package.json not found')
            return []

        root = os.path.dirname(package)
        items = []
        with open(package) as fp:
            try:
                obj = json.loads(fp.read())
                browser = {v: k for k, v in obj.get('browser', {}).items()}
                deps = obj.get('dependencies')
                devDeps = obj.get('devDependencies')
                if deps:
                    items += [{
                        'name': x,
                        'dev': False,
                        'alias': browser.get(x, '')
                    } for x in deps]
                if devDeps:
                    items += [{
                        'name': x,
                        'dev': True,
                        'alias': browser.get(x, '')
                    } for x in devDeps]
            except json.JSONDecodeError:
                util.error(self.vim, 'Decode error for %s' % package)
                return []

        candidates = []
        for item in items:
            jsonpath = os.path.join(root, 'node_modules', item['name'],
                                    'package.json')
            if not os.access(jsonpath, os.R_OK):
                continue
            stat = os.stat(jsonpath)
            with open(jsonpath) as fp:
                try:
                    obj = json.loads(fp.read())
                    mtime = stat.st_mtime
                    version = obj.get('version', 'unknown')
                    name = item['alias'] if item['alias'] else item['name']
                    candidates.append({
                        'word':
                        item['name'],
                        'abbr':
                        '%s (%s) %s' %
                        (name, version, '[D]' if item['dev'] else ''),
                        'action__path':
                        os.path.dirname(jsonpath),
                        'source__prod':
                        not item['dev'],
                        'source__mtime':
                        mtime,
                        'source__root':
                        root,
                        'source__name':
                        item['name'],
                    })
                except json.JSONDecodeError:
                    util.error(self.vim, 'Decode error for %s' % jsonpath)
                    continue

        candidates = sorted(candidates,
                            key=itemgetter('source__prod', 'source__mtime'),
                            reverse=True)
        return candidates
Example #13
0
 def _get_gists(self, url):
     try:
         with urllib.request.urlopen(url) as res:
             return json.loads(res.read().decode('utf-8'))
     except urllib.error.HTTPError as e:
         util.error(self.vim, 'Error {} api url:{}'.format(e.reason, url))