robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
13.5 KiB405 linesraw
1local M = vim._defer_require('vim.ui', {
2  img = ..., --- @module 'vim.ui.img'
3})
4
5---@class vim.ui.select.Opts
6---@inlinedoc
7---
8--- Prompt text.
9--- (default: `"Select one of:"`)
10---@field prompt? string
11---
12--- Decides how to format items when displayed in the picker.
13--- (default: `tostring`)
14---@field format_item? fun(item: any):string
15---
16--- Decides how to preview an item by preparing a scratch buffer with the item details (including text, highlighting, etc.).
17--- When the picker decides to "preview" an item, it should call this function.
18--- Must return a table with these keys:
19---     - {buf}? (`integer`) Buffer containing the previewed item details, or nil if no preview should be shown.
20---     - {pos}? (`[integer, integer]`) Specifies the (1,0)-indexed cursor position in the preview buffer. If nil, should be treated as `{ 1, 0 }`.
21---     - {pos_end}? (`[integer, integer]`) Specifies the (1,0)-indexed (end-exclusive) end position of the preview range. If nil, no range is intended for a preview.
22---@field preview_item? fun(item: any):{buf?:integer, pos?:[integer,integer], pos_end?:[integer,integer]}
23---
24--- Arbitrary hint string indicating the item shape. The picker may wish to use this to infer the
25--- structure or semantics of `items`, or the context in which select() was called.
26---@field kind? string
27
28--- Prompts the user to pick from a list of items, allowing arbitrary (potentially asynchronous)
29--- work until `on_choice`. This is the standard "picker" interface, used by |z=|, |:tselect|, etc.
30---
31--- Plugins may override `vim.ui.select` to provide a custom picker; they are expected to call the
32--- `format_item` and `preview_item` handlers (if any) provided by the caller. They may also use the
33--- `kind` hint (if provided by the caller) to decide how to handle some items.
34---
35--- Note: the default `vim.ui.select` currently doesn't support preview.
36---
37--- Example:
38---
39--- ```lua
40--- vim.ui.select({ 'tabs', 'spaces' }, {
41---   prompt = 'Select tabs or spaces:',
42---   format_item = function(item)
43---     return ('I choose %s!'):format(item)
44---   end,
45---   preview_item = function(item)
46---     local lines = { 'This is ' .. vim.inspect(item) }
47---     local buf = vim.api.nvim_create_buf(false, true)
48---     vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
49---     vim.bo[buf].bufhidden = 'wipe'
50---     return { buf = buf }
51---   end,
52--- }, function(choice)
53---   vim.o.expandtab = choice == 'spaces'
54---   vim.print(('Selected "%s" => expandtab=%s'):format(choice, vim.o.expandtab))
55--- end)
56--- ```
57---
58---@generic T
59---@param items T[] Arbitrary items
60---@param opts vim.ui.select.Opts Options
61---@param on_choice fun(item: T|nil, idx: integer|nil) Called once the user made a choice.
62--- `idx` is the 1-based index of `item` within `items`, or `nil` if the user aborted the dialog.
63function M.select(items, opts, on_choice)
64  vim.validate('items', items, 'table')
65  vim.validate('on_choice', on_choice, 'function')
66  opts = opts or {}
67  local choices = { opts.prompt or 'Select one of:' }
68  local format_item = opts.format_item or tostring
69  for i, item in
70    ipairs(items --[[@as any[] ]])
71  do
72    table.insert(choices, string.format('%d: %s', i, format_item(item)))
73  end
74  local choice = vim.fn.inputlist(choices)
75  if choice < 1 or choice > #items then
76    on_choice(nil, nil)
77  else
78    on_choice(items[choice], choice)
79  end
80end
81
82---@class vim.ui.input.Opts
83---@inlinedoc
84---
85---Text of the prompt
86---@field prompt? string
87---
88---Default reply to the input
89---@field default? string
90---
91---Specifies type of completion supported
92---for input. Supported types are the same
93---that can be supplied to a user-defined
94---command using the "-complete=" argument.
95---See |:command-completion|
96---@field completion? string
97---
98---Function that will be used for highlighting
99---user inputs.
100---@field highlight? function
101---
102---Input scope, as in "This input is for something at cursor/line/etc scope".
103---Can be used by `vim.ui.input` implementations to tweak behavior and presentation.
104---For example, the input may adjust the floating window position: near the cursor if
105---`cursor`, in window corner if `buffer` or `window`, etc.
106---@field scope? 'cursor'|'line'|'buffer'|'window'|'tabpage'|'editor'|'project'
107
108--- Prompts the user for input, allowing arbitrary (potentially asynchronous) work until
109--- `on_confirm`.
110---
111--- Example:
112---
113--- ```lua
114--- local opts = { prompt = 'Enter value for shiftwidth: ', scope = 'buffer' }
115--- vim.ui.input(opts, function(input)
116---     vim.o.shiftwidth = tonumber(input)
117--- end)
118--- ```
119---
120---@param opts? vim.ui.input.Opts Additional options. See |input()|
121---@param on_confirm fun(input?: string)
122---               Called once the user confirms or abort the input.
123---               `input` is what the user typed (it might be
124---               an empty string if nothing was entered), or
125---               `nil` if the user aborted the dialog.
126function M.input(opts, on_confirm)
127  vim.validate('opts', opts, 'table', true)
128  vim.validate('on_confirm', on_confirm, 'function')
129
130  opts = (opts and not vim.tbl_isempty(opts)) and opts or vim.empty_dict()
131
132  -- Note that vim.fn.input({}) returns an empty string when cancelled.
133  -- vim.ui.input() should distinguish aborting from entering an empty string.
134  local _canceled = vim.NIL
135  opts = vim.tbl_extend('keep', opts, { cancelreturn = _canceled })
136
137  -- EmmyLua workaround: a direct call resolves the table overload correctly.
138  local ok, input = pcall(function()
139    return vim.fn.input(opts)
140  end)
141  if not ok or input == _canceled then
142    on_confirm(nil)
143  else
144    on_confirm(input)
145  end
146end
147
148---@class vim.ui.open.Opts
149---@inlinedoc
150---
151--- Command used to open the path or URL.
152---@field cmd? string[]
153
154--- Opens `path` with the system default handler (macOS `open`, Windows `explorer.exe`, Linux
155--- `xdg-open`, …), or returns (but does not show) an error message on failure.
156---
157--- Can also be invoked with `:Open`. [:Open]()
158---
159--- Expands "~/" and environment variables in filesystem paths.
160---
161--- Examples:
162---
163--- ```lua
164--- -- Asynchronous.
165--- vim.ui.open("https://neovim.io/")
166--- vim.ui.open("~/path/to/file")
167--- -- Use the "osurl" command to handle the path or URL.
168--- vim.ui.open("gh#neovim/neovim!29490", { cmd = { 'osurl' } })
169--- -- Synchronous (wait until the process exits).
170--- local cmd, err = vim.ui.open("$VIMRUNTIME")
171--- if cmd then
172---   cmd:wait()
173--- end
174--- ```
175---
176---@param path string Path or URL to open
177---@param opt? vim.ui.open.Opts Options
178---
179---@return vim.SystemObj|nil # Command object, or nil if not found.
180---@return nil|string # Error message on failure, or nil on success.
181---
182---@see |vim.system()|
183function M.open(path, opt)
184  vim.validate('path', path, 'string')
185  local is_uri = path:match('%w+:')
186  if not is_uri then
187    path = vim.fs.normalize(path)
188  end
189
190  opt = opt or {}
191  local cmd ---@type string[]
192  local job_opt = { text = true, detach = true } --- @type vim.SystemOpts
193
194  if opt.cmd then
195    cmd = vim.list_extend(vim.list_slice(opt.cmd) --[[@as string[] ]], { path })
196  else
197    local open_cmd, err = M._get_open_cmd()
198    if err then
199      return nil, err
200    end
201    ---@cast open_cmd string[]
202    if open_cmd[1] == 'xdg-open' then
203      job_opt.stdout = false
204      job_opt.stderr = false
205    elseif open_cmd[1] == 'cmd.exe' and is_uri then
206      path = path:gsub('([&|<>^%%!])', '^%1') -- Escape cmd.exe special chars. #41337
207    end
208    cmd = vim.list_extend(open_cmd, { path })
209  end
210
211  return vim.system(cmd, job_opt), nil
212end
213
214--- Get an available command used to open the path or URL.
215---
216--- @return string[]|nil # Command, or nil if not found.
217--- @return nil|string # Error message on failure, or nil on success.
218function M._get_open_cmd()
219  if vim.fn.has('mac') == 1 then
220    return { 'open' }, nil
221  elseif vim.fn.has('win32') == 1 then
222    return { 'cmd.exe', '/c', 'start', '' }, nil
223  elseif vim.fn.executable('xdg-open') == 1 then
224    return { 'xdg-open' }, nil
225  elseif vim.fn.executable('wslview') == 1 then
226    return { 'wslview' }, nil
227  elseif vim.fn.executable('explorer.exe') == 1 then
228    return { 'explorer.exe' }, nil
229  elseif vim.fn.executable('lemonade') == 1 then
230    return { 'lemonade', 'open' }, nil
231  else
232    return nil, 'vim.ui.open: no handler found (tried: wslview, explorer.exe, xdg-open, lemonade)'
233  end
234end
235
236--- @param bufnr integer
237local get_lsp_urls = function(bufnr)
238  local has_lsp_support = false
239  for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do
240    has_lsp_support = has_lsp_support or client:supports_method('textDocument/documentLink', bufnr)
241  end
242  if not has_lsp_support then
243    return {}
244  end
245  local params = { textDocument = vim.lsp.util.make_text_document_params(bufnr) }
246  local results = vim.lsp.buf_request_sync(bufnr, 'textDocument/documentLink', params)
247
248  local urls = {}
249  for client_id, result in pairs(results or {}) do
250    if result.error then
251      vim.lsp.log.error(result.error)
252    else
253      local client = assert(vim.lsp.get_client_by_id(client_id))
254      local lsp_position = vim.lsp.util.make_position_params(0, client.offset_encoding).position
255      local position = vim.pos.lsp(bufnr, lsp_position, client.offset_encoding)
256
257      local document_links = result.result or {} ---@type lsp.DocumentLink[]
258      for _, document_link in ipairs(document_links) do
259        local range = vim.range.lsp(bufnr, document_link.range, client.offset_encoding)
260        if document_link.target and range:has(position) then
261          local target = document_link.target ---@type string
262          if vim.startswith(target, 'file://') then
263            target = vim.uri_to_fname(target)
264          end
265          table.insert(urls, target)
266        end
267      end
268    end
269  end
270  return urls
271end
272
273--- Returns all URLs at cursor, if any.
274--- @return string[]
275function M._get_urls()
276  local urls = {} ---@type string[]
277
278  local bufnr = vim.api.nvim_get_current_buf()
279  local cursor = vim.api.nvim_win_get_cursor(0)
280  local row = cursor[1] - 1
281  local col = cursor[2]
282
283  urls = vim.list_extend(urls, get_lsp_urls(bufnr))
284
285  local extmarks = vim.api.nvim_buf_get_extmarks(bufnr, -1, { row, col }, { row, col }, {
286    details = true,
287    type = 'highlight',
288    overlap = true,
289  })
290  for _, v in ipairs(extmarks) do
291    local details = v[4]
292    if details and details.url then
293      urls[#urls + 1] = details.url
294    end
295  end
296
297  local highlighter = vim.treesitter.highlighter.active[bufnr]
298  if highlighter then
299    local range = { row, col, row, col }
300    local ltree = highlighter.tree:language_for_range(range)
301    local lang = ltree:lang()
302    local query = vim.treesitter.query.get(lang, 'highlights')
303    if query then
304      local tree = assert(ltree:tree_for_range(range))
305      for _, match, metadata in query:iter_matches(tree:root(), bufnr, row, row + 1) do
306        for id, nodes in pairs(match) do
307          for _, node in ipairs(nodes) do
308            if vim.treesitter.node_contains(node, range) then
309              local url = metadata[id] and metadata[id].url
310              if url and match[url] then
311                for _, n in
312                  ipairs(match[url] --[[@as TSNode[] ]])
313                do
314                  urls[#urls + 1] =
315                    vim.treesitter.get_node_text(n, bufnr, { metadata = metadata[url] })
316                end
317              end
318            end
319          end
320        end
321      end
322    end
323  end
324
325  if #urls == 0 then
326    -- If all else fails, use the filename under the cursor
327    table.insert(
328      urls,
329      vim._with({ go = { isfname = vim.o.isfname .. ',@-@' } }, function()
330        return vim.fn.expand('<cfile>')
331      end)
332    )
333  end
334
335  return urls
336end
337
338do
339  --- Cache of active progress messages, keyed by msg_id
340  --- TODO(justinmk): visibility of "stale" (never-finished) Progress. https://github.com/neovim/neovim/pull/35428#discussion_r2942696157
341  ---@type table<integer, vim.event.progress.data>
342  local progress = {}
343
344  -- store progress events
345  local progress_group, progress_autocmd = nil, nil
346
347  --- Initialize Progress handlers.
348  local function progress_init()
349    progress_group = vim.api.nvim_create_augroup('nvim.ui.progress_status', { clear = true })
350    progress_autocmd = require('vim._core.util').nvim_on('Progress', progress_group, {
351      desc = 'Tracks progress messages for vim.ui.progress_status()',
352    }, function(ev)
353      if not ev.data or not ev.data.id then
354        return
355      end
356      --- @cast ev.data vim.event.progress.data
357      ev.data.percent = ev.data.percent or 0
358      progress[ev.data.id] = ev.data
359
360      -- Clear finished items
361      if
362        ev.data.status == 'success'
363        or ev.data.percent == 100
364        or ev.data.status == 'failed'
365        or ev.data.status == 'cancel'
366      then
367        progress[ev.data.id] = nil
368      end
369    end)
370  end
371
372  --- Gets a status description summarizing currently running progress messages.
373  --- - If none: returns empty string
374  --- - If N item running: "AVG%(N)"
375  ---@param running vim.event.progress.data[]
376  ---@return string
377  local function progress_status_fmt(running)
378    local count = #running
379    if count == 0 then
380      return '' -- nothing to show
381    else
382      local sum = 0 ---@type integer
383      for _, progress_item in ipairs(running) do
384        sum = sum + (progress_item.percent or 0)
385      end
386      local avg = math.floor(sum / count)
387      return string.format('%d%%(%d)', avg, count)
388    end
389  end
390
391  --- Gets a status description summarizing currently running progress messages.
392  --- Convenient for inclusion in 'statusline'.
393  ---
394  ---@return string # Progress status
395  function M.progress_status()
396    if progress_autocmd == nil then
397      progress_init()
398    end
399
400    local running = vim.tbl_values(progress)
401    return progress_status_fmt(running) or ''
402  end
403end
404
405return M