robin/artio.nvim

minimal ui2 fuzzy finder for Neovim

git clone https://git.robinwobin.dev/robin/artio.nvim

robinfeat!: collapse qflist actions into one8fb9b8a

main
20.2 KiB773 linesraw
1local function lzrq(modname)
2  return setmetatable({}, {
3    __index = function(_, key)
4      return require(modname)[key]
5    end,
6  })
7end
8
9local artio = lzrq("artio")
10local config = lzrq("artio.config")
11local utils = lzrq("artio.utils")
12
13local function extend(t1, ...)
14  return vim.tbl_deep_extend("force", t1, ...)
15end
16
17local builtins = {}
18
19builtins.builtins = function(props)
20  props = props or {}
21
22  return artio.generic(
23    vim.tbl_keys(builtins),
24    extend({
25      prompt = "builtins",
26      on_close = function(fname, _)
27        if not builtins[fname] then
28          return
29        end
30
31        artio.schedule(builtins[fname])
32      end,
33    }, props)
34  )
35end
36
37---@class artio.picker.generic.fs.Props : artio.Picker.config
38---@field base_dir? string
39
40local findprg = vim.fn.executable("fd") == 1 and "fd -H -p -a -t f --color=never --"
41  or "find . -type f -iregex '.*$*.*'"
42
43---@class artio.picker.files.Props : artio.picker.generic.fs.Props
44---@field findprg? string
45
46---@param props? artio.picker.files.Props
47builtins.files = function(props)
48  props = props or {}
49  props.findprg = props.findprg or findprg
50
51  local base_dir = props.base_dir or vim.fn.getcwd(0)
52
53  return artio.pick(extend({
54    prompt = "files",
55    live = false,
56    get_items = utils.make_cmd(props.findprg, {
57      cwd = base_dir,
58    }),
59    fn = artio.sorter,
60    on_close = function(text, _)
61      artio.schedule(function()
62        utils.edit(text)
63      end)
64    end,
65    format_item = function(item)
66      return vim.fs.relpath(base_dir, item) or item
67    end,
68    get_icon = config.get().opts.use_icons and function(item)
69      return require("mini.icons").get("file", item.v)
70    end or nil,
71    preview_item = function(item)
72      return { buf = vim.fn.bufadd(item) }
73    end,
74    actions = extend(
75      {},
76      utils.make_fileactions(function(item)
77        return vim.fn.bufnr(item.v, true)
78      end),
79      utils.make_setqflistaction(function(item)
80        return { filename = item.v }
81      end)
82    ),
83  }, props))
84end
85
86---@class artio.picker.grep.Props : artio.picker.generic.fs.Props
87---@field grepprg? string
88
89---@param props? artio.picker.grep.Props
90builtins.grep = function(props)
91  props = props or {}
92  props.grepprg = props.grepprg or vim.o.grepprg
93
94  local base_dir = props.base_dir or vim.fn.getcwd(0)
95  local ui2 = require("vim._core.ui2")
96  local grepcmd = utils.make_cmd(props.grepprg, {
97    cwd = base_dir,
98  })
99
100  return artio.pick(extend({
101    prompt = "grep",
102    live = true,
103    get_items = function(input)
104      if input == "" then
105        return {}
106      end
107
108      local lines, err = grepcmd(input)
109      if err then
110        return vim
111          .iter(ipairs(lines))
112          :map(function(i, l)
113            return {
114              id = i,
115              v = {},
116              text = l,
117            }
118          end)
119          :totable()
120      end
121
122      local co = coroutine.running()
123      assert(co)
124
125      coroutine.wrap(vim.schedule_wrap(function()
126        vim.fn.setloclist(ui2.wins.cmd, {}, " ", {
127          title = "grep[" .. input .. "]",
128          lines = lines,
129          efm = vim.o.grepformat,
130          nr = "$",
131        })
132        local results = vim
133          .iter(ipairs(vim.fn.getloclist(ui2.wins.cmd)))
134          :map(function(i, locitem)
135            local name = vim.fs.abspath(vim.fn.bufname(locitem.bufnr))
136            return {
137              id = i,
138              v = { name, locitem.lnum, locitem.col },
139              text = ("%s:%d:%d:%s"):format(vim.fs.relpath(base_dir, name), locitem.lnum, locitem.col, locitem.text),
140            }
141          end)
142          :totable()
143        coroutine.resume(co, results)
144      end))()
145
146      return coroutine.yield()
147    end,
148    fn = artio.sorter,
149    on_close = function(item, _)
150      artio.schedule(function()
151        local win = vim.api.nvim_get_current_win()
152        utils.edit(item[1], { win = win })
153        vim.api.nvim_win_set_cursor(win, { item[2], item[3] })
154      end)
155    end,
156    preview_item = function(item)
157      return { buf = vim.fn.bufadd(item[1]), pos = { item[2], 0 } }
158    end,
159    get_icon = config.get().opts.use_icons and function(item)
160      return item.v[1] and require("mini.icons").get("file", item.v[1]) or nil
161    end or nil,
162    hl_item = utils.hl_qfitem,
163    actions = extend(
164      {},
165      utils.make_setqflistaction(function(item)
166        return { filename = item.v[1], lnum = item.v[2], col = item.v[3], text = item.text }
167      end)
168    ),
169  }, props))
170end
171
172local function find_oldfiles()
173  return vim
174    .iter(vim.v.oldfiles)
175    :filter(function(v)
176      return vim.uv.fs_stat(v) --[[@as boolean]]
177    end)
178    :totable()
179end
180
181builtins.oldfiles = function(props)
182  props = props or {}
183  local lst = find_oldfiles()
184
185  return artio.generic(
186    lst,
187    extend({
188      prompt = "oldfiles",
189      on_close = function(text, _)
190        artio.schedule(function()
191          utils.edit(text)
192        end)
193      end,
194      get_icon = config.get().opts.use_icons and function(item)
195        return require("mini.icons").get("file", item.v)
196      end or nil,
197      preview_item = function(item)
198        return { buf = vim.fn.bufadd(item) }
199      end,
200      actions = extend(
201        {},
202        utils.make_setqflistaction(function(item)
203          return { filename = item.v }
204        end)
205      ),
206    }, props)
207  )
208end
209
210builtins.buffergrep = function(props)
211  props = props or {}
212  local win = vim.api.nvim_get_current_win()
213  local buf = vim.api.nvim_win_get_buf(win)
214  local n = vim.api.nvim_buf_line_count(buf)
215  local lst = {} ---@type integer[]
216  for i = 1, n do
217    lst[#lst + 1] = i
218  end
219
220  local pad = #tostring(lst[#lst])
221
222  return artio.generic(
223    lst,
224    extend({
225      prompt = "buffergrep",
226      on_close = function(row, _)
227        vim.schedule(function()
228          vim.api.nvim_win_set_cursor(win, { row, 0 })
229        end)
230      end,
231      format_item = function(row)
232        return vim.api.nvim_buf_get_lines(buf, row - 1, row, true)[1]
233      end,
234      preview_item = function(row)
235        return { buf = buf, pos = { row, 0 } }
236      end,
237      get_icon = function(row)
238        local v = tostring(row.v)
239        return ("%s%s"):format((" "):rep(pad - #v), v)
240      end,
241      actions = extend(
242        {},
243        utils.make_setqflistaction(function(item)
244          return { filename = vim.api.nvim_buf_get_name(buf), lnum = item.v }
245        end)
246      ),
247    }, props)
248  )
249end
250
251local function find_helptags()
252  local buf = vim.api.nvim_create_buf(false, true)
253  vim.bo[buf].buftype = "help"
254  local tags = vim.api.nvim_buf_call(buf, function()
255    return vim.fn.taglist(".*")
256  end)
257  vim.api.nvim_buf_delete(buf, { force = true })
258  return vim.tbl_map(function(t)
259    return t.name
260  end, tags)
261end
262
263builtins.helptags = function(props)
264  props = props or {}
265  local lst = find_helptags()
266
267  return artio.generic(
268    lst,
269    extend({
270      prompt = "helptags",
271      on_close = function(text, _)
272        vim.schedule(function()
273          vim.cmd.help(text)
274        end)
275      end,
276      preview_item = function(tag)
277        local buf = vim.api.nvim_create_buf(false, true)
278
279        vim.bo[buf].bufhidden = "wipe"
280        vim.bo[buf].buftype = "help"
281
282        vim._with({ buf = buf }, function()
283          vim.cmd.help(tag)
284        end)
285
286        return { buf = buf }
287      end,
288    }, props)
289  )
290end
291
292local function find_buffers()
293  return vim
294    .iter(vim.api.nvim_list_bufs())
295    :filter(function(bufnr)
296      return vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].buflisted
297    end)
298    :totable()
299end
300
301builtins.buffers = function(props)
302  props = props or {}
303  local lst = find_buffers()
304
305  return artio.generic(
306    lst,
307    vim.tbl_extend("force", {
308      prompt = "buffers",
309      format_item = function(bufnr)
310        return vim.api.nvim_buf_get_name(bufnr)
311      end,
312      on_close = function(bufnr, _)
313        vim.schedule(function()
314          vim.cmd.buffer(bufnr)
315        end)
316      end,
317      get_icon = config.get().opts.use_icons and function(item)
318        return require("mini.icons").get("file", vim.api.nvim_buf_get_name(item.v))
319      end or nil,
320      preview_item = function(item)
321        return { buf = item }
322      end,
323    }, props)
324  )
325end
326
327---@param currentfile string
328---@param item string
329---@return integer score
330local function matchproximity(currentfile, item)
331  currentfile = vim.fs.abspath(currentfile)
332  local parts = vim.split(currentfile, "/", { trimempty = true })
333  item = vim.fs.abspath(item)
334
335  return vim.iter(ipairs(vim.split(item, "/", { trimempty = true }))):fold(0, function(score, i, part)
336    if part == parts[i] then
337      return score + 50
338    end
339    return score
340  end)
341end
342
343--- uses the regular files picker as a base
344--- - boosts items in the bufferlist
345--- - proportionally boosts items that match closely to the current file in proximity within the filesystem
346builtins.smart = function(props)
347  props = props or {}
348  local currentbuf = vim.fn.bufnr("%")
349  local currentfile = vim.api.nvim_buf_get_name(currentbuf)
350  currentfile = vim.fs.abspath(currentfile)
351  local alternatebuf = vim.fn.bufnr("#")
352  local lbufnr = vim.fn.bufnr("$")
353  local bufnr_len = #(string.format("%d", lbufnr))
354
355  props.findprg = props.findprg or findprg
356  local base_dir = vim.fn.getcwd(0)
357
358  local recentlst = vim
359    .iter(find_buffers())
360    :map(function(buf)
361      local v = vim.api.nvim_buf_get_name(buf)
362      return { path = vim.fs.abspath(v), buf = buf }
363    end)
364    :totable()
365
366  return artio.pick(extend({
367    prompt = "smart",
368    live = false,
369    get_items = function(_)
370      local lst = utils.make_cmd(props.findprg, {
371        cwd = base_dir,
372      })()
373
374      local results = vim
375        .iter({ recentlst, lst })
376        :flatten(1)
377        :map(function(x)
378          if type(x) == "string" then
379            x = { path = x }
380          end
381          return x
382        end)
383        :map(function(x)
384          if x.buf and x.buf == currentbuf then
385            x.current = true
386          elseif x.buf and x.buf == alternatebuf then
387            x.alt = true
388          end
389          return x
390        end)
391        :totable()
392
393      return vim.list.unique(results, function(x)
394        return x.path
395      end)
396    end,
397    fn = artio.mergesorters(
398      "base",
399      -- use default sorter but only display buffer files if input is empty
400      function(l, input)
401        if #input == 0 then
402          return vim
403            .iter(l)
404            :map(function(item)
405              if not item.v.buf then
406                return
407              end
408              return { item.id, {}, 0 }
409            end)
410            :totable()
411        end
412
413        return artio.sorter(l, input)
414      end,
415      -- boost files that are open as buffers
416      function(l, _)
417        return vim
418          .iter(l)
419          :map(function(item)
420            if not item.v.buf then
421              return
422            end
423            return { item.id, {}, 100 }
424          end)
425          :totable()
426      end,
427      -- boost files that are close in proximity to the current file
428      function(l, _)
429        return vim
430          .iter(l)
431          :map(function(item)
432            return { item.id, {}, matchproximity(currentfile, item.v.path) }
433          end)
434          :totable()
435      end
436    ),
437    on_close = function(v, _)
438      artio.schedule(function()
439        utils.edit(v.path)
440      end)
441    end,
442    format_item = function(v)
443      local path = vim.fs.relpath(base_dir, v.path) or v.path
444      local ind = v.current and "%" or v.alt and "#" or " "
445      return v.buf and string.format("%s (%0" .. bufnr_len .. "d) %s", ind, v.buf, path)
446        or string.format("%s " .. string.rep(" ", bufnr_len + 2) .. " %s", ind, path)
447    end,
448    hl_item = function(_)
449      return {
450        { { 0, 2 }, "Special" },
451        { { 2, 3 }, "Delimiter" },
452        { { 3, 3 + bufnr_len }, "Number" },
453        { { 3 + bufnr_len, 3 + bufnr_len + 1 }, "NonText" },
454      }
455    end,
456    get_icon = config.get().opts.use_icons and function(item)
457      return require("mini.icons").get("file", item.v.path)
458    end or nil,
459    preview_item = function(v)
460      return { buf = vim.fn.bufadd(v.path) }
461    end,
462    actions = extend(
463      {},
464      utils.make_fileactions(function(item)
465        return vim.fn.bufnr(item.v.path, true)
466      end),
467      utils.make_setqflistaction(function(item)
468        return { filename = item.v.path }
469      end)
470    ),
471  }, props))
472end
473
474builtins.colorschemes = function(props)
475  props = props or {}
476  local files = vim.api.nvim_get_runtime_file("colors/*.{vim,lua}", true)
477  local lst = vim.tbl_map(function(f)
478    return vim.fs.basename(f):gsub("%.[^.]+$", "")
479  end, files)
480
481  local current = vim.g.colors_name
482  local bg = vim.o.background
483
484  return artio.generic(
485    lst,
486    extend({
487      prompt = "colorschemes",
488      on_close = function(text, _)
489        vim.schedule(function()
490          vim.cmd.colorscheme(text)
491        end)
492      end,
493      on_quit = function()
494        -- reset colorscheme
495        vim.schedule(function()
496          if vim.g.colors_name ~= current then
497            vim.cmd.colorscheme(current)
498          end
499        end)
500      end,
501      preview_item = function(item)
502        vim.cmd.colorscheme(item)
503        vim.o.background = bg
504
505        return {}
506      end,
507    }, props)
508  )
509end
510
511builtins.highlights = function(props)
512  props = props or {}
513  local hlout = vim.split(vim.api.nvim_exec2([[ highlight ]], { output = true }).output, "\n", { trimempty = true })
514
515  local maxw = 0
516
517  local hls = vim
518    .iter(hlout)
519    :map(function(hl)
520      local sp = string.find(hl, "%s", 1)
521      maxw = sp > maxw and sp or maxw
522      return { hl:sub(1, sp - 1), hl }
523    end)
524    :fold({}, function(t, hl)
525      local pad = math.max(1, math.min(20, maxw) - #hl[1] + 1)
526      t[hl[1]] = string.gsub(hl[2], "%s+", (" "):rep(pad), 1)
527      return t
528    end)
529
530  return artio.generic(
531    vim.tbl_keys(hls),
532    extend({
533      prompt = "highlights",
534      on_close = function(hlname, _)
535        vim.schedule(function()
536          vim.cmd(("verbose hi %s"):format(hlname))
537        end)
538      end,
539      format_item = function(hlname)
540        return hls[hlname]
541      end,
542      hl_item = function(hlname)
543        local x_start, x_end = string.find(hlname.text, "%sxxx")
544
545        return {
546          { { 0, #hlname.v }, hlname.v },
547          { { x_start, x_end }, hlname.v },
548        }
549      end,
550    }, props)
551  )
552end
553
554---@private
555---@param severity vim.diagnostic.Severity
556---@return string
557local function get_severity_hl(severity)
558  if severity == vim.diagnostic.severity.ERROR then
559    return "DiagnosticError"
560  elseif severity == vim.diagnostic.severity.WARN then
561    return "DiagnosticWarn"
562  elseif severity == vim.diagnostic.severity.INFO then
563    return "DiagnosticInfo"
564  elseif severity == vim.diagnostic.severity.HINT then
565    return "DiagnosticHint"
566  end
567  return ""
568end
569
570---@class artio.picker.diagnostics.Props : artio.Picker.config
571---@field buf? integer defaults to workspace
572
573---@param props? artio.picker.diagnostics.Props
574builtins.diagnostics = function(props)
575  props = props or {}
576  local lst = vim.diagnostic.get(props.buf)
577
578  return artio.generic(
579    lst,
580    extend({
581      prompt = "diagnostics",
582      format_item = function(item)
583        local text = item.message
584        if item.code then
585          text = ("%s [%s]"):format(text, item.code)
586        end
587        return ("%d:%d :: %s"):format(item.end_lnum, item.end_col, text)
588      end,
589      on_close = function(item, _)
590        vim.schedule(function()
591          local win = vim.fn.bufwinid(item.bufnr)
592          if win < 0 then
593            vim.api.nvim_win_set_buf(0, item.bufnr)
594            win = 0
595          end
596          vim.api.nvim_set_current_win(win)
597          vim.api.nvim_win_set_cursor(win, { item.end_lnum + 1, item.end_col })
598        end)
599      end,
600      hl_item = function(item)
601        return {
602          { { 0, #item.text }, get_severity_hl(item.v.severity) },
603        }
604      end,
605      get_icon = function(item)
606        if item.v.severity == vim.diagnostic.severity.ERROR then
607          return "E", get_severity_hl(item.v.severity)
608        elseif item.v.severity == vim.diagnostic.severity.WARN then
609          return "W", get_severity_hl(item.v.severity)
610        elseif item.v.severity == vim.diagnostic.severity.INFO then
611          return "I", get_severity_hl(item.v.severity)
612        elseif item.v.severity == vim.diagnostic.severity.HINT then
613          return "H", get_severity_hl(item.v.severity)
614        end
615        return " "
616      end,
617    }, props)
618  )
619end
620
621---@param props? artio.picker.diagnostics.Props
622builtins.diagnostics_buffer = function(props)
623  props = props or {}
624  props.buf = props.buf or vim.api.nvim_get_current_buf()
625  return builtins.diagnostics(props)
626end
627
628---@class artio.picker.keymaps.Props : artio.Picker.config
629---@field modes? string[] defaults to all
630
631---@param props? artio.picker.keymaps.Props
632builtins.keymaps = function(props)
633  props = props or {}
634  props.modes = props.modes or { "n", "i", "c", "v", "x", "s", "o", "t", "l" }
635
636  ---@type vim.api.keyset.get_keymap[]
637  local lst = vim.iter(props.modes):fold({}, function(keymaps, mode)
638    vim.iter(vim.api.nvim_get_keymap(mode)):each(function(km)
639      keymaps[#keymaps + 1] = km
640    end)
641    return keymaps
642  end)
643
644  return artio.generic(
645    lst,
646    extend({
647      prompt = "keymaps",
648      format_item = function(km)
649        return ("%s %s %s | %s"):format(km.mode, km.lhs, km.rhs, km.desc)
650      end,
651      ---@param km vim.api.keyset.get_keymap
652      on_close = function(km, _)
653        vim.schedule(function()
654          local out = vim.api.nvim_cmd({
655            cmd = ("%smap"):format(km.mode),
656            args = { km.lhs },
657          }, {
658            output = true,
659          })
660          vim.print(out)
661        end)
662      end,
663    }, props)
664  )
665end
666
667builtins.commands = function(props)
668  props = props or {}
669  local lst = vim.api.nvim_get_commands({})
670
671  return artio.generic(
672    vim.tbl_values(lst),
673    extend({
674      prompt = "commands",
675      ---@param item vim.api.keyset.command_info
676      format_item = function(item)
677        return item.name
678      end,
679      ---@param cmd vim.api.keyset.command_info
680      on_close = function(cmd, _)
681        local nargs = vim.F.npcall(tonumber, cmd.nargs)
682        local fmt = (nargs and nargs > 0) and ":%s " or ":%s"
683
684        artio.schedule(function()
685          vim.api.nvim_feedkeys(string.format(fmt, cmd.name), "n", false)
686        end)
687      end,
688      hl_item = function(item)
689        return {
690          { { 0, #item.v.name }, "@function.macro.vim" },
691        }
692      end,
693    }, props)
694  )
695end
696
697builtins.quickfix = function(props)
698  props = props or {}
699
700  local qfid = vim.fn.getqflist({ id = 0 }).id
701  local qflist = vim.fn.getqflist({ id = qfid, items = 0 }).items
702
703  return artio.generic(
704    vim
705      .iter(ipairs(qflist))
706      :map(function(_, item)
707        item.name = vim.fn.bufname(item.bufnr)
708        return item
709      end)
710      :totable(),
711    extend({
712      prompt = "quickfix",
713      on_close = function(_, idx)
714        artio.schedule(function()
715          vim.cmd([[copen]])
716          local win = vim.fn.getqflist({ id = qfid, winid = 0 }).winid
717          vim.api.nvim_win_set_cursor(win, { idx, 0 })
718        end)
719      end,
720      format_item = function(item)
721        return string.format("%s:%d:%d:%s", item.name, item.lnum, item.col, item.text)
722      end,
723      preview_item = function(item)
724        return { buf = item.bufnr, pos = { item.lnum, item.col }, pos_end = { item.end_lnum, item.end_col } }
725      end,
726      get_icon = config.get().opts.use_icons and function(item)
727        return require("mini.icons").get("file", item.v.name)
728      end or nil,
729      hl_item = utils.hl_qfitem,
730      actions = extend(
731        {},
732        utils.make_setqflistaction(function(item)
733          return item.v
734        end)
735      ),
736    }, props)
737  )
738end
739
740builtins.document_symbols = function(props)
741  props = props or {}
742
743  local buf = vim.api.nvim_get_current_buf()
744  local win = vim.api.nvim_get_current_win()
745
746  vim.lsp.buf.document_symbol({
747    on_list = function(what)
748      local lst = what.items
749
750      return artio.select(lst, {
751        prompt = "document_symbols",
752        format_item = function(v)
753          return v.text
754        end,
755        preview_item = function(v)
756          return {
757            buf = buf,
758            pos = { v.lnum, v.col },
759            pos_end = { v.end_lnum, v.end_col },
760          }
761        end,
762      }, function(v, _)
763        if not v then
764          return
765        end
766
767        vim.api.nvim_win_set_cursor(win, { v.lnum, v.col })
768      end, props)
769    end,
770  })
771end
772
773return builtins