-- finder.lua — Minimal async fuzzy finder + grep for Neovim ≥ 0.11 -- Non-blocking, debounced, stable selection, correct scrolling, match highlights. -- Hardened for races, Windows paths, and cwd/root mismatches. local M = {} --------------------------------------------------------------------- -- Config --------------------------------------------------------------------- M.config = { file_cmd = nil, -- "fd" | "fdfind" | nil (auto) grep_cmd = 'rg', -- ripgrep binary page_size = 60, -- soft cap; real viewport height is measured debounce_ms = 80, cache_ttl_sec = 20, max_items = 5000, -- safety cap for massive outputs debug = false, } --------------------------------------------------------------------- -- State --------------------------------------------------------------------- local S = { active = false, mode = nil, -- "files" | "grep" root = nil, is_git = false, cache = {}, timer = nil, ns = vim.api.nvim_create_namespace('finder_ns'), aug = nil, gen = 0, -- session generation id -- async jobs job_files = nil, job_rg = nil, -- UI win_inp = nil, buf_inp = nil, win_res = nil, buf_res = nil, -- Data query = '', items = {}, -- full set (files or grep lines) filtered = {}, -- current view positions = {}, -- positions[i] = { {scol, ecol}, ... } for filtered[i] select = 1, -- absolute index in filtered (1-based) scroll = 0, -- top index (0-based) } --------------------------------------------------------------------- -- Utils --------------------------------------------------------------------- local function L(msg, data) if not M.config.debug then return end local s = '[finder] ' .. msg if data ~= nil then s = s .. ' ' .. vim.inspect(data) end vim.schedule(function() vim.notify(s) end) end local function now_sec() return vim.loop.now() / 1000 end local function clamp(v, lo, hi) return (v < lo) and lo or ((v > hi) and hi or v) end local function cmd_exists(bin) return vim.fn.executable(bin) == 1 end local function debounce(fn, ms) if S.timer then S.timer:stop() S.timer:close() S.timer = nil end S.timer = vim.loop.new_timer() S.timer:start(ms, 0, function() if S.timer then S.timer:stop() S.timer:close() S.timer = nil end vim.schedule(fn) end) end local function is_windows() local sys = vim.loop.os_uname().sysname return sys == 'Windows_NT' end local function is_abs_path(p) if is_windows() then -- C:\... or \\server\share... return p:match('^%a:[/\\]') or p:match('^[/\\][/\\]') else return p:sub(1, 1) == '/' end end local function joinpath(a, b) return vim.fs.normalize(vim.fs.joinpath(a, b)) end local function to_abs_in_root(root, p) if is_abs_path(p) then return p end local joined = joinpath(root, p) local rp = vim.loop.fs_realpath(joined) return rp or joined end local function project_root() local obj = vim.system({ 'git', 'rev-parse', '--show-toplevel' }, { text = true }):wait() if obj.code == 0 and obj.stdout and obj.stdout ~= '' then S.is_git = true return vim.trim(obj.stdout) end S.is_git = false -- Respect Neovim cwd, not process cwd return vim.fn.getcwd(0, 0) end local function resolve_file_cmd() if M.config.file_cmd then return M.config.file_cmd end if cmd_exists('fd') then return 'fd' end if cmd_exists('fdfind') then return 'fdfind' end return nil end local function page_rows() if S.win_res and vim.api.nvim_win_is_valid(S.win_res) then local h = vim.api.nvim_win_get_height(S.win_res) return math.max(1, h) end return math.max(1, math.min(M.config.page_size, vim.o.lines)) end --------------------------------------------------------------------- -- Render helpers --------------------------------------------------------------------- local function ensure_visible() local page = page_rows() local sel = clamp(S.select, 1, #S.filtered) local top = S.scroll + 1 local bot = S.scroll + page if sel < top then S.scroll = sel - 1 elseif sel > bot then S.scroll = sel - page end S.scroll = clamp(S.scroll, 0, math.max(#S.filtered - page, 0)) end --------------------------------------------------------------------- -- Render --------------------------------------------------------------------- local function render() if not (S.active and S.buf_res and vim.api.nvim_buf_is_valid(S.buf_res)) then return end ensure_visible() local total = #S.filtered local view = {} if total == 0 then view = { '-- no matches --' } else local start_idx = S.scroll + 1 local end_idx = math.min(start_idx + page_rows() - 1, total) for i = start_idx, end_idx do view[#view + 1] = S.filtered[i] end end for i = 1, #view do if type(view[i]) ~= 'string' then view[i] = tostring(view[i] or '') end end vim.bo[S.buf_res].modifiable = true vim.bo[S.buf_res].readonly = false vim.api.nvim_buf_set_lines(S.buf_res, 0, -1, false, view) vim.api.nvim_buf_clear_namespace(S.buf_res, S.ns, 0, -1) -- match highlights (visible window only) vim.api.nvim_set_hl(0, 'FinderMatch', { link = 'Search', default = true }) for i = 1, #view do local idx = S.scroll + i local spans = S.positions[idx] if spans then for _, se in ipairs(spans) do local scol, ecol = se[1], se[2] if ecol > scol then vim.api.nvim_buf_set_extmark(S.buf_res, S.ns, i - 1, scol, { end_col = ecol, hl_group = 'FinderMatch', }) end end end end -- selection highlight if total > 0 and #view > 0 then vim.api.nvim_set_hl(0, 'FinderSelection', { link = 'CursorLine', default = true }) local rel = clamp(S.select - S.scroll, 1, #view) vim.api.nvim_buf_set_extmark(S.buf_res, S.ns, rel - 1, 0, { end_line = rel, hl_group = 'FinderSelection', hl_eol = true, }) end vim.bo[S.buf_res].modifiable = false L('render', { select = S.select, scroll = S.scroll, total = total, lines = #view }) end --------------------------------------------------------------------- -- Querying / Filtering --------------------------------------------------------------------- local function compute_positions_files(items, q) local ok, res = pcall(vim.fn.matchfuzzypos, items, q) if not ok or type(res) ~= 'table' then return {}, {} end local out_items = res[1] or {} local pos = res[2] or {} local filtered, positions = {}, {} for i, v in ipairs(out_items) do filtered[i] = (type(v) == 'string') and v or tostring(v or '') local cols = pos[i] or {} local spans = {} for _, c in ipairs(cols) do local start0 = (c > 0) and (c - 1) or 0 spans[#spans + 1] = { start0, start0 + 1 } end positions[i] = spans end return filtered, positions end local function compute_positions_grep(lines, q) if q == '' then return lines, {} end local pat = vim.pesc(q) local positions = {} for i, line in ipairs(lines) do local sidx = 1 local spans = {} if type(line) ~= 'string' then line = tostring(line or '') end while true do local s, e = string.find(line, pat, sidx, true) if not s then break end spans[#spans + 1] = { s - 1, e } -- 0-based start, exclusive end sidx = e + 1 if #spans > 64 then break end end positions[i] = (#spans > 0) and spans or nil end return lines, positions end --------------------------------------------------------------------- -- set_items --------------------------------------------------------------------- local function set_items(list) list = list or {} if #list > M.config.max_items then local tmp = {} for i = 1, M.config.max_items do tmp[i] = list[i] end list = tmp end for i, v in ipairs(list) do if type(v) ~= 'string' then list[i] = tostring(v or '') end end S.items = list S.filtered = list S.positions = {} S.select = 1 S.scroll = 0 render() end --------------------------------------------------------------------- -- set_query --------------------------------------------------------------------- local function set_query(q) local prev_val = S.filtered[S.select] S.query = q if S.mode == 'grep' then local filtered, pos = compute_positions_grep(S.items, q) S.filtered, S.positions = filtered, pos else if q == '' then S.filtered = S.items S.positions = {} else local filtered, pos = compute_positions_files(S.items, q) S.filtered, S.positions = filtered, pos end end for i, v in ipairs(S.filtered) do if type(v) ~= 'string' then S.filtered[i] = tostring(v or '') end end -- preserve previous pick if still present local idx = 1 if prev_val then for i, v in ipairs(S.filtered) do if v == prev_val then idx = i break end end end S.select = clamp(idx, 1, #S.filtered) ensure_visible() render() L('set_query', { query = q, filtered = #S.filtered }) end --------------------------------------------------------------------- -- Move / Accept --------------------------------------------------------------------- local function move_down() if #S.filtered == 0 then return end S.select = clamp(S.select + 1, 1, #S.filtered) ensure_visible() render() end local function move_up() if #S.filtered == 0 then return end S.select = clamp(S.select - 1, 1, #S.filtered) ensure_visible() render() end local function accept_selection_files() local pick = S.filtered[S.select] if not pick then return end local file = to_abs_in_root(S.root, pick) local edit_cb = function() vim.cmd.edit(vim.fn.fnameescape(file)) end M.close() vim.schedule(edit_cb) end local function parse_vimgrep(line) -- Robust against Windows drive letters and extra colons in path. -- Greedy file capture up to last "::" local file, lnum = line:match('^(.*):(%d+):') if not file then return nil end return file, tonumber(lnum) or 1 end local function accept_selection_grep() local pick = S.filtered[S.select] if not pick then return end local file, lnum = parse_vimgrep(pick) if not file then return end file = to_abs_in_root(S.root, file) lnum = tonumber(lnum) or 1 local edit_cb = function() vim.cmd.edit(vim.fn.fnameescape(file)) if vim.api.nvim_get_current_buf() > 0 then pcall(vim.api.nvim_win_set_cursor, 0, { lnum, 0 }) end end M.close() vim.schedule(edit_cb) end --------------------------------------------------------------------- -- Backends --------------------------------------------------------------------- local function cancel_job(j) if not j then return end pcall(function() j:kill(15) end) -- SIGTERM if available end local function collect_files_async(cb) local gen = S.gen local root = S.root local c = S.cache[root] if c and c.files and now_sec() - c.files.at < M.config.cache_ttl_sec then cb(c.files.list) return end -- Prefer fd/fdfind, then git ls-files, then blocking glob fallback. local file_cmd = resolve_file_cmd() if file_cmd then local args = { file_cmd, '--type', 'f', '--hidden', '--follow', '--color', 'never', '--exclude', '.git' } if file_cmd == 'fd' or file_cmd == 'fdfind' then table.insert(args, '--strip-cwd-prefix') end cancel_job(S.job_files) S.job_files = vim.system(args, { text = true, cwd = root }, function(obj) if not (S.active and gen == S.gen) then return end local list if obj.code == 0 and obj.stdout then local raw = vim.split(obj.stdout, '\n', { trimempty = true }) list = {} for i = 1, #raw do list[i] = to_abs_in_root(root, raw[i]) end else list = {} end if #list == 0 and S.is_git and cmd_exists('git') then -- fallback to git ls-files, still async local gargs = { 'git', 'ls-files', '-co', '--exclude-standard', '-z' } cancel_job(S.job_files) S.job_files = vim.system(gargs, { text = true, cwd = root }, function(o2) if not (S.active and gen == S.gen) then return end local glist = {} if o2.code == 0 and o2.stdout then for p in o2.stdout:gmatch('([^%z]+)') do glist[#glist + 1] = to_abs_in_root(root, p) end end if #glist > M.config.max_items then local tmp = {} for i = 1, M.config.max_items do tmp[i] = glist[i] end glist = tmp end S.cache[root] = S.cache[root] or {} S.cache[root].files = { list = glist, at = now_sec() } vim.schedule(function() if S.active and gen == S.gen then cb(glist) end end) end) return end if #list > M.config.max_items then local tmp = {} for i = 1, M.config.max_items do tmp[i] = list[i] end list = tmp end S.cache[root] = S.cache[root] or {} S.cache[root].files = { list = list, at = now_sec() } vim.schedule(function() if S.active and gen == S.gen then cb(list) end end) end) return end -- Last-resort blocking fallback (no fd, not git, or git failed) local list = vim.fn.globpath(root, '**/*', false, true) list = vim.tbl_filter(function(p) return vim.fn.isdirectory(p) == 0 end, list) if #list > M.config.max_items then local tmp = {} for i = 1, M.config.max_items do tmp[i] = list[i] end list = tmp end S.cache[root] = S.cache[root] or {} S.cache[root].files = { list = list, at = now_sec() } cb(list) end local function grep_async(query, cb) local gen = S.gen if query == '' then cb({}) return end local rg = M.config.grep_cmd if rg ~= 'rg' and not cmd_exists(rg) then rg = 'rg' end if not cmd_exists(rg) then cb({}) return end local args = { rg, '--vimgrep', '--hidden', '--smart-case', '--no-heading', '--no-config', '--color', 'never', '--path-separator', '/', '--', query, } cancel_job(S.job_rg) S.job_rg = vim.system(args, { text = true, cwd = S.root }, function(obj) if not (S.active and gen == S.gen) then return end local list = {} if obj.code == 0 and obj.stdout then list = vim.split(obj.stdout, '\n', { trimempty = true }) end if #list > M.config.max_items then local tmp = {} for i = 1, M.config.max_items do tmp[i] = list[i] end list = tmp end vim.schedule(function() if S.active and gen == S.gen then cb(list) end end) end) end --------------------------------------------------------------------- -- Layout --------------------------------------------------------------------- local function open_layout(prompt) S.buf_inp = vim.api.nvim_create_buf(false, true) S.buf_res = vim.api.nvim_create_buf(false, true) for _, b in ipairs({ S.buf_inp, S.buf_res }) do vim.bo[b].buflisted = false vim.bo[b].bufhidden = 'wipe' vim.bo[b].swapfile = false end vim.bo[S.buf_inp].buftype = 'prompt' vim.bo[S.buf_res].buftype = 'nofile' vim.bo[S.buf_res].modifiable = false vim.bo[S.buf_res].readonly = false local width = math.floor(vim.o.columns * 0.8) local height = math.min(math.floor(vim.o.lines * 0.5), M.config.page_size + 2) local col = math.floor((vim.o.columns - width) / 2) local row = math.floor((vim.o.lines - height) * 0.7) S.win_inp = vim.api.nvim_open_win(S.buf_inp, true, { relative = 'editor', style = 'minimal', border = 'rounded', width = width, height = 1, col = col, row = row, focusable = true, zindex = 200, }) vim.fn.prompt_setprompt(S.buf_inp, prompt) S.win_res = vim.api.nvim_open_win(S.buf_res, false, { relative = 'editor', style = 'minimal', border = 'single', width = width, height = math.max(1, height - 2), col = col, row = row + 2, focusable = false, zindex = 199, }) vim.wo[S.win_res].cursorline = false vim.wo[S.win_res].cursorlineopt = 'line' if S.aug then pcall(vim.api.nvim_del_augroup_by_id, S.aug) end S.aug = vim.api.nvim_create_augroup('finder_session', { clear = true }) vim.api.nvim_create_autocmd('WinEnter', { group = S.aug, callback = function() if not S.active then return end local w = vim.api.nvim_get_current_win() if w == S.win_inp or w == S.win_res then return end local cfg = vim.api.nvim_win_get_config(w) if cfg and cfg.relative == '' then M.close() end end, }) vim.api.nvim_create_autocmd({ 'BufHidden', 'BufLeave' }, { group = S.aug, buffer = S.buf_inp, callback = function() if S.active then M.close() end end, }) vim.api.nvim_create_autocmd('VimResized', { group = S.aug, callback = function() if S.active then render() end end, }) vim.cmd.startinsert() L('open_layout', { win_inp = S.win_inp, win_res = S.win_res }) end local function close_layout() for _, win in ipairs({ S.win_inp, S.win_res }) do if win and vim.api.nvim_win_is_valid(win) then pcall(vim.api.nvim_win_close, win, true) end end for _, buf in ipairs({ S.buf_inp, S.buf_res }) do if buf and vim.api.nvim_buf_is_valid(buf) then pcall(vim.api.nvim_buf_delete, buf, { force = true }) end end if S.aug then pcall(vim.api.nvim_del_augroup_by_id, S.aug) S.aug = nil end L('close_layout') end --------------------------------------------------------------------- -- Input handlers --------------------------------------------------------------------- local function attach_handlers() local opts = { buffer = S.buf_inp, nowait = true, silent = true, noremap = true } vim.keymap.set('i', '', move_down, opts) vim.keymap.set('i', '', move_up, opts) vim.keymap.set('i', '', move_down, opts) vim.keymap.set('i', '', move_up, opts) vim.keymap.set('i', '', function() if S.mode == 'grep' then accept_selection_grep() else accept_selection_files() end end, opts) vim.keymap.set('i', '', function() M.close() end, opts) vim.keymap.set('i', '', function() M.close() end, opts) vim.api.nvim_create_autocmd({ 'TextChangedI', 'TextChangedP' }, { group = S.aug, buffer = S.buf_inp, callback = function() debounce(function() if not (S.active and vim.api.nvim_buf_is_valid(S.buf_inp)) then return end -- Prompt buffers usually return only the user input, but strip prompt defensively. local raw = vim.fn.getline('.') local prompt = (S.mode == 'files') and '^Search:%s*' or '^Grep:%s*' local q = raw:gsub(prompt, '') if S.mode == 'grep' then grep_async(q, function(list) if not S.active then return end S.items = list set_query(q) end) else set_query(q) end end, M.config.debounce_ms) end, }) L('keymaps attached', opts) end --------------------------------------------------------------------- -- Public --------------------------------------------------------------------- function M.files() if S.active then M.close() end S.active = true S.gen = S.gen + 1 S.mode = 'files' S.root = project_root() open_layout('Search: ') attach_handlers() collect_files_async(function(list) if not S.active then return end set_items(list) end) end function M.grep() if S.active then M.close() end S.active = true S.gen = S.gen + 1 S.mode = 'grep' S.root = project_root() open_layout('Grep: ') attach_handlers() S.items = {} set_query('') end function M.close() if not S.active then return end -- stop timers and jobs first if S.timer then S.timer:stop() S.timer:close() S.timer = nil end cancel_job(S.job_rg) S.job_rg = nil cancel_job(S.job_files) S.job_files = nil close_layout() S.active = false S.mode, S.root = nil, nil S.items, S.filtered, S.positions = {}, {}, {} S.query, S.select, S.scroll = '', 1, 0 L('session closed') end function M.setup(opts) M.config = vim.tbl_deep_extend('force', M.config, opts or {}) if M.config.file_cmd and not cmd_exists(M.config.file_cmd) then vim.notify(("finder: file_cmd '%s' not found"):format(M.config.file_cmd), vim.log.levels.WARN) end if M.config.grep_cmd and not cmd_exists(M.config.grep_cmd) then vim.notify( ("finder: grep_cmd '%s' not found, will try 'rg'"):format(M.config.grep_cmd), vim.log.levels.WARN ) end L('setup', M.config) end return M