robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 13return 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 ) 21local ok , message =pcall ( tostring , err ) 22return 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 ) 29local offset =above and 1 or 0 30local repeated =vim . fn [ 'repeat' ]( { '' } , vim . v . count1 ) 31local linenr =vim . api . nvim_win_get_cursor ( 0 )[ 1 ] 32vim . api . nvim_buf_set_lines ( 0 , linenr - offset , linenr - offset , true , repeated ) 33end 34 35function M . space_above () 36add_blank ( true ) 37end 38 39function M . space_below () 40add_blank () 41end 42 43--- Gets a buffer by name 44--- @param name string 45--- @return integer? 46function M . get_buf_by_name ( name ) 47for _ , buf in ipairs ( vim . api . nvim_list_bufs ()) do 48if vim . api . nvim_buf_get_name ( buf ) == name then 49return buf 50end 51end 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? 60local function resolved_path ( path ) 61if not path or path == '' then 62return '' 63end 64return vim . fn . resolve ( vim . fs . abspath ( path )) 65end 66 67return vim . api . nvim_win_call ( winnr , function () 68local current_buf =vim . api . nvim_win_get_buf ( winnr ) 69local current =resolved_path ( vim . api . nvim_buf_get_name ( current_buf )) 70 71-- Check if the current buffer is already the target file 72if current == resolved_path ( file ) then 73return current_buf 74end 75 76-- Read the file into the buffer 77vim . cmd . edit ( vim . fn . fnameescape ( file )) 78return vim . api . nvim_get_current_buf () 79end ) 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 ) 86if type ( mods ) == 'string' then 87mods =vim . api . nvim_parse_cmd ( mods .. ' edit' ). mods 88end 89if ( mods . tab or 0 ) > 0 or ( mods . split or '' ) ~= '' or mods . horizontal or mods . vertical then 90local buf =M . get_buf_by_name ( file ) 91if buf == nil then 92buf =vim . api . nvim_create_buf ( true , false ) 93end 94vim . cmd . sbuffer { buf , mods =mods } 95end 96vim . 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 ) 104local fd =io . open ( file , 'rb' ) 105if not fd then 106return nil 107end 108local chunk =fd : read ( size ) 109fd : close () 110return 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 ) 120local parser =vim . treesitter . get_parser ( bufnr ) 121if not parser then 122return false 123end 124-- Parse from buffer start through one line past line2 to include injection closing markers 125local range ={ line1 - 1 , 0 , line2 - 1 , - 1 } 126parser : parse ( { 0 , 0 , line2 , - 1 } ) 127local lang_tree =parser : language_for_range ( range ) 128return 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 () 137local chan_id =vim . bo . channel 138if chan_id == 0 or vim . bo . buftype ~= 'terminal' then 139return '' 140end 141 142local info =vim . api . nvim_get_chan_info ( chan_id ) 143if info . exitcode and info . exitcode >= 0 then 144-- use non-breaking space to avoid fillchar 145return string . format ( '[Exit:\226\128\175%d]' , info . exitcode ) 146end 147return '' 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 159local 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 170local middle ='' 171for _ , mid in ipairs ( ref_middles ) do 172if repo : match ( mid . pattern ) then 173middle =mid [ target_type ] 174if middle ~= '' then 175break 176end 177end 178end 179 180if middle == '' then 181return nil 182end 183repo =repo : gsub ( '/+$' , '' ) 184return ( '%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 ) 193err =err : match ( '^[^\n]*' ) or err 194--- @type string 195err =err : match ( 'Vim%b():%s*(.*)' ) or err : match ( 'Vim:%s*(.*)' ) or ( err : gsub ( '^.-:%d+:%s*' , '' )) 196return ( 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 ) 202if not vim . api then 203error ( msg , 2 ) 204end 205vim . 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 ) 216vim . schedule ( function () 217local notify =once and vim . notify_once or vim . notify 218notify (( '%s: %s' ): format ( name , msg ), level or vim . log . levels . ERROR ) 219end ) 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 ) 239vim . validate ( 'opts_or_fn' , opts_or_fn , { 'function' , 'table' } ) 240local opts --- @type vim.api.keyset.create_autocmd 241if type ( opts_or_fn ) == 'function' then 242fn , opts =opts_or_fn , {} 243else 244opts =opts_or_fn 245end 246opts . group =group 247if type ( opts . group ) == 'string' then 248opts . group =vim . api . nvim_create_augroup ( opts . group , { clear =false } ) 249end 250opts . callback =fn 251return vim . api . nvim_create_autocmd ( events , opts ) 252end 253 254return M