robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief 2--- The `vim.lsp.buf_…` functions perform operations for LSP clients attached to the current buffer. 3 4local api =vim . api 5local nvim_on =require ( 'vim._core.util' ). nvim_on 6local lsp =vim . lsp 7local validate =vim . validate 8local util =require ( 'vim.lsp.util' ) 9local npcall =vim . npcall 10local Range =require ( 'vim.treesitter._range' ) 11 12local M ={} 13 14--- @param params? table 15--- @return fun(client: vim.lsp.Client): lsp.TextDocumentPositionParams 16local function client_positional_params ( params ) 17local win =api . nvim_get_current_win () 18return function ( client ) 19local ret =util . make_position_params ( win , client . offset_encoding ) 20if params then 21ret =vim . tbl_extend ( 'force' , ret , params ) 22end 23return ret 24end 25end 26 27local hover_ns =api . nvim_create_namespace ( 'nvim.lsp.hover_range' ) 28local rename_ns =api . nvim_create_namespace ( 'nvim.lsp.rename_range' ) 29 30--- Returns false if the LSP response is stale and should be discarded. 31--- @param ctx lsp.HandlerContext 32--- @return boolean 33local function ctx_is_valid ( ctx ) 34local bufnr =ctx . bufnr 35if 36not bufnr 37or not api . nvim_buf_is_valid ( bufnr ) 38or api . nvim_get_current_buf () ~= bufnr 39or lsp . util . buf_versions [ bufnr ] ~= ctx . version 40then 41return false 42end 43---@type lsp.Position? 44local p =ctx . params and ctx . params . position 45if not p then 46return true 47end 48 49local c =lsp . get_client_by_id ( ctx . client_id ) 50local enc =c and c . offset_encoding 51if not enc then 52return false 53end 54 55local cur_pos =vim . pos . cursor ( 0 ) 56local pos =vim . pos . lsp ( bufnr , p , enc ) 57return cur_pos == pos 58end 59 60--- @class vim.lsp.buf.hover.Opts : vim.lsp.util.open_floating_preview.Opts 61--- @field silent? boolean 62 63--- Displays hover information about the symbol under the cursor in a floating 64--- window. The window will be dismissed on cursor move. 65--- Calling the function twice will jump into the floating window 66--- (thus by default, "KK" will open the hover window and focus it). 67--- In the floating window, all commands and mappings are available as usual, 68--- except that "q" dismisses the window. 69--- You can scroll the contents the same as you would any other buffer. 70--- 71--- Note: to disable hover highlights, add the following to your config: 72--- 73--- ```lua 74--- vim.api.nvim_create_autocmd('ColorScheme', { 75--- callback = function() 76--- vim.api.nvim_set_hl(0, 'LspReferenceTarget', {}) 77--- end, 78--- }) 79--- ``` 80--- @param config? vim.lsp.buf.hover.Opts 81function M . hover ( config ) 82validate ( 'config' , config , 'table' , true ) 83 84config =config or {} 85config . focus_id ='textDocument/hover' 86 87lsp . buf_request_all ( 0 , 'textDocument/hover' , client_positional_params (), function ( results , ctx ) 88local bufnr =ctx . bufnr 89if not bufnr or not ctx_is_valid ( ctx ) then 90return -- Ignore result if context changed. Can happen for slow LS. 91end 92 93-- Filter errors from results 94local results1 ={} --- @type table<integer,lsp.Hover> 95local nresults =0 96local empty_response =false 97 98for client_id , resp in pairs ( results ) do 99local err , result =resp . err , resp . result 100if err then 101lsp . log . error ( err . code , err . message ) 102elseif result and result . contents then 103-- Make sure the response is not empty 104-- Five response shapes: 105-- - MarkupContent: { kind="markdown", value="doc" } 106-- - MarkedString-string: "doc" 107-- - MarkedString-pair: { language="c", value="doc" } 108-- - MarkedString[]-string: { "doc1", ... } 109-- - MarkedString[]-pair: { { language="c", value="doc1" }, ... } 110local valid =false 111if type ( result . contents ) == 'table' then 112local value_len =# ( 113vim . tbl_get ( result . contents , 'value' ) -- MarkupContent or MarkedString-pair 114or vim . tbl_get ( result . contents , 1 , 'value' ) -- MarkedString[]-pair 115or result . contents [ 1 ] -- MarkedString[]-string 116or '' 117) 118valid =value_len > 0 119elseif type ( result . contents ) == 'string' then 120valid =# result . contents > 0 121end 122 123if valid then 124results1 [ client_id ] =result 125nresults =nresults + 1 126else 127empty_response =true 128end 129end 130end 131 132if nresults == 0 then 133if config . silent ~= true then 134if empty_response then 135vim . notify ( 'Empty hover response' , vim . log . levels . INFO ) 136else 137vim . notify ( 'No information available' , vim . log . levels . INFO ) 138end 139end 140return 141end 142 143local contents ={} --- @type string[] 144local MarkupKind =lsp . protocol . MarkupKind 145local format =MarkupKind . Markdown 146 147for client_id , result in pairs ( results1 ) do 148local client =assert ( lsp . get_client_by_id ( client_id )) 149if nresults > 1 then 150-- Show client name if there are multiple clients 151contents [ # contents + 1 ] =string . format ( '# %s' , client . name ) 152end 153 154if type ( result . contents ) == 'table' and result . contents . kind == MarkupKind . PlainText then 155if nresults == 1 then 156-- Only one client: use PlainText format 157format =MarkupKind . PlainText 158contents =vim . split ( result . contents . value or '' , '\n' , { trimempty =true } ) 159else 160-- Multiple clients: surround plaintext with ``` to get correct formatting 161contents [ # contents + 1 ] ='```' 162vim . list_extend ( 163contents , 164vim . split ( result . contents . value or '' , '\n' , { trimempty =true } ) 165) 166contents [ # contents + 1 ] ='```' 167end 168else 169vim . list_extend ( contents , util . convert_input_to_markdown_lines ( result . contents )) 170end 171if result . range then 172local range =vim . range . lsp ( bufnr , result . range , client . offset_encoding ) 173 174vim . hl . range ( 175bufnr , 176hover_ns , 177'LspReferenceTarget' , 178{ range . start_row , range . start_col } , 179{ range . end_row , range . end_col } , 180{ priority =vim . hl . priorities . user } 181) 182end 183contents [ # contents + 1 ] ='---' 184end 185 186-- Remove last linebreak ('---') if contents is not empty 187if # contents > 0 then 188contents [ # contents ] =nil 189end 190 191local _ , winid =lsp . util . open_floating_preview ( contents , format , config ) 192 193nvim_on ( 'WinClosed' , nil , { pattern =tostring ( winid ), once =true } , function () 194api . nvim_buf_clear_namespace ( bufnr , hover_ns , 0 , - 1 ) 195return true 196end ) 197end ) 198end 199 200--- @param name vim.lsp.protocol.Method.ClientToServer.Request 201--- @param params lsp.DocumentSymbolParams|lsp.WorkspaceSymbolParams 202--- @param opts? vim.lsp.ListOpts 203local function request_with_opts ( name , params , opts ) 204local req_handler --- @type function? 205if opts then 206--- @param err lsp.ResponseError? 207--- @param result lsp.DocumentSymbol[]|lsp.SymbolInformation[]|lsp.WorkspaceSymbol[]|nil 208--- @param ctx lsp.HandlerContext 209--- @param config? vim.lsp.ListOpts 210req_handler =function ( err , result , ctx , config ) 211local client =assert ( lsp . get_client_by_id ( ctx . client_id )) 212local handler =client . handlers [ name ] or lsp . handlers [ name ] 213handler ( err , result , ctx , vim . tbl_extend ( 'force' , config or {} , opts )) 214end 215end 216lsp . buf_request ( 0 , name , params , req_handler ) 217end 218 219---@param method vim.lsp.protocol.Method.ClientToServer.Request 220---@param context? lsp.ReferenceContext 221---@param opts? vim.lsp.ListOpts 222local function get_locations ( method , context , opts ) 223opts =opts or {} 224---@diagnostic disable-next-line: undefined-field 225if opts . reuse_win then 226vim . deprecate ( 227'vim.lsp.buf.<method>({ reuse_win = true })' , 228"vim.lsp.buf.<method>() and the value of 'switchbuf' of preference" , 229'0.13' 230) 231end 232 233local pos =opts . pos or vim . pos . cursor ( 0 ) 234local buf =pos . buf 235 236local clients =lsp . get_clients ( { method =method , bufnr =buf } ) 237if not next ( clients ) then 238vim . notify ( lsp . _unsupported_method ( method ), vim . log . levels . WARN ) 239return 240end 241 242local from =vim . fn . getpos ( '.' ) 243from [ 1 ] =buf 244local tagname =vim . fn . expand ( '<cword>' ) 245 246lsp . buf_request_all ( buf , method , function ( client ) 247---@type lsp.TextDocumentPositionParams 248local params ={ 249textDocument =util . make_text_document_params ( buf ), 250position =pos : to_lsp ( client . offset_encoding ), 251} 252if method == 'textDocument/references' then 253---@cast params lsp.ReferenceParams 254params . context =context or { includeDeclaration =true } 255end 256return params 257end , function ( results ) 258---@type vim.quickfix.entry[] 259local all_items ={} 260 261for client_id , res in pairs ( results ) do 262local client =assert ( lsp . get_client_by_id ( client_id )) 263local locations ={} 264if res then 265locations =vim . islist ( res . result ) and res . result or { res . result } 266end 267local items =util . locations_to_items ( locations , client . offset_encoding ) 268vim . list_extend ( all_items , items ) 269end 270 271local name =string . gsub ( assert ( method : match ( 'textDocument/(.*)' )), '(%u)' , ' %1' ): lower () 272if vim . tbl_isempty ( all_items ) then 273vim . notify (( 'No %s found' ): format ( name ), vim . log . levels . INFO ) 274return 275end 276 277---@type vim.fn.setqflist.what 278local what ={ 279title =name : gsub ( '^%l' , string . upper ), 280items =all_items , 281context ={ bufnr =buf , method =method } , 282} 283if opts . on_list then 284validate ( 'opts.on_list' , opts . on_list , 'function' ) 285opts . on_list ( what ) 286else 287if opts . loclist then 288vim . fn . setloclist ( 0 , {} , ' ' , what ) 289else 290vim . fn . setqflist ( {} , ' ' , what ) 291end 292 293if 294# all_items == 1 295and method ~= 'textDocument/implementation' 296and method ~= 'textDocument/references' 297then 298local tagstack ={ { tagname =tagname , from =from } } 299vim . fn . settagstack ( vim . fn . bufwinid ( buf ), { items =tagstack } , 't' ) 300if opts . loclist then 301vim . cmd ( 'lfirst' ) 302else 303vim . cmd ( 'cfirst' ) 304end 305else 306if opts . loclist then 307vim . cmd ( 'botright lopen' ) 308else 309vim . cmd ( 'botright copen' ) 310end 311end 312end 313end ) 314end 315 316--- @class vim.lsp.ListOpts 317--- 318--- list-handler replacing the default handler. 319--- Called for any non-empty result. 320--- The default handler populates the quickfix (or location) list with the result. 321--- If there is a single result (and the method is not `implementation` or `references`), 322--- it pushes a tag onto the tagstack and jumps to the result. 323--- For example, when `loclist == false` (the default), the handler is equivalent to: 324--- ```lua 325--- local function on_list(what) 326--- vim.fn.setqflist({}, ' ', what) 327--- if 328--- #what.items == 1 329--- and what.context.method ~= 'textDocument/implementation' 330--- and what.context.method ~= 'textDocument/references' 331--- then 332--- local tagstack = { { tagname = tagname, from = from } } 333--- vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't') 334--- vim.cmd('cfirst') 335--- else 336--- vim.cmd('botright copen') 337--- end 338--- end 339--- 340--- vim.lsp.buf.definition({ on_list = on_list }) 341--- vim.lsp.buf.references(nil, { on_list = on_list }) 342--- ``` 343--- The list can be transformed before it is shown. For example, to remove 344--- duplicate locations returned by multiple clients: 345--- ```lua 346--- local function on_list(what) 347--- vim.list.unique(what.items, function(item) 348--- return ('%s\0%d\0%d\0%d\0%d'):format( 349--- item.filename or '', 350--- item.lnum or 0, 351--- item.col or 0, 352--- item.end_lnum or 0, 353--- item.end_col or 0 354--- ) 355--- end) 356--- vim.fn.setqflist({}, ' ', what) 357--- vim.cmd('botright copen') 358--- end 359--- 360--- vim.lsp.buf.definition({ on_list = on_list }) 361--- vim.lsp.buf.references(nil, { on_list = on_list }) 362--- ``` 363--- See |setqflist-what| for the structure of the `what` parameter. 364--- @field on_list? fun(what: vim.fn.setqflist.what) 365--- 366--- Whether to use the |location-list| or the |quickfix| list in the default handler. 367--- ```lua 368--- vim.lsp.buf.definition({ loclist = true }) 369--- vim.lsp.buf.references(nil, { loclist = false }) 370--- ``` 371--- @field loclist? boolean 372--- 373--- Position on a buffer to request. 374--- (default: cursor position) 375--- @field pos? vim.Pos 376 377--- Jumps to the declaration of the symbol under the cursor. 378--- @note Many servers do not implement this method. Generally, see |vim.lsp.buf.definition()| instead. 379--- @param opts? vim.lsp.ListOpts 380function M . declaration ( opts ) 381validate ( 'opts' , opts , 'table' , true ) 382get_locations ( 'textDocument/declaration' , nil , opts ) 383end 384 385--- Jumps to the definition of the symbol under the cursor. 386--- @param opts? vim.lsp.ListOpts 387function M . definition ( opts ) 388validate ( 'opts' , opts , 'table' , true ) 389get_locations ( 'textDocument/definition' , nil , opts ) 390end 391 392--- Jumps to the definition of the type of the symbol under the cursor. 393--- @param opts? vim.lsp.ListOpts 394function M . type_definition ( opts ) 395validate ( 'opts' , opts , 'table' , true ) 396get_locations ( 'textDocument/typeDefinition' , nil , opts ) 397end 398 399--- Lists all the implementations for the symbol under the cursor in the 400--- quickfix window. 401--- @param opts? vim.lsp.ListOpts 402function M . implementation ( opts ) 403validate ( 'opts' , opts , 'table' , true ) 404get_locations ( 'textDocument/implementation' , nil , opts ) 405end 406 407--- @param results table<integer,{err: lsp.ResponseError?, result: lsp.SignatureHelp?}> 408local function process_signature_help_results ( results ) 409local signatures ={} --- @type [vim.lsp.Client,lsp.SignatureInformation][] 410local active_signature =1 411 412-- Pre-process results 413for client_id , r in pairs ( results ) do 414local err =r . err 415local client =assert ( lsp . get_client_by_id ( client_id )) 416if err then 417vim . notify ( 418client . name .. ': ' .. tostring ( err . code ) .. ': ' .. err . message , 419vim . log . levels . ERROR 420) 421api . nvim_command ( 'redraw' ) 422else 423local result =r . result 424if result and result . signatures then 425for i , sig in ipairs ( result . signatures ) do 426sig . activeParameter =sig . activeParameter or result . activeParameter 427local idx =# signatures + 1 428if ( result . activeSignature or 0 ) + 1 == i then 429active_signature =idx 430end 431signatures [ idx ] ={ client , sig } 432end 433end 434end 435end 436 437return signatures , active_signature 438end 439 440local sig_help_ns =api . nvim_create_namespace ( 'nvim.lsp.signature_help' ) 441 442--- @class vim.lsp.buf.signature_help.Opts : vim.lsp.util.open_floating_preview.Opts 443--- @field silent? boolean 444 445--- Displays signature information about the symbol under the cursor in a 446--- floating window. Allows cycling through signature overloads with `<C-s>`, 447--- which can be remapped via `<Plug>(nvim.lsp.ctrl-s)` 448--- 449--- Example: 450--- 451--- ```lua 452--- vim.keymap.set('n', '<C-b>', '<Plug>(nvim.lsp.ctrl-s)') 453--- ``` 454--- 455--- @param config? vim.lsp.buf.signature_help.Opts 456function M . signature_help ( config ) 457validate ( 'config' , config , 'table' , true ) 458 459local method ='textDocument/signatureHelp' 460 461config =config and vim . deepcopy ( config ) or {} 462config . focus_id =method 463local user_title =config . title 464 465lsp . buf_request_all ( 0 , method , client_positional_params (), function ( results , ctx ) 466if not ctx_is_valid ( ctx ) then 467return -- Ignore result if context changed. Can happen for slow LS. 468end 469 470local signatures , active_signature =process_signature_help_results ( results ) 471 472if not next ( signatures ) then 473if config . silent ~= true then 474vim . notify ( 'No signature help available' , vim . log . levels . INFO ) 475end 476return 477end 478 479local ft =vim . bo [ assert ( ctx . bufnr )]. filetype 480local total =# signatures 481local can_cycle =total > 1 and config . focusable ~= false 482local idx =active_signature - 1 483 484--- @param update_win? integer 485local function show_signature ( update_win ) 486idx =( idx % total ) + 1 487local signature =assert ( signatures [ idx ]) 488local client , result =signature [ 1 ], signature [ 2 ] 489--- @type string[]? 490local triggers = 491vim . tbl_get ( client . server_capabilities , 'signatureHelpProvider' , 'triggerCharacters' ) 492local lines , hl = 493util . convert_signature_help_to_markdown_lines ( { signatures ={ result } } , ft , triggers ) 494if not lines then 495return 496end 497 498-- Show title only if there are multiple clients or multiple signatures. 499if total > 1 then 500local sfx =total > 1 501and string . format ( ' (%d/%d)%s' , idx , total , can_cycle and ' (<C-s> to cycle)' or '' ) 502or '' 503config . title =user_title or string . format ( 'Signature Help: %s%s' , client . name , sfx ) 504-- If no border is set, render title inside the window. 505if not ( config . border or vim . o . winborder ~= '' ) then 506table . insert ( lines , 1 , '# ' .. config . title ) 507if hl then 508hl [ 1 ] =hl [ 1 ] + 1 509hl [ 3 ] =hl [ 3 ] + 1 510end 511end 512end 513 514config . _update_win =update_win 515 516local buf , win =util . open_floating_preview ( lines , 'markdown' , config ) 517 518if hl then 519api . nvim_buf_clear_namespace ( buf , sig_help_ns , 0 , - 1 ) 520vim . hl . range ( 521buf , 522sig_help_ns , 523'LspSignatureActiveParameter' , 524{ hl [ 1 ], hl [ 2 ] } , 525{ hl [ 3 ], hl [ 4 ] } 526) 527end 528return buf , win 529end 530 531local fbuf , fwin =show_signature () 532 533if can_cycle then 534vim . keymap . set ( 'n' , '<Plug>(nvim.lsp.ctrl-s)' , function () 535show_signature ( fwin ) 536end , { 537buf =fbuf , 538desc ='Cycle next signature' , 539} ) 540if vim . fn . hasmapto ( '<Plug>(nvim.lsp.ctrl-s)' , 'n' ) == 0 then 541vim . keymap . set ( 'n' , '<C-s>' , '<Plug>(nvim.lsp.ctrl-s)' , { 542buf =fbuf , 543desc ='Cycle next signature' , 544} ) 545end 546end 547end ) 548end 549 550---@param bufnr integer 551---@param mode "v"|"V" 552---@return {start: [integer,integer], end: [integer,integer]} using (1, 0) indexing 553local function range_from_selection ( bufnr , mode ) 554-- TODO: Use `vim.fn.getregionpos()` instead. 555 556-- [bufnum, lnum, col, off]; both row and column 1-indexed 557local start =vim . fn . getpos ( 'v' ) 558local end_ =vim . fn . getpos ( '.' ) 559local start_row =start [ 2 ] 560local start_col =start [ 3 ] 561local end_row =end_ [ 2 ] 562local end_col =end_ [ 3 ] 563 564-- A user can start visual selection at the end and move backwards 565-- Normalize the range to start < end 566if start_row == end_row and end_col < start_col then 567end_col , start_col =start_col , end_col --- @type integer, integer 568elseif end_row < start_row then 569start_row , end_row =end_row , start_row --- @type integer, integer 570start_col , end_col =end_col , start_col --- @type integer, integer 571end 572if mode == 'V' then 573start_col =1 574local lines =api . nvim_buf_get_lines ( bufnr , end_row - 1 , end_row , true ) 575end_col =# lines [ 1 ] 576end 577return { 578[ 'start' ] ={ start_row , start_col - 1 } , 579[ 'end' ] ={ end_row , end_col - 1 } , 580} 581end 582 583--- @class vim.lsp.buf.format.Opts 584--- @inlinedoc 585--- 586--- Can be used to specify FormattingOptions. Some unspecified options will be 587--- automatically derived from the current Nvim options. 588--- See https://microsoft.github.io/language-server-protocol/specification/#formattingOptions 589--- @field formatting_options? lsp.FormattingOptions 590--- 591--- Time in milliseconds allowed for each formatting request. On timeout, cancels 592--- the request and continues with the next client. With async=true, there is no 593--- timeout unless this option is set. Responses received after the request times 594--- out are ignored. 595--- (default: `1000` for synchronous requests) 596--- @field timeout_ms? integer 597--- 598--- Restrict formatting to the clients attached to the given buffer. 599--- (default: current buffer) 600--- @field bufnr? integer 601--- 602--- Predicate used to filter clients. Receives a client as argument and must 603--- return a boolean. Clients matching the predicate are included. Example: 604--- ```lua 605--- -- Never request typescript-language-server for formatting 606--- vim.lsp.buf.format { 607--- filter = function(client) return client.name ~= "ts_ls" end 608--- } 609--- ``` 610--- @field filter? fun(client: vim.lsp.Client): boolean? 611--- 612--- If true the method won't block. 613--- Editing the buffer while formatting asynchronous can lead to unexpected 614--- changes. 615--- (Default: false) 616--- @field async? boolean 617--- 618--- Restrict formatting to the client with ID (client.id) matching this field. 619--- @field id? integer 620--- 621--- Restrict formatting to the client with name (client.name) matching this field. 622--- @field name? string 623--- 624--- Range to format. 625--- Table must contain `start` and `end` keys with {row,col} tuples using 626--- (1,0) indexing. The end column can be -1 to format through the end of the line. 627--- Can also be a list of tables that contain `start` and `end` keys as described above, 628--- in which case `textDocument/rangesFormatting` support is required. 629--- (Default: current selection in visual mode, `nil` in other modes, 630--- formatting the full buffer) 631--- @field range? {start:[integer,integer],end:[integer, integer]}|{start:[integer,integer],end:[integer,integer]}[] 632 633--- Formats a buffer using the attached (and optionally filtered) language 634--- server clients. 635--- 636--- @param opts? vim.lsp.buf.format.Opts 637function M . format ( opts ) 638validate ( 'opts' , opts , 'table' , true ) 639 640opts =opts or {} 641local bufnr =vim . _resolve_bufnr ( opts . bufnr ) 642local mode =api . nvim_get_mode (). mode 643local range =opts . range 644-- Try to use visual selection if no range is given 645if not range and ( mode == 'v' or mode == 'V' ) then 646range =range_from_selection ( bufnr , mode ) 647end 648 649local passed_multiple_ranges =( range and # range ~= 0 and type ( range [ 1 ]) == 'table' ) 650local method ---@type vim.lsp.protocol.Method.ClientToServer.Request 651if passed_multiple_ranges then 652method ='textDocument/rangesFormatting' 653elseif range then 654method ='textDocument/rangeFormatting' 655else 656method ='textDocument/formatting' 657end 658 659local clients =lsp . get_clients ( { 660id =opts . id , 661bufnr =bufnr , 662name =opts . name , 663method =method , 664} ) 665if opts . filter then 666clients =vim . tbl_filter ( opts . filter , clients ) 667end 668 669if # clients == 0 then 670vim . notify ( '[LSP] Format request failed, no matching language servers.' ) 671end 672 673--- @param client vim.lsp.Client 674--- @param params lsp.DocumentFormattingParams 675--- @return lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams 676local function set_range ( client , params ) 677--- @param r {start:[integer,integer],end:[integer, integer]} 678local function to_lsp_range ( r ) 679if r [ 'end' ][ 2 ] == - 1 then 680local end_line =api . nvim_buf_get_lines ( bufnr , r [ 'end' ][ 1 ] - 1 , r [ 'end' ][ 1 ], true )[ 1 ] 681return { 682start =vim . pos ( bufnr , r . start [ 1 ] - 1 , r . start [ 2 ]): to_lsp ( client . offset_encoding ), 683[ 'end' ] =vim . pos ( bufnr , r [ 'end' ][ 1 ] - 1 , # end_line ): to_lsp ( client . offset_encoding ), 684} 685end 686return util . make_given_range_params ( r . start , r [ 'end' ], bufnr , client . offset_encoding ). range 687end 688 689--- @type lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams 690local ret =params 691if passed_multiple_ranges then 692--- @cast range {start:[integer,integer],end:[integer, integer]}[] 693--- @cast ret lsp.DocumentRangesFormattingParams 694ret . ranges =vim . tbl_map ( to_lsp_range , range ) 695elseif range then 696--- @cast range {start:[integer,integer],end:[integer, integer]} 697--- @cast ret lsp.DocumentRangeFormattingParams 698ret . range =to_lsp_range ( range ) 699end 700return ret 701end 702 703if opts . async then 704--- @param idx? integer 705--- @param client? vim.lsp.Client 706local function do_format ( idx , client ) 707if not idx or not client then 708return 709end 710local params =set_range ( client , util . make_formatting_params ( opts . formatting_options )) 711local timer =opts . timeout_ms and assert ( vim . uv . new_timer ()) 712local success , request_id =client : request ( method , params , function ( ... ) 713if timer then 714if timer : is_closing () then 715return 716end 717timer : close () 718end 719local handler =client . handlers [ method ] or lsp . handlers [ method ] 720handler ( ... ) 721do_format ( next ( clients , idx )) 722end , bufnr ) 723if timer and not timer : is_closing () then 724if not success then 725timer : close () 726return 727end 728timer : start ( 729assert ( opts . timeout_ms ), 7300 , 731vim . schedule_wrap ( function () 732if timer : is_closing () then 733return 734end 735timer : close () 736if request_id and client . requests [ request_id ] then 737client : cancel_request ( request_id ) 738end 739vim . notify ( string . format ( '[LSP][%s] timeout' , client . name ), vim . log . levels . WARN ) 740do_format ( next ( clients , idx )) 741end ) 742) 743end 744end 745do_format ( next ( clients )) 746else 747local timeout_ms =opts . timeout_ms or 1000 748for _ , client in pairs ( clients ) do 749local params =set_range ( client , util . make_formatting_params ( opts . formatting_options )) 750local result , err =client : request_sync ( method , params , timeout_ms , bufnr ) 751if result and result . result then 752util . apply_text_edits ( result . result , bufnr , client . offset_encoding ) 753elseif err then 754vim . notify ( string . format ( '[LSP][%s] %s' , client . name , err ), vim . log . levels . WARN ) 755end 756end 757end 758end 759 760--- @class vim.lsp.buf.rename.Opts 761--- @inlinedoc 762--- 763--- Predicate used to filter clients. Receives a client as argument and 764--- must return a boolean. Clients matching the predicate are included. 765--- @field filter? fun(client: vim.lsp.Client): boolean? 766--- 767--- Restrict clients used for rename to ones where client.name matches 768--- this field. 769--- @field name? string 770--- 771--- (default: current buffer) 772--- @field bufnr? integer 773 774--- Renames all references to the symbol under the cursor. 775--- 776---@param new_name string|nil If not provided, the user will be prompted for a new 777--- name using |vim.ui.input()|. 778---@param opts? vim.lsp.buf.rename.Opts Additional options: 779function M . rename ( new_name , opts ) 780validate ( 'new_name' , new_name , 'string' , true ) 781validate ( 'opts' , opts , 'table' , true ) 782 783opts =opts or {} 784local bufnr =vim . _resolve_bufnr ( opts . bufnr ) 785local clients =lsp . get_clients ( { 786bufnr =bufnr , 787name =opts . name , 788-- Clients must at least support rename, prepareRename is optional 789method ='textDocument/rename' , 790} ) 791if opts . filter then 792clients =vim . tbl_filter ( opts . filter , clients ) 793end 794 795if # clients == 0 then 796vim . notify ( '[LSP] Rename, no matching language servers with rename capability.' ) 797end 798 799local win =api . nvim_get_current_win () 800 801-- Compute early to account for cursor movements after going async 802local cword =vim . fn . expand ( '<cword>' ) 803 804--- @param range lsp.Range 805--- @param position_encoding 'utf-8'|'utf-16'|'utf-32' 806local function get_text_at_range ( range , position_encoding ) 807local vim_range =vim . range . lsp ( bufnr , range , position_encoding ) 808return api . nvim_buf_get_text ( 809bufnr , 810vim_range . start_row , 811vim_range . start_col , 812vim_range . end_row , 813vim_range . end_col , 814{} 815)[ 1 ] 816end 817 818--- @param idx? integer 819--- @param client? vim.lsp.Client 820local function try_use_client ( idx , client ) 821if not idx or not client then 822return 823end 824 825--- @param name string 826local function rename ( name ) 827local params =util . make_position_params ( win , client . offset_encoding ) --[[@as lsp.RenameParams]] 828params . newName =name 829local handler =client . handlers [ 'textDocument/rename' ] or lsp . handlers [ 'textDocument/rename' ] 830client : request ( 'textDocument/rename' , params , function ( ... ) 831handler ( ... ) 832try_use_client ( next ( clients , idx )) 833end , bufnr ) 834end 835 836if client : supports_method ( 'textDocument/prepareRename' ) then 837local params =util . make_position_params ( win , client . offset_encoding ) 838---@param result? lsp.PrepareRenameResult 839client : request ( 'textDocument/prepareRename' , params , function ( err , result ) 840if err or result == nil then 841if next ( clients , idx ) then 842try_use_client ( next ( clients , idx )) 843else 844local msg =err and ( 'Error on prepareRename: ' .. ( err . message or '' )) 845or 'Nothing to rename' 846vim . notify ( msg , vim . log . levels . INFO ) 847end 848return 849end 850 851if new_name then 852rename ( new_name ) 853return 854end 855 856local range ---@type vim.Range? 857if result . start then 858range =vim . range . lsp ( bufnr , result , client . offset_encoding ) 859elseif result . range then 860range =vim . range . lsp ( bufnr , result . range , client . offset_encoding ) 861end 862if range then 863vim . hl . range ( 864bufnr , 865rename_ns , 866'LspReferenceTarget' , 867{ range . start_row , range . start_col } , 868{ range . end_row , range . end_col } , 869{ priority =vim . hl . priorities . user } 870) 871end 872 873local prompt_opts ={ 874prompt ='New Name: ' , 875scope ='cursor' , 876} 877if result . placeholder then 878prompt_opts . default =result . placeholder 879elseif result . start then 880prompt_opts . default =get_text_at_range ( result , client . offset_encoding ) 881else 882prompt_opts . default =cword 883end 884vim . ui . input ( prompt_opts , function ( input ) 885if input and # input ~= 0 then 886rename ( input ) 887end 888api . nvim_buf_clear_namespace ( bufnr , rename_ns , 0 , - 1 ) 889end ) 890end , bufnr ) 891else 892assert ( 893client : supports_method ( 'textDocument/rename' ), 894'Client must support textDocument/rename' 895) 896if new_name then 897rename ( new_name ) 898return 899end 900 901local prompt_opts ={ 902prompt ='New Name: ' , 903default =cword , 904scope ='cursor' , 905} 906vim . ui . input ( prompt_opts , function ( input ) 907if not input or # input == 0 then 908return 909end 910rename ( input ) 911end ) 912end 913end 914 915try_use_client ( next ( clients )) 916end 917 918--- Lists all the references to the symbol under the cursor in the quickfix window. 919--- 920---@param context lsp.ReferenceContext? Context for the request 921---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references 922---@param opts? vim.lsp.ListOpts 923function M . references ( context , opts ) 924validate ( 'context' , context , 'table' , true ) 925validate ( 'opts' , opts , 'table' , true ) 926get_locations ( 'textDocument/references' , context , opts ) 927end 928 929--- Lists all symbols in the current buffer in the |location-list|. 930--- @param opts? vim.lsp.ListOpts 931function M . document_symbol ( opts ) 932validate ( 'opts' , opts , 'table' , true ) 933opts =vim . tbl_deep_extend ( 'keep' , opts or {} , { loclist =true } ) 934local params ={ textDocument =util . make_text_document_params () } 935request_with_opts ( 'textDocument/documentSymbol' , params , opts ) 936end 937 938--- @param client_id integer 939--- @param method vim.lsp.protocol.Method.ClientToServer.Request 940--- @param params table 941--- @param handler? lsp.Handler 942--- @param bufnr? integer 943local function request_with_id ( client_id , method , params , handler , bufnr ) 944local client =lsp . get_client_by_id ( client_id ) 945if not client then 946vim . notify ( 947string . format ( 'Client with id=%d disappeared during hierarchy request' , client_id ), 948vim . log . levels . WARN 949) 950return 951end 952client : request ( method , params , handler , bufnr ) 953end 954 955--- @param item lsp.TypeHierarchyItem|lsp.CallHierarchyItem 956local function format_hierarchy_item ( item ) 957if not item . detail or # item . detail == 0 then 958return item . name 959end 960return string . format ( '%s %s' , item . name , item . detail ) 961end 962 963--- @alias vim.lsp.buf.HierarchyMethod 964--- | 'typeHierarchy/subtypes' 965--- | 'typeHierarchy/supertypes' 966--- | 'callHierarchy/incomingCalls' 967--- | 'callHierarchy/outgoingCalls' 968 969--- @type table<vim.lsp.buf.HierarchyMethod, 'type' | 'call'> 970local hierarchy_methods ={ 971[ 'typeHierarchy/subtypes' ] ='type' , 972[ 'typeHierarchy/supertypes' ] ='type' , 973[ 'callHierarchy/incomingCalls' ] ='call' , 974[ 'callHierarchy/outgoingCalls' ] ='call' , 975} 976 977--- @param method vim.lsp.buf.HierarchyMethod 978local function hierarchy ( method ) 979local kind =hierarchy_methods [ method ] 980 981local prepare_method =kind == 'type' and 'textDocument/prepareTypeHierarchy' 982or 'textDocument/prepareCallHierarchy' 983 984local bufnr =api . nvim_get_current_buf () 985local clients =lsp . get_clients ( { bufnr =bufnr , method =prepare_method } ) 986if not next ( clients ) then 987vim . notify ( lsp . _unsupported_method ( method ), vim . log . levels . WARN ) 988return 989end 990 991local win =api . nvim_get_current_win () 992 993lsp . buf_request_all ( bufnr , prepare_method , function ( client ) 994return util . make_position_params ( win , client . offset_encoding ) 995end , function ( req_results ) 996local results ={} --- @type [integer, lsp.TypeHierarchyItem|lsp.CallHierarchyItem][] 997for client_id , res in pairs ( req_results ) do 998if res . err then 999vim . notify ( res . err . message , vim . log . levels . WARN ) 1000elseif res . result then 1001local result =res . result --- @type lsp.TypeHierarchyItem[]|lsp.CallHierarchyItem[] 1002for _ , item in ipairs ( result ) do 1003results [ # results + 1 ] ={ client_id , item } 1004end 1005end 1006end 1007 1008if # results == 0 then 1009vim . notify ( 'No item resolved' , vim . log . levels . WARN ) 1010elseif # results == 1 then 1011local client_id , item =results [ 1 ][ 1 ], results [ 1 ][ 2 ] 1012request_with_id ( client_id , method , { item =item } , nil , bufnr ) 1013else 1014vim . ui . select ( results , { 1015prompt =string . format ( 'Select a %s hierarchy item:' , kind ), 1016kind =kind .. 'hierarchy' , 1017format_item =function ( x ) 1018return format_hierarchy_item ( x [ 2 ]) 1019end , 1020} , function ( x ) 1021if x then 1022local client_id , item =x [ 1 ], x [ 2 ] 1023request_with_id ( client_id , method , { item =item } , nil , bufnr ) 1024end 1025end ) 1026end 1027end ) 1028end 1029 1030--- Lists all the call sites of the symbol under the cursor in the 1031--- |quickfix| window. If the symbol can resolve to multiple 1032--- items, the user can pick one in the |inputlist()|. 1033function M . incoming_calls () 1034hierarchy ( 'callHierarchy/incomingCalls' ) 1035end 1036 1037--- Lists all the items that are called by the symbol under the 1038--- cursor in the |quickfix| window. If the symbol can resolve to 1039--- multiple items, the user can pick one in the |inputlist()|. 1040function M . outgoing_calls () 1041hierarchy ( 'callHierarchy/outgoingCalls' ) 1042end 1043 1044--- Lists all the subtypes or supertypes of the symbol under the 1045--- cursor in the |quickfix| window. If the symbol can resolve to 1046--- multiple items, the user can pick one using |vim.ui.select()|. 1047---@param kind "subtypes"|"supertypes" 1048function M . typehierarchy ( kind ) 1049validate ( 'kind' , kind , function ( v ) 1050return v == 'subtypes' or v == 'supertypes' 1051end ) 1052 1053local method =kind == 'subtypes' and 'typeHierarchy/subtypes' or 'typeHierarchy/supertypes' 1054hierarchy ( method ) 1055end 1056 1057--- List workspace folders. 1058--- 1059function M . list_workspace_folders () 1060local workspace_folders ={} 1061for _ , client in pairs ( lsp . get_clients ( { bufnr =0 } )) do 1062for _ , folder in pairs ( client . workspace_folders or {} ) do 1063table . insert ( workspace_folders , folder . name ) 1064end 1065end 1066return workspace_folders 1067end 1068 1069--- Add the folder at path to the workspace folders. If {path} is 1070--- not provided, the user will be prompted for a path using |input()|. 1071--- @param workspace_folder? string 1072function M . add_workspace_folder ( workspace_folder ) 1073validate ( 'workspace_folder' , workspace_folder , 'string' , true ) 1074 1075workspace_folder =workspace_folder 1076or npcall ( vim . fn . input , 'Workspace Folder: ' , vim . fn . expand ( '%:p:h' ), 'dir' ) 1077api . nvim_command ( 'redraw' ) 1078if not ( workspace_folder and # workspace_folder > 0 ) then 1079return 1080end 1081if vim . fn . isdirectory ( workspace_folder ) == 0 then 1082vim . notify ( workspace_folder .. ' is not a valid directory' ) 1083return 1084end 1085local bufnr =api . nvim_get_current_buf () 1086for _ , client in pairs ( lsp . get_clients ( { bufnr =bufnr } )) do 1087client : _add_workspace_folder ( workspace_folder ) 1088end 1089end 1090 1091--- Remove the folder at path from the workspace folders. If 1092--- {path} is not provided, the user will be prompted for 1093--- a path using |input()|. 1094--- @param workspace_folder? string 1095function M . remove_workspace_folder ( workspace_folder ) 1096validate ( 'workspace_folder' , workspace_folder , 'string' , true ) 1097 1098workspace_folder =workspace_folder 1099or npcall ( vim . fn . input , 'Workspace Folder: ' , vim . fn . expand ( '%:p:h' )) 1100api . nvim_command ( 'redraw' ) 1101if not workspace_folder or # workspace_folder == 0 then 1102return 1103end 1104local bufnr =api . nvim_get_current_buf () 1105for _ , client in pairs ( lsp . get_clients ( { bufnr =bufnr } )) do 1106client : _remove_workspace_folder ( workspace_folder ) 1107end 1108vim . notify ( workspace_folder .. 'is not currently part of the workspace' ) 1109end 1110 1111--- Lists all symbols in the current workspace in the quickfix window. 1112--- 1113--- The list is filtered against {query}; if the argument is omitted from the 1114--- call, the user is prompted to enter a string on the command line. An empty 1115--- string means no filtering is done. 1116--- 1117--- @param query string? optional 1118--- @param opts? vim.lsp.ListOpts 1119function M . workspace_symbol ( query , opts ) 1120validate ( 'query' , query , 'string' , true ) 1121validate ( 'opts' , opts , 'table' , true ) 1122 1123query =query or npcall ( vim . fn . input , 'Query: ' ) 1124if query == nil then 1125return 1126end 1127local params ={ query =query } 1128request_with_opts ( 'workspace/symbol' , params , opts ) 1129end 1130 1131--- @class vim.lsp.WorkspaceDiagnosticsOpts 1132--- @inlinedoc 1133--- 1134--- Only request diagnostics from the indicated client. If nil, the request is sent to all clients. 1135--- @field client_id? integer 1136 1137--- Request workspace-wide diagnostics. 1138--- @param opts? vim.lsp.WorkspaceDiagnosticsOpts 1139--- @see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_diagnostic 1140function M . workspace_diagnostics ( opts ) 1141validate ( 'opts' , opts , 'table' , true ) 1142 1143lsp . diagnostic . _workspace_diagnostics ( opts or {} ) 1144end 1145 1146--- Send request to the server to resolve document highlights for the current 1147--- text document position. This request can be triggered by a key mapping or 1148--- by events such as `CursorHold`, e.g.: 1149--- 1150--- ```vim 1151--- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() 1152--- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() 1153--- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() 1154--- ``` 1155--- 1156--- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups 1157--- to be defined or you won't be able to see the actual highlights. 1158--- |hl-LspReferenceText| 1159--- |hl-LspReferenceRead| 1160--- |hl-LspReferenceWrite| 1161function M . document_highlight () 1162lsp . buf_request ( 0 , 'textDocument/documentHighlight' , client_positional_params ()) 1163end 1164 1165--- Removes document highlights from current buffer. 1166function M . clear_references () 1167util . buf_clear_references () 1168end 1169 1170---@nodoc 1171---@class vim.lsp.CodeActionResultEntry 1172---@field err? lsp.ResponseError 1173---@field result? (lsp.Command|lsp.CodeAction)[] 1174---@field context lsp.HandlerContext 1175 1176--- Corresponds to `lsp.CodeActionContext`, but all fields are optional: 1177--- @class vim.lsp.buf.code_action.context : lsp.CodeActionContext 1178--- @inlinedoc 1179--- 1180--- Inferred from the current position if not provided. 1181--- @field diagnostics? lsp.Diagnostic[] 1182--- 1183--- `CodeActionKind`s used to filter the code actions. Most servers support values like "refactor" or "quickfix". 1184--- @field only? lsp.CodeActionKind[] 1185--- 1186--- Why code actions were requested. 1187--- @field triggerKind? lsp.CodeActionTriggerKind 1188 1189--- @class vim.lsp.buf.code_action.Opts 1190--- @inlinedoc 1191--- 1192--- @field context? vim.lsp.buf.code_action.context 1193--- 1194--- Predicate taking a code action or command and the provider's ID. 1195--- If it returns false, the action is filtered out. 1196--- @field filter? fun(x: lsp.CodeAction|lsp.Command, client_id: integer):boolean 1197--- 1198--- When set to `true`, and there is just one remaining action 1199--- (after filtering), the action is applied without user query. 1200--- @field apply? boolean 1201--- 1202--- Range for which code actions should be requested. 1203--- If in visual mode this defaults to the active selection. 1204--- Table must contain `start` and `end` keys with {row,col} tuples 1205--- using mark-like indexing. See |api-indexing| 1206--- @field range? {start: integer[], end: integer[]} 1207 1208--- This is not public because the main extension point is 1209--- vim.ui.select which can be overridden independently. 1210--- 1211--- Can't call/use vim.lsp.handlers['textDocument/codeAction'] because it expects 1212--- `(err, CodeAction[] | Command[], ctx)`, but we want to aggregate the results 1213--- from multiple clients to have 1 single UI prompt for the user, yet we still 1214--- need to be able to link a `CodeAction|Command` to the right client for 1215--- `codeAction/resolve` 1216---@param results table<integer, vim.lsp.CodeActionResultEntry> 1217---@param opts? vim.lsp.buf.code_action.Opts 1218local function on_code_action_results ( results , opts ) 1219---@param a lsp.Command|lsp.CodeAction 1220---@param client_id integer 1221local function action_filter ( a , client_id ) 1222-- filter by specified action kind 1223if opts and opts . context then 1224if opts . context . only then 1225if not a . kind then 1226return false 1227end 1228local found =false 1229for _ , o in ipairs ( opts . context . only ) do 1230-- action kinds are hierarchical with . as a separator: when requesting only 'type-annotate' 1231-- this filter allows both 'type-annotate' and 'type-annotate.foo', for example 1232if a . kind == o or vim . startswith ( a . kind , o .. '.' ) then 1233found =true 1234break 1235end 1236end 1237if not found then 1238return false 1239end 1240end 1241-- Only show disabled code actions when the trigger kind is "Invoked". 1242if a . disabled and opts . context . triggerKind ~= lsp . protocol . CodeActionTriggerKind . Invoked then 1243return false 1244end 1245end 1246-- filter by user function 1247if opts and opts . filter and not opts . filter ( a , client_id ) then 1248return false 1249end 1250-- no filter removed this action 1251return true 1252end 1253 1254---@type {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}[] 1255local actions ={} 1256for _ , result in pairs ( results ) do 1257for _ , action in pairs ( result . result or {} ) do 1258if action_filter ( action , result . context . client_id ) then 1259table . insert ( actions , { action =action , ctx =result . context } ) 1260end 1261end 1262end 1263if # actions == 0 then 1264vim . notify ( 'No code actions available' , vim . log . levels . INFO ) 1265return 1266end 1267 1268---@param action lsp.Command|lsp.CodeAction 1269---@param client vim.lsp.Client 1270---@param ctx lsp.HandlerContext 1271local function apply_action ( action , client , ctx ) 1272if action . edit then 1273util . apply_workspace_edit ( action . edit , client . offset_encoding ) 1274end 1275local a_cmd =action . command 1276if a_cmd then 1277local command =type ( a_cmd ) == 'table' and a_cmd or action 1278--- @cast command lsp.Command 1279client : exec_cmd ( command , ctx ) 1280end 1281end 1282 1283---@param choice? {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext} 1284local function on_user_choice ( choice ) 1285if not choice then 1286return 1287end 1288 1289-- textDocument/codeAction can return either Command[] or CodeAction[] 1290-- 1291-- CodeAction 1292-- ... 1293-- edit?: WorkspaceEdit -- <- must be applied before command 1294-- command?: Command 1295-- 1296-- Command: 1297-- title: string 1298-- command: string 1299-- arguments?: any[] 1300 1301local client =assert ( lsp . get_client_by_id ( choice . ctx . client_id )) 1302local action =choice . action 1303local bufnr =assert ( choice . ctx . bufnr , 'Must have buffer number' ) 1304 1305-- Only code actions are resolved, so if we have a command, just apply it. 1306if type ( action . title ) == 'string' and type ( action . command ) == 'string' then 1307apply_action ( action , client , choice . ctx ) 1308return 1309end 1310 1311-- Work around incorrect union narrowing: EmmyLuaLs/emmylua-analyzer-rust#1239. 1312---@cast action lsp.CodeAction 1313if action . disabled then 1314vim . notify ( action . disabled . reason , vim . log . levels . ERROR ) 1315return 1316end 1317 1318if not ( action . edit and action . command ) and client : supports_method ( 'codeAction/resolve' ) then 1319client : request ( 'codeAction/resolve' , action , function ( err , resolved_action ) 1320if err then 1321-- If resolve fails, try to apply the edit/command from the original code action. 1322if action . edit or action . command then 1323apply_action ( action , client , choice . ctx ) 1324else 1325vim . notify ( err . code .. ': ' .. err . message , vim . log . levels . ERROR ) 1326end 1327else 1328apply_action ( resolved_action , client , choice . ctx ) 1329end 1330end , bufnr ) 1331else 1332apply_action ( action , client , choice . ctx ) 1333end 1334end 1335 1336-- If options.apply is given, and there are just one remaining code action, 1337-- apply it directly without querying the user. 1338if opts and opts . apply and # actions == 1 then 1339on_user_choice ( actions [ 1 ]) 1340return 1341end 1342 1343---@param item {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext} 1344local function format_item ( item ) 1345local clients =lsp . get_clients ( { bufnr =item . ctx . bufnr } ) 1346local title =item . action . title : gsub ( '\r\n' , '\\r\\n' ): gsub ( '\n' , '\\n' ) 1347 1348if item . action . disabled then 1349title =title .. ' (disabled)' 1350end 1351 1352if # clients == 1 then 1353return title 1354end 1355 1356local source =assert ( lsp . get_client_by_id ( item . ctx . client_id )). name 1357return ( '%s [%s]' ): format ( title , source ) 1358end 1359 1360local select_opts ={ 1361prompt ='Code actions:' , 1362kind ='codeaction' , 1363format_item =format_item , 1364} 1365vim . ui . select ( actions , select_opts , on_user_choice ) 1366end 1367 1368---@param diagnostic vim.Diagnostic 1369---@param bufnr integer 1370---@param lnum integer 1371---@param col integer 1372---@return boolean 1373local function diagnostic_contains_cursor ( diagnostic , bufnr , lnum , col ) 1374local start =vim . pos ( bufnr , diagnostic . lnum , diagnostic . col ) 1375local finish = 1376vim . pos ( bufnr , diagnostic . end_lnum or diagnostic . lnum , diagnostic . end_col or diagnostic . col ) 1377local cursor =vim . pos ( bufnr , lnum , col ) 1378 1379if start == finish then 1380return cursor == start 1381end 1382 1383return start <= cursor and cursor < finish 1384end 1385 1386--- Selects a code action (LSP: "textDocument/codeAction" request) available at cursor position. 1387--- 1388---@param opts? vim.lsp.buf.code_action.Opts 1389---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction 1390---@see vim.lsp.protocol.CodeActionTriggerKind 1391function M . code_action ( opts ) 1392validate ( 'options' , opts , 'table' , true ) 1393opts =opts or {} 1394-- Detect old API call code_action(context) which should now be 1395-- code_action({ context = context} ) 1396--- @diagnostic disable-next-line:undefined-field 1397if opts . diagnostics or opts . only then 1398opts ={ options =opts } 1399end 1400local context =opts . context and vim . deepcopy ( opts . context ) or {} 1401if not context . triggerKind then 1402context . triggerKind =lsp . protocol . CodeActionTriggerKind . Invoked 1403end 1404local mode =api . nvim_get_mode (). mode 1405local bufnr =api . nvim_get_current_buf () 1406local win =api . nvim_get_current_win () 1407local range =opts . range 1408if range == nil and ( mode == 'v' or mode == 'V' ) then 1409range =range_from_selection ( bufnr , mode ) 1410end 1411local cursor =api . nvim_win_get_cursor ( win ) 1412local lnum =cursor [ 1 ] - 1 1413local col =cursor [ 2 ] 1414local clients =lsp . get_clients ( { bufnr =bufnr , method ='textDocument/codeAction' } ) 1415if not next ( clients ) then 1416vim . notify ( lsp . _unsupported_method ( 'textDocument/codeAction' ), vim . log . levels . WARN ) 1417return 1418end 1419 1420lsp . buf_request_all ( bufnr , 'textDocument/codeAction' , function ( client ) 1421local params 1422 1423if range then 1424validate ( 'range' , range , 'table' ) 1425validate ( 'range.start' , range . start , 'table' ) 1426validate ( 'range.end' , range [ 'end' ], 'table' ) 1427params = 1428util . make_given_range_params ( range . start , range [ 'end' ], bufnr , client . offset_encoding ) 1429else 1430params =util . make_range_params ( win , client . offset_encoding ) 1431end 1432 1433--- @cast params lsp.CodeActionParams 1434 1435if context . diagnostics then 1436params . context =context 1437else 1438local ns_push =lsp . diagnostic . get_namespace ( client . id ) 1439local diagnostics ={} 1440 1441client : _provider_foreach ( 'textDocument/diagnostic' , function ( cap ) 1442--- @cast cap lsp.DiagnosticRegistrationOptions 1443local ns_pull =lsp . diagnostic . get_namespace ( client . id , true , cap . identifier ) 1444vim . list_extend ( 1445diagnostics , 1446vim . diagnostic . get ( bufnr , { namespace =ns_pull , lnum =lnum } ) 1447) 1448end ) 1449 1450vim . list_extend ( diagnostics , vim . diagnostic . get ( bufnr , { namespace =ns_push , lnum =lnum } )) 1451if range == nil then 1452diagnostics =vim . tbl_filter ( function ( diagnostic ) 1453return diagnostic_contains_cursor ( diagnostic , bufnr , lnum , col ) 1454end , diagnostics ) 1455end 1456params . context =vim . tbl_extend ( 'force' , context , { 1457---@diagnostic disable-next-line: no-unknown 1458diagnostics =vim . tbl_map ( function ( d ) 1459return d . user_data . lsp 1460end , diagnostics ), 1461} ) 1462end 1463 1464return params 1465end , function ( results ) 1466on_code_action_results ( results , opts ) 1467end ) 1468end 1469 1470---@type { index: integer, ranges: lsp.Range[] }? 1471local selection_ranges =nil 1472 1473---@param range lsp.Range 1474local function select_range ( range ) 1475local start_line =range . start . line 1476local end_line =range [ 'end' ]. line 1477 1478local start_col =range . start . character 1479local end_col =range [ 'end' ]. character 1480 1481Range . visual_select ( { start_line , start_col , end_line , end_col } ) 1482end 1483 1484---@param range lsp.Range 1485local function is_empty ( range ) 1486return range . start . line == range [ 'end' ]. line and range . start . character == range [ 'end' ]. character 1487end 1488 1489--- [lsp-incremental-selection]() 1490--- 1491--- Expands or contracts a |Visual| selection at cursor, based on ranges given by LSP. The 1492--- `direction` parameter specifies the number of times to expand the selection. Negative values 1493--- will shrink the selection. 1494--- 1495--- @param direction integer 1496--- @param timeout_ms integer? (default: `1000`) Maximum time (milliseconds) to wait for a result. 1497function M . selection_range ( direction , timeout_ms ) 1498validate ( 'direction' , direction , 'number' ) 1499validate ( 'timeout_ms' , timeout_ms , 'number' , true ) 1500 1501if selection_ranges then 1502local new_index =selection_ranges . index + direction 1503selection_ranges . index =math . min ( # selection_ranges . ranges , math . max ( 1 , new_index )) 1504 1505select_range ( assert ( selection_ranges . ranges [ selection_ranges . index ])) 1506return 1507end 1508 1509local method ='textDocument/selectionRange' 1510local client =lsp . get_clients ( { method =method , bufnr =0 } )[ 1 ] 1511if not client then 1512vim . notify ( lsp . _unsupported_method ( method ), vim . log . levels . WARN ) 1513return 1514end 1515 1516local position_params =util . make_position_params ( 0 , client . offset_encoding ) 1517 1518---@type lsp.SelectionRangeParams 1519local params ={ 1520textDocument =position_params . textDocument , 1521positions ={ position_params . position } , 1522} 1523 1524timeout_ms =timeout_ms or 1000 1525local result , err =lsp . buf_request_sync ( 0 , method , params , timeout_ms ) 1526if err then 1527local err_message =type ( err ) == 'table' and lsp . rpc . format_rpc_error ( err ) or err 1528lsp . log . error ( 'selectionRange request failed: ' .. err_message ) 1529return 1530end 1531if not result or not result [ client . id ] or not result [ client . id ]. result then 1532return 1533end 1534if result [ client . id ]. error then 1535lsp . log . error ( result [ client . id ]. error . code , result [ client . id ]. error . message ) 1536end 1537 1538-- We only requested one range, thus we get the first and only response here. 1539local response =assert ( result [ client . id ]. result [ 1 ]) ---@type lsp.SelectionRange? 1540local ranges ={} ---@type lsp.Range[] 1541local lines =api . nvim_buf_get_lines ( 0 , 0 , - 1 , false ) 1542 1543-- Populate the list of ranges from the given request. 1544while response do 1545local range =response . range 1546if not is_empty ( range ) then 1547local start_line =range . start . line 1548local end_line =range [ 'end' ]. line 1549range . start . character =vim . str_byteindex ( 1550lines [ start_line + 1 ] or '' , 1551client . offset_encoding , 1552range . start . character , 1553false 1554) 1555range [ 'end' ]. character =vim . str_byteindex ( 1556lines [ end_line + 1 ] or '' , 1557client . offset_encoding , 1558range [ 'end' ]. character , 1559false 1560) 1561ranges [ # ranges + 1 ] =range 1562end 1563response =response . parent 1564end 1565 1566-- Clear selection ranges when leaving visual mode. 1567nvim_on ( 'ModeChanged' , nil , { once =true , pattern ='v*:*' } , function () 1568selection_ranges =nil 1569end ) 1570 1571if # ranges > 0 then 1572local index =math . min ( # ranges , math . max ( 1 , direction )) 1573selection_ranges ={ index =index , ranges =ranges } 1574select_range ( assert ( ranges [ index ])) 1575end 1576end 1577 1578return M