Make the comparator work with entries coming from other sources

This commit is contained in:
Dmytro Meleshko 2021-11-12 21:51:21 +02:00
parent 10be0baf3c
commit 45adb7b7b3
2 changed files with 18 additions and 14 deletions

View File

@ -67,20 +67,26 @@ end
This source also provides a comparator function which uses information from the word indexer
to sort completion results based on the distance of the word from the cursor line. It will also
sort completion results coming from other sources, such as Language Servers, which might improve
accuracy of their suggestions too. The usage is as follows:
accuracy of their suggestions too. The usage is, unfortunately, pretty hacky:
```lua
local cmp_buffer = require('cmp_buffer')
local cmp = require('cmp')
local cmp_buffer = require('cmp_buffer').new()
-- You have to register and use a source with a different name from 'buffer'
-- because otherwise duplicate buffer sources will both be indexing the same
-- file twice, in parallel.
cmp.register_source('buffer_with_distance', cmp_buffer)
cmp.setup({
sources = {
{ name = 'buffer' }
{ name = 'buffer_with_distance' }, -- NOT 'buffer'!
-- The rest of your sources...
},
sorting = {
comparators = {
cmp_buffer.compare_word_distance,
function(...) return cmp_buffer:compare_word_distance(...) end,
-- The rest of your comparators...
}
}

View File

@ -94,22 +94,20 @@ source._get_buffers = function(self, opts)
return buffers
end
source._get_distance_from_entry = function(entry)
if getmetatable(entry.source.source).__index == source then
local buf = entry.source.source.buffers[entry.context.bufnr]
if buf then
local distances = buf:get_words_distances(entry.context.cursor.line + 1)
return distances[entry.completion_item.filterText] or distances[entry.completion_item.label]
end
source._get_distance_from_entry = function(self, entry)
local buf = self.buffers[entry.context.bufnr]
if buf then
local distances = buf:get_words_distances(entry.context.cursor.line + 1)
return distances[entry.completion_item.filterText] or distances[entry.completion_item.label]
end
end
source.compare_word_distance = function(entry1, entry2)
source.compare_word_distance = function(self, entry1, entry2)
if entry1.context ~= entry2.context then
return
end
local dist1 = source._get_distance_from_entry(entry1) or math.huge
local dist2 = source._get_distance_from_entry(entry2) or math.huge
local dist1 = self:_get_distance_from_entry(entry1) or math.huge
local dist2 = self:_get_distance_from_entry(entry2) or math.huge
if dist1 ~= dist2 then
return dist1 < dist2
end