robin/artio.nvim

minimal ui2 fuzzy finder for Neovim

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

robinbuiltins: add missing file actions to smart picker54b0625

main
7.7 KiB330 linesraw
1local View = require("artio.view")
2
3---@alias artio.Picker.item { id: integer, v: any, text: string, icon?: string, icon_hl?: string, hls?: artio.Picker.hl[] }
4---@alias artio.Picker.match { [1]: integer, [2]: integer[], [3]: integer } item, positions, score
5---@alias artio.Picker.matches table<integer, artio.Picker.match> id: match
6---@alias artio.Picker.sorter fun(lst: artio.Picker.item[], input: string): artio.Picker.matches
7---@alias artio.Picker.hl [[integer, integer], string]
8---@alias artio.Picker.action fun(self: artio.Picker)
9
10---@class artio.Picker.config
11---@field items artio.Picker.item[]|string[]
12---@field fn artio.Picker.sorter
13---@field on_close fun(text: string, idx: integer)
14---@field get_items? fun(input: string): artio.Picker.item[]
15---@field format_item? fun(item: any): string
16---@field preview_item? fun(item: any):{buf?:integer, pos?:[integer,integer], pos_end?:[integer,integer]}
17---@field get_icon? fun(item: artio.Picker.item): string, string
18---@field hl_item? fun(item: artio.Picker.item): artio.Picker.hl[]
19---@field on_quit? fun()
20---@field live? boolean
21---@field prompt? string
22---@field defaulttext? string
23---@field prompttext? string
24---@field opts? artio.config.opts
25---@field win? artio.config.win
26---@field actions? table<string, artio.Picker.action>
27---@field mappings? table<string, 'up'|'down'|'accept'|'cancel'|'togglepreview'|string>
28
29---@class artio.Picker : artio.Picker.config
30---@field co thread?
31---@field thread function
32---@field input string
33---@field liveinput? string
34---@field idx integer 1-indexed
35---@field matches artio.Picker.match[]
36---@field marked table<integer, true|nil>
37---@field live boolean
38---@field opts artio.config.opts
39---@field win artio.config.win
40local Picker = {}
41Picker.__index = Picker
42
43---@type artio.Picker?
44Picker.active_picker = nil
45
46---@param props artio.Picker.config
47function Picker:new(props)
48  vim.validate("Picker.items", props.items, function(v)
49    if not v then
50      return props.get_items and type(props.get_items) == "function"
51    end
52    return type(v) == "table" and vim.islist(v)
53  end)
54  vim.validate("Picker:fn", props.fn, "function")
55  vim.validate("Picker:on_close", props.on_close, "function")
56
57  local t = vim.tbl_deep_extend("force", {
58    closed = false,
59    prompt = "",
60    input = nil,
61    liveinput = nil,
62    idx = 0,
63    matches = {},
64    marked = {},
65  }, require("artio.config").get(), props)
66
67  if not t.prompttext then
68    t.prompttext = t.opts.prompt_title and ("%s %s"):format(t.prompt, t.opts.promptprefix) or t.opts.promptprefix
69  end
70
71  t.live = vim.F.if_nil(t.live, t.get_items ~= nil)
72
73  if t.live then
74    t.input = ""
75    t.liveinput = t.defaulttext or ""
76  else
77    t.input = t.defaulttext or ""
78    t.liveinput = ""
79  end
80
81  return setmetatable(t, Picker)
82end
83
84---@enum artio.Picker.Action
85local action_enum = {
86  accept = 0,
87  cancel = 1,
88}
89
90function Picker:open()
91  local ui2 = require("vim._core.ui2")
92
93  if Picker.active_picker and Picker.active_picker ~= self then
94    Picker.active_picker:close(true)
95  end
96  Picker.active_picker = self
97
98  self.view = View:new(self)
99
100  ui2.check_targets()
101  self.thread = coroutine.wrap(function()
102    -- self:getitems("")
103    -- self.items = self.items or {}
104
105    self.view:open()
106
107    self:initkeymaps()
108
109    self.co = coroutine.running()
110
111    vim.api.nvim_exec_autocmds("User", { pattern = "ArtioEnter" })
112
113    local result = coroutine.yield()
114
115    self:close()
116
117    while true do
118      if result == action_enum.cancel or result ~= action_enum.accept then
119        if self.on_quit then
120          self.on_quit()
121        end
122        break
123      end
124
125      local current = self.matches[self.idx] and self.matches[self.idx][1]
126      if not current then
127        break
128      end
129
130      local item = self.items[current]
131      if item then
132        self.on_close(item.v, item.id)
133      end
134
135      break
136    end
137
138    vim.api.nvim_exec_autocmds("User", { pattern = "ArtioLeave" })
139  end)
140  self.thread()
141end
142
143function Picker:resume()
144  if not self.closed then
145    return
146  end
147  self.closed = false
148
149  self:open()
150end
151
152---@param free? boolean
153function Picker:close(free)
154  if self.closed then
155    return
156  end
157
158  if self.view then
159    self.view:close()
160  end
161
162  self:delkeymaps()
163
164  self.closed = true
165
166  if free then
167    self:free()
168  end
169end
170
171function Picker:free()
172  if self == nil then
173    return
174  end
175  self.items = nil
176  self.matches = nil
177  self.marked = nil
178  self = nil
179  vim.schedule(function()
180    collectgarbage("collect")
181  end)
182end
183
184function Picker:initkeymaps()
185  local ui2 = require("vim._core.ui2")
186
187  ---@type vim.keymap.set.Opts
188  local opts = { buf = ui2.bufs.cmd }
189
190  if self.actions then
191    vim.iter(pairs(self.actions)):each(function(k, v)
192      vim.keymap.set("i", ("<Plug>(artio-action-%s)"):format(k), v, opts)
193    end)
194  end
195  if self.mappings then
196    vim.iter(pairs(self.mappings)):each(function(k, v)
197      vim.keymap.set("i", k, ("<Plug>(artio-action-%s)"):format(v), opts)
198    end)
199  end
200end
201
202function Picker:delkeymaps()
203  local ui2 = require("vim._core.ui2")
204
205  local keymaps = vim.api.nvim_buf_get_keymap(ui2.bufs.cmd, "i")
206
207  vim.iter(ipairs(keymaps)):each(function(_, v)
208    if v.lhs:match("^<Plug>(artio-action-") or (v.rhs and v.rhs:match("^<Plug>(artio-action-")) then
209      vim.api.nvim_buf_del_keymap(ui2.bufs.cmd, "i", v.lhs)
210    end
211  end)
212end
213
214function Picker:accept()
215  self.thread(action_enum.accept)
216end
217
218function Picker:cancel()
219  self.thread(action_enum.cancel)
220end
221
222function Picker:fix()
223  self.idx = math.max(self.idx, self.opts.preselect and 1 or 0)
224  self.idx = math.min(self.idx, #self.matches)
225end
226
227local function item_is_structured(item)
228  return type(item) == "table" and item.id and item.v and item.text
229end
230
231function Picker:getitems(input)
232  if (self.items == nil or self.live) and self.get_items then
233    self.items = self.get_items(input)
234  end
235
236  if #self.items > 0 and not item_is_structured(self.items[1]) then
237    self.items = vim
238      .iter(ipairs(self.items))
239      :map(function(i, v)
240        local text
241        if self.format_item and vim.is_callable(self.format_item) then
242          text = self.format_item(v)
243        end
244
245        return {
246          id = i,
247          v = v,
248          text = text or v,
249        }
250      end)
251      :totable()
252  end
253end
254
255---@param input? string
256function Picker:getmatches(input)
257  assert(coroutine.running(), "Picker:getmatches needs to be called from a coroutine")
258
259  if not input then
260    input = self.live and self.liveinput or self.input
261  end
262  self:getitems(input)
263  assert(self.items ~= nil, "Picker.items cannot be nil after Picker:getitems")
264
265  -- if live, ignore sorting
266  if self.live then
267    self.matches = self:getallmatches()
268    return
269  end
270
271  self.matches = vim.tbl_values(self.fn(self.items, input))
272  table.sort(self.matches, function(a, b)
273    return a[3] > b[3]
274  end)
275end
276
277---@return artio.Picker.match[]
278function Picker:getallmatches()
279  return vim
280    .iter(ipairs(self.items))
281    :map(function(_, v)
282      return { v.id, {}, 0 }
283    end)
284    :totable()
285end
286
287---@param idx integer
288---@param yes? boolean
289function Picker:mark(idx, yes)
290  self.marked[idx] = yes == nil and true or yes
291end
292
293---@return integer[]
294function Picker:getmarked()
295  return vim
296    .iter(pairs(self.marked))
297    :map(function(k, v)
298      return v and k or nil
299    end)
300    :totable()
301end
302
303---@param idx? integer index in items
304---@return artio.Picker.item?
305function Picker:getcurrent(idx)
306  if not idx then
307    local i = self.idx
308    idx = self.matches[i] and self.matches[i][1]
309  end
310  if not idx then
311    return
312  end
313
314  return self.items[idx]
315end
316
317function Picker:togglelive()
318  -- check if live can be toggled
319  if not self.get_items then
320    return
321  end
322
323  -- reset fuzzy search when enabling live search
324  if not self.live then
325    self.input = ""
326  end
327  self.live = not self.live
328end
329
330return Picker