robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
8.3 KiB254 linesraw
1-- Nursery for random things that may later find their way into stdlib if they mature.
2
3local M = {}
4
5-- Generated from async.nvim/lua/async/_errors.lua: start
6local nil_error = 'error(nil)'
7
8--- Normalize a failed Lua operation for error slots where `nil` means success.
9--- @param err any
10--- @return any
11--- @private
12function M._normalize_error(err)
13  return err == nil and nil_error or err
14end
15
16--- Convert an error to a string without letting its metamethod interrupt cleanup.
17--- @param err any
18--- @return string
19--- @private
20function M._stringify_error(err)
21  local ok, message = pcall(tostring, err)
22  return ok and message or '<unprintable error>'
23end
24-- Generated from async.nvim/lua/async/_errors.lua: end
25
26--- Adds one or more blank lines above or below the cursor.
27--- @param above? boolean Place blank line(s) above the cursor
28local function add_blank(above)
29  local offset = above and 1 or 0
30  local repeated = vim.fn['repeat']({ '' }, vim.v.count1)
31  local linenr = vim.api.nvim_win_get_cursor(0)[1]
32  vim.api.nvim_buf_set_lines(0, linenr - offset, linenr - offset, true, repeated)
33end
34
35function M.space_above()
36  add_blank(true)
37end
38
39function M.space_below()
40  add_blank()
41end
42
43--- Gets a buffer by name
44--- @param name string
45--- @return integer?
46function M.get_buf_by_name(name)
47  for _, buf in ipairs(vim.api.nvim_list_bufs()) do
48    if vim.api.nvim_buf_get_name(buf) == name then
49      return buf
50    end
51  end
52end
53
54--- Edit a file in a specific window
55--- @param winnr integer
56--- @param file string
57--- @return number buffer number of the edited buffer
58M.edit_in = function(winnr, file)
59  --- @param path string?
60  local function resolved_path(path)
61    if not path or path == '' then
62      return ''
63    end
64    return vim.fn.resolve(vim.fs.abspath(path))
65  end
66
67  return vim.api.nvim_win_call(winnr, function()
68    local current_buf = vim.api.nvim_win_get_buf(winnr)
69    local current = resolved_path(vim.api.nvim_buf_get_name(current_buf))
70
71    -- Check if the current buffer is already the target file
72    if current == resolved_path(file) then
73      return current_buf
74    end
75
76    -- Read the file into the buffer
77    vim.cmd.edit(vim.fn.fnameescape(file))
78    return vim.api.nvim_get_current_buf()
79  end)
80end
81
82--- :edit, but it respects commands like :hor, :vert, :tab, etc.
83--- @param file string
84--- @param mods string|vim.api.keyset.cmd_mods Modifier string ("vertical") or structured mods table.
85function M.wrapped_edit(file, mods)
86  if type(mods) == 'string' then
87    mods = vim.api.nvim_parse_cmd(mods .. ' edit').mods
88  end
89  if (mods.tab or 0) > 0 or (mods.split or '') ~= '' or mods.horizontal or mods.vertical then
90    local buf = M.get_buf_by_name(file)
91    if buf == nil then
92      buf = vim.api.nvim_create_buf(true, false)
93    end
94    vim.cmd.sbuffer { buf, mods = mods }
95  end
96  vim.cmd.edit { file }
97end
98
99--- Read a chunk of data from a file
100--- @param file string
101--- @param size integer
102--- @return string? chunk or nil on error
103function M.read_chunk(file, size)
104  local fd = io.open(file, 'rb')
105  if not fd then
106    return nil
107  end
108  local chunk = fd:read(size)
109  fd:close()
110  return tostring(chunk)
111end
112
113--- Check if a range in a buffer is inside a Lua codeblock via treesitter injection.
114--- Used by :source to detect Lua code in non-Lua files (e.g., vimdoc).
115--- @param bufnr integer Buffer number
116--- @param line1 integer Start line (1-indexed)
117--- @param line2 integer End line (1-indexed)
118--- @return boolean True if the range is in a Lua injection
119function M.source_is_lua(bufnr, line1, line2)
120  local parser = vim.treesitter.get_parser(bufnr)
121  if not parser then
122    return false
123  end
124  -- Parse from buffer start through one line past line2 to include injection closing markers
125  local range = { line1 - 1, 0, line2 - 1, -1 }
126  parser:parse({ 0, 0, line2, -1 })
127  local lang_tree = parser:language_for_range(range)
128  return lang_tree:lang() == 'lua'
129end
130
131--- Returns the exit code string for the current buffer, given:
132--- - Channel is attached to the current buffer
133--- - Current buffer is a terminal buffer
134---
135--- @return string
136function M.term_exitcode()
137  local chan_id = vim.bo.channel
138  if chan_id == 0 or vim.bo.buftype ~= 'terminal' then
139    return ''
140  end
141
142  local info = vim.api.nvim_get_chan_info(chan_id)
143  if info.exitcode and info.exitcode >= 0 then
144    -- use non-breaking space to avoid fillchar
145    return string.format('[Exit:\226\128\175%d]', info.exitcode)
146  end
147  return ''
148end
149
150--- Compute a link to a target on a forge host
151--- @param repo string URL of repo, usually "https://<domain>/<user>/<name>"
152--- @param target string Identifier of a target, like commit hash or tag name
153--- @param target_type "commit"|"tag"
154--- @return string? # Example: <repo>/releases/tag/<target>
155function M.get_forge_url(repo, target, target_type)
156  -- The structure <host>/<middle>/<target> works for most forges. Like:
157  -- - https://github.com/neovim/nvim-lspconfig/commit/e146efa
158  -- - https://github.com/neovim/nvim-lspconfig/releases/tag/v2.8.0
159  local ref_middles = {
160    { pattern = '^https://github%.com/', commit = 'commit', tag = 'releases/tag' },
161    { pattern = '^https://gitlab%.com/', commit = '-/commit', tag = '-/tags' },
162    { pattern = '^https://git%.sr%.ht/', commit = 'commit', tag = 'refs' },
163    { pattern = '^https://tangled%.org/', commit = 'commit', tag = 'tags' },
164    { pattern = '^https://bitbucket%.org/', commit = 'commits', tag = 'src' },
165
166    -- Fall back to Forgejo style since there is no fixed host
167    { pattern = '^https://', commit = 'commit', tag = 'src/tag' },
168  }
169
170  local middle = ''
171  for _, mid in ipairs(ref_middles) do
172    if repo:match(mid.pattern) then
173      middle = mid[target_type]
174      if middle ~= '' then
175        break
176      end
177    end
178  end
179
180  if middle == '' then
181    return nil
182  end
183  repo = repo:gsub('/+$', '')
184  return ('%s/%s/%s'):format(repo, middle, target)
185end
186
187--- Gets a scrubbed message from a pcall'd command error (drops Lua context/traceback):
188--- "…/editor.lua:123: Vim(put):E484: xx" => "E484: xx"
189---
190--- @param err string
191--- @return string
192function M.cmd_errmsg(err)
193  err = err:match('^[^\n]*') or err
194  --- @type string
195  err = err:match('Vim%b():%s*(.*)') or err:match('Vim:%s*(.*)') or (err:gsub('^.-:%d+:%s*', ''))
196  return (err:gsub('^Lua:%s*', ''))
197end
198
199--- Display a Vim error code (EXX), or raise an error without editor APIs.
200--- @param msg string
201function M.echo_err(msg)
202  if not vim.api then
203    error(msg, 2)
204  end
205  vim.api.nvim_echo({ { msg } }, true, { err = true })
206end
207
208--- Shows a message from a builtin plugin, prefixed with the plugin name.
209---
210--- Scheduled, so it is safe to call from |api-fast| contexts.
211--- @param name string Plugin name, e.g. "zip".
212--- @param msg string
213--- @param level? integer Level from |vim.log.levels|. Defaults to ERROR.
214--- @param once? boolean Only show the message once.
215function M.notify(name, msg, level, once)
216  vim.schedule(function()
217    local notify = once and vim.notify_once or vim.notify
218    notify(('%s: %s'):format(name, msg), level or vim.log.levels.ERROR)
219  end)
220end
221
222--- Define event-handlers (autocmds) ergonomically.
223---
224--- Examples:
225--- ```lua
226---   local nvim_on = require('vim._core.util').nvim_on
227---   nvim_on('BufWritePost', group, function(ev) print(ev.file) end)
228---   nvim_on({ 'BufRead', 'BufNew' }, group, { pattern = '*.lua' }, function(ev) end)
229---   nvim_on('VimLeavePre', nil, function() end)
230--- ```
231---
232--- @param events vim.api.keyset.events|vim.api.keyset.events[] Event(s) to watch. See |autocmd-events|.
233--- @param group string|integer? Group name or id, or `nil`.
234--- @param opts_or_fn vim.api.keyset.create_autocmd Options.
235--- @param fn fun(ev: vim.api.keyset.create_autocmd.callback_args): boolean? Event handler.
236--- @return integer # Autocmd id (see |nvim_create_autocmd()|).
237--- @overload fun(events: vim.api.keyset.events|vim.api.keyset.events[], group: string|integer?, fn: fun(ev: vim.api.keyset.create_autocmd.callback_args): boolean?): integer
238function M.nvim_on(events, group, opts_or_fn, fn)
239  vim.validate('opts_or_fn', opts_or_fn, { 'function', 'table' })
240  local opts --- @type vim.api.keyset.create_autocmd
241  if type(opts_or_fn) == 'function' then
242    fn, opts = opts_or_fn, {}
243  else
244    opts = opts_or_fn
245  end
246  opts.group = group
247  if type(opts.group) == 'string' then
248    opts.group = vim.api.nvim_create_augroup(opts.group, { clear = false })
249  end
250  opts.callback = fn
251  return vim.api.nvim_create_autocmd(events, opts)
252end
253
254return M