robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local M =vim . _defer_require ( 'vim.ui' , { 2img =... , --- @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 ) 64vim . validate ( 'items' , items , 'table' ) 65vim . validate ( 'on_choice' , on_choice , 'function' ) 66opts =opts or {} 67local choices ={ opts . prompt or 'Select one of:' } 68local format_item =opts . format_item or tostring 69for i , item in 70ipairs ( items --[[@as any[] ]] ) 71do 72table . insert ( choices , string . format ( '%d: %s' , i , format_item ( item ))) 73end 74local choice =vim . fn . inputlist ( choices ) 75if choice < 1 or choice > # items then 76on_choice ( nil , nil ) 77else 78on_choice ( items [ choice ], choice ) 79end 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 ) 127vim . validate ( 'opts' , opts , 'table' , true ) 128vim . validate ( 'on_confirm' , on_confirm , 'function' ) 129 130opts =( 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. 134local _canceled =vim . NIL 135opts =vim . tbl_extend ( 'keep' , opts , { cancelreturn =_canceled } ) 136 137-- EmmyLua workaround: a direct call resolves the table overload correctly. 138local ok , input =pcall ( function () 139return vim . fn . input ( opts ) 140end ) 141if not ok or input == _canceled then 142on_confirm ( nil ) 143else 144on_confirm ( input ) 145end 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 ) 184vim . validate ( 'path' , path , 'string' ) 185local is_uri =path : match ( '%w+:' ) 186if not is_uri then 187path =vim . fs . normalize ( path ) 188end 189 190opt =opt or {} 191local cmd ---@type string[] 192local job_opt ={ text =true , detach =true } --- @type vim.SystemOpts 193 194if opt . cmd then 195cmd =vim . list_extend ( vim . list_slice ( opt . cmd ) --[[@as string[] ]] , { path } ) 196else 197local open_cmd , err =M . _get_open_cmd () 198if err then 199return nil , err 200end 201---@cast open_cmd string[] 202if open_cmd [ 1 ] == 'xdg-open' then 203job_opt . stdout =false 204job_opt . stderr =false 205elseif open_cmd [ 1 ] == 'cmd.exe' and is_uri then 206path =path : gsub ( '([&|<>^%%!])' , '^%1' ) -- Escape cmd.exe special chars. #41337 207end 208cmd =vim . list_extend ( open_cmd , { path } ) 209end 210 211return 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 () 219if vim . fn . has ( 'mac' ) == 1 then 220return { 'open' } , nil 221elseif vim . fn . has ( 'win32' ) == 1 then 222return { 'cmd.exe' , '/c' , 'start' , '' } , nil 223elseif vim . fn . executable ( 'xdg-open' ) == 1 then 224return { 'xdg-open' } , nil 225elseif vim . fn . executable ( 'wslview' ) == 1 then 226return { 'wslview' } , nil 227elseif vim . fn . executable ( 'explorer.exe' ) == 1 then 228return { 'explorer.exe' } , nil 229elseif vim . fn . executable ( 'lemonade' ) == 1 then 230return { 'lemonade' , 'open' } , nil 231else 232return nil , 'vim.ui.open: no handler found (tried: wslview, explorer.exe, xdg-open, lemonade)' 233end 234end 235 236--- @param bufnr integer 237local get_lsp_urls =function ( bufnr ) 238local has_lsp_support =false 239for _ , client in pairs ( vim . lsp . get_clients ( { bufnr =bufnr } )) do 240has_lsp_support =has_lsp_support or client : supports_method ( 'textDocument/documentLink' , bufnr ) 241end 242if not has_lsp_support then 243return {} 244end 245local params ={ textDocument =vim . lsp . util . make_text_document_params ( bufnr ) } 246local results =vim . lsp . buf_request_sync ( bufnr , 'textDocument/documentLink' , params ) 247 248local urls ={} 249for client_id , result in pairs ( results or {} ) do 250if result . error then 251vim . lsp . log . error ( result . error ) 252else 253local client =assert ( vim . lsp . get_client_by_id ( client_id )) 254local lsp_position =vim . lsp . util . make_position_params ( 0 , client . offset_encoding ). position 255local position =vim . pos . lsp ( bufnr , lsp_position , client . offset_encoding ) 256 257local document_links =result . result or {} ---@type lsp.DocumentLink[] 258for _ , document_link in ipairs ( document_links ) do 259local range =vim . range . lsp ( bufnr , document_link . range , client . offset_encoding ) 260if document_link . target and range : has ( position ) then 261local target =document_link . target ---@type string 262if vim . startswith ( target , 'file://' ) then 263target =vim . uri_to_fname ( target ) 264end 265table . insert ( urls , target ) 266end 267end 268end 269end 270return urls 271end 272 273--- Returns all URLs at cursor, if any. 274--- @return string[] 275function M . _get_urls () 276local urls ={} ---@type string[] 277 278local bufnr =vim . api . nvim_get_current_buf () 279local cursor =vim . api . nvim_win_get_cursor ( 0 ) 280local row =cursor [ 1 ] - 1 281local col =cursor [ 2 ] 282 283urls =vim . list_extend ( urls , get_lsp_urls ( bufnr )) 284 285local extmarks =vim . api . nvim_buf_get_extmarks ( bufnr , - 1 , { row , col } , { row , col } , { 286details =true , 287type ='highlight' , 288overlap =true , 289} ) 290for _ , v in ipairs ( extmarks ) do 291local details =v [ 4 ] 292if details and details . url then 293urls [ # urls + 1 ] =details . url 294end 295end 296 297local highlighter =vim . treesitter . highlighter . active [ bufnr ] 298if highlighter then 299local range ={ row , col , row , col } 300local ltree =highlighter . tree : language_for_range ( range ) 301local lang =ltree : lang () 302local query =vim . treesitter . query . get ( lang , 'highlights' ) 303if query then 304local tree =assert ( ltree : tree_for_range ( range )) 305for _ , match , metadata in query : iter_matches ( tree : root (), bufnr , row , row + 1 ) do 306for id , nodes in pairs ( match ) do 307for _ , node in ipairs ( nodes ) do 308if vim . treesitter . node_contains ( node , range ) then 309local url =metadata [ id ] and metadata [ id ]. url 310if url and match [ url ] then 311for _ , n in 312ipairs ( match [ url ] --[[@as TSNode[] ]] ) 313do 314urls [ # urls + 1 ] = 315vim . treesitter . get_node_text ( n , bufnr , { metadata =metadata [ url ] } ) 316end 317end 318end 319end 320end 321end 322end 323end 324 325if # urls == 0 then 326-- If all else fails, use the filename under the cursor 327table . insert ( 328urls , 329vim . _with ( { go ={ isfname =vim . o . isfname .. ',@-@' } } , function () 330return vim . fn . expand ( '<cfile>' ) 331end ) 332) 333end 334 335return 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> 342local progress ={} 343 344-- store progress events 345local progress_group , progress_autocmd =nil , nil 346 347--- Initialize Progress handlers. 348local function progress_init () 349progress_group =vim . api . nvim_create_augroup ( 'nvim.ui.progress_status' , { clear =true } ) 350progress_autocmd =require ( 'vim._core.util' ). nvim_on ( 'Progress' , progress_group , { 351desc ='Tracks progress messages for vim.ui.progress_status()' , 352} , function ( ev ) 353if not ev . data or not ev . data . id then 354return 355end 356--- @cast ev.data vim.event.progress.data 357ev . data . percent =ev . data . percent or 0 358progress [ ev . data . id ] =ev . data 359 360-- Clear finished items 361if 362ev . data . status == 'success' 363or ev . data . percent == 100 364or ev . data . status == 'failed' 365or ev . data . status == 'cancel' 366then 367progress [ ev . data . id ] =nil 368end 369end ) 370end 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 377local function progress_status_fmt ( running ) 378local count =# running 379if count == 0 then 380return '' -- nothing to show 381else 382local sum =0 ---@type integer 383for _ , progress_item in ipairs ( running ) do 384sum =sum + ( progress_item . percent or 0 ) 385end 386local avg =math . floor ( sum / count ) 387return string . format ( '%d%%(%d)' , avg , count ) 388end 389end 390 391--- Gets a status description summarizing currently running progress messages. 392--- Convenient for inclusion in 'statusline'. 393--- 394---@return string # Progress status 395function M . progress_status () 396if progress_autocmd == nil then 397progress_init () 398end 399 400local running =vim . tbl_values ( progress ) 401return progress_status_fmt ( running ) or '' 402end 403end 404 405return M