summaryrefslogtreecommitdiff
path: root/rplugin/python3/deoplete/source/buffer.py
blob: 3ed4eb89c65542e6e23f892ab3537fdbd0e4326e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# ============================================================================
# FILE: buffer.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license
# ============================================================================

from .base import Base

import functools
import operator
from deoplete.util import parse_buffer_pattern, getlines


class Source(Base):

    def __init__(self, vim):
        super().__init__(vim)

        self.name = 'buffer'
        self.mark = '[B]'
        self.__buffers = {}
        self.__max_lines = 5000

    def on_event(self, context):
        if ((context['bufnr'] not in self.__buffers) or
                context['event'] == 'BufWritePost'):
            self.__make_cache(context)

    def gather_candidates(self, context):
        self.__make_cache(context)

        buffers = [x['candidates'] for x in self.__buffers.values()
                   if x['filetype'] in context['filetypes']]
        if not buffers:
            return []

        return [{'word': x} for x in
                functools.reduce(operator.add, buffers)]

    def __make_cache(self, context):
        try:
            if (context['bufnr'] in self.__buffers and
                    context['event'] != 'BufWritePost' and
                    len(self.vim.current.buffer) > self.__max_lines):
                line = context['position'][1]
                buffer = self.__buffers[context['bufnr']]
                buffer['candidates'] += parse_buffer_pattern(
                        getlines(self.vim, max([1, line-500]), line+500),
                        context['keyword_patterns'],
                        context['complete_str'])
                buffer['candidates'] = list(set(buffer['candidates']))
            else:
                self.__buffers[context['bufnr']] = {
                    'filetype': context['filetype'],
                    'candidates': parse_buffer_pattern(
                        getlines(self.vim),
                        context['keyword_patterns'],
                        context['complete_str'])
                }
        except UnicodeDecodeError:
            return []