Skip to content

Commit

Permalink
feat: add fuzzy matching sorter experimentally
Browse files Browse the repository at this point in the history
  • Loading branch information
delphinus committed Jan 15, 2024
1 parent 9c18474 commit e9204e2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lua/frecency/picker.lua
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ function Picker:start(opts)
prompt_title = "Frecency",
finder = finder,
previewer = config_values.file_previewer(opts),
sorter = sorters.get_substr_matcher(),
sorter = require "frecency.sorter",
on_input_filter_cb = self:on_input_filter_cb(opts),
attach_mappings = function(prompt_bufnr)
return self:attach_mappings(prompt_bufnr)
Expand Down
49 changes: 49 additions & 0 deletions lua/frecency/sorter.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
local sorters = require "telescope.sorters"

---@type table<string, string[]>
local regexp_cache = {}

---@param prompt string
local function regexps(prompt)
if not regexp_cache[prompt] then
---@type string[]
local res = {}
for c in prompt:lower():gmatch "." do
local escaped = c:gsub([=[[%^%$%(%)%%%.%[%]%*%+%-%?]]=], "%%%0")
table.insert(res, escaped)
end
regexp_cache[prompt] = res
end
return regexp_cache[prompt]
end

return sorters.Sorter:new {
---@param prompt string
---@param display string
highlighter = function(_, prompt, display)
local converted = display:lower()
local res = regexps(prompt)
---@type { start: number, finish: number }[]
local highlights = {}
local init = 1
for _, re in ipairs(res) do
local start, finish = converted:find(re, init)
if start and finish then
init = finish + 1
table.insert(highlights, { start = start, finish = finish })
end
end
return highlights
end,

---@param prompt string
---@param entry FrecencyEntry
scoring_function = function(_, prompt, _, entry)
if #prompt == 0 then
return 1
end
local res = regexps(prompt)
local display = entry.ordinal:lower()
return display:match(table.concat(res, ".*")) and entry.index or -1
end,
}

0 comments on commit e9204e2

Please sign in to comment.