robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief 2--- The `vim.lsp.completion` module enables insert-mode completion driven by an LSP server. Call 3--- `enable()` to make it available through Nvim builtin completion (via the |CompleteDone| event). 4--- Specify `autotrigger=true` to activate "auto-completion" when you type any of the server-defined 5--- `triggerCharacters`. Use CTRL-Y to select an item from the completion menu. |complete_CTRL-Y| 6--- 7--- Example: activate LSP-driven auto-completion: 8--- ```lua 9--- -- Works best if 'completeopt' has "noselect". 10--- -- Use CTRL-Y to select an item. |complete_CTRL-Y| 11--- vim.cmd[[set completeopt+=menuone,noselect,popup]] 12--- vim.lsp.start({ 13--- name = 'ts_ls', 14--- cmd = …, 15--- on_attach = function(client, bufnr) 16--- vim.lsp.completion.enable(true, client.id, bufnr, { 17--- autotrigger = true, 18--- convert = function(item) 19--- return { abbr = item.label:gsub('%b()', '') } 20--- end, 21--- }) 22--- end, 23--- }) 24--- ``` 25--- 26--- [lsp-autocompletion]() 27--- 28--- The LSP `triggerCharacters` field decides when to trigger autocompletion. If you want to trigger 29--- on EVERY keypress you can either: 30--- - Extend `client.server_capabilities.completionProvider.triggerCharacters` on `LspAttach`, 31--- before you call `vim.lsp.completion.enable(… {autotrigger=true})`. See the |lsp-attach| example. 32--- - Call `vim.lsp.completion.get()` from an |InsertCharPre| autocommand. 33--- 34--- If the server provides `commitCharacters` for a completion item, typing one 35--- of those characters while the item is selected accepts the completion and 36--- then inserts the character. To disable this: 37--- 38--- ```lua 39--- vim.lsp.completion.enable(true, client_id, bufnr, { commit_characters = false }) 40--- ``` 41 42local M ={} 43 44local api =vim . api 45local nvim_on =require ( 'vim._core.util' ). nvim_on 46local lsp =vim . lsp 47local protocol =lsp . protocol 48 49local rtt_ms =50.0 50local ns_to_ms =0.000001 51 52--- @alias vim.lsp.CompletionResult lsp.CompletionList | lsp.CompletionItem[] 53 54-- TODO(mariasolos): Remove this declaration once we figure out a better way to handle 55-- literal/anonymous types (see https://github.com/neovim/neovim/pull/27542/files#r1495259331). 56--- @nodoc 57--- @class lsp.ItemDefaults 58--- @field commitCharacters string[]? 59--- @field editRange lsp.Range | { insert: lsp.Range, replace: lsp.Range } | nil 60--- @field insertTextFormat lsp.InsertTextFormat? 61--- @field insertTextMode lsp.InsertTextMode? 62--- @field data any 63 64--- @nodoc 65--- @class vim.lsp.completion.BufHandle 66--- @field clients table<integer, vim.lsp.Client> 67--- @field triggers table<string, vim.lsp.Client[]> 68--- @field convert? fun(item: lsp.CompletionItem): table 69 70--- @type table<integer, vim.lsp.completion.BufHandle> 71local buf_handles ={} 72 73--- @nodoc 74--- @class vim.lsp.completion.Context 75local Context ={ 76cursor =nil , --- @type [integer, integer]? 77last_request_time =nil , --- @type integer? 78pending_requests ={} , --- @type function[] 79isIncomplete =false , 80-- Handles "completionItem/resolve". 81resolve_handler =nil , --- @type CompletionResolver? 82} 83 84--- @nodoc 85function Context : cancel_pending () 86for _ , cancel in ipairs ( self . pending_requests ) do 87cancel () 88end 89 90self . pending_requests ={} 91end 92 93--- @nodoc 94function Context : reset () 95-- Note that the cursor isn't reset here, it needs to survive a `CompleteDone` event. 96self . isIncomplete =false 97self . last_request_time =nil 98self : cancel_pending () 99if self . resolve_handler then 100self . resolve_handler : cleanup () 101self . resolve_handler =nil 102end 103end 104 105--- @type uv.uv_timer_t? 106local completion_timer =nil 107 108--- @return uv.uv_timer_t 109local function new_timer () 110return ( assert ( vim . uv . new_timer ())) 111end 112 113local function reset_timer () 114if completion_timer then 115completion_timer : stop () 116completion_timer : close () 117end 118 119completion_timer =nil 120end 121 122--- @param window integer 123--- @param warmup integer 124--- @return fun(sample: number): number 125local function exp_avg ( window , warmup ) 126local count =0 127local sum =0 128local value =0.0 129 130return function ( sample ) 131if count < warmup then 132count =count + 1 133sum =sum + sample 134value =sum / count 135else 136local factor =2.0 / ( window + 1 ) 137value =value * ( 1 - factor ) + sample * factor 138end 139return value 140end 141end 142local compute_new_average =exp_avg ( 10 , 10 ) 143 144--- Calculates the adaptive debounce time based on the elapsed time since the last request. 145--- 146--- @param last_request_time integer? 147--- @param current_rtt_ms number 148--- @return number 149local function adaptive_debounce ( last_request_time , current_rtt_ms ) 150if not last_request_time then 151return current_rtt_ms 152end 153local ms_since_request =( vim . uv . hrtime () - last_request_time ) * ns_to_ms 154return math . max (( ms_since_request - current_rtt_ms ) * - 1 , 0 ) 155end 156 157--- @param flag string 158--- @return boolean 159local function has_completeopt ( flag ) 160return vim . list_contains ( vim . opt . completeopt : get () --[[@as string[] ]] , flag ) 161end 162 163--- @param s string? 164--- @return string? 165local function nonempty ( s ) 166return s ~= '' and s or nil 167end 168 169--- @param input string Unparsed snippet 170--- @return string # Parsed snippet if successful, else returns its input 171local function parse_snippet ( input ) 172local ok , parsed =pcall ( function () 173return lsp . _snippet_grammar . parse ( input ) 174end ) 175return ok and tostring ( parsed ) or input 176end 177 178--- @param item lsp.CompletionItem 179local function apply_snippet ( item ) 180if item . textEdit then 181vim . snippet . expand ( item . textEdit . newText ) 182elseif item . insertText then 183vim . snippet . expand ( item . insertText ) 184end 185end 186 187--- @param item lsp.CompletionItem 188--- @param word string 189--- @param prefix string 190--- @param match fun(word: string, prefix: string): boolean 191local function fallback_filtertext ( item , word , prefix , match ) 192if item . filterText and not match ( word , prefix ) and match ( item . filterText , prefix ) then 193return item . filterText 194end 195return word 196end 197 198--- Returns text that should be inserted when a selecting completion item. The 199--- precedence is as follows: textEdit.newText > insertText > label 200--- 201--- See https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion 202--- 203--- @param item lsp.CompletionItem 204--- @param prefix string 205--- @param match fun(text: string, prefix: string):boolean 206--- @return string 207local function get_completion_word ( item , prefix , match ) 208if item . insertTextFormat == protocol . InsertTextFormat . Snippet then 209if item . textEdit or ( item . insertText and item . insertText ~= '' ) then 210-- Use label instead of text if text has different starting characters. 211-- label is used as abbr (=displayed), but word is used for filtering 212-- This is required for things like postfix completion. 213-- E.g. in lua: 214-- 215-- local f = {} 216-- f@| 217-- ▲ 218-- └─ cursor 219-- 220-- item.textEdit.newText: table.insert(f, $0) 221-- label: insert 222-- 223-- Typing `i` would remove the candidate because newText starts with `t`. 224local text =parse_snippet ( nonempty ( item . insertText ) or assert ( item . textEdit ). newText ) 225local filter_text =nonempty ( item . filterText ) 226local word =# text < # item . label and vim . fn . matchstr ( text , '\\k*' ) 227or ( filter_text and vim . fn . match ( item . label , '^\\k' ) == - 1 and filter_text or item . label ) 228return fallback_filtertext ( item , word , prefix , match ) 229else 230return item . label 231end 232elseif item . textEdit then 233local word =item . textEdit . newText 234word =string . gsub ( word , '\r\n?' , '\n' ) 235word =word : match ( '([^\n]*)' ) or word 236return fallback_filtertext ( item , word , prefix , match ) 237elseif item . insertText and item . insertText ~= '' then 238local word =string . gsub ( item . insertText , '\r\n?' , '\n' ) 239word =word : match ( '([^\n]*)' ) or word 240return fallback_filtertext ( item , word , prefix , match ) 241end 242return item . label 243end 244 245--- Applies the given defaults to the completion item, modifying it in place. 246--- 247--- @param item lsp.CompletionItem 248--- @param defaults lsp.ItemDefaults? 249--- @param apply_kind lsp.CompletionItemApplyKinds? 250local function apply_defaults ( item , defaults , apply_kind ) 251if not defaults then 252return 253end 254 255-- Unset means Replace for every field. 256apply_kind =apply_kind or {} 257 258local merge =apply_kind . commitCharacters == protocol . ApplyKind . Merge 259and defaults . commitCharacters 260 261item . commitCharacters =merge 262-- No dedup, it ends up as a flat string anyway. 263and vim . list_extend ( item . commitCharacters or {} , merge ) 264-- An empty list means no commit chars, not use the defaults. 265or ( item . commitCharacters or defaults . commitCharacters ) 266 267item . insertTextFormat =item . insertTextFormat or defaults . insertTextFormat 268item . insertTextMode =item . insertTextMode or defaults . insertTextMode 269 270item . data =apply_kind . data == protocol . ApplyKind . Merge 271and type ( defaults . data ) == 'table' 272and type ( item . data ) == 'table' 273and vim . tbl_extend ( 'force' , defaults . data , item . data ) 274or vim . nonnil ( item . data , defaults . data ) 275 276if defaults . editRange then 277local textEdit =item . textEdit or {} 278item . textEdit =textEdit --[[@as lsp.TextEdit|lsp.InsertReplaceEdit]] 279textEdit . newText =textEdit . newText 280or item . textEditText 281or nonempty ( item . insertText ) 282or item . label 283if defaults . editRange . start then 284textEdit . range =textEdit . range or defaults . editRange 285elseif defaults . editRange . insert then 286textEdit . insert =defaults . editRange . insert 287textEdit . replace =defaults . editRange . replace 288end 289end 290end 291 292--- @param result vim.lsp.CompletionResult 293--- @return lsp.CompletionItem[] 294local function get_items ( result ) 295if result . items then 296-- When we have a list, apply the defaults and return an array of items. 297for _ , item in ipairs ( result . items ) do 298---@diagnostic disable-next-line: param-type-mismatch 299apply_defaults ( item , result . itemDefaults , result . applyKind ) 300end 301result . itemDefaults =nil 302return result . items 303else 304-- Else just return the items as they are. 305---@cast result lsp.CompletionItem[] 306return result 307end 308end 309 310---Returns an item's documentation value and its markup kind. 311---@param item lsp.CompletionItem 312---@return string 313---@return lsp.MarkupKind 314local function get_doc ( item ) 315local doc =item . documentation 316local default_kind =protocol . MarkupKind . Markdown 317if not doc then 318return '' , default_kind 319end 320if type ( doc ) == 'string' then 321return doc , default_kind 322end 323if type ( doc ) == 'table' and type ( doc . value ) == 'string' then 324return doc . value , doc . kind 325end 326 327vim . notify ( 'invalid documentation value: ' .. vim . inspect ( doc ), vim . log . levels . WARN ) 328return '' , default_kind 329end 330 331---@return fun(value: string, prefix: string): boolean, integer? 332local function item_matcher () 333local fuzzy =has_completeopt ( 'fuzzy' ) 334local ignorecase , smartcase =vim . o . ignorecase , vim . o . smartcase 335return function ( value , prefix ) 336if prefix == '' then 337return true , nil 338end 339if fuzzy then 340local score =vim . fn . matchfuzzypos ( { value } , prefix )[ 3 ] ---@type table 341return # score > 0 , score [ 1 ] 342end 343 344if ignorecase and ( not smartcase or not prefix : find ( '%u' )) then 345return vim . startswith ( value : lower (), prefix : lower ()), nil 346end 347return vim . startswith ( value , prefix ), nil 348end 349end 350 351--- Generate kind text for completion color items 352--- Parse color from doc and return colored symbol ■ 353--- 354---@param item table completion item with kind and documentation 355---@return string? kind text or "■" for colors 356---@return string? highlight group for colors 357local function generate_kind ( item ) 358if not protocol . CompletionItemKind [ item . kind ] then 359return 'Unknown' 360end 361if item . kind ~= protocol . CompletionItemKind . Color then 362return protocol . CompletionItemKind [ item . kind ] --[[@as string]] 363end 364local doc =get_doc ( item ) 365if # doc == 0 then 366return 367end 368 369-- extract hex from RGB format 370local r , g , b =doc : match ( 'rgb%((%d+)%s*,?%s*(%d+)%s*,?%s*(%d+)%)' ) 371local hex =r 372and string . format ( 373'%02x%02x%02x' , 374vim . _assert_integer ( r ), 375vim . _assert_integer ( g ), 376vim . _assert_integer ( b ) 377) 378or doc : match ( '#?([%da-fA-F]+)' ) 379 380if not hex then 381return 382end 383 384-- expand 3-digit hex to 6-digit 385if # hex == 3 then 386hex =hex : gsub ( '.' , '%1%1' ) 387end 388 389if # hex ~= 6 then 390return 391end 392 393hex =hex : lower () 394local group =( '@lsp.color.%s' ): format ( hex ) 395if next ( api . nvim_get_hl ( 0 , { name =group } )) == nil then 396api . nvim_set_hl ( 0 , group , { fg ='#' .. hex } ) 397end 398 399return '■' , group 400end 401 402---Returns the [complete-items] info for an LSP completion item, its markup kind, and whether the 403---info is complete. 404---The info is complete when all of the fields of the item required to build it are present. If the 405---info is not complete, resolving the item (via completionItem/resolve) may populate the missing 406---fields. 407---@param item lsp.CompletionItem 408---@param popup boolean 'completeopt' has "popup" 409---@return string 410---@return lsp.MarkupKind 411---@return boolean complete 412local function complete_item_info ( item , popup ) 413local info , kind =get_doc ( item ) 414 415if item . detail and item . detail ~= '' then 416local detail_block =( '```%s\n%s\n```' ): format ( vim . bo . filetype , item . detail ) 417if info == '' then 418info =detail_block 419elseif not info : find ( item . detail , 1 , true ) then 420info =detail_block .. '\n' .. info 421end 422end 423 424if info == '' and popup and item . insertTextFormat == protocol . InsertTextFormat . Snippet then 425local text =item . insertText or ( item . textEdit and item . textEdit . newText ) 426if text then 427local snippet =parse_snippet ( text ) 428info =( '```%s\n%s\n```' ): format ( vim . bo . filetype , snippet ) 429end 430end 431 432local complete =item . detail ~= nil and item . documentation ~= nil 433return info , kind , complete 434end 435 436--- Flatten commitCharacters array to a string; keep only the first codepoint 437--- of each entry. 438--- 439--- @param chars string[] 440--- @return string 441local function commit_chars_str ( chars ) 442if type ( chars ) ~= 'table' then 443return '' 444end 445local result ={} --- @type string[] 446for _ , ch in ipairs ( chars ) do 447-- commit characters "should have `length=1`" and superfluous 448-- characters are ignored. Keep the first codepoint. 449local b =type ( ch ) == 'string' and ch : byte ( 1 ) 450if b and b ~= 0 then 451local n =vim . str_utf_end ( ch , 1 ) 452-- Only whole characters: multibyte fragments pair up across entries, NUL truncates. 453if b < 0x80 or n > 0 then 454result [ # result + 1 ] =ch : sub ( 1 , 1 + n ) 455end 456end 457end 458return table . concat ( result ) 459end 460 461--- @param item lsp.CompletionItem 462--- @param lnum integer 463--- @return integer? 464local function edit_start_char ( item , lnum ) 465local edit =item . textEdit 466if not edit then 467return nil 468elseif edit . range and edit . range . start . line == lnum then 469return edit . range . start . character 470elseif edit . insert and edit . insert . start . line == lnum then 471return edit . insert . start . character 472end 473end 474 475--- Completion options for a buffer, fields from a dynamic registration. 476--- 477--- @param client vim.lsp.Client 478--- @param bufnr integer 479--- @return lsp.CompletionOptions 480local function completion_options ( client , bufnr ) 481local static =client . server_capabilities . completionProvider or {} 482for _ , reg in ipairs ( client : _get_registrations ( 'completionProvider' , bufnr ) or {} ) do 483local opts =reg . registerOptions 484if type ( opts ) == 'table' then 485return vim . tbl_extend ( 'keep' , opts , static ) 486end 487end 488return static 489end 490 491--- Turns the result of a `textDocument/completion` request into vim-compatible 492--- |complete-items|. 493--- 494--- @param result vim.lsp.CompletionResult Result of `textDocument/completion` 495--- @param prefix string prefix to filter the completion items 496--- @param client_id integer? Client ID 497--- @param server_start_boundary integer? server start boundary 498--- @param line string? current line content 499--- @param lnum integer? 0-indexed line number 500--- @param encoding? 'utf-8'|'utf-16'|'utf-32' encoding 501--- @param default_start_byte integer? 0-indexed start byte for items without an edit range 502--- @return table[] 503--- @see complete-items 504function M . _lsp_to_complete_items ( 505result , 506prefix , 507client_id , 508server_start_boundary , 509line , 510lnum , 511encoding , 512default_start_byte 513) 514local items =get_items ( result ) 515if vim . tbl_isempty ( items ) then 516return {} 517end 518 519local match_item_by_value =item_matcher () 520local popup =has_completeopt ( 'popup' ) 521---@type fun(item: lsp.CompletionItem, item_prefix: string): boolean, integer? 522local matches 523if not prefix : find ( '%w' ) then 524matches =function ( _ , _ ) 525return true 526end 527else 528---@param item lsp.CompletionItem 529---@param item_prefix string text the item replaces, up to the cursor 530matches =function ( item , item_prefix ) 531local filter_text =nonempty ( item . filterText ) 532if filter_text then 533return match_item_by_value ( filter_text , item_prefix ) 534end 535 536if item . textEdit and not item . textEdit . newText then 537-- server took care of filtering 538return true 539end 540 541return match_item_by_value ( item . label , item_prefix ) 542end 543end 544 545local candidates ={} 546local bufnr =api . nvim_get_current_buf () 547local user_convert =vim . tbl_get ( buf_handles , bufnr , 'convert' ) 548local user_cmp =vim . tbl_get ( buf_handles , bufnr , 'cmp' ) 549local client =client_id and lsp . get_client_by_id ( client_id ) 550local server_supports_resolve =client 551and completion_options ( client , bufnr ). resolveProvider == true 552local use_commit =vim . tbl_get ( buf_handles , bufnr , 'commit_characters' ) ~= false 553local commit_support =client 554and vim . tbl_get ( 555client . capabilities , 556'textDocument' , 557'completion' , 558'completionItem' , 559'commitCharactersSupport' 560) 561 562local all_commit_chars =client and completion_options ( client , bufnr ). allCommitCharacters 563local all_commit_str =all_commit_chars and commit_chars_str ( all_commit_chars ) or nil 564 565for _ , item in ipairs ( items ) do 566local pad , item_prefix ='' , prefix 567if server_start_boundary and line and lnum and encoding then 568local start_char =edit_start_char ( item , lnum ) 569local start_byte =start_char and vim . str_byteindex ( line , encoding , start_char , false ) 570or default_start_byte 571if start_byte and start_byte > server_start_boundary then 572pad =line : sub ( server_start_boundary + 1 , start_byte ) 573item_prefix =prefix : sub ( # pad + 1 ) 574end 575end 576 577local match , score =matches ( item , item_prefix ) 578if match then 579local word =pad .. get_completion_word ( item , item_prefix , match_item_by_value ) 580 581local hl_group ='' 582if 583---@diagnostic disable-next-line: deprecated 584item . deprecated 585or vim . list_contains (( item . tags or {} ), protocol . CompletionTag . Deprecated ) 586then 587hl_group ='DiagnosticDeprecated' 588end 589local kind , kind_hlgroup =generate_kind ( item ) 590local info , info_kind , info_complete =complete_item_info ( item , popup ) 591local commit_chars --- @type string? 592if use_commit then 593if commit_support and item . commitCharacters then 594-- may be '': an explicit empty list also suppresses allCommitCharacters 595commit_chars =commit_chars_str ( item . commitCharacters ) 596else 597commit_chars =all_commit_str 598end 599end 600local completion_item ={ 601word =word , 602abbr =( '%s%s' ): format ( item . label , vim . tbl_get ( item , 'labelDetails' , 'detail' ) or '' ), 603kind =kind , 604menu =vim . tbl_get ( item , 'labelDetails' , 'description' ) or '' , 605info =info , 606icase =1 , 607dup =1 , 608empty =1 , 609abbr_hlgroup =hl_group , 610kind_hlgroup =kind_hlgroup , 611preselect =item . preselect , 612commit_chars =commit_chars , 613user_data ={ 614nvim ={ 615lsp ={ 616completion_item =item , 617info_kind =info_kind , 618completion_item_needs_resolving =server_supports_resolve and not info_complete , 619client_id =client_id , 620} , 621} , 622} , 623_fuzzy_score =score , 624} 625if user_convert then 626completion_item =vim . tbl_extend ( 'keep' , user_convert ( item ), completion_item ) 627end 628table . insert ( candidates , completion_item ) 629end 630end 631 632if not user_cmp then 633--- @param a { user_data: { nvim: { lsp: { completion_item: lsp.CompletionItem } } } } 634--- @param b { user_data: { nvim: { lsp: { completion_item: lsp.CompletionItem } } } } 635local function compare_by_sortText_and_label ( a , b ) 636local itema =a . user_data . nvim . lsp . completion_item 637local itemb =b . user_data . nvim . lsp . completion_item 638return ( nonempty ( itema . sortText ) or itema . label ) < ( nonempty ( itemb . sortText ) or itemb . label ) 639end 640 641local use_fuzzy_sort =has_completeopt ( 'fuzzy' ) 642and not has_completeopt ( 'nosort' ) 643and not result . isIncomplete 644and # prefix > 0 645 646local compare_fn =use_fuzzy_sort 647and function ( a , b ) 648local score_a =a . _fuzzy_score or 0 649local score_b =b . _fuzzy_score or 0 650if score_a ~= score_b then 651return score_a > score_b 652end 653return compare_by_sortText_and_label ( a , b ) 654end 655or compare_by_sortText_and_label 656 657table . sort ( candidates , compare_fn ) 658end 659return candidates 660end 661 662--- @param lnum integer 0-indexed 663--- @param line string 664--- @param items lsp.CompletionItem[] 665--- @param encoding 'utf-8'|'utf-16'|'utf-32' 666--- @return integer? 667local function adjust_start_col ( lnum , line , items , encoding ) 668local min_start_char =nil 669for _ , item in pairs ( items ) do 670local start_char =edit_start_char ( item , lnum ) 671if start_char and ( not min_start_char or start_char < min_start_char ) then 672min_start_char =start_char 673end 674end 675if min_start_char then 676return vim . str_byteindex ( line , encoding , min_start_char , false ) 677else 678return nil 679end 680end 681 682--- @param line string line content 683--- @param lnum integer 0-indexed line number 684--- @param cursor_col integer 685--- @param client_id integer client ID 686--- @param client_start_boundary integer 0-indexed word boundary 687--- @param server_start_boundary? integer 0-indexed word boundary, based on textEdit.range.start.character 688--- @param result vim.lsp.CompletionResult 689--- @param encoding 'utf-8'|'utf-16'|'utf-32' 690--- @return table[] matches 691--- @return integer? server_start_boundary 692function M . _convert_results ( 693line , 694lnum , 695cursor_col , 696client_id , 697client_start_boundary , 698server_start_boundary , 699result , 700encoding 701) 702-- Completion response items may be relative to a position different than `client_start_boundary`. 703-- Concrete example, with lua-language-server: 704-- 705-- require('plenary.asy| 706-- ▲ ▲ ▲ 707-- │ │ └── cursor_pos: 20 708-- │ └────── client_start_boundary: 17 709-- └────────────── textEdit.range.start.character: 9 710-- .newText = 'plenary.async' 711-- ^^^ 712-- prefix (We'd remove everything not starting with `asy`, 713-- so we'd eliminate the `plenary.async` result 714-- 715-- `adjust_start_col` is used to prefer the language server boundary. 716-- 717local candidates =get_items ( result ) 718local curstartbyte =adjust_start_col ( lnum , line , candidates , encoding ) 719if server_start_boundary == nil then 720server_start_boundary =curstartbyte 721elseif curstartbyte ~= nil and curstartbyte ~= server_start_boundary then 722server_start_boundary =client_start_boundary 723end 724local prefix =line : sub (( server_start_boundary or client_start_boundary ) + 1 , cursor_col ) 725local default_start_byte =curstartbyte and client_start_boundary or nil 726local matches =M . _lsp_to_complete_items ( 727result , 728prefix , 729client_id , 730server_start_boundary , 731line , 732lnum , 733encoding , 734default_start_byte 735) 736 737return matches , server_start_boundary 738end 739 740-- NOTE: The reason we don't use `lsp.buf_request_all` here is because we want to filter the clients 741-- that received the request based on the trigger characters. 742--- @param clients table<integer, vim.lsp.Client> # keys != client_id 743--- @param bufnr integer 744--- @param win integer 745--- @param ctx? lsp.CompletionContext 746--- @param callback fun(responses: table<integer, { err: lsp.ResponseError, result: vim.lsp.CompletionResult }>) 747--- @return function # Cancellation function 748local function request ( clients , bufnr , win , ctx , callback ) 749local responses ={} --- @type table<integer, { err: lsp.ResponseError, result: any }> 750local request_ids ={} --- @type table<integer, integer> 751local remaining_requests =vim . tbl_count ( clients ) 752 753for _ , client in pairs ( clients ) do 754local client_id =client . id 755local params =lsp . util . make_position_params ( win , client . offset_encoding ) 756--- @cast params lsp.CompletionParams 757params . context =ctx 758local ok , request_id =client : request ( 'textDocument/completion' , params , function ( err , result ) 759responses [ client_id ] ={ err =err , result =result } 760remaining_requests =remaining_requests - 1 761if remaining_requests == 0 then 762callback ( responses ) 763end 764end , bufnr ) 765 766if ok then 767request_ids [ client_id ] =request_id 768end 769end 770 771return function () 772for client_id , request_id in pairs ( request_ids ) do 773local client =lsp . get_client_by_id ( client_id ) 774if client then 775client : cancel_request ( request_id ) 776end 777end 778end 779end 780 781---@param bufnr integer 782---@return string 783local function get_augroup ( bufnr ) 784return string . format ( 'nvim.lsp.completion_%d' , bufnr ) 785end 786 787--- Updates the completion preview popup: configures conceal level, applies Treesitter or 788--- fallback syntax, and resizes height to fit content 789--- 790--- @param winid integer 791--- @param bufnr integer 792--- @param kind? string 793local function update_popup_window ( winid , bufnr , kind ) 794if winid and api . nvim_win_is_valid ( winid ) and bufnr and api . nvim_buf_is_valid ( bufnr ) then 795if kind == protocol . MarkupKind . Markdown then 796vim . wo [ winid ]. conceallevel =2 797vim . treesitter . start ( bufnr , kind ) 798end 799local all =api . nvim_win_text_height ( winid ). all 800api . nvim_win_resize ( winid , - 1 , all ) 801end 802end 803 804--- Handles the LSP "completionItem/resolve" 805--- 806--- @nodoc 807--- @class CompletionResolver 808--- @field timer uv.uv_timer_t? Timer used for debouncing 809--- @field bufnr integer? Buffer number for which the resolution is triggered 810--- @field word string? Word being completed 811--- @field last_request_time integer? Last request timestamp 812--- @field doc_rtt_ms number Last request timestamp 813--- @field doc_compute_new_average fun(sample: number): number Last request timestamp 814local CompletionResolver ={} 815CompletionResolver . __index =CompletionResolver 816 817--- @nodoc 818--- 819--- Creates a new instance of `resolve_completion_item`. 820--- 821--- @return CompletionResolver 822function CompletionResolver . new () 823local self =setmetatable ( {} , CompletionResolver ) 824self . timer =nil 825self . bufnr =nil 826self . word =nil 827self . last_request_time =nil 828self . doc_rtt_ms =100 829self . doc_compute_new_average =exp_avg ( 10 , 5 ) 830return self 831end 832 833--- @nodoc 834--- 835--- Cancels any pending requests. 836function CompletionResolver : cancel_pending_requests () 837if self . bufnr then 838lsp . util . _cancel_requests ( { 839method ='completionItem/resolve' , 840bufnr =self . bufnr , 841} ) 842end 843end 844 845--- @nodoc 846--- 847--- Cleans up the timer and cancels any ongoing requests. 848function CompletionResolver : cleanup () 849if self . timer and not self . timer : is_closing () then 850self . timer : stop () 851self . timer : close () 852end 853self . timer =nil 854self : cancel_pending_requests () 855end 856 857--- @nodoc 858--- 859--- Checks if the completionItem/resolve request is valid by ensuring the buffer 860--- and word are valid. 861--- 862--- @return boolean, table Validity of the request and the completion info 863function CompletionResolver : is_valid () 864local cmp_info =vim . fn . complete_info ( { 'selected' , 'completed' } ) 865return self . bufnr ~= nil 866and api . nvim_buf_is_valid ( self . bufnr ) 867and api . nvim_get_current_buf () == self . bufnr 868and vim . startswith ( api . nvim_get_mode (). mode , 'i' ) 869and vim . fn . pumvisible () ~= 0 870and ( vim . tbl_get ( cmp_info , 'completed' , 'word' ) or '' ) == self . word , 871cmp_info 872end 873 874--- @nodoc 875--- 876--- Invokes and handles "completionItem/resolve". 877--- 878--- @param bufnr integer The buffer number where the request is triggered 879--- @param param table The parameters for the LSP request 880--- @param selected_word string The word being completed 881function CompletionResolver : request ( bufnr , param , selected_word ) 882self : cleanup () 883 884self . bufnr =bufnr 885self . word =selected_word 886local debounce_time =adaptive_debounce ( self . last_request_time , self . doc_rtt_ms ) 887 888self . timer =vim . defer_fn ( function () 889local valid , cmp_info =self : is_valid () 890if not valid then 891self : cleanup () 892return 893end 894self : cancel_pending_requests () 895 896local client_id =vim . tbl_get ( cmp_info . completed , 'user_data' , 'nvim' , 'lsp' , 'client_id' ) 897local client =client_id and lsp . get_client_by_id ( client_id ) 898-- completionItem/resolve is not registrable, so supports_method() would 899-- only see the static capability. 900if not client or not completion_options ( client , bufnr ). resolveProvider then 901return 902end 903 904local start_time =vim . uv . hrtime () 905self . last_request_time =start_time 906 907---@param result lsp.CompletionItem 908client : request ( 'completionItem/resolve' , param , function ( err , result ) 909local end_time =vim . uv . hrtime () 910local response_time =( end_time - start_time ) * ns_to_ms 911self . doc_rtt_ms =self . doc_compute_new_average ( response_time ) 912 913if err or not result or next ( result ) == nil then 914if err then 915vim . notify ( err . message , vim . log . levels . WARN ) 916end 917return 918end 919 920valid , cmp_info =self : is_valid () 921if not valid then 922return 923end 924 925local info , kind =complete_item_info ( result , has_completeopt ( 'popup' )) 926if info ~= '' and info ~= cmp_info . completed . info then 927local windata =api . nvim__complete_set ( cmp_info . selected , { info =info } ) 928update_popup_window ( windata . winid , windata . bufnr , kind ) 929end 930end , bufnr ) 931end , math . floor ( debounce_time )) 932end 933 934--- Defines a CompleteChanged handler to highlight the completion info popup and request/display LSP 935--- completion item documentation via completionItem/resolve 936--- @param group string 937--- @param bufnr integer 938local function on_completechanged ( group , bufnr ) 939nvim_on ( 'CompleteChanged' , group , { 940buf =bufnr , 941desc ='Highlight completion info popup and request/display LSP completion item documentation via completionItem/resolve' , 942} , function ( ev ) 943local completed_item =vim . v . event . completed_item or {} 944local user_data =vim . tbl_get ( completed_item , 'user_data' , 'nvim' , 'lsp' ) 945if not user_data then 946return 947end 948if ( completed_item . info or '' ) ~= '' then 949local data =vim . fn . complete_info ( { 'selected' } ) 950update_popup_window ( data . preview_winid , data . preview_bufnr , user_data . info_kind ) 951end 952 953if user_data . completion_item_needs_resolving then 954Context . resolve_handler =Context . resolve_handler or CompletionResolver . new () 955Context . resolve_handler : request ( 956ev . buf , 957user_data . completion_item , 958assert ( completed_item . word ) 959) 960end 961end ) 962end 963 964local function on_complete_done () 965local completed_item =api . nvim_get_vvar ( 'completed_item' ) 966if not completed_item or not completed_item . user_data or not completed_item . user_data . nvim then 967Context : reset () 968return 969end 970 971local cursor_row , cursor_col =unpack ( api . nvim_win_get_cursor ( 0 )) --- @type integer, integer 972cursor_row =cursor_row - 1 973local completion_item =completed_item . user_data . nvim . lsp . completion_item --- @type lsp.CompletionItem 974local client_id =completed_item . user_data . nvim . lsp . client_id --- @type integer 975if not completion_item or not client_id then 976Context : reset () 977return 978end 979 980local bufnr =api . nvim_get_current_buf () 981local expand_snippet =completion_item . insertTextFormat == protocol . InsertTextFormat . Snippet 982and ( completion_item . textEdit ~= nil or completion_item . insertText ~= nil ) 983 984Context : reset () 985 986local client =lsp . get_client_by_id ( client_id ) 987if not client then 988return 989end 990 991local position_encoding =client . offset_encoding or 'utf-16' 992local resolve_provider =completion_options ( client , bufnr ). resolveProvider 993 994-- Keep reference to avoid race where completion/resolve response arrives after on_insert_leave 995-- and Context.cursor got cleared before clear_word() gets called 996local context_cursor =assert ( Context . cursor ) 997 998local function clear_word () 999if not expand_snippet then 1000return nil 1001end 1002 1003-- Remove the already inserted word. 1004api . nvim_buf_set_text ( 1005bufnr , 1006context_cursor [ 1 ] - 1 , 1007context_cursor [ 2 ] - 1 , 1008cursor_row , 1009cursor_col , 1010{ '' } 1011) 1012end 1013 1014local function exec_command () 1015local command =completion_item . command 1016if command then 1017client : exec_cmd ( command , { bufnr =bufnr } ) 1018end 1019end 1020 1021--- @param edits lsp.TextEdit[] 1022local function apply_additional_edits ( edits ) 1023-- The edits can move the cursor; keep it where it was. 1024lsp . util . apply_text_edits ( edits , bufnr , position_encoding , nil , { keep_cursor =true } ) 1025end 1026 1027clear_word () 1028 1029local edits =completion_item . additionalTextEdits 1030local has_edits =edits ~= nil and next ( edits ) ~= nil 1031if has_edits then 1032apply_additional_edits ( assert ( edits )) 1033end 1034if expand_snippet then 1035apply_snippet ( completion_item ) 1036end 1037 1038-- Nothing to gain if the item carried its edits, or it cannot be resolved. 1039if has_edits or not resolve_provider or type ( completion_item ) ~= 'table' then 1040exec_command () 1041return 1042end 1043 1044--- @param result lsp.CompletionItem 1045client : request ( 'completionItem/resolve' , completion_item , function ( err , result ) 1046if not api . nvim_buf_is_valid ( bufnr ) then 1047return 1048end 1049if err then 1050vim . notify_once ( err . message , vim . log . levels . WARN ) 1051elseif result then 1052if result . additionalTextEdits then 1053apply_additional_edits ( result . additionalTextEdits ) 1054end 1055-- A resolved command replaces the one the item came with. 1056if result . command then 1057completion_item . command =result . command 1058end 1059end 1060exec_command () 1061end , bufnr ) 1062end 1063 1064---@param bufnr integer 1065---@return integer 1066local function register_completedone ( bufnr ) 1067local group =api . nvim_create_augroup ( get_augroup ( bufnr ), { clear =false } ) 1068if # api . nvim_get_autocmds ( { buf =bufnr , event ='CompleteDone' , group =group } ) > 0 then 1069return group 1070end 1071 1072nvim_on ( 'CompleteDone' , group , { buf =bufnr } , function () 1073local reason =api . nvim_get_vvar ( 'event' ). reason ---@type string 1074if reason == 'accept' then 1075on_complete_done () 1076elseif reason == 'cancel' then 1077-- <C-e> dismissed the pum; stop re-querying an incomplete list. 1078Context : reset () 1079end 1080end ) 1081 1082return group 1083end 1084 1085--- @param bufnr integer 1086--- @param clients table<integer, vim.lsp.Client> 1087--- @param ctx lsp.CompletionContext 1088local function trigger ( bufnr , clients , ctx ) 1089reset_timer () 1090Context : cancel_pending () 1091 1092if vim . fn . pumvisible () ~= 0 and not Context . isIncomplete then 1093return 1094end 1095 1096if ctx and ctx . triggerKind == protocol . CompletionTriggerKind . Invoked then 1097register_completedone ( bufnr ) 1098end 1099 1100local win =api . nvim_get_current_win () 1101local cursor_row =api . nvim_win_get_cursor ( win )[ 1 ] 1102local start_time =vim . uv . hrtime () --[[@as integer]] 1103Context . last_request_time =start_time 1104 1105local cancel_request =request ( clients , bufnr , win , ctx , function ( responses ) 1106local end_time =vim . uv . hrtime () 1107rtt_ms =compute_new_average (( end_time - start_time ) * ns_to_ms ) 1108 1109Context . pending_requests ={} 1110Context . isIncomplete =false 1111 1112local new_cursor_row , cursor_col =unpack ( api . nvim_win_get_cursor ( win )) --- @type integer, integer 1113local row_changed =new_cursor_row ~= cursor_row 1114local mode =api . nvim_get_mode (). mode 1115if row_changed or not ( mode == 'i' or mode == 'ic' ) then 1116return 1117end 1118 1119local line =api . nvim_get_current_line () 1120local line_to_cursor =line : sub ( 1 , cursor_col ) 1121local word_boundary =vim . fn . match ( line_to_cursor , '\\k*$' ) 1122 1123local matches ={} 1124 1125local server_start_boundary --- @type integer? 1126for client_id , response in pairs ( responses ) do 1127local client =lsp . get_client_by_id ( client_id ) 1128if response . err then 1129local msg =( '%s: %s %s' ): format ( 1130client and client . name or 'UNKNOWN' , 1131response . err . code or 'NO_CODE' , 1132response . err . message 1133) 1134vim . notify_once ( msg , vim . log . levels . WARN ) 1135end 1136 1137local result =response . result 1138if type ( result ) == 'table' and result . items == vim . NIL then 1139error ( 1140( '%s: completion response has items=null, expected CompletionItem[]' ): format ( 1141client and client . name or 'UNKNOWN' 1142) 1143) 1144-- result is CompletionItem[] or CompletionList; result.items may be empty, and 1145-- an empty incomplete list means request again when needed. 1146elseif not vim . isnil ( result ) then 1147Context . isIncomplete =Context . isIncomplete or result . isIncomplete 1148if # ( result . items or result ) > 0 then 1149local encoding =client and client . offset_encoding or 'utf-16' 1150local client_matches , tmp_server_start_boundary 1151client_matches , tmp_server_start_boundary =M . _convert_results ( 1152line , 1153cursor_row - 1 , 1154cursor_col , 1155client_id , 1156word_boundary , 1157nil , 1158result , 1159encoding 1160) 1161 1162server_start_boundary =tmp_server_start_boundary or server_start_boundary 1163vim . list_extend ( matches , client_matches ) 1164end 1165end 1166end 1167 1168--- @type table[] 1169local prev_matches =vim . fn . complete_info ( { 'items' , 'matches' } )[ 'items' ] 1170 1171--- @param prev_match table 1172prev_matches =vim . tbl_filter ( function ( prev_match ) 1173local client_id =vim . tbl_get ( prev_match , 'user_data' , 'nvim' , 'lsp' , 'client_id' ) 1174if client_id and responses [ client_id ] ~= nil then 1175return false 1176end 1177return vim . tbl_get ( prev_match , 'match' ) 1178end , prev_matches ) 1179 1180matches =vim . list_extend ( prev_matches , matches ) 1181local user_cmp =vim . tbl_get ( buf_handles , bufnr , 'cmp' ) 1182if user_cmp then 1183table . sort ( matches , user_cmp ) 1184end 1185 1186local start_col =( server_start_boundary or word_boundary ) + 1 1187Context . cursor ={ cursor_row , start_col } 1188if # matches > 0 and has_completeopt ( 'popup' ) then 1189local group =get_augroup ( bufnr ) 1190if # api . nvim_get_autocmds ( { buf =bufnr , event ='CompleteChanged' , group =group } ) == 0 then 1191on_completechanged ( group , bufnr ) 1192end 1193end 1194vim . fn . complete ( start_col , matches ) 1195end ) 1196 1197table . insert ( Context . pending_requests , cancel_request ) 1198end 1199 1200--- @param handle vim.lsp.completion.BufHandle 1201local function on_insert_char_pre ( handle ) 1202if Context . isIncomplete then 1203reset_timer () 1204 1205local debounce_ms =adaptive_debounce ( Context . last_request_time , rtt_ms ) 1206local ctx ={ triggerKind =protocol . CompletionTriggerKind . TriggerForIncompleteCompletions } 1207if debounce_ms == 0 then 1208vim . schedule ( function () 1209M . get ( { ctx =ctx } ) 1210end ) 1211else 1212completion_timer =new_timer () 1213completion_timer : start ( 1214math . floor ( debounce_ms ), 12150 , 1216vim . schedule_wrap ( function () 1217M . get ( { ctx =ctx } ) 1218end ) 1219) 1220end 1221 1222return 1223end 1224 1225if vim . fn . pumvisible () ~= 0 then 1226return 1227end 1228 1229local char =vim . v . char 1230local matched_clients =handle . triggers [ char ] 1231-- Discard pending trigger char, complete the "latest" one. 1232-- Can happen if a mapping inputs multiple trigger chars simultaneously. 1233reset_timer () 1234if matched_clients then 1235completion_timer =assert ( vim . uv . new_timer ()) 1236completion_timer : start ( 25 , 0 , function () 1237reset_timer () 1238vim . schedule ( function () 1239trigger ( api . nvim_get_current_buf (), matched_clients , { 1240triggerKind =protocol . CompletionTriggerKind . TriggerCharacter , 1241triggerCharacter =char , 1242} ) 1243end ) 1244end ) 1245end 1246end 1247 1248local function on_insert_leave () 1249reset_timer () 1250Context . cursor =nil 1251Context : reset () 1252end 1253 1254--- @param client_id integer 1255--- @param bufnr integer 1256local function disable_completions ( client_id , bufnr ) 1257local handle =buf_handles [ bufnr ] 1258if not handle then 1259return 1260end 1261 1262handle . clients [ client_id ] =nil 1263if not next ( handle . clients ) then 1264buf_handles [ bufnr ] =nil 1265api . nvim_del_augroup_by_name ( get_augroup ( bufnr )) 1266else 1267for char , clients in pairs ( handle . triggers ) do 1268--- @param c vim.lsp.Client 1269handle . triggers [ char ] =vim . tbl_filter ( function ( c ) 1270return c . id ~= client_id 1271end , clients ) 1272end 1273end 1274end 1275 1276--- @inlinedoc 1277--- @class vim.lsp.completion.BufferOpts 1278--- @field autotrigger? boolean (default: false) When true, completion triggers automatically based on the server's `triggerCharacters`. 1279--- @field convert? fun(item: lsp.CompletionItem): table Transforms an LSP CompletionItem to |complete-items|. 1280--- @field cmp? fun(a: table, b: table): boolean Comparator for sorting merged completion items from all servers. 1281--- @field commit_characters? boolean (default: true) When false, commit characters are ignored. 1282 1283---@param client_id integer 1284---@param bufnr integer 1285---@param opts vim.lsp.completion.BufferOpts 1286local function enable_completions ( client_id , bufnr , opts ) 1287local buf_handle =buf_handles [ bufnr ] 1288if not buf_handle then 1289buf_handle ={ 1290clients ={} , 1291triggers ={} , 1292convert =opts . convert , 1293cmp =opts . cmp , 1294commit_characters =opts . commit_characters ~= false , 1295} 1296buf_handles [ bufnr ] =buf_handle 1297 1298-- Set up autocommands. 1299local group =register_completedone ( bufnr ) 1300nvim_on ( 'BufUnload' , group , { 1301buf =bufnr , 1302desc ='vim.lsp.completion: clean up on unload' , 1303} , function ( ev ) 1304buf_handles [ ev . buf ] =nil 1305api . nvim_del_augroup_by_id ( group ) 1306end ) 1307nvim_on ( 'LspDetach' , group , { 1308buf =bufnr , 1309desc ='vim.lsp.completion: clean up client on detach' , 1310} , function ( ev ) 1311disable_completions ( ev . data . client_id , ev . buf ) 1312end ) 1313 1314if opts . autotrigger then 1315nvim_on ( 'InsertCharPre' , group , { buf =bufnr } , function () 1316on_insert_char_pre ( buf_handles [ bufnr ]) 1317end ) 1318nvim_on ( 'InsertLeave' , group , { buf =bufnr } , on_insert_leave ) 1319end 1320end 1321 1322if not buf_handle . clients [ client_id ] then 1323local client =assert ( lsp . get_client_by_id ( client_id ), 'invalid client ID' ) 1324 1325-- Add the new client to the buffer's clients. 1326buf_handle . clients [ client_id ] =client 1327 1328-- Add the new client to the clients that should be triggered by its trigger characters. 1329--- @type string[] 1330local triggers =completion_options ( client , bufnr ). triggerCharacters or {} 1331for _ , char in ipairs ( triggers ) do 1332local clients_for_trigger =buf_handle . triggers [ char ] 1333if not clients_for_trigger then 1334clients_for_trigger ={} 1335buf_handle . triggers [ char ] =clients_for_trigger 1336end 1337local client_exists =vim . iter ( clients_for_trigger ): any ( function ( c ) 1338return c . id == client_id 1339end ) 1340if not client_exists then 1341table . insert ( clients_for_trigger , client ) 1342end 1343end 1344end 1345end 1346 1347--- Enables or disables completions from the given language client in the given 1348--- buffer. Effects of enabling completions are: 1349--- 1350--- - Calling |vim.lsp.completion.get()| uses the enabled clients to retrieve completion candidates. 1351--- - Selecting a completion item shows a preview popup ("completionItem/resolve") if 'completeopt' 1352--- has "popup". 1353--- - Accepting a completion item using `<c-y>` applies side effects like expanding snippets, 1354--- text edits (e.g. insert import statements) and executing associated commands. This works for 1355--- completions triggered via autotrigger, 'omnifunc' or [vim.lsp.completion.get()]. 1356--- 1357--- Examples: |lsp-attach| |lsp-completion| 1358--- 1359--- @note |vim.lsp.omnifunc()| (|i_CTRL-X_CTRL-O|) queries every client that advertises completion, 1360--- including clients that were disabled by `enable(false)`. To suppress completions for a client, 1361--- clear its capability on |LspAttach|: `client.server_capabilities.completionProvider = nil`. 1362--- 1363--- @note Behavior of `autotrigger=true` is controlled by the LSP `triggerCharacters` field. You 1364--- can override it on LspAttach, see |lsp-autocompletion|. 1365--- 1366--- @param enable boolean True to enable, false to disable 1367--- @param client_id integer Client ID 1368--- @param bufnr integer Buffer handle, or 0 for the current buffer 1369--- @param opts? vim.lsp.completion.BufferOpts 1370function M . enable ( enable , client_id , bufnr , opts ) 1371bufnr =vim . _resolve_bufnr ( bufnr ) 1372 1373if enable then 1374enable_completions ( client_id , bufnr , opts or {} ) 1375else 1376disable_completions ( client_id , bufnr ) 1377end 1378end 1379 1380--- @inlinedoc 1381--- @class vim.lsp.completion.get.Opts 1382--- @field ctx? lsp.CompletionContext Completion context. Defaults to a trigger kind of `invoked`. 1383 1384--- Triggers LSP completion once in the current buffer, if LSP completion is enabled 1385--- (see |lsp-attach| |lsp-completion|). 1386--- 1387--- Use CTRL-Y to select an item from the completion menu. |complete_CTRL-Y| 1388--- 1389--- To invoke manually with CTRL-space, use this mapping: 1390--- ```lua 1391--- -- Use CTRL-space to trigger LSP completion. 1392--- -- Use CTRL-Y to select an item. |complete_CTRL-Y| 1393--- vim.keymap.set('i', '<c-space>', function() 1394--- vim.lsp.completion.get() 1395--- end) 1396--- ``` 1397--- 1398--- @param opts? vim.lsp.completion.get.Opts 1399function M . get ( opts ) 1400opts =opts or {} 1401local ctx =opts . ctx or { triggerKind =protocol . CompletionTriggerKind . Invoked } 1402local bufnr =api . nvim_get_current_buf () 1403local clients =( buf_handles [ bufnr ] or {} ). clients or {} 1404 1405trigger ( bufnr , clients , ctx ) 1406end 1407 1408--- Implements 'omnifunc' compatible LSP completion. 1409--- 1410--- @see |complete-functions| 1411--- @see |complete-items| 1412--- @see |CompleteDone| 1413--- 1414--- @param findstart integer 0 or 1, decides behavior 1415--- @param base integer findstart=0, text to match against 1416--- 1417--- @return integer|table Decided by {findstart}: 1418--- - findstart=1: column where the completion starts, or -2 or -3 1419--- - findstart=0: list of matches (actually just calls |complete()|) 1420function M . _omnifunc ( findstart , base ) 1421lsp . log . debug ( 'omnifunc.findstart' , { findstart =findstart , base =base } ) 1422local bufnr =api . nvim_get_current_buf () 1423local clients =lsp . get_clients ( { bufnr =bufnr , method ='textDocument/completion' } ) 1424local remaining =# clients 1425if remaining == 0 then 1426return findstart == 1 and - 1 or {} 1427end 1428 1429trigger ( bufnr , clients , { triggerKind =protocol . CompletionTriggerKind . Invoked } ) 1430 1431-- Return -2 to signal that we should continue completion so that we can 1432-- async complete. 1433return - 2 1434end 1435 1436return M