Use cache for locality sort

This commit is contained in:
hrsh7th
2022-03-30 21:36:42 +09:00
parent a5024f916a
commit c1d0cd0fc5

View File

@@ -1,4 +1,5 @@
local types = require('cmp.types') local types = require('cmp.types')
local cache = require('cmp.utils.cache')
local misc = require('cmp.utils.misc') local misc = require('cmp.utils.misc')
local compare = {} local compare = {}
@@ -102,6 +103,7 @@ end
compare.locality = setmetatable({ compare.locality = setmetatable({
lines_count = 10, lines_count = 10,
lines_cache = cache.new(),
locality_map = {}, locality_map = {},
update = function(self) update = function(self)
local config = require('cmp').get_config() local config = require('cmp').get_config()
@@ -109,23 +111,35 @@ compare.locality = setmetatable({
return return
end end
self.locality_map = {}
local win, buf = vim.api.nvim_get_current_win(), vim.api.nvim_get_current_buf() 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 cursor_row = vim.api.nvim_win_get_cursor(win)[1] - 1
local max = vim.api.nvim_buf_line_count(buf) 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 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 buffer = vim.api.nvim_buf_get_lines(buf, i, i + 1, false)[1] or ''
local regexp = vim.regex(config.completion.keyword_pattern) local locality_map = self.lines_cache:ensure({ 'line', buffer }, function()
while buffer ~= ''do local locality_map = {}
local s, e = regexp:match_str(buffer) local regexp = vim.regex(config.completion.keyword_pattern)
if s and e then while buffer ~= '' do
local w = string.sub(buffer, s + 1, e) local s, e = regexp:match_str(buffer)
self.locality_map[w] = math.min(self.locality_map[w] or math.huge, math.abs(i - cursor_row)) if s and e then
buffer = string.sub(buffer, e + 1) local w = string.sub(buffer, s + 1, e)
else locality_map[w] = math.min(locality_map[w] or math.huge, math.abs(i - cursor_row))
break buffer = string.sub(buffer, e + 1)
else
break
end
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 end
end end