diff --git a/lua/cmp/config/compare.lua b/lua/cmp/config/compare.lua index ab8d2c9..2913f9a 100644 --- a/lua/cmp/config/compare.lua +++ b/lua/cmp/config/compare.lua @@ -1,4 +1,5 @@ local types = require('cmp.types') +local cache = require('cmp.utils.cache') local misc = require('cmp.utils.misc') local compare = {} @@ -102,6 +103,7 @@ end compare.locality = setmetatable({ lines_count = 10, + lines_cache = cache.new(), locality_map = {}, update = function(self) local config = require('cmp').get_config() @@ -109,23 +111,35 @@ compare.locality = setmetatable({ return end - self.locality_map = {} - local win, buf = vim.api.nvim_get_current_win(), vim.api.nvim_get_current_buf() local cursor_row = vim.api.nvim_win_get_cursor(win)[1] - 1 local max = vim.api.nvim_buf_line_count(buf) + + if self.lines_cache:get('buf') ~= buf then + self.lines_cache:clear() + self.lines_cache:set('buf', buf) + end + + self.locality_map = {} for i = math.max(0, cursor_row - self.lines_count), math.min(max, cursor_row + self.lines_count) do local buffer = vim.api.nvim_buf_get_lines(buf, i, i + 1, false)[1] or '' - local regexp = vim.regex(config.completion.keyword_pattern) - while buffer ~= ''do - local s, e = regexp:match_str(buffer) - if s and e then - local w = string.sub(buffer, s + 1, e) - self.locality_map[w] = math.min(self.locality_map[w] or math.huge, math.abs(i - cursor_row)) - buffer = string.sub(buffer, e + 1) - else - break + local locality_map = self.lines_cache:ensure({ 'line', buffer }, function() + local locality_map = {} + local regexp = vim.regex(config.completion.keyword_pattern) + while buffer ~= '' do + local s, e = regexp:match_str(buffer) + if s and e then + local w = string.sub(buffer, s + 1, e) + locality_map[w] = math.min(locality_map[w] or math.huge, math.abs(i - cursor_row)) + buffer = string.sub(buffer, e + 1) + else + break + end end + return locality_map + end) + for w, d in pairs(locality_map) do + self.locality_map[w] = math.min(self.locality_map[w] or d, math.abs(i - cursor_row)) end end end