robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local protocol =require ( 'vim.lsp.protocol' ) 2local validate =vim . validate 3local api =vim . api 4local nvim_on =require ( 'vim._core.util' ). nvim_on 5local list_extend =vim . list_extend 6local uv =vim . uv 7 8local M ={} 9 10--- @param border string|(string|[string,string])[] 11--- @return never 12local function border_error ( border ) 13error ( 14string . format ( 15'invalid floating preview border: %s. :help vim.api.nvim_open_win()' , 16vim . inspect ( border ) 17), 182 19) 20end 21 22local border_size ={ 23none ={ 0 , 0 } , 24single ={ 2 , 2 } , 25double ={ 2 , 2 } , 26rounded ={ 2 , 2 } , 27solid ={ 2 , 2 } , 28shadow ={ 1 , 1 } , 29bold ={ 2 , 2 } , 30} 31 32--- Check the border given by opts or the default border for the additional 33--- size it adds to a float. 34--- @param opts? vim.lsp.util.open_floating_preview.Opts 35--- @return integer height 36--- @return integer width 37local function get_border_size ( opts ) 38local border =opts and opts . border or vim . o . winborder 39 40if border == '' then 41border ='none' 42end 43 44-- Convert winborder string option with custom characters into a table 45if type ( border ) == 'string' and border : find ( ',' ) then 46border =vim . split ( border , ',' ) 47end 48 49if type ( border ) == 'string' then 50if not border_size [ border ] then 51border_error ( border ) 52end 53local r =border_size [ border ] 54return r [ 1 ], r [ 2 ] 55end 56 57if 8 % # border ~= 0 then 58border_error ( border ) 59end 60 61--- @param id integer 62--- @return string 63local function elem ( id ) 64id =( id - 1 ) % # border + 1 65local e =border [ id ] 66if type ( e ) == 'table' then 67-- border specified as a table of <character, highlight group> 68return e [ 1 ] 69elseif type ( e ) == 'string' then 70-- border specified as a list of border characters 71return e 72end 73-- EmmyLua rejects `never` as a subtype of the declared string result. 74---@diagnostic disable-next-line: return-type-mismatch 75return border_error ( border ) 76end 77 78--- @param e string 79--- @return integer 80local function border_height ( e ) 81return # e > 0 and 1 or 0 82end 83 84local top , bottom =elem ( 2 ), elem ( 6 ) 85local height =border_height ( top ) + border_height ( bottom ) 86 87local right , left =elem ( 4 ), elem ( 8 ) 88local width =vim . fn . strdisplaywidth ( right ) + vim . fn . strdisplaywidth ( left ) 89 90return height , width 91end 92 93--- Splits string at newlines, optionally removing unwanted blank lines. 94--- 95--- @param s string Multiline string 96--- @param no_blank boolean? Drop blank lines for each @param/@return (except one empty line 97--- separating each, and before a codeblock). 98--- Workaround for https://github.com/LuaLS/lua-language-server/issues/2333 99local function split_lines ( s , no_blank ) 100s =string . gsub ( s , '\r\n?' , '\n' ) 101local raw =vim . split ( s , '\n' , { plain =true , trimempty =true } ) 102 103--- @param l string 104--- @return boolean # true if line begins a (4-space-indented) codeblock. #40860 105local function codeblock ( l ) 106return l : find ( '^ ' ) ~= nil or l : find ( '^\t' ) ~= nil 107end 108 109local lines ={} 110local in_desc =true -- Main description block, before seeing any @foo. 111for i , line in ipairs ( raw ) do 112local start_annotation =not not line : find ( '^ ?%@.?[pr]' ) 113in_desc =( not start_annotation ) and in_desc or false 114if start_annotation and no_blank and not ( lines [ # lines ] or '' ): find ( '^%s*$' ) then 115table . insert ( lines , '' ) -- Separate each @foo with a blank line. 116end 117 118local blank =line : find ( '^%s*$' ) 119local keep_blank =blank and codeblock ( raw [ i + 1 ] or '' ) -- Keep if it precedes a codeblock. #40860 120if in_desc or not no_blank or not blank or keep_blank then 121table . insert ( lines , line ) 122end 123end 124return lines 125end 126 127local function create_window_without_focus () 128local prev =api . nvim_get_current_win () 129vim . cmd . new () 130local new =api . nvim_get_current_win () 131api . nvim_set_current_win ( prev ) 132return new 133end 134 135--- @param fn fun(x:any):any[] 136--- @return function 137local function sort_by_key ( fn ) 138return function ( a , b ) 139local ka , kb =fn ( a ), fn ( b ) 140assert ( # ka == # kb ) 141for i =1 , # ka do 142if ka [ i ] ~= kb [ i ] then 143return ka [ i ] < kb [ i ] 144end 145end 146-- every value must have been equal here, which means it's not less than. 147return false 148end 149end 150 151-- TODO(ofseed): remove these exported functions by replacing their usages with `vim.pos`. 152local get_lines =require ( 'vim.pos._util' ). get_lines 153local get_line =require ( 'vim.pos._util' ). get_line 154 155local cursor_ns =api . nvim_create_namespace ( 'nvim.lsp.util.cursor' ) 156 157--- Anchors the cursor to the text under it, so edits before it don't drag it along. 158--- 159--- @param bufnr integer 160--- @return fun()? # Restores the cursor and deletes the mark. 161local function anchor_cursor ( bufnr ) 162local win =api . nvim_get_current_win () 163if api . nvim_win_get_buf ( win ) ~= bufnr then 164return function () end 165end 166local cursor =api . nvim_win_get_cursor ( win ) 167local mark =api . nvim_buf_set_extmark ( bufnr , cursor_ns , cursor [ 1 ] - 1 , cursor [ 2 ], {} ) 168return function () 169local pos =api . nvim_buf_get_extmark_by_id ( bufnr , cursor_ns , mark , {} ) 170api . nvim_buf_del_extmark ( bufnr , cursor_ns , mark ) 171if pos [ 1 ] and api . nvim_win_is_valid ( win ) and api . nvim_win_get_buf ( win ) == bufnr then 172api . nvim_win_set_cursor ( win , { pos [ 1 ] + 1 , pos [ 2 ] } ) 173end 174end 175end 176 177--- @class vim.lsp.util.apply_text_edits.Opts 178--- @inlinedoc 179--- 180--- Keep the cursor on the text it is on, instead of letting the edits move it. 181--- (default: `false`) 182--- @field keep_cursor? boolean 183 184--- Applies a list of text edits to a buffer. Note: this mutates `text_edits` (sorts in-place and 185--- adds `_index` fields). 186--- 187---@param text_edits (lsp.TextEdit|lsp.AnnotatedTextEdit)[] 188---@param bufnr integer Buffer id 189---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 190---@param change_annotations? table<string, lsp.ChangeAnnotation> 191---@param opts? vim.lsp.util.apply_text_edits.Opts 192---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit 193function M . apply_text_edits ( text_edits , bufnr , position_encoding , change_annotations , opts ) 194validate ( 'text_edits' , text_edits , 'table' , false ) 195validate ( 'bufnr' , bufnr , 'number' , false ) 196validate ( 'position_encoding' , position_encoding , 'string' , false ) 197validate ( 'change_annotations' , change_annotations , 'table' , true ) 198validate ( 'opts' , opts , 'table' , true ) 199opts =opts or {} 200 201if not next ( text_edits ) then 202return 203end 204 205assert ( bufnr ~= 0 , 'Explicit buffer number is required' ) 206 207if not api . nvim_buf_is_loaded ( bufnr ) then 208vim . fn . bufload ( bufnr ) 209end 210 211local marks ={} --- @type table<string,[integer,integer]> 212local has_eol_text_edit =false 213 214local function apply_text_edits () 215-- Fix reversed range and indexing each text_edits 216for index , text_edit in ipairs ( text_edits ) do 217--- @cast text_edit lsp.TextEdit & { _index?: integer } 218-- XXX: Preserve existing _index to avoid surprises if the same edit is reapplied. #39344 219if text_edit . _index == nil then 220text_edit . _index =index 221end 222 223if 224text_edit . range . start . line > text_edit . range [ 'end' ]. line 225or text_edit . range . start . line == text_edit . range [ 'end' ]. line 226and text_edit . range . start . character > text_edit . range [ 'end' ]. character 227then 228local start =text_edit . range . start 229text_edit . range . start =text_edit . range [ 'end' ] 230text_edit . range [ 'end' ] =start 231end 232end 233 234--- @cast text_edits ((lsp.TextEdit|lsp.AnnotatedTextEdit)&{_index: integer})[] 235 236-- The checker rejects this array against its own inferred intersection type. 237--- @diagnostic disable-next-line: param-type-mismatch 238table . sort ( text_edits , function ( a , b ) 239if a . range . start . line ~= b . range . start . line then 240return a . range . start . line > b . range . start . line 241end 242if a . range . start . character ~= b . range . start . character then 243return a . range . start . character > b . range . start . character 244end 245return a . _index > b . _index 246end ) 247 248-- save and restore local marks since they get deleted by nvim_buf_set_lines 249for _ , m in pairs ( vim . fn . getmarklist ( bufnr )) do 250if m . mark : match ( "^'[a-z]$" ) then 251marks [ m . mark : sub ( 2 , 2 )] ={ m . pos [ 2 ], m . pos [ 3 ] - 1 } -- api-indexed 252end 253end 254 255for _ , text_edit in ipairs ( text_edits ) do 256-- Normalize line ending 257text_edit . newText , _ =string . gsub ( text_edit . newText , '\r\n?' , '\n' ) 258 259-- Convert from LSP style ranges to Neovim style ranges. 260local range =vim . range . lsp ( bufnr , text_edit . range , position_encoding ) 261local start_row , start_col , end_row , end_col = 262range . start_row , range . start_col , range . end_row , range . end_col 263local text =vim . split ( text_edit . newText , '\n' , { plain =true } ) 264 265local max =api . nvim_buf_line_count ( bufnr ) 266-- If the whole edit is after the lines in the buffer we can simply add the new text to the end 267-- of the buffer. 268if max <= start_row then 269api . nvim_buf_set_lines ( bufnr , max , max , false , text ) 270has_eol_text_edit =true 271else 272local last_line_len =# get_line ( bufnr , math . min ( end_row , max - 1 )) 273-- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't 274-- accept it so we should fix it here. 275if max <= end_row then 276end_row =max - 1 277end_col =last_line_len 278has_eol_text_edit =true 279else 280-- If the replacement is over the end of a line (i.e. end_col is equal to the line length and the 281-- replacement text ends with a newline We can likely assume that the replacement is assumed 282-- to be meant to replace the newline with another newline and we need to make sure this 283-- doesn't add an extra empty line. E.g. when the last line to be replaced contains a '\r' 284-- in the file some servers (clangd on windows) will include that character in the line 285-- while nvim_buf_set_text doesn't count it as part of the line. 286if 287end_col >= last_line_len 288and text_edit . range [ 'end' ]. character > end_col 289and # text_edit . newText > 0 290and string . sub ( text_edit . newText , - 1 ) == '\n' 291then 292table . remove ( text , # text ) 293end 294end 295-- Make sure we don't go out of bounds for end_col 296end_col =math . min ( last_line_len , end_col ) 297 298api . nvim_buf_set_text ( bufnr , start_row , start_col , end_row , end_col , text ) 299end 300end 301end 302 303--- Track how many times each change annotation is applied to build up the final description. 304---@type table<string, integer> 305local change_count ={} 306 307-- If there are any annotated text edits, we need to confirm them before applying the edits. 308local confirmations ={} ---@type table<string, integer> 309for _ , text_edit in ipairs ( text_edits ) do 310if text_edit . annotationId then 311assert ( 312change_annotations ~= nil , 313'change_annotations must be provided for annotated text edits' 314) 315 316local annotation =change_annotations [ text_edit . annotationId ] 317if not annotation then 318error ( string . format ( 'No change annotation found for ID: %s' , text_edit . annotationId )) 319end 320 321if annotation . needsConfirmation then 322confirmations [ text_edit . annotationId ] =( confirmations [ text_edit . annotationId ] or 0 ) + 1 323end 324 325change_count [ text_edit . annotationId ] =( change_count [ text_edit . annotationId ] or 0 ) + 1 326end 327end 328 329if next ( confirmations ) then 330local message ={ 'Apply all changes?' } 331for id , count in pairs ( confirmations ) do 332local annotation =assert ( change_annotations )[ id ] 333message [ # message + 1 ] =annotation . label 334.. ( annotation . description and ( string . format ( ': %s' , annotation . description )) or '' ) 335.. ( count > 1 and string . format ( ' (%d)' , count ) or '' ) 336end 337 338local response =vim . fn . confirm ( table . concat ( message , '\n' ), '&Yes\n&No' , 1 , 'Question' ) 339if response ~= 1 then 340return 341end 342end 343 344-- Anchor after the prompt, so the mark only exists while the buffer is actually being edited. 345local restore_cursor =opts . keep_cursor and anchor_cursor ( bufnr ) or nil 346apply_text_edits () 347 348if change_annotations ~= nil and next ( change_count ) then 349local change_message ={ 'Applied changes:' } 350for id , count in pairs ( change_count ) do 351local annotation =change_annotations [ id ] 352change_message [ # change_message + 1 ] =annotation . label 353.. ( annotation . description and ( ': ' .. annotation . description ) or '' ) 354.. ( count > 1 and string . format ( ' (%d)' , count ) or '' ) 355end 356vim . notify ( table . concat ( change_message , '\n' ), vim . log . levels . INFO ) 357end 358 359local max =api . nvim_buf_line_count ( bufnr ) 360 361-- no need to restore marks that still exist 362for _ , m in pairs ( vim . fn . getmarklist ( bufnr )) do 363marks [ m . mark : sub ( 2 , 2 )] =nil 364end 365-- restore marks 366for mark , pos in pairs ( marks ) do 367if pos then 368-- make sure we don't go out of bounds 369pos [ 1 ] =math . min ( pos [ 1 ], max ) 370pos [ 2 ] =math . min ( pos [ 2 ], # get_line ( bufnr , pos [ 1 ] - 1 )) 371api . nvim_buf_set_mark ( bufnr or 0 , mark , pos [ 1 ], pos [ 2 ]) 372end 373end 374 375-- Remove final line if needed 376local fix_eol =has_eol_text_edit 377fix_eol =fix_eol and ( vim . bo [ bufnr ]. eol or ( vim . bo [ bufnr ]. fixeol and not vim . bo [ bufnr ]. binary )) 378fix_eol =fix_eol and get_line ( bufnr , max - 1 ) == '' 379if fix_eol then 380api . nvim_buf_set_lines ( bufnr , - 2 , - 1 , false , {} ) 381end 382 383if restore_cursor then 384restore_cursor () 385end 386end 387 388--- Applies a `TextDocumentEdit`, which is a list of changes to a single 389--- document. 390--- 391---@param text_document_edit lsp.TextDocumentEdit 392---@param index? integer: Optional index of the edit, if from a list of edits (or nil, if not from a list) 393---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 394---@param change_annotations? table<string, lsp.ChangeAnnotation> 395---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit 396function M . apply_text_document_edit ( 397text_document_edit , 398index , 399position_encoding , 400change_annotations 401) 402validate ( 'position_encoding' , position_encoding , 'string' ) 403 404local text_document =text_document_edit . textDocument 405local bufnr =vim . uri_to_bufnr ( text_document . uri ) 406 407-- `VersionedTextDocumentIdentifier`s version may be null 408-- https://microsoft.github.io/language-server-protocol/specification#versionedTextDocumentIdentifier 409if 410-- For lists of text document edits, 411-- do not check the version after the first edit. 412not ( index and index > 1 ) 413and ( 414text_document . version ~= vim . NIL 415and text_document . version > 0 416and M . buf_versions [ bufnr ] > text_document . version 417) 418then 419( 'Buffer ' , text_document . uri , ' newer than edits.' ) 420return 421end 422 423-- Snippet edits are not supported or advertised in our client capabilities. 424local edits =text_document_edit . edits --[[@as (lsp.TextEdit|lsp.AnnotatedTextEdit)[] ]] 425M . apply_text_edits ( edits , bufnr , position_encoding , change_annotations ) 426end 427 428--- @param path string 429local function path_components ( path ) 430return vim . split ( path , '/' , { plain =true } ) 431end 432 433--- @param path string[] 434--- @param prefix string[] 435--- @return boolean 436local function path_under_prefix ( path , prefix ) 437for i , c in ipairs ( prefix ) do 438if c ~= path [ i ] then 439return false 440end 441end 442return true 443end 444 445--- Get list of loaded writable buffers whose filename matches the given path 446--- prefix (normalized full path). 447---@param prefix string 448---@return integer[] 449local function get_writable_bufs ( prefix ) 450local prefix_parts =path_components ( prefix ) 451local buffers ={} --- @type integer[] 452for _ , buf in ipairs ( api . nvim_list_bufs ()) do 453-- No need to care about unloaded or nofile buffers. Also :saveas won't work for them. 454if 455api . nvim_buf_is_loaded ( buf ) 456and not vim . list_contains ( { 'nofile' , 'nowrite' } , vim . bo [ buf ]. buftype ) 457then 458local bname =api . nvim_buf_get_name ( buf ) 459local path =path_components ( vim . fs . normalize ( bname , { plain =true } )) 460if path_under_prefix ( path , prefix_parts ) then 461buffers [ # buffers + 1 ] =buf 462end 463end 464end 465return buffers 466end 467 468--- @param s string 469local function escape_gsub_repl ( s ) 470return ( s : gsub ( '%%' , '%%%%' )) 471end 472 473--- @class vim.lsp.util.rename.Opts 474--- @inlinedoc 475--- @field overwrite? boolean 476--- @field ignoreIfExists? boolean 477 478--- Rename old_fname to new_fname 479--- 480--- Existing buffers are renamed as well, while maintaining their bufnr. 481--- 482--- It deletes existing buffers that conflict with the renamed file name only when 483--- * `opts` requests overwriting; or 484--- * the conflicting buffers are not loaded, so that deleting them does not result in data loss. 485--- 486--- @param old_fname string 487--- @param new_fname string 488--- @param opts? vim.lsp.util.rename.Opts Options: 489function M . rename ( old_fname , new_fname , opts ) 490opts =opts or {} 491local skip =not opts . overwrite or opts . ignoreIfExists 492 493local old_fname_full =uv . fs_realpath ( vim . fs . normalize ( old_fname , { plain =true } )) 494if not old_fname_full then 495vim . notify ( 'Invalid path: ' .. old_fname , vim . log . levels . ERROR ) 496return 497end 498 499local target_exists =uv . fs_stat ( new_fname ) ~= nil 500if target_exists and skip then 501vim . notify ( new_fname .. ' already exists. Skipping rename.' , vim . log . levels . ERROR ) 502return 503end 504 505local buf_rename ={} ---@type table<integer, {from: string, to: string}> 506local old_fname_pat ='^' .. vim . pesc ( old_fname_full ) 507for _ , b in ipairs ( get_writable_bufs ( old_fname_full )) do 508-- Renaming a buffer may conflict with another buffer that happens to have the same name. In 509-- most cases, this would have been already detected by the file conflict check above, but the 510-- conflicting buffer may not be associated with a file. For example, 'buftype' can be "nofile" 511-- or "nowrite", or the buffer can be a normal buffer but has not been written to the file yet. 512-- Renaming should fail in such cases to avoid losing the contents of the conflicting buffer. 513local old_bname =api . nvim_buf_get_name ( b ) 514local new_bname =old_bname : gsub ( old_fname_pat , escape_gsub_repl ( new_fname )) 515if vim . fn . bufexists ( new_bname ) == 1 then 516local existing_buf =vim . fn . bufnr ( new_bname ) 517if api . nvim_buf_is_loaded ( existing_buf ) and skip then 518vim . notify ( 519new_bname .. ' already exists in the buffer list. Skipping rename.' , 520vim . log . levels . ERROR 521) 522return 523end 524-- no need to preserve if such a buffer is empty 525api . nvim_buf_delete ( existing_buf ) 526end 527 528buf_rename [ b ] ={ from =old_bname , to =new_bname } 529end 530 531local newdir =vim . fs . dirname ( new_fname ) 532vim . fn . mkdir ( newdir , 'p' ) 533 534assert ( os . rename ( old_fname_full , new_fname )) 535 536local old_undofile =vim . fn . undofile ( old_fname_full ) 537if uv . fs_stat ( old_undofile ) ~= nil then 538local new_undofile =vim . fn . undofile ( new_fname ) 539vim . fn . mkdir ( vim . fs . dirname ( new_undofile ), 'p' ) 540os . rename ( old_undofile , new_undofile ) 541end 542 543for b , rename in pairs ( buf_rename ) do 544-- Rename with :saveas. This does two things: 545-- * Unset BF_WRITE_MASK, so that users don't get E13 when they do :write. 546-- * Send didClose and didOpen via textDocument/didSave handler. 547vim . _with ( { buf =b } , function () 548vim . cmd ( 'keepalt saveas! ' .. vim . fn . fnameescape ( rename . to )) 549end ) 550-- Delete the new buffer with the old name created by :saveas. nvim_buf_delete and 551-- :bwipeout are futile because the buffer will be added again somewhere else. 552vim . cmd ( 'bdelete! ' .. vim . fn . bufnr ( rename . from )) 553end 554end 555 556--- @param change lsp.CreateFile 557local function create_file ( change ) 558local opts =change . options or {} 559-- from spec: Overwrite wins over `ignoreIfExists` 560local fname =vim . uri_to_fname ( change . uri ) 561if not opts . ignoreIfExists or opts . overwrite then 562vim . fn . mkdir ( vim . fs . dirname ( fname ), 'p' ) 563local file =io . open ( fname , 'w' ) 564if file then 565file : close () 566end 567end 568vim . fn . bufadd ( fname ) 569end 570 571--- @param change lsp.DeleteFile 572local function delete_file ( change ) 573local opts =change . options or {} 574local fname =vim . uri_to_fname ( change . uri ) 575local bufnr =vim . fn . bufadd ( fname ) 576vim . fs . rm ( fname , { 577force =opts . ignoreIfNotExists , 578recursive =opts . recursive , 579} ) 580api . nvim_buf_delete ( bufnr , { force =true } ) 581end 582 583--- Applies a `WorkspaceEdit`. 584--- 585---@param workspace_edit lsp.WorkspaceEdit 586---@param position_encoding 'utf-8'|'utf-16'|'utf-32' (required) 587---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit 588function M . apply_workspace_edit ( workspace_edit , position_encoding ) 589validate ( 'workspace_edit' , workspace_edit , 'table' ) 590validate ( 'position_encoding' , position_encoding , 'string' ) 591 592if workspace_edit . documentChanges then 593for idx , change in ipairs ( workspace_edit . documentChanges ) do 594if change . kind == 'rename' then 595local options =change . options --[[@as vim.lsp.util.rename.Opts]] 596M . rename ( vim . uri_to_fname ( change . oldUri ), vim . uri_to_fname ( change . newUri ), options ) 597elseif change . kind == 'create' then 598create_file ( change ) 599elseif change . kind == 'delete' then 600delete_file ( change ) 601elseif change . kind then --- @diagnostic disable-line:undefined-field 602error ( string . format ( 'Unsupported change: %q' , vim . inspect ( change ))) 603else 604local bufnr =vim . uri_to_bufnr ( change . textDocument . uri ) 605M . apply_text_document_edit ( change , idx , position_encoding , workspace_edit . changeAnnotations ) 606-- avoid triggering OptionSet 607if not vim . bo [ bufnr ]. buflisted then 608vim . bo [ bufnr ]. buflisted =true 609end 610end 611end 612return 613end 614 615local all_changes =workspace_edit . changes 616if not ( all_changes and not vim . tbl_isempty ( all_changes )) then 617return 618end 619 620for uri , changes in pairs ( all_changes ) do 621local bufnr =vim . uri_to_bufnr ( uri ) 622M . apply_text_edits ( changes , bufnr , position_encoding , workspace_edit . changeAnnotations ) 623-- avoid triggering OptionSet 624if not vim . bo [ bufnr ]. buflisted then 625vim . bo [ bufnr ]. buflisted =true 626end 627end 628end 629 630--- Converts any of `MarkedString` | `MarkedString[]` | `MarkupContent` into 631--- a list of lines containing valid markdown. Useful to populate the hover 632--- window for `textDocument/hover`, for parsing the result of 633--- `textDocument/signatureHelp`, and potentially others. 634--- 635--- Note that if the input is of type `MarkupContent` and its kind is `plaintext`, 636--- then the corresponding value is returned without further modifications. 637--- 638---@diagnostic disable-next-line: deprecated 639---@param input lsp.MarkedString|lsp.MarkedString[]|lsp.MarkupContent 640---@param contents string[]? List of strings to extend with converted lines. Defaults to {}. 641---@return string[] extended with lines of converted markdown. 642---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover 643function M . convert_input_to_markdown_lines ( input , contents ) 644contents =contents or {} 645-- MarkedString variation 1 646if type ( input ) == 'string' then 647list_extend ( contents , split_lines ( input , true )) 648else 649assert ( type ( input ) == 'table' , 'Expected a table for LSP input' ) 650-- MarkupContent 651if input . kind then 652local value =input . value or '' 653list_extend ( contents , split_lines ( value , true )) 654-- MarkupString variation 2 655elseif input . language then 656table . insert ( contents , '```' .. input . language ) 657list_extend ( contents , split_lines ( input . value or '' )) 658table . insert ( contents , '```' ) 659-- By deduction, this must be MarkedString[] 660else 661-- Use our existing logic to handle MarkedString 662for _ , marked_string in ipairs ( input ) do 663M . convert_input_to_markdown_lines ( marked_string , contents ) 664end 665end 666end 667if ( contents [ 1 ] == '' or contents [ 1 ] == nil ) and # contents == 1 then 668return {} 669end 670return contents 671end 672 673--- Returns the line/column-based position in `contents` at the given offset. 674--- 675---@param offset integer 676---@param contents string[] 677---@return { [1]: integer, [2]: integer }? 678local function get_pos_from_offset ( offset , contents ) 679local i =0 680for l , line in ipairs ( contents ) do 681if offset >= i and offset < i + # line then 682return { l - 1 , offset - i + 1 } 683else 684i =i + # line + 1 685end 686end 687end 688 689--- Converts `textDocument/signatureHelp` response to markdown lines. 690--- 691---@param signature_help lsp.SignatureHelp Response of `textDocument/SignatureHelp` 692---@param ft string? filetype that will be use as the `lang` for the label markdown code block 693---@param triggers string[]? list of trigger characters from the lsp server. used to better determine parameter offsets 694---@return string[]? # lines of converted markdown. 695---@return Range4? # highlight range for the active parameter 696---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp 697function M . convert_signature_help_to_markdown_lines ( signature_help , ft , triggers ) 698--The active signature. If omitted or the value lies outside the range of 699--`signatures` the value defaults to zero or is ignored if `signatures.length == 0`. 700--Whenever possible implementors should make an active decision about 701--the active signature and shouldn't rely on a default value. 702local contents ={} --- @type string[] 703local active_offset ---@type [integer, integer]? 704local active_signature =signature_help . activeSignature or 0 705-- If the activeSignature is not inside the valid range, then clip it. 706-- In 3.15 of the protocol, activeSignature was allowed to be negative 707if active_signature >= # signature_help . signatures or active_signature < 0 then 708active_signature =0 709end 710local signature =signature_help . signatures [ active_signature + 1 ] 711if not signature then 712return 713end 714signature =vim . deepcopy ( signature ) 715local label =signature . label 716if ft then 717-- wrap inside a code block for proper rendering 718label =( '```%s\n%s\n```' ): format ( ft , label ) 719end 720list_extend ( contents , vim . split ( label , '\n' , { plain =true , trimempty =true } )) 721local doc =signature . documentation 722if doc then 723-- if LSP returns plain string, we treat it as plaintext. This avoids 724-- special characters like underscore or similar from being interpreted 725-- as markdown font modifiers 726if type ( doc ) == 'string' then 727doc ={ kind ='plaintext' , value =doc } 728end 729-- Add delimiter if there is documentation to display 730if doc . value ~= '' then 731contents [ # contents + 1 ] ='---' 732end 733M . convert_input_to_markdown_lines ( doc , contents ) 734end 735if signature . parameters and # signature . parameters > 0 then 736local active_parameter =signature . activeParameter or signature_help . activeParameter 737 738-- NOTE: We intentionally violate the LSP spec, which states that if `activeParameter` 739-- is not provided or is out-of-bounds, it should default to 0. 740-- Instead, we default to `nil`, as most clients do. In practice, 'no active parameter' 741-- is better default than 'first parameter' and aligns better with user expectations. 742-- Related discussion: https://github.com/microsoft/language-server-protocol/issues/1271 743if 744not active_parameter 745or active_parameter == vim . NIL 746or active_parameter < 0 747or active_parameter >= # signature . parameters 748then 749return contents , nil 750end 751 752-- The active parameter was checked against the bounds of this array above. 753local parameter =assert ( signature . parameters [ active_parameter + 1 ]) 754local parameter_label =parameter . label 755if type ( parameter_label ) == 'table' then 756active_offset =parameter_label 757else 758local offset =1 ---@type integer? 759-- try to set the initial offset to the first found trigger character 760for _ , t in ipairs ( triggers or {} ) do 761local trigger_offset =signature . label : find ( t , 1 , true ) 762if trigger_offset and ( offset == 1 or trigger_offset < offset ) then 763offset =trigger_offset 764end 765end 766for p , param in pairs ( signature . parameters ) do 767local plabel =param . label 768assert ( type ( plabel ) == 'string' , 'Expected label to be a string' ) 769offset =signature . label : find ( plabel , offset , true ) 770if not offset then 771break 772end 773if p == active_parameter + 1 then 774active_offset ={ offset - 1 , offset + # parameter_label - 1 } 775break 776end 777offset =offset + # plabel + 1 778end 779end 780if parameter . documentation then 781M . convert_input_to_markdown_lines ( parameter . documentation , contents ) 782end 783end 784 785local active_hl =nil 786if active_offset then 787-- Treat LSP's uinteger offsets as integers for arithmetic. 788--- @cast active_offset [integer, integer] 789-- Account for the start of the markdown block. 790if ft then 791active_offset [ 1 ] =active_offset [ 1 ] + # contents [ 1 ] 792active_offset [ 2 ] =active_offset [ 2 ] + # contents [ 1 ] 793end 794 795local a_start =get_pos_from_offset ( active_offset [ 1 ], contents ) 796local a_end =get_pos_from_offset ( active_offset [ 2 ], contents ) 797if a_start and a_end then 798active_hl ={ a_start [ 1 ], a_start [ 2 ], a_end [ 1 ], a_end [ 2 ] } 799end 800end 801 802return contents , active_hl 803end 804 805--- Creates a table with sensible default options for a floating window. The 806--- table can be passed to |nvim_open_win()|. 807--- 808---@param width integer window width (in character cells) 809---@param height integer window height (in character cells) 810---@param opts? vim.lsp.util.open_floating_preview.Opts 811---@return vim.api.keyset.win_config 812function M . make_floating_popup_options ( width , height , opts ) 813validate ( 'opts' , opts , 'table' , true ) 814opts =opts or {} 815validate ( 'opts.offset_x' , opts . offset_x , 'number' , true ) 816validate ( 'opts.offset_y' , opts . offset_y , 'number' , true ) 817 818local lines_above =vim . fn . winline () - 1 819local lines_below =vim . fn . winheight ( 0 ) - lines_above 820if opts . relative == 'mouse' then 821lines_above =vim . fn . getmousepos (). line - 1 822lines_below =vim . fn . winheight ( 0 ) - lines_above 823elseif opts . relative == 'editor' then 824-- No cursor to anchor against; treat the whole editor as space below. 825lines_above =0 826lines_below =vim . o . lines 827end 828 829local anchor_bias =opts . anchor_bias or 'auto' 830 831local anchor_below --- @type boolean? 832 833if anchor_bias == 'below' then 834anchor_below =( lines_below > lines_above ) or ( height <= lines_below ) 835elseif anchor_bias == 'above' then 836local anchor_above =( lines_above > lines_below ) or ( height <= lines_above ) 837anchor_below =not anchor_above 838else 839anchor_below =lines_below > lines_above 840end 841 842local border_height =get_border_size ( opts ) 843local row , col --- @type integer?, integer? 844if anchor_below then 845height =math . max ( math . min ( lines_below - border_height , height ), 0 ) 846row =1 847else 848height =math . max ( math . min ( lines_above - border_height , height ), 0 ) 849row =0 850end 851 852local wincol =vim . fn . wincol () 853if opts . relative == 'mouse' then 854wincol =vim . fn . getmousepos (). column 855elseif opts . relative == 'editor' then 856wincol =0 857end 858 859local anchor --- @type 'NW'|'NE'|'SW'|'SE' 860if wincol + width + ( opts . offset_x or 0 ) <= vim . o . columns then 861anchor =anchor_below and 'NW' or 'SW' 862col =0 863else 864anchor =anchor_below and 'NE' or 'SE' 865col =1 866end 867 868local title =(( opts . border or vim . o . winborder ~= '' ) and opts . title ) and opts . title or nil 869local title_pos --- @type 'left'|'center'|'right'? 870 871if title then 872title_pos =opts . title_pos or 'center' 873end 874 875return { 876anchor =anchor , 877row =row + ( opts . offset_y or 0 ), 878col =col + ( opts . offset_x or 0 ), 879height =height , 880focusable =opts . focusable , 881relative =( opts . relative == 'mouse' or opts . relative == 'editor' ) and opts . relative 882or 'cursor' , 883style ='minimal' , 884width =width , 885border =opts . border , 886zindex =opts . zindex or ( api . nvim_win_get_config ( 0 ). zindex or 49 ) + 1 , 887title =title , 888title_pos =title_pos , 889} 890end 891 892--- @class vim.lsp.util.show_document.Opts 893--- @inlinedoc 894--- 895--- Jump to existing window if buffer is already open. 896--- @field reuse_win? boolean 897--- 898--- Whether to focus/jump to location if possible. 899--- (defaults: true) 900--- @field focus? boolean 901 902--- Shows document and optionally jumps to the location. 903--- 904---@param location lsp.Location|lsp.LocationLink 905---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 906---@param opts? vim.lsp.util.show_document.Opts 907---@return boolean `true` if succeeded 908function M . show_document ( location , position_encoding , opts ) 909validate ( 'position_encoding' , position_encoding , 'string' ) 910 911-- location may be Location or LocationLink 912local uri =location . uri or location . targetUri 913if uri == nil then 914return false 915end 916local range =location . range or location . targetSelectionRange 917return M . _show_document ( uri , range , position_encoding , opts ) 918end 919 920--- Shows a document, preserving its cursor position when no range is given. 921--- @private 922--- @param uri string 923--- @param range lsp.Range? 924--- @param position_encoding 'utf-8'|'utf-16'|'utf-32' 925--- @param opts? vim.lsp.util.show_document.Opts 926--- @return boolean 927function M . _show_document ( uri , range , position_encoding , opts ) 928local bufnr =vim . uri_to_bufnr ( uri ) 929 930-- Return early if the buffer fails to load, to avoid partial setup. 931local loaded , err =pcall ( vim . fn . bufload , bufnr ) 932if not loaded then 933vim . notify ( tostring ( err ), vim . log . levels . ERROR ) 934return false 935end 936 937opts =opts or {} 938local focus =vim . nonnil ( opts . focus , true ) 939if focus then 940-- Save position in jumplist 941vim . cmd ( "normal! m'" ) 942 943-- Push a new item into tagstack 944local from ={ vim . fn . bufnr ( '%' ), vim . fn . line ( '.' ), vim . fn . col ( '.' ), 0 } 945local items ={ { tagname =vim . fn . expand ( '<cword>' ), from =from } } 946vim . fn . settagstack ( vim . fn . win_getid (), { items =items } , 't' ) 947end 948 949local win =opts . reuse_win and vim . fn . win_findbuf ( bufnr )[ 1 ] 950or focus and api . nvim_get_current_win () 951or create_window_without_focus () 952 953vim . bo [ bufnr ]. buflisted =true 954api . nvim_win_set_buf ( win , bufnr ) 955if focus then 956api . nvim_set_current_win ( win ) 957end 958 959if range then 960-- Jump to new location (adjusting for encoding of characters) 961local pos =vim . pos . lsp ( bufnr , range . start , position_encoding ) 962local row , col =pos . row , pos . col 963api . nvim_win_set_cursor ( win , { row + 1 , col } ) 964vim . _with ( { win =win } , function () 965-- Open folds under the cursor 966vim . cmd ( 'normal! zv' ) 967end ) 968 969-- nvim_win_set_cursor clamps to last char at EOL. In insert mode the cursor 970-- should be past the last char (append position). 971if api . nvim_get_mode (). mode == 'i' then 972local line =api . nvim_buf_get_lines ( bufnr , row , row + 1 , false )[ 1 ] or '' 973if col >= # line then 974api . nvim_feedkeys ( vim . keycode ( '<End>' ), 'n' , false ) 975end 976end 977end 978 979return true 980end 981 982--- Previews a location in a floating window 983--- 984--- behavior depends on type of location: 985--- - for Location, range is shown (e.g., function definition) 986--- - for LocationLink, targetRange is shown (e.g., body of function definition) 987--- 988---@param location lsp.Location|lsp.LocationLink 989---@param opts? vim.lsp.util.open_floating_preview.Opts 990---@return integer? buffer id of float window 991---@return integer? window id of float window 992function M . preview_location ( location , opts ) 993-- location may be LocationLink or Location (more useful for the former) 994local uri =location . targetUri or location . uri 995if uri == nil then 996return 997end 998local bufnr =vim . uri_to_bufnr ( uri ) 999if not api . nvim_buf_is_loaded ( bufnr ) then 1000vim . fn . bufload ( bufnr ) 1001end 1002local range =location . targetRange or location . range 1003local contents =api . nvim_buf_get_lines ( bufnr , range . start . line , range [ 'end' ]. line + 1 , false ) 1004local syntax =vim . bo [ bufnr ]. syntax 1005if syntax == '' then 1006-- When no syntax is set, we use filetype as fallback. This might not result 1007-- in a valid syntax definition. 1008-- An empty syntax is more common now with TreeSitter, since TS disables syntax. 1009syntax =vim . bo [ bufnr ]. filetype 1010end 1011opts =opts or {} 1012opts . focus_id ='location' 1013return M . open_floating_preview ( contents , syntax , opts ) 1014end 1015 1016--- @param name string 1017--- @param value any 1018local function find_window_by_var ( name , value ) 1019for _ , win in ipairs ( api . nvim_list_wins ()) do 1020if vim . w [ win ][ name ] == value then 1021return win 1022end 1023end 1024end 1025 1026---@param winnr integer 1027---@return boolean `true` if `winnr` is a valid floating window 1028local function is_float ( winnr ) 1029return api . nvim_win_is_valid ( winnr ) and vim . fn . win_gettype ( winnr ) == 'popup' 1030end 1031 1032---Returns true if the line is empty or only contains whitespace. 1033---@param line string? 1034---@return boolean 1035local function is_blank_line ( line ) 1036return line ~= nil and line : match ( '^%s*$' ) ~= nil 1037end 1038 1039---Returns true if the line corresponds to a Markdown thematic break. 1040---@see https://github.github.com/gfm/#thematic-break 1041---@param line string 1042---@return boolean 1043local function is_separator_line ( line ) 1044local i =1 1045-- 1. Skip up to 3 leading spaces 1046local leading_spaces =3 1047while i <= # line and line : byte ( i ) == string . byte ( ' ' ) and leading_spaces > 0 do 1048i =i + 1 1049leading_spaces =leading_spaces - 1 1050end 1051-- 2. Determine the delimiter character 1052local delimiter =line : byte ( i ) -- nil if i > #line 1053if 1054delimiter ~= string . byte ( '-' ) 1055and delimiter ~= string . byte ( '_' ) 1056and delimiter ~= string . byte ( '*' ) 1057then 1058return false 1059end 1060local ndelimiters =1 1061i =i + 1 1062-- 3. Iterate until found non-whitespace or other than expected delimiter 1063while i <= # line do 1064local char =line : byte ( i ) 1065if char == delimiter then 1066ndelimiters =ndelimiters + 1 1067elseif not ( char == string . byte ( ' ' ) or char == string . byte ( '\t' )) then 1068return false 1069end 1070i =i + 1 1071end 1072return ndelimiters >= 3 1073end 1074 1075---Replaces separator lines by the given divider and removing surrounding blank lines. 1076---@param contents string[] 1077---@param divider string 1078---@return string[] 1079local function replace_separators ( contents , divider ) 1080local trimmed ={} 1081local l =1 1082while l <= # contents do 1083local line =assert ( contents [ l ]) 1084if is_separator_line ( line ) then 1085if l > 1 and is_blank_line ( contents [ l - 1 ]) then 1086table . remove ( trimmed ) 1087end 1088table . insert ( trimmed , divider ) 1089if is_blank_line ( contents [ l + 1 ]) then 1090l =l + 1 1091end 1092else 1093table . insert ( trimmed , line ) 1094end 1095l =l + 1 1096end 1097 1098return trimmed 1099end 1100 1101---Collapses successive blank lines in the input table into a single one. 1102---@param contents string[] 1103---@return string[] 1104local function collapse_blank_lines ( contents ) 1105local collapsed ={} 1106local l =1 1107while l <= # contents do 1108local line =contents [ l ] 1109if is_blank_line ( line ) then 1110while is_blank_line ( contents [ l + 1 ]) do 1111l =l + 1 1112end 1113end 1114table . insert ( collapsed , line ) 1115l =l + 1 1116end 1117return collapsed 1118end 1119 1120local function get_markdown_fences () 1121local fences ={} --- @type table<string,string> 1122for _ , fence in 1123pairs ( vim . g . markdown_fenced_languages or {} --[[@as string[] ]] ) 1124do 1125local lang , syntax =fence : match ( '^(.*)=(.*)$' ) 1126if lang then 1127fences [ lang ] =syntax 1128end 1129end 1130return fences 1131end 1132 1133--- @deprecated 1134--- Converts markdown into syntax highlighted regions by stripping the code 1135--- blocks and converting them into highlighted code. 1136--- This will by default insert a blank line separator after those code block 1137--- regions to improve readability. 1138--- 1139--- This method configures the given buffer and returns the lines to set. 1140--- 1141--- If you want to open a popup with fancy markdown, use `open_floating_preview` instead 1142--- 1143---@param bufnr integer 1144---@param contents string[] of lines to show in window 1145---@param opts? table with optional fields 1146--- - height of floating window 1147--- - max_height maximal height of floating window 1148--- - max_width maximal width of floating window 1149--- - separator insert separator after code block 1150--- - width of floating window 1151--- - wrap_at character to wrap at for computing height 1152---@return table stripped content 1153function M . stylize_markdown ( bufnr , contents , opts ) 1154vim . deprecate ( 'vim.lsp.util.stylize_markdown' , nil , '0.14' ) 1155validate ( 'contents' , contents , 'table' ) 1156validate ( 'opts' , opts , 'table' , true ) 1157opts =opts or {} 1158 1159-- table of fence types to {ft, begin, end} 1160-- when ft is nil, we get the ft from the regex match 1161local matchers ={ 1162block ={ nil , '```+%s*([a-zA-Z0-9_]*)' , '```+' } , 1163pre ={ nil , '<pre>([a-z0-9]*)' , '</pre>' } , 1164code ={ '' , '<code>' , '</code>' } , 1165text ={ 'text' , '<text>' , '</text>' } , 1166} 1167 1168--- @param line string 1169--- @return {pattern:string,ft:string}? 1170local function match_begin ( line ) 1171for _ , pattern in pairs ( matchers ) do 1172--- @type string? 1173local ret =line : match ( string . format ( '^%%s*%s%%s*$' , pattern [ 2 ])) 1174if ret then 1175return { 1176pattern =pattern [ 3 ], 1177ft =pattern [ 1 ] or ret , 1178} 1179end 1180end 1181end 1182 1183--- @param line string 1184--- @param match {pattern:string,ft:string} 1185--- @return string? 1186local function match_end ( line , match ) 1187return line : match ( string . format ( '^%%s*%s%%s*$' , match . pattern )) 1188end 1189 1190-- Clean up 1191contents =vim . split ( table . concat ( contents , '\n' ), '\n' , { trimempty =true } ) 1192 1193local stripped ={} --- @type string[] 1194local highlights ={} --- @type {ft:string,start:integer,finish:integer}[] 1195 1196local i =1 1197while i <= # contents do 1198local line =assert ( contents [ i ]) 1199local match =match_begin ( line ) 1200if match then 1201local start =# stripped 1202i =i + 1 1203while i <= # contents do 1204line =assert ( contents [ i ]) 1205if match_end ( line , match ) then 1206i =i + 1 1207break 1208end 1209stripped [ # stripped + 1 ] =line 1210i =i + 1 1211end 1212table . insert ( highlights , { 1213ft =match . ft , 1214start =start + 1 , 1215finish =# stripped , 1216} ) 1217-- add a separator, but not on the last line 1218if opts . separator and i < # contents then 1219stripped [ # stripped + 1 ] ='---' 1220end 1221else 1222-- strip any empty lines or separators prior to this separator in actual markdown 1223if line : match ( '^---+$' ) then 1224while 1225stripped [ # stripped ] 1226and ( stripped [ # stripped ]: match ( '^%s*$' ) or stripped [ # stripped ]: match ( '^---+$' )) 1227do 1228stripped [ # stripped ] =nil 1229end 1230end 1231-- add the line if its not an empty line following a separator 1232if 1233not ( line : match ( '^%s*$' ) and stripped [ # stripped ] and stripped [ # stripped ]: match ( '^---+$' )) 1234then 1235stripped [ # stripped + 1 ] =line 1236end 1237i =i + 1 1238end 1239end 1240 1241-- Handle some common html escape sequences 1242--- @type string[] 1243stripped =vim . tbl_map ( 1244--- @param line string 1245function ( line ) 1246local escapes ={ 1247[ '>' ] ='>' , 1248[ '<' ] ='<' , 1249[ '"' ] ='"' , 1250[ ''' ] ="'" , 1251[ ' ' ] =' ' , 1252[ ' ' ] =' ' , 1253[ '&' ] ='&' , 1254} 1255return ( line : gsub ( '&[^ ;]+;' , escapes )) 1256end , 1257stripped 1258) 1259 1260-- Compute size of float needed to show (wrapped) lines 1261opts . wrap_at =opts . wrap_at or ( vim . wo [ 'wrap' ] and api . nvim_win_get_width ( 0 )) 1262local width =M . _make_floating_popup_size ( stripped , opts ) 1263 1264local sep_line =string . rep ( '─' , math . min ( width , opts . wrap_at or width )) 1265 1266for l , line in ipairs ( stripped ) do 1267if line : match ( '^---+$' ) then 1268stripped [ l ] =sep_line 1269end 1270end 1271 1272api . nvim_buf_set_lines ( bufnr , 0 , - 1 , false , stripped ) 1273 1274local idx =1 1275-- keep track of syntaxes we already included. 1276-- no need to include the same syntax more than once 1277local langs ={} --- @type table<string,boolean> 1278local fences =get_markdown_fences () 1279--- @param ft string 1280--- @param start integer 1281--- @param finish integer 1282local function apply_syntax_to_region ( ft , start , finish ) 1283if ft == '' then 1284vim . cmd ( 1285string . format ( 1286'syntax region markdownCode start=+\\%%%dl+ end=+\\%%%dl+ keepend extend' , 1287start , 1288finish + 1 1289) 1290) 1291return 1292end 1293ft =fences [ ft ] or ft 1294local name =ft .. idx 1295idx =idx + 1 1296local lang ='@' .. ft : upper () 1297if not langs [ lang ] then 1298-- HACK: reset current_syntax, since some syntax files like markdown won't load if it is already set 1299pcall ( api . nvim_buf_del_var , bufnr , 'current_syntax' ) 1300if # api . nvim_get_runtime_file (( 'syntax/%s.vim' ): format ( ft ), true ) == 0 then 1301return 1302end 1303--- @diagnostic disable-next-line:param-type-mismatch 1304pcall ( vim . cmd , string . format ( 'syntax include %s syntax/%s.vim' , lang , ft )) 1305langs [ lang ] =true 1306end 1307vim . cmd ( 1308string . format ( 1309'syntax region %s start=+\\%%%dl+ end=+\\%%%dl+ contains=%s keepend' , 1310name , 1311start , 1312finish + 1 , 1313lang 1314) 1315) 1316end 1317 1318-- needs to run in the buffer for the regions to work 1319vim . _with ( { buf =bufnr } , function () 1320-- we need to apply lsp_markdown regions speperately, since otherwise 1321-- markdown regions can "bleed" through the other syntax regions 1322-- and mess up the formatting 1323local last =1 1324for _ , h in ipairs ( highlights ) do 1325if last < h . start then 1326apply_syntax_to_region ( 'lsp_markdown' , last , h . start - 1 ) 1327end 1328apply_syntax_to_region ( h . ft , h . start , h . finish ) 1329last =h . finish + 1 1330end 1331if last <= # stripped then 1332apply_syntax_to_region ( 'lsp_markdown' , last , # stripped ) 1333end 1334end ) 1335 1336return stripped 1337end 1338 1339--- @class (private) vim.lsp.util._normalize_markdown.Opts 1340--- @field width? integer Thematic breaks are expanded to this size. Defaults to 80. 1341 1342--- Normalizes Markdown input to a canonical form. 1343--- 1344--- The returned Markdown adheres to the GitHub Flavored Markdown (GFM) 1345--- specification, as required by the LSP. 1346--- 1347--- The following transformations are made: 1348--- 1349--- 1. Carriage returns ('\r') and empty lines at the beginning and end are removed 1350--- 2. Successive empty lines are collapsed into a single empty line 1351--- 3. Thematic breaks are expanded to the given width 1352--- 1353---@param contents string[] 1354---@param opts? vim.lsp.util._normalize_markdown.Opts 1355---@return string[] table of lines containing normalized Markdown 1356---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#markupContent 1357---@see https://github.github.com/gfm 1358function M . _normalize_markdown ( contents , opts ) 1359validate ( 'contents' , contents , 'table' ) 1360validate ( 'opts' , opts , 'table' , true ) 1361opts =opts or {} 1362 1363-- 1. Carriage returns are removed 1364contents =vim . split ( table . concat ( contents , '\n' ): gsub ( '\r' , '' ), '\n' , { trimempty =true } ) 1365 1366-- 2. Successive empty lines are collapsed into a single empty line 1367contents =collapse_blank_lines ( contents ) 1368 1369-- 3. Thematic breaks are expanded to the given width 1370local divider =string . rep ( '─' , opts . width or 80 ) 1371contents =replace_separators ( contents , divider ) 1372 1373return contents 1374end 1375 1376--- Closes the preview window 1377--- 1378---@param winnr integer window id of preview window 1379---@param bufnrs table? optional list of ignored buffers 1380local function close_preview_window ( winnr , bufnrs ) 1381vim . schedule ( function () 1382-- exit if we are in one of ignored buffers 1383if bufnrs and vim . list_contains ( bufnrs , api . nvim_get_current_buf ()) then 1384return 1385end 1386 1387local augroup ='nvim.preview_window_' .. winnr 1388pcall ( api . nvim_del_augroup_by_name , augroup ) 1389 1390-- Preview window was converted to a normal window (e.g. |CTRL-W_H|): 1391-- keep it open and stop managing it. 1392if api . nvim_win_is_valid ( winnr ) and not is_float ( winnr ) then 1393local srcbuf =vim . w [ winnr ]. lsp_floating_bufnr 1394if 1395srcbuf 1396and api . nvim_buf_is_valid ( srcbuf ) 1397and vim . b [ srcbuf ]. lsp_floating_preview == winnr 1398then 1399vim . b [ srcbuf ]. lsp_floating_preview =nil 1400end 1401return 1402end 1403 1404pcall ( api . nvim_win_close , winnr , true ) 1405end ) 1406end 1407 1408--- Creates autocommands to close a preview window when events happen. 1409--- 1410---@param events table list of events 1411---@param winnr integer window id of preview window 1412---@param floating_bufnr integer floating preview buffer 1413---@param bufnr integer buffer that opened the floating preview buffer 1414---@see autocmd-events 1415local function close_preview_autocmd ( events , winnr , floating_bufnr , bufnr ) 1416local augroup =api . nvim_create_augroup ( 'nvim.preview_window_' .. winnr , { 1417clear =true , 1418} ) 1419 1420-- close the preview window when entered a buffer that is not 1421-- the floating window buffer or the buffer that spawned it 1422nvim_on ( 'BufLeave' , augroup , { buf =bufnr } , function () 1423vim . schedule ( function () 1424-- When jumping to the quickfix window from the preview window, 1425-- do not close the preview window. 1426if api . nvim_get_option_value ( 'filetype' , { buf =0 } ) ~= 'qf' then 1427close_preview_window ( winnr , { floating_bufnr , bufnr } ) 1428end 1429end ) 1430end ) 1431 1432if # events > 0 then 1433nvim_on ( events , augroup , { buf =bufnr } , function () 1434close_preview_window ( winnr ) 1435end ) 1436end 1437end 1438 1439--- Computes size of float needed to show contents (with optional wrapping) 1440--- 1441---@param contents string[] of lines to show in window 1442---@param opts? vim.lsp.util.open_floating_preview.Opts 1443---@return integer width size of float 1444---@return integer height size of float 1445function M . _make_floating_popup_size ( contents , opts ) 1446validate ( 'contents' , contents , 'table' ) 1447validate ( 'opts' , opts , 'table' , true ) 1448opts =opts or {} 1449 1450local width =opts . width 1451local height =opts . height 1452local wrap_at =opts . wrap_at 1453local max_width =opts . max_width 1454local max_height =opts . max_height 1455local line_widths ={} --- @type table<integer,integer> 1456 1457if not width then 1458width =0 1459for i , line in ipairs ( contents ) do 1460-- TODO(ashkan) use nvim_strdisplaywidth if/when that is introduced. 1461line_widths [ i ] =vim . fn . strdisplaywidth ( line : gsub ( '%z' , '\n' )) 1462width =math . max ( line_widths [ i ], width ) 1463end 1464end 1465 1466local _ , border_width =get_border_size ( opts ) 1467local screen_width =opts . relative == 'editor' and vim . o . columns or api . nvim_win_get_width ( 0 ) 1468width =math . min ( width , screen_width ) 1469 1470-- make sure borders are always inside the screen 1471width =math . min ( width , screen_width - border_width ) 1472 1473-- Make sure that the width is large enough to fit the title. 1474local title_length =0 1475local chunks =type ( opts . title ) == 'string' and { { opts . title } } or opts . title or {} 1476for _ , chunk in 1477ipairs ( chunks --[=[@as [string, string][] ]=] ) 1478do 1479title_length =title_length + vim . fn . strdisplaywidth ( chunk [ 1 ]) 1480end 1481 1482width =math . max ( width , title_length ) 1483 1484if wrap_at then 1485wrap_at =math . min ( wrap_at , width ) 1486end 1487 1488if max_width then 1489width =math . min ( width , max_width ) 1490wrap_at =math . min ( wrap_at or max_width , max_width ) 1491end 1492 1493if not height then 1494height =# contents 1495if wrap_at and width >= wrap_at then 1496height =0 1497if vim . tbl_isempty ( line_widths ) then 1498for _ , line in ipairs ( contents ) do 1499local line_width =vim . fn . strdisplaywidth ( line : gsub ( '%z' , '\n' )) 1500height =height + math . max ( 1 , math . ceil ( line_width / wrap_at )) 1501end 1502else 1503for i =1 , # contents do 1504height =height + math . max ( 1 , math . ceil ( line_widths [ i ] / wrap_at )) 1505end 1506end 1507end 1508end 1509if max_height then 1510height =math . min ( height , max_height ) 1511end 1512 1513return width , height 1514end 1515 1516--- @class vim.lsp.util.open_floating_preview.Opts 1517--- 1518--- Height of floating window 1519--- @field height? integer 1520--- 1521--- Width of floating window 1522--- @field width? integer 1523--- 1524--- Wrap long lines 1525--- (default: `true`) 1526--- @field wrap? boolean 1527--- 1528--- Character to wrap at for computing height when wrap is enabled 1529--- @field wrap_at? integer 1530--- 1531--- Maximal width of floating window 1532--- @field max_width? integer 1533--- 1534--- Maximal height of floating window 1535--- @field max_height? integer 1536--- 1537--- If a popup with this id is opened, then focus it 1538--- @field focus_id? string 1539--- 1540--- List of events that closes the floating window 1541--- @field close_events? table 1542--- 1543--- Make float focusable. 1544--- (default: `true`) 1545--- @field focusable? boolean 1546--- 1547--- If `true`, and if {focusable} is also `true`, focus an existing floating 1548--- window with the same {focus_id} 1549--- (default: `true`) 1550--- @field focus? boolean 1551--- 1552--- offset to add to `col` 1553--- @field offset_x? integer 1554--- 1555--- offset to add to `row` 1556--- @field offset_y? integer 1557--- @field border? ''|'none'|'single'|'double'|'rounded'|'solid'|'shadow'|'bold'|(string|[string,string])[] override `border` 1558--- @field zindex? integer override `zindex`, defaults to 50 1559--- @field title? string|[string,string][] 1560--- @field title_pos? 'left'|'center'|'right' 1561--- 1562--- (default: `'cursor'`) 1563--- @field relative? 'mouse'|'cursor'|'editor' 1564--- 1565--- Adjusts placement relative to cursor. 1566--- - "auto": place window based on which side of the cursor has more lines 1567--- - "above": place the window above the cursor unless there are not enough lines 1568--- to display the full window height. 1569--- - "below": place the window below the cursor unless there are not enough lines 1570--- to display the full window height. 1571--- (default: `'auto'`) 1572--- @field anchor_bias? 'auto'|'above'|'below' 1573--- 1574--- @field _update_win? integer 1575 1576--- Shows contents in a floating window. 1577--- 1578---@param contents table of lines to show in window 1579---@param syntax string of syntax to set for opened buffer 1580---@param opts? vim.lsp.util.open_floating_preview.Opts with optional fields 1581--- (additional keys are filtered with |vim.lsp.util.make_floating_popup_options()| 1582--- before they are passed on to |nvim_open_win()|) 1583---@return integer bufnr of newly created float window 1584---@return integer winid of newly created float window preview window 1585function M . open_floating_preview ( contents , syntax , opts ) 1586validate ( 'contents' , contents , 'table' ) 1587validate ( 'syntax' , syntax , 'string' , true ) 1588validate ( 'opts' , opts , 'table' , true ) 1589opts =opts or {} 1590opts . wrap =opts . wrap ~= false -- wrapping by default 1591opts . focus =opts . focus ~= false 1592opts . close_events =opts . close_events or { 'CursorMoved' , 'CursorMovedI' , 'InsertCharPre' } 1593 1594local bufnr =api . nvim_get_current_buf () 1595 1596local floating_winnr =opts . _update_win 1597 1598-- Create/get the buffer 1599local floating_bufnr --- @type integer 1600if floating_winnr then 1601floating_bufnr =api . nvim_win_get_buf ( floating_winnr ) 1602else 1603-- check if this popup is focusable and we need to focus 1604if opts . focus_id and opts . focusable ~= false and opts . focus then 1605-- Go back to previous window if we are in a focusable one 1606local current_winnr =api . nvim_get_current_win () 1607if vim . w [ current_winnr ][ opts . focus_id ] and is_float ( current_winnr ) then 1608api . nvim_command ( 'wincmd p' ) 1609return bufnr , current_winnr 1610end 1611do 1612local win =find_window_by_var ( opts . focus_id , bufnr ) 1613if win and is_float ( win ) and vim . fn . pumvisible () == 0 then 1614-- focus and return the existing buf, win 1615api . nvim_set_current_win ( win ) 1616api . nvim_command ( 'stopinsert' ) 1617return api . nvim_win_get_buf ( win ), win 1618end 1619end 1620end 1621 1622-- check if another floating preview already exists for this buffer 1623-- and close it if needed 1624local existing_float =vim . b [ bufnr ]. lsp_floating_preview 1625if existing_float and is_float ( existing_float ) then 1626api . nvim_win_close ( existing_float , true ) 1627end 1628floating_bufnr =api . nvim_create_buf ( false , true ) 1629end 1630 1631-- Set up the contents, using treesitter for markdown 1632local do_stylize =syntax == 'markdown' and vim . g . syntax_on ~= nil 1633 1634if do_stylize then 1635local width =M . _make_floating_popup_size ( contents , opts ) 1636contents =M . _normalize_markdown ( contents , { width =width } ) 1637else 1638-- Clean up input: trim empty lines 1639contents =vim . split ( table . concat ( contents , '\n' ), '\n' , { trimempty =true } ) 1640 1641if syntax then 1642vim . bo [ floating_bufnr ]. syntax =syntax 1643end 1644end 1645 1646vim . bo [ floating_bufnr ]. modifiable =true 1647api . nvim_buf_set_lines ( floating_bufnr , 0 , - 1 , false , contents ) 1648 1649if floating_winnr then 1650api . nvim_win_set_config ( floating_winnr , { 1651border =opts . border , 1652title =opts . title , 1653} ) 1654else 1655-- Compute size of float needed to show (wrapped) lines 1656if opts . wrap then 1657opts . wrap_at =opts . wrap_at or api . nvim_win_get_width ( 0 ) 1658else 1659opts . wrap_at =nil 1660end 1661 1662-- TODO(lewis6991): These function assume the current window to determine options, 1663-- therefore it won't work for opts._update_win and the current window if the floating 1664-- window 1665local width , height =M . _make_floating_popup_size ( contents , opts ) 1666local float_option =M . make_floating_popup_options ( width , height , opts ) 1667 1668floating_winnr =api . nvim_open_win ( floating_bufnr , false , float_option ) 1669 1670api . nvim_buf_set_keymap ( 1671floating_bufnr , 1672'n' , 1673'q' , 1674'<cmd>bdelete<cr>' , 1675{ silent =true , noremap =true , nowait =true } 1676) 1677close_preview_autocmd ( opts . close_events , floating_winnr , floating_bufnr , bufnr ) 1678 1679-- save focus_id 1680if opts . focus_id then 1681api . nvim_win_set_var ( floating_winnr , opts . focus_id , bufnr ) 1682end 1683api . nvim_buf_set_var ( bufnr , 'lsp_floating_preview' , floating_winnr ) 1684api . nvim_win_set_var ( floating_winnr , 'lsp_floating_bufnr' , bufnr ) 1685end 1686 1687nvim_on ( 1688'WinClosed' , 1689api . nvim_create_augroup ( 'nvim.closing_floating_preview' , { clear =true } ), 1690function ( args ) 1691local winid =vim . _assert_integer ( args . match ) 1692local preview_bufnr =vim . w [ winid ]. lsp_floating_bufnr --- @type integer? 1693if 1694preview_bufnr 1695and api . nvim_buf_is_valid ( preview_bufnr ) 1696and winid == vim . b [ preview_bufnr ]. lsp_floating_preview 1697then 1698vim . b [ bufnr ]. lsp_floating_preview =nil 1699return true 1700end 1701end 1702) 1703 1704vim . wo [ floating_winnr ]. foldenable =false -- Disable folding. 1705vim . wo [ floating_winnr ]. wrap =opts . wrap -- Soft wrapping. 1706vim . wo [ floating_winnr ]. linebreak =true -- Break lines a bit nicer 1707vim . wo [ floating_winnr ]. breakindent =true -- Slightly better list presentation. 1708vim . wo [ floating_winnr ]. smoothscroll =true -- Scroll by screen-line instead of buffer-line. 1709vim . wo [ floating_winnr ]. winfixbuf =true -- Disable buffer switching. 1710 1711vim . bo [ floating_bufnr ]. modifiable =false 1712vim . bo [ floating_bufnr ]. bufhidden ='wipe' 1713 1714if do_stylize then 1715vim . wo [ floating_winnr ]. conceallevel =2 1716vim . wo [ floating_winnr ]. concealcursor ='' 1717vim . bo [ floating_bufnr ]. filetype ='markdown' 1718vim . treesitter . start ( floating_bufnr ) 1719if not opts . height then 1720-- Reduce window height if TS highlighter conceals code block backticks. 1721local win_height =api . nvim_win_get_height ( floating_winnr ) 1722local text_height =api . nvim_win_text_height ( floating_winnr , { max_height =win_height } ). all 1723if text_height < win_height then 1724api . nvim_win_resize ( floating_winnr , - 1 , text_height ) 1725end 1726end 1727end 1728 1729return floating_bufnr , floating_winnr 1730end 1731 1732do --[[ References ]] 1733local reference_ns =api . nvim_create_namespace ( 'nvim.lsp.references' ) 1734 1735--- Removes document highlights from a buffer. 1736--- 1737---@param bufnr integer? Buffer id 1738function M . buf_clear_references ( bufnr ) 1739api . nvim_buf_clear_namespace ( bufnr or 0 , reference_ns , 0 , - 1 ) 1740end 1741 1742--- Shows a list of document highlights for a certain buffer. 1743--- 1744---@param bufnr integer Buffer id 1745---@param references lsp.DocumentHighlight[] objects to highlight 1746---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 1747---@see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent 1748function M . buf_highlight_references ( bufnr , references , position_encoding ) 1749validate ( 'bufnr' , bufnr , 'number' , true ) 1750validate ( 'position_encoding' , position_encoding , 'string' , false ) 1751for _ , reference in ipairs ( references ) do 1752local range =vim . range . lsp ( bufnr , reference . range , position_encoding ) 1753 1754local document_highlight_kind ={ 1755[ protocol . DocumentHighlightKind . Text ] ='LspReferenceText' , 1756[ protocol . DocumentHighlightKind . Read ] ='LspReferenceRead' , 1757[ protocol . DocumentHighlightKind . Write ] ='LspReferenceWrite' , 1758} 1759local kind =reference [ 'kind' ] or protocol . DocumentHighlightKind . Text 1760vim . hl . range ( 1761bufnr , 1762reference_ns , 1763document_highlight_kind [ kind ], 1764{ range . start_row , range . start_col } , 1765{ range . end_row , range . end_col } , 1766{ priority =vim . hl . priorities . user } 1767) 1768end 1769end 1770end 1771 1772local position_sort =sort_by_key ( function ( v ) 1773return { v . start . line , v . start . character } 1774end ) 1775 1776--- Returns the items with the byte position calculated correctly and in sorted 1777--- order, for display in quickfix and location lists. 1778--- 1779--- The `user_data` field of each resulting item will contain the original 1780--- `Location` or `LocationLink` it was computed from. 1781--- 1782--- The result can be passed to the {list} argument of |setqflist()| or 1783--- |setloclist()|. 1784--- 1785---@param locations lsp.Location[]|lsp.LocationLink[] 1786---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 1787---@return vim.quickfix.entry[] # See |setqflist()| for the format 1788function M . locations_to_items ( locations , position_encoding ) 1789validate ( 'position_encoding' , position_encoding , 'string' ) 1790 1791local items ={} --- @type vim.quickfix.entry[] 1792 1793---@type table<string, {start: lsp.Position, end: lsp.Position, location: lsp.Location|lsp.LocationLink}[]> 1794local grouped ={} 1795for _ , d in ipairs ( locations ) do 1796-- locations may be Location or LocationLink 1797local uri =d . uri or d . targetUri 1798local range =d . range or d . targetSelectionRange 1799grouped [ uri ] =grouped [ uri ] or {} 1800table . insert ( grouped [ uri ], { start =range . start , [ 'end' ] =range [ 'end' ], location =d } ) 1801end 1802 1803for uri , rows in vim . spairs ( grouped ) do 1804table . sort ( rows , position_sort ) 1805local filename =vim . uri_to_fname ( uri ) 1806 1807local line_numbers ={} 1808for _ , temp in ipairs ( rows ) do 1809table . insert ( line_numbers , temp . start . line ) 1810if temp . start . line ~= temp [ 'end' ]. line then 1811table . insert ( line_numbers , temp [ 'end' ]. line ) 1812end 1813end 1814 1815-- get all the lines for this uri 1816local lines =get_lines ( vim . uri_to_bufnr ( uri ), line_numbers ) 1817 1818for _ , temp in ipairs ( rows ) do 1819local pos =temp . start 1820local end_pos =temp [ 'end' ] 1821local row =pos . line 1822local end_row =end_pos . line 1823local line =lines [ row ] 1824local end_line =lines [ end_row ] 1825local col =vim . str_byteindex ( line , position_encoding , pos . character , false ) 1826local end_col =vim . str_byteindex ( end_line , position_encoding , end_pos . character , false ) 1827 1828items [ # items + 1 ] ={ 1829filename =filename , 1830lnum =row + 1 , 1831end_lnum =end_row + 1 , 1832col =col + 1 , 1833end_col =end_col + 1 , 1834text =line , 1835user_data =temp . location , 1836} 1837end 1838end 1839return items 1840end 1841 1842--- Converts symbols to quickfix list items. 1843--- 1844---@param symbols lsp.DocumentSymbol[]|lsp.SymbolInformation[]|lsp.WorkspaceSymbol[] list of symbols 1845---@param bufnr? integer buffer handle or 0 for current, defaults to current 1846---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 1847---@return vim.quickfix.entry[] # See |setqflist()| for the format 1848function M . symbols_to_items ( symbols , bufnr , position_encoding ) 1849validate ( 'position_encoding' , position_encoding , 'string' ) 1850 1851bufnr =vim . _resolve_bufnr ( bufnr ) 1852 1853local items ={} --- @type vim.quickfix.entry[] 1854for _ , symbol in ipairs ( symbols ) do 1855--- @type string?, vim.Range? 1856local filename , range 1857 1858if symbol . location then 1859--- @cast symbol lsp.SymbolInformation 1860filename =vim . uri_to_fname ( symbol . location . uri ) 1861range =vim . range . lsp ( bufnr , symbol . location . range , position_encoding ) 1862elseif symbol . selectionRange then 1863--- @cast symbol lsp.DocumentSymbol 1864filename =api . nvim_buf_get_name ( bufnr ) 1865range =vim . range . lsp ( bufnr , symbol . selectionRange , position_encoding ) 1866end 1867 1868if filename and range then 1869local kind =protocol . SymbolKind [ symbol . kind ] or 'Unknown' 1870---@diagnostic disable-next-line: deprecated 1871local is_deprecated =not vim . isnil ( symbol . deprecated or nil ) 1872or ( 1873not vim . isnil ( symbol . tags ) 1874and vim . tbl_contains ( symbol . tags , protocol . SymbolTag . Deprecated ) 1875) 1876local text =string . format ( 1877'[%s] %s%s%s' , 1878kind , 1879symbol . name , 1880not vim . isnil ( symbol . containerName ) and ' in ' .. symbol . containerName or '' , 1881is_deprecated and ' (deprecated)' or '' 1882) 1883 1884items [ # items + 1 ] ={ 1885filename =filename , 1886lnum =range . start_row + 1 , 1887col =range . start_col + 1 , 1888end_lnum =range . end_row + 1 , 1889end_col =range . end_col + 1 , 1890kind =kind , 1891text =text , 1892} 1893end 1894 1895if symbol . children then 1896list_extend ( items , M . symbols_to_items ( symbol . children , bufnr , position_encoding )) 1897end 1898end 1899 1900return items 1901end 1902 1903--- Creates a `TextDocumentPositionParams` object for the current buffer and cursor position. 1904--- 1905---@param win integer?: |window-ID| or 0 for current, defaults to current 1906---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 1907---@return lsp.TextDocumentPositionParams 1908---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams 1909function M . make_position_params ( win , position_encoding ) 1910win =win or 0 1911return { 1912textDocument =M . make_text_document_params ( api . nvim_win_get_buf ( win )), 1913position =vim . pos . cursor ( win ): to_lsp ( position_encoding ), 1914} 1915end 1916 1917--- Using the current position in the current buffer, creates an object that 1918--- can be used as a building block for several LSP requests, such as 1919--- `textDocument/codeAction`, `textDocument/colorPresentation`, 1920--- `textDocument/rangeFormatting`. 1921--- 1922---@param win integer?: |window-ID| or 0 for current, defaults to current 1923---@param position_encoding "utf-8"|"utf-16"|"utf-32" 1924---@return { textDocument: { uri: lsp.DocumentUri }, range: lsp.Range } 1925function M . make_range_params ( win , position_encoding ) 1926win =win or 0 1927local buf =api . nvim_win_get_buf ( win ) 1928local position =vim . pos . cursor ( buf , api . nvim_win_get_cursor ( win )): to_lsp ( position_encoding ) 1929return { 1930textDocument =M . make_text_document_params ( buf ), 1931range ={ start =position , [ 'end' ] =position } , 1932} 1933end 1934 1935--- Using the given range in the current buffer, creates an object that 1936--- is similar to |vim.lsp.util.make_range_params()|. 1937--- 1938---@param start_pos [integer,integer]? {row,col} mark-indexed position. 1939--- Defaults to the start of the last visual selection. 1940---@param end_pos [integer,integer]? {row,col} mark-indexed position. 1941--- Defaults to the end of the last visual selection. 1942---@param bufnr integer? buffer handle or 0 for current, defaults to current 1943---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 1944---@return { textDocument: { uri: lsp.DocumentUri }, range: lsp.Range } 1945function M . make_given_range_params ( start_pos , end_pos , bufnr , position_encoding ) 1946validate ( 'start_pos' , start_pos , 'table' , true ) 1947validate ( 'end_pos' , end_pos , 'table' , true ) 1948validate ( 'position_encoding' , position_encoding , 'string' ) 1949 1950bufnr =vim . _resolve_bufnr ( bufnr ) 1951local start_row , start_col =unpack ( start_pos or api . nvim_buf_get_mark ( bufnr , '<' )) 1952local end_row , end_col =unpack ( end_pos or api . nvim_buf_get_mark ( bufnr , '>' )) 1953return { 1954textDocument =M . make_text_document_params ( bufnr ), 1955range =vim . range . mark ( bufnr , start_row , start_col , end_row , end_col ): to_lsp ( position_encoding ), 1956} 1957end 1958 1959--- Creates a `TextDocumentIdentifier` object for the current buffer. 1960--- 1961---@param bufnr integer?: Buffer handle, defaults to current 1962---@return lsp.TextDocumentIdentifier 1963---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier 1964function M . make_text_document_params ( bufnr ) 1965return { uri =vim . uri_from_bufnr ( bufnr or 0 ) } 1966end 1967 1968--- Create the workspace params 1969---@param added lsp.WorkspaceFolder[] 1970---@param removed lsp.WorkspaceFolder[] 1971---@return lsp.DidChangeWorkspaceFoldersParams 1972function M . make_workspace_params ( added , removed ) 1973return { event ={ added =added , removed =removed } } 1974end 1975 1976--- Returns indentation size. 1977--- 1978---@see 'shiftwidth' 1979---@param bufnr integer?: Buffer handle, defaults to current 1980---@return integer indentation size 1981function M . get_effective_tabstop ( bufnr ) 1982validate ( 'bufnr' , bufnr , 'number' , true ) 1983local bo =bufnr and vim . bo [ bufnr ] or vim . bo 1984local sw =bo . shiftwidth 1985return ( sw == 0 and bo . tabstop ) or sw 1986end 1987 1988--- Creates a `DocumentFormattingParams` object for the current buffer and cursor position. 1989--- 1990---@param options lsp.FormattingOptions? with valid `FormattingOptions` entries 1991---@return lsp.DocumentFormattingParams object 1992---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting 1993function M . make_formatting_params ( options ) 1994validate ( 'options' , options , 'table' , true ) 1995options =vim . tbl_extend ( 'keep' , options or {} , { 1996tabSize =M . get_effective_tabstop (), 1997insertSpaces =vim . bo . expandtab , 1998} ) --[[@as lsp.FormattingOptions]] 1999return { 2000textDocument ={ uri =vim . uri_from_bufnr ( 0 ) } , 2001options =options , 2002} 2003end 2004 2005--- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. 2006--- 2007---@deprecated 2008---@param buf integer buffer number (0 for current) 2009---@param row integer 0-indexed line 2010---@param col integer 0-indexed byte offset in line 2011---@param position_encoding 'utf-8'|'utf-16'|'utf-32' 2012---@return integer `position_encoding` index of the character in line {row} column {col} in buffer {buf} 2013function M . character_offset ( buf , row , col , position_encoding ) 2014vim . deprecate ( 'vim.lsp.util.character_offset' , 'vim.str_utfindex' , '0.14' ) 2015validate ( 'position_encoding' , position_encoding , 'string' ) 2016 2017local line =get_line ( buf , row ) 2018return vim . str_utfindex ( line , position_encoding , col , false ) 2019end 2020 2021---@class (private) vim.lsp.util._cancel_requests.Filter 2022---@field bufnr? integer 2023---@field clients? vim.lsp.Client[] 2024---@field method? vim.lsp.protocol.Method.ClientToServer.Request 2025---@field type? string 2026 2027--- Cancel all {filter}ed requests. 2028--- 2029---@param filter? vim.lsp.util._cancel_requests.Filter 2030function M . _cancel_requests ( filter ) 2031filter =filter or {} 2032local bufnr =filter . bufnr and vim . _resolve_bufnr ( filter . bufnr ) or nil 2033local clients =filter . clients 2034local method =filter . method 2035local type =filter . type 2036 2037for _ , client in 2038ipairs ( clients or vim . lsp . get_clients ( { 2039bufnr =bufnr , 2040method =method , 2041} )) 2042do 2043for id , request in pairs ( client . requests ) do 2044if 2045( bufnr == nil or bufnr == request . bufnr ) 2046and ( method == nil or method == request . method ) 2047and ( type == nil or type == request . type ) 2048then 2049client : cancel_request ( id ) 2050end 2051end 2052end 2053end 2054 2055---@nodoc 2056---@type table<integer,integer> 2057M . buf_versions =setmetatable ( {} , { 2058__index =function ( t , bufnr ) 2059return rawget ( t , bufnr ) or 0 2060end , 2061} ) 2062 2063return M