robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- @brief 2--- This module provides the LSP "inline completion" feature, for completing multiline text (e.g., 3--- whole methods) instead of just a word or line, which may result in "syntactically or 4--- semantically incorrect" code. Unlike regular completion, this is typically presented as overlay 5--- text instead of a menu of completion candidates. 6--- 7--- LSP spec: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.18/specification/#textDocument_inlineCompletion 8--- 9--- To try it out, here is a quickstart example using Copilot: [lsp-copilot]() 10--- 11--- 1. Install Copilot: 12--- ```sh 13--- npm install --global @github/copilot-language-server 14--- ``` 15--- 2. Define a config, (or copy `lsp/copilot.lua` from https://github.com/neovim/nvim-lspconfig): 16--- ```lua 17--- vim.lsp.config('copilot', { 18--- cmd = { 'copilot-language-server', '--stdio' }, 19--- root_markers = { '.git' }, 20--- init_options = { 21--- editorInfo = { 22--- name = 'Neovim', version = tostring(vim.version()) }, 23--- editorPluginInfo = { name = 'Neovim', version = tostring(vim.version()) }, 24--- }, 25--- }) 26--- ``` 27--- 3. Activate the config: 28--- ```lua 29--- vim.lsp.enable('copilot') 30--- ``` 31--- 4. Sign in to Copilot, or use the `:LspCopilotSignIn` command from https://github.com/neovim/nvim-lspconfig 32--- 5. Enable inline completion: 33--- ```lua 34--- vim.lsp.inline_completion.enable() 35--- ``` 36--- 6. Set a keymap for `vim.lsp.inline_completion.get()` and invoke the keymap. 37 38local util =require ( 'vim.lsp.util' ) 39local log =require ( 'vim.lsp.log' ) 40local protocol =require ( 'vim.lsp.protocol' ) 41local grammar =require ( 'vim.lsp._snippet_grammar' ) 42local api =vim . api 43local nvim_on =require ( 'vim._core.util' ). nvim_on 44 45local Capability =require ( 'vim.lsp._capability' ) 46 47local M ={} 48 49local namespace =api . nvim_create_namespace ( 'nvim.lsp.inline_completion' ) 50 51---@class vim.lsp.inline_completion.Item 52---@field _index integer The index among all items form all clients. 53---@field client_id integer Client ID 54---@field insert_text string|lsp.StringValue The text to be inserted, can be a snippet. 55---@field _filter_text? string 56---@field range? vim.Range Which range it be applied. 57---@field command? lsp.Command Corresponding server command. 58 59---@class (private) vim.lsp.inline_completion.ClientState 60---@field items? lsp.InlineCompletionItem[] 61 62---@class (private) vim.lsp.inline_completion.Completor : vim.lsp.Capability 63---@field active table<integer, vim.lsp.inline_completion.Completor?> 64---@field timer? uv.uv_timer_t Timer for debouncing automatic requests 65---@field current? vim.lsp.inline_completion.Item Currently selected item 66---@field _overlay? boolean Whether `current` replaces buffer text, per its original range 67---@field client_state table<integer, vim.lsp.inline_completion.ClientState> 68local Completor ={ 69name ='inline_completion' , 70method ='textDocument/inlineCompletion' , 71active ={} , 72} 73Completor . __index =Completor 74setmetatable ( Completor , Capability ) 75Capability . all [ Completor . name ] =Completor 76 77---@package 78---@param buf integer 79---@return vim.lsp.inline_completion.Completor 80function Completor : new ( buf ) 81self =Capability . new ( self , buf ) 82self . client_state ={} 83nvim_on ( { 'InsertEnter' , 'CursorMovedI' , 'TextChangedP' } , self . augroup , { buf =buf } , function () 84self : automatic_request () 85end ) 86nvim_on ( { 'InsertLeave' } , self . augroup , { buf =buf } , function () 87self : abort () 88end ) 89return self 90end 91 92---@package 93function Completor : destroy () 94self : reset_timer () 95api . nvim_buf_clear_namespace ( self . bufnr , namespace , 0 , - 1 ) 96Capability . destroy ( self ) 97end 98 99--- Longest common prefix 100--- 101---@param a string 102---@param b string 103---@return integer index where the common prefix ends, exclusive 104local function lcp ( a , b ) 105local i , la , lb =1 , # a , # b 106while i <= la and i <= lb and a : sub ( i , i ) == b : sub ( i , i ) do 107i =i + 1 108end 109return i 110end 111 112--- `lsp.Handler` for `textDocument/inlineCompletion`. 113--- 114---@package 115---@param err? lsp.ResponseError 116---@param result? lsp.InlineCompletionItem[]|lsp.InlineCompletionList 117---@param ctx lsp.HandlerContext 118function Completor : handler ( err , result , ctx ) 119if err then 120log . error ( 'inline_completion' , err ) 121return 122end 123if not result or not vim . startswith ( api . nvim_get_mode (). mode , 'i' ) then 124return 125end 126 127local items =result . items or result 128self . client_state [ ctx . client_id ]. items =items 129self : select ( 1 ) 130end 131 132---@package 133function Completor : count_items () 134local n =0 135for _ , state in pairs ( self . client_state ) do 136local items =state . items 137if items then 138n =n + # items 139end 140end 141return n 142end 143 144---@package 145---@param i integer 146---@return integer?, lsp.InlineCompletionItem? 147function Completor : get_item ( i ) 148local n =self : count_items () 149i =i % ( n + 1 ) 150---@type integer[] 151local client_ids =vim . tbl_keys ( self . client_state ) 152table . sort ( client_ids ) 153for _ , client_id in ipairs ( client_ids ) do 154local items =self . client_state [ client_id ]. items 155if items then 156if i > # items then 157i =i - # items 158else 159return client_id , items [ i ] 160end 161end 162end 163end 164 165--- Select the {index}-th completion item. 166--- 167---@package 168---@param index integer 169---@param show_index? boolean 170function Completor : select ( index , show_index ) 171self . current =nil 172local client_id , item =self : get_item ( index ) 173if not client_id or not item then 174self : hide () 175return 176end 177 178local client =assert ( vim . lsp . get_client_by_id ( client_id )) 179local range =item . range and vim . range . lsp ( self . bufnr , item . range , client . offset_encoding ) 180self . current ={ 181_index =index , 182client_id =client_id , 183insert_text =item . insertText , 184range =range , 185_filter_text =item . filterText , 186command =item . command , 187} 188-- Recorded here because `show()` may grow the range over typed characters. 189self . _overlay =range ~= nil and not range : is_empty () 190 191local hint =show_index and ( ' (%d/%d)' ): format ( index , self : count_items ()) or nil 192self : show ( hint ) 193end 194 195--- Show or update the current completion item. 196--- 197---@package 198---@param hint? string 199function Completor : show ( hint ) 200self : hide () 201local current =self . current 202if not current then 203return 204end 205 206local insert_text =current . insert_text 207local text =type ( insert_text ) == 'string' and insert_text 208or tostring ( grammar . parse ( insert_text . value )) 209local lines ={} ---@type [string, string][][] 210for s in vim . gsplit ( text , '\n' , { plain =true } ) do 211table . insert ( lines , { { s , 'ComplHint' } } ) 212end 213if hint then 214table . insert ( lines [ # lines ], { hint , 'ComplHintMore' } ) 215end 216 217local row , col ---@type integer, integer 218if current . range then 219row , col =current . range : to_extmark () 220else 221row , col = 222vim . pos . cursor ( self . bufnr , api . nvim_win_get_cursor ( vim . fn . bufwinid ( self . bufnr ))): to_extmark () 223end 224 225-- To ensure that virtual text remains visible continuously (without flickering) 226-- while the user is editing the buffer, we allow displaying expired virtual text. 227-- Since the position of virtual text may become invalid after document changes, 228-- out-of-range items are ignored. 229local line_text =api . nvim_buf_get_lines ( self . bufnr , row , row + 1 , false )[ 1 ] 230if not ( line_text and # line_text >= col ) then 231self . current =nil 232return 233end 234 235-- The first line of the text to be inserted 236-- usually contains characters entered by the user, 237-- which should be skipped before displaying the virtual text. 238-- Splitting on a nonempty separator always yields a line, with its first chunk. 239local virt_text =assert ( lines [ 1 ]) 240assert ( virt_text [ 1 ]) 241local skip =lcp ( line_text : sub ( col + 1 ), virt_text [ 1 ][ 1 ]) 242local winid =api . nvim_get_current_win () 243-- At least, characters before the cursor should be skipped. 244if api . nvim_win_get_buf ( winid ) == self . bufnr then 245local cursor_row , cursor_col = 246vim . pos . cursor ( self . bufnr , api . nvim_win_get_cursor ( winid )): to_extmark () 247if row == cursor_row then 248-- Characters typed since the request lie past the item's range, so `accept()` 249-- would leave them behind. `skip` stops where the buffer stops matching. 250if current . range and col + skip - 1 >= cursor_col then 251local start_row , start_col , _ , end_col =current . range : to_extmark () 252if end_col < cursor_col then 253current . range =vim . range . extmark ( self . bufnr , start_row , start_col , row , cursor_col ) 254end 255end 256skip =math . max ( skip , cursor_col - col + 1 ) 257end 258end 259virt_text [ 1 ][ 1 ] =virt_text [ 1 ][ 1 ]: sub ( skip ) 260col =col + skip - 1 261 262local virt_lines ={ unpack ( lines , 2 ) } 263for i , s in ipairs ( virt_lines ) do 264if # s == 1 and s [ 1 ][ 1 ] == '' then 265virt_lines [ i ] ={} 266end 267end 268 269api . nvim_buf_set_extmark ( self . bufnr , namespace , row , col , { 270virt_text =virt_text , 271virt_lines =virt_lines , 272virt_text_pos =( self . _overlay and 'overlay' ) or 'inline' , 273hl_mode ='combine' , 274} ) 275end 276 277--- Hide the current completion item. 278--- 279---@package 280function Completor : hide () 281api . nvim_buf_clear_namespace ( self . bufnr , namespace , 0 , - 1 ) 282end 283 284---@package 285---@param kind lsp.InlineCompletionTriggerKind 286function Completor : request ( kind ) 287for client_id in pairs ( self . client_state ) do 288local client =assert ( vim . lsp . get_client_by_id ( client_id )) 289---@type lsp.InlineCompletionContext 290local context ={ triggerKind =kind } 291if 292kind == protocol . InlineCompletionTriggerKind . Invoked and api . nvim_get_mode (). mode : match ( '^v' ) 293then 294context . selectedCompletionInfo ={ 295range =util . make_given_range_params ( nil , nil , self . bufnr , client . offset_encoding ). range , 296text =table . concat ( vim . fn . getregion ( vim . fn . getpos ( "'<" ), vim . fn . getpos ( "'>" )), '\n' ), 297} 298end 299 300---@type lsp.InlineCompletionParams 301local params ={ 302textDocument =util . make_text_document_params ( self . bufnr ), 303position =util . make_position_params ( 0 , client . offset_encoding ). position , 304context =context , 305} 306client : request ( 'textDocument/inlineCompletion' , params , function ( ... ) 307self : handler ( ... ) 308end , self . bufnr ) 309end 310end 311 312---@private 313function Completor : reset_timer () 314local timer =self . timer 315if timer then 316self . timer =nil 317if not timer : is_closing () then 318timer : stop () 319timer : close () 320end 321end 322end 323 324--- Automatically request with debouncing, used as callbacks in autocmd events. 325--- 326---@package 327function Completor : automatic_request () 328self : show () 329self : reset_timer () 330self . timer =vim . defer_fn ( function () 331self : request ( protocol . InlineCompletionTriggerKind . Automatic ) 332end , 200 ) 333end 334 335--- Abort the current completion item and pending requests. 336--- 337---@package 338function Completor : abort () 339util . _cancel_requests ( { 340bufnr =self . bufnr , 341method ='textDocument/inlineCompletion' , 342type ='pending' , 343} ) 344self : reset_timer () 345self : hide () 346self . current =nil 347end 348 349--- Accept the current completion item to the buffer. 350--- 351---@package 352---@param item vim.lsp.inline_completion.Item 353function Completor : accept ( item ) 354local insert_text =item . insert_text 355if type ( insert_text ) == 'string' then 356if item . range then 357local start_row , start_col , end_row , end_col =item . range : to_extmark () 358-- The line may have shrunk past the range since the item arrived. 359local end_line =api . nvim_buf_get_lines ( self . bufnr , end_row , end_row + 1 , true )[ 1 ] 360end_col =math . min ( end_col , # end_line ) 361 362local lines =vim . split ( insert_text , '\n' ) 363api . nvim_buf_set_text ( self . bufnr , start_row , start_col , end_row , end_col , lines ) 364local win =api . nvim_get_current_win () 365win =api . nvim_win_get_buf ( win ) == self . bufnr and win or vim . fn . bufwinid ( self . bufnr ) 366local row , col =item . range : to_mark () 367api . nvim_win_set_cursor ( win , { 368row + # lines - 1 , 369( # lines == 1 and col or 0 ) + # lines [ # lines ], 370} ) 371else 372api . nvim_paste ( insert_text , false , 0 ) 373end 374elseif insert_text . kind == 'snippet' then 375vim . snippet . expand ( insert_text . value ) 376end 377 378-- Execute the command *after* inserting this completion. 379if item . command then 380local client =assert ( vim . lsp . get_client_by_id ( item . client_id )) 381client : exec_cmd ( item . command , { bufnr =self . bufnr } ) 382end 383end 384 385--- Query whether inline completion is enabled in the {filter}ed scope 386---@param filter? vim.lsp.capability.enable.Filter 387function M . is_enabled ( filter ) 388return vim . lsp . _capability . is_enabled ( 'inline_completion' , filter ) 389end 390 391--- Enables or disables inline completion for the {filter}ed scope, 392--- inline completion will automatically be refreshed when you are in insert mode. 393--- 394--- To "toggle", pass the inverse of `is_enabled()`: 395--- 396--- ```lua 397--- vim.lsp.inline_completion.enable(not vim.lsp.inline_completion.is_enabled()) 398--- ``` 399--- 400---@param enable? boolean true/nil to enable, false to disable 401---@param filter? vim.lsp.capability.enable.Filter 402function M . enable ( enable , filter ) 403vim . lsp . _capability . enable ( 'inline_completion' , enable , filter ) 404end 405 406---@class vim.lsp.inline_completion.select.Opts 407---@inlinedoc 408--- 409--- (default: current buffer) 410---@field bufnr? integer 411--- 412--- The number of candidates to move by. 413--- A positive integer moves forward by {count} candidates, 414--- while a negative integer moves backward by {count} candidates. 415--- (default: v:count1) 416---@field count? integer 417--- 418--- Whether to loop around file or not. Similar to 'wrapscan'. 419--- (default: `true`) 420---@field wrap? boolean 421 422--- Switch between available inline completion candidates. 423--- 424---@param opts? vim.lsp.inline_completion.select.Opts 425function M . select ( opts ) 426vim . validate ( 'opts' , opts , 'table' , true ) 427opts =opts or {} 428local bufnr =vim . _resolve_bufnr ( opts . bufnr ) 429local completor =Completor . active [ bufnr ] 430if not completor then 431return 432end 433 434local count =opts . count or vim . v . count1 435local wrap =opts . wrap ~= false 436 437local current =completor . current 438if not current then 439return 440end 441 442local n =completor : count_items () 443local index =current . _index + count 444if wrap then 445index =( index - 1 ) % n + 1 446else 447index =math . max ( 1 , math . min ( index , n )) 448end 449completor : select ( index , true ) 450end 451 452---@class vim.lsp.inline_completion.get.Opts 453---@inlinedoc 454--- 455--- Buffer handle, or 0 for current. 456--- (default: 0) 457---@field bufnr? integer 458--- 459--- A callback triggered when a completion item is accepted. 460--- You can use it to modify the completion item that is about to be accepted 461--- and return it to apply the changes, 462--- or return `nil` to prevent the changes from being applied to the buffer 463--- so you can implement custom behavior. 464---@field on_accept? fun(item: vim.lsp.inline_completion.Item): vim.lsp.inline_completion.Item? 465 466--- Accept the currently displayed completion candidate to the buffer. 467--- 468--- It returns false when no candidate can be accepted, 469--- so you can use the return value to implement a fallback: 470--- 471--- ```lua 472--- vim.keymap.set('i', '<Tab>', function() 473--- if not vim.lsp.inline_completion.get() then 474--- return '<Tab>' 475--- end 476--- end, { expr = true, desc = 'Accept the current inline completion' }) 477--- ```` 478---@param opts? vim.lsp.inline_completion.get.Opts 479---@return boolean `true` if a completion was applied, else `false`. 480function M . get ( opts ) 481vim . validate ( 'opts' , opts , 'table' , true ) 482opts =opts or {} 483 484local bufnr =vim . _resolve_bufnr ( opts . bufnr ) 485local on_accept =opts . on_accept 486 487local completor =Completor . active [ bufnr ] 488if completor and completor . current then 489-- Schedule apply to allow `get()` can be mapped with `<expr>`. 490vim . schedule ( function () 491local item =completor . current 492completor : abort () 493if not item then 494return 495end 496 497-- Note that we do not intend for `on_accept` 498-- to take effect when there is no current item. 499if on_accept then 500local accepted_item =on_accept ( item ) 501if accepted_item then 502completor : accept ( accepted_item ) 503end 504else 505completor : accept ( item ) 506end 507end ) 508return true 509end 510 511return false 512end 513 514return M