robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1-- Default user-commands, autocmds, mappings, menus. 2 3local nvim_on =require ( 'vim._core.util' ). nvim_on 4 5--- Default user commands 6do 7vim . api . nvim_create_user_command ( 'Inspect' , function ( cmd ) 8if cmd . bang then 9vim . ( vim . inspect_pos ()) 10else 11vim . show_pos () 12end 13end , { desc ='Inspect highlights and extmarks at the cursor' , bang =true } ) 14 15vim . api . nvim_create_user_command ( 'InspectTree' , function ( cmd ) 16local opts ={ lang =cmd . fargs [ 1 ] } 17 18if cmd . mods ~= '' or cmd . count ~= 0 then 19local count =cmd . count ~= 0 and cmd . count or '' 20local new =cmd . mods ~= '' and 'new' or 'vnew' 21 22opts . command =( '%s %s%s' ): format ( cmd . mods , count , new ) 23end 24 25vim . treesitter . inspect_tree ( opts ) 26end , { desc ='Inspect treesitter language tree for buffer' , count =true , nargs ='?' } ) 27 28vim . api . nvim_create_user_command ( 'EditQuery' , function ( cmd ) 29vim . treesitter . query . edit ( cmd . fargs [ 1 ]) 30end , { 31desc ='Edit treesitter query' , 32nargs ='?' , 33complete =function () 34return vim . treesitter . language . _complete () 35end , 36} ) 37 38vim . api . nvim_create_user_command ( 'Open' , function ( cmd ) 39if # cmd . fargs == 0 then 40local current_file =vim . fn . expand ( '%' ) 41if current_file ~= '' then 42vim . ui . open ( current_file ) 43end 44else 45vim . ui . open ( assert ( cmd . fargs [ 1 ])) 46end 47end , { 48desc ='Open file with system default handler. See :help vim.ui.open()' , 49nargs ='?' , 50complete ='file' , 51} ) 52end 53 54--- Default mappings 55do 56--- Default maps for * and # in visual mode. 57--- 58--- See |v_star-default| and |v_#-default| 59do 60--- @param forward 0|1 61local function _visual_search ( forward ) 62local pos =vim . fn . getpos ( '.' ) 63local vpos =vim . fn . getpos ( 'v' ) 64local mode =vim . fn . mode () 65local chunks =vim . fn . getregion ( pos , vpos , { type =mode } ) 66local esc_chunks =vim 67. iter ( chunks ) 68: map ( function ( v ) 69return vim . fn . escape ( v , [[\]] ) 70end ) 71: totable () 72local esc_pat =table . concat ( esc_chunks , [[\n]] ) 73if # esc_pat == 0 then 74vim . api . nvim_echo ( { { 'E348: No string under cursor' } } , true , { err =true } ) 75return '<Esc>' 76end 77local search =[[\V]] .. esc_pat 78 79vim . fn . setreg ( '/' , search ) 80vim . fn . histadd ( '/' , search ) 81vim . v . searchforward =forward 82 83-- The count has to be adjusted when searching backwards and the cursor 84-- isn't positioned at the beginning of the selection 85local count =vim . v . count1 86if forward == 0 then 87local _ , line , col , _ =unpack ( pos ) 88local _ , vline , vcol , _ =unpack ( vpos ) 89if 90line > vline 91or mode == 'v' and line == vline and col > vcol 92or mode == 'V' and col ~= 1 93or mode == '\22' and col > vcol 94then 95count =count + 1 96end 97end 98return '<Esc>' .. count .. 'n' 99end 100 101vim . keymap . set ( 'x' , '*' , function () 102return _visual_search ( 1 ) 103end , { desc =':help v_star-default' , expr =true } ) 104vim . keymap . set ( 'x' , '#' , function () 105return _visual_search ( 0 ) 106end , { desc =':help v_#-default' , expr =true } ) 107end 108 109--- Map Y to y$. This mimics the behavior of D and C. See |Y-default| 110vim . keymap . set ( 'n' , 'Y' , 'y$' , { desc =':help Y-default' } ) 111 112--- Use normal! <C-L> to prevent inserting raw <C-L> when using i_<C-O>. #17473 113--- 114--- See |CTRL-L-default| 115vim . keymap . set ( 116'n' , 117'<C-L>' , 118'<Cmd>nohlsearch<Bar>diffupdate' 119.. '<Bar>call nvim_buf_clear_namespace(0, nvim_create_namespace("nvim.multicursor"), 0, -1)' 120.. '<Bar>normal! <C-L><CR>' , 121{ desc =':help CTRL-L-default' } 122) 123 124--- Set undo points when deleting text in insert mode. 125--- 126--- See |i_CTRL-U-default| and |i_CTRL-W-default| 127vim . keymap . set ( 'i' , '<C-U>' , '<C-G>u<C-U>' , { desc =':help i_CTRL-U-default' } ) 128vim . keymap . set ( 'i' , '<C-W>' , '<C-G>u<C-W>' , { desc =':help i_CTRL-W-default' } ) 129 130--- Use the same flags as the previous substitution with &. 131--- 132--- Use : instead of <Cmd> so that ranges are supported. #19365 133--- 134--- See |&-default| 135vim . keymap . set ( 'n' , '&' , ':&&<CR>' , { desc =':help &-default' } ) 136 137--- Use @ in Visual mode to execute a macro on each line of the selection. #21422 138--- This only make sense in linewise Visual mode. #28287 139--- 140--- Includes @@ too. 141vim . keymap . set ( 142'x' , 143'@' , 144"mode() ==# 'V' ? ':normal! @'.getcharstr().'<CR>' : '@'" , 145{ silent =true , expr =true , desc =':help v_@-default' } 146) 147 148--- Map |gx| to call |vim.ui.open| on the `textDocument/documentLink` or <cfile> at cursor. 149do 150--- @param uri string 151local function do_open ( uri ) 152local cmd , err =vim . ui . open ( uri ) 153local rv =cmd and cmd : wait ( 1000 ) or nil 154if cmd and rv and rv . code ~= 0 then 155err =( 'vim.ui.open: command %s (%d): %s' ): format ( 156( rv . code == 124 and 'timeout' or 'failed' ), 157rv . code , 158vim . inspect ( cmd . cmd ) 159) 160end 161return err 162end 163 164local gx_desc = 165'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)' 166vim . keymap . set ( { 'n' } , 'gx' , function () 167for _ , url in ipairs ( require ( 'vim.ui' ). _get_urls ()) do 168local err =do_open ( url ) 169if err then 170vim . notify ( err , vim . log . levels . ERROR ) 171end 172end 173end , { desc =gx_desc } ) 174vim . keymap . set ( { 'x' } , 'gx' , function () 175local lines = 176vim . fn . getregion ( vim . fn . getpos ( '.' ), vim . fn . getpos ( 'v' ), { type =vim . fn . mode () } ) 177-- Trim whitespace on each line and concatenate. 178local err =do_open ( table . concat ( vim . iter ( lines ): map ( vim . trim ): totable ())) 179if err then 180vim . notify ( err , vim . log . levels . ERROR ) 181end 182end , { desc =gx_desc } ) 183end 184 185--- Default maps for built-in commenting. 186--- 187--- See |gc-default| and |gcc-default|. 188do 189local operator_rhs =function () 190return require ( 'vim._comment' ). operator () 191end 192vim . keymap . set ( { 'n' , 'x' } , 'gc' , operator_rhs , { expr =true , desc ='Toggle comment' } ) 193 194local line_rhs =function () 195return require ( 'vim._comment' ). operator () .. '_' 196end 197vim . keymap . set ( 'n' , 'gcc' , line_rhs , { expr =true , desc ='Toggle comment line' } ) 198 199local textobject_rhs =function () 200require ( 'vim._comment' ). textobject () 201end 202vim . keymap . set ( { 'o' } , 'gc' , textobject_rhs , { desc ='Comment textobject' } ) 203end 204 205--- Default maps for LSP functions. 206--- 207--- These are mapped unconditionally to avoid different behavior depending on whether an LSP 208--- client is attached. If no client is attached, or if a server does not support a capability, an 209--- error message is displayed rather than exhibiting different behavior. 210--- 211--- See |grr|, |grn|, |gra|, |gri|, |grt| |gO|, |i_CTRL-S|. 212do 213vim . keymap . set ( 'n' , 'grn' , function () 214vim . lsp . buf . rename () 215end , { desc ='vim.lsp.buf.rename()' } ) 216 217vim . keymap . set ( { 'n' , 'x' } , 'gra' , function () 218vim . lsp . buf . code_action () 219end , { desc ='vim.lsp.buf.code_action()' } ) 220 221vim . keymap . set ( 'n' , 'grx' , function () 222vim . lsp . codelens . run () 223end , { desc ='vim.lsp.codelens.run()' } ) 224 225vim . keymap . set ( 'n' , 'grr' , function () 226vim . lsp . buf . references () 227end , { desc ='vim.lsp.buf.references()' } ) 228 229vim . keymap . set ( 'n' , 'gri' , function () 230vim . lsp . buf . implementation () 231end , { desc ='vim.lsp.buf.implementation()' } ) 232 233vim . keymap . set ( 'n' , 'grt' , function () 234vim . lsp . buf . type_definition () 235end , { desc ='vim.lsp.buf.type_definition()' } ) 236 237vim . keymap . set ( 'n' , 'gO' , function () 238vim . lsp . buf . document_symbol () 239end , { desc ='vim.lsp.buf.document_symbol()' } ) 240 241vim . keymap . set ( { 'i' , 's' } , '<C-S>' , function () 242vim . lsp . buf . signature_help () 243end , { desc ='vim.lsp.buf.signature_help()' } ) 244end 245 246do 247---@param direction vim.snippet.Direction 248---@param key string 249local function set_snippet_jump ( direction , key ) 250vim . keymap . set ( { 'i' , 's' } , key , function () 251if vim . snippet . active ( { direction =direction } ) then 252return string . format ( '<Cmd>lua vim.snippet.jump(%d)<CR>' , direction ) 253else 254return key 255end 256end , { 257desc ='vim.snippet.jump if active, otherwise ' .. key , 258expr =true , 259silent =true , 260} ) 261end 262 263set_snippet_jump ( 1 , '<Tab>' ) 264set_snippet_jump ( - 1 , '<S-Tab>' ) 265end 266 267--- Map [d and ]d to move to the previous/next diagnostic. Map <C-W>d to open a floating window 268--- for the diagnostic under the cursor. 269--- 270--- See |[d-default|, |]d-default|, and |CTRL-W_d-default|. 271do 272vim . keymap . set ( 'n' , ']d' , function () 273vim . diagnostic . jump ( { count =vim . v . count1 } ) 274end , { desc ='Jump to the next diagnostic in the current buffer' } ) 275 276vim . keymap . set ( 'n' , '[d' , function () 277vim . diagnostic . jump ( { count =- vim . v . count1 } ) 278end , { desc ='Jump to the previous diagnostic in the current buffer' } ) 279 280vim . keymap . set ( 'n' , ']D' , function () 281vim . diagnostic . jump ( { count =vim . _maxint , wrap =false } ) 282end , { desc ='Jump to the last diagnostic in the current buffer' } ) 283 284vim . keymap . set ( 'n' , '[D' , function () 285vim . diagnostic . jump ( { count =- vim . _maxint , wrap =false } ) 286end , { desc ='Jump to the first diagnostic in the current buffer' } ) 287 288vim . keymap . set ( 'n' , '<C-W>d' , function () 289vim . diagnostic . open_float () 290end , { desc ='Show diagnostics under the cursor' } ) 291 292vim . keymap . set ( 293'n' , 294'<C-W><C-D>' , 295'<C-W>d' , 296{ remap =true , desc ='Show diagnostics under the cursor' } 297) 298end 299 300--- Execute a command and print errors without a stacktrace. 301--- @param opts vim.api.keyset.cmd Arguments to |nvim_cmd()| 302local function cmd ( opts ) 303local ok , err =pcall ( vim . api . nvim_cmd , opts , {} ) 304if not ok then 305vim . api . nvim_echo ( { { require ( 'vim._core.util' ). cmd_errmsg ( err ) } } , true , { err =true } ) 306end 307end 308 309--- vim-unimpaired style mappings. See: https://github.com/tpope/vim-unimpaired 310do 311-- Quickfix mappings 312vim . keymap . set ( 'n' , '[q' , function () 313cmd ( { cmd ='cprevious' , count =vim . v . count1 } ) 314end , { desc =':cprevious' } ) 315 316vim . keymap . set ( 'n' , ']q' , function () 317cmd ( { cmd ='cnext' , count =vim . v . count1 } ) 318end , { desc =':cnext' } ) 319 320vim . keymap . set ( 'n' , '[Q' , function () 321cmd ( { cmd ='crewind' , count =vim . v . count ~= 0 and vim . v . count or nil } ) 322end , { desc =':crewind' } ) 323 324vim . keymap . set ( 'n' , ']Q' , function () 325cmd ( { cmd ='clast' , count =vim . v . count ~= 0 and vim . v . count or nil } ) 326end , { desc =':clast' } ) 327 328vim . keymap . set ( 'n' , '[<C-Q>' , function () 329cmd ( { cmd ='cpfile' , count =vim . v . count1 } ) 330end , { desc =':cpfile' } ) 331 332vim . keymap . set ( 'n' , ']<C-Q>' , function () 333cmd ( { cmd ='cnfile' , count =vim . v . count1 } ) 334end , { desc =':cnfile' } ) 335 336-- Location list mappings 337vim . keymap . set ( 'n' , '[l' , function () 338cmd ( { cmd ='lprevious' , count =vim . v . count1 } ) 339end , { desc =':lprevious' } ) 340 341vim . keymap . set ( 'n' , ']l' , function () 342cmd ( { cmd ='lnext' , count =vim . v . count1 } ) 343end , { desc =':lnext' } ) 344 345vim . keymap . set ( 'n' , '[L' , function () 346cmd ( { cmd ='lrewind' , count =vim . v . count ~= 0 and vim . v . count or nil } ) 347end , { desc =':lrewind' } ) 348 349vim . keymap . set ( 'n' , ']L' , function () 350cmd ( { cmd ='llast' , count =vim . v . count ~= 0 and vim . v . count or nil } ) 351end , { desc =':llast' } ) 352 353vim . keymap . set ( 'n' , '[<C-L>' , function () 354cmd ( { cmd ='lpfile' , count =vim . v . count1 } ) 355end , { desc =':lpfile' } ) 356 357vim . keymap . set ( 'n' , ']<C-L>' , function () 358cmd ( { cmd ='lnfile' , count =vim . v . count1 } ) 359end , { desc =':lnfile' } ) 360 361-- Argument list 362vim . keymap . set ( 'n' , '[a' , function () 363cmd ( { cmd ='previous' , count =vim . v . count1 } ) 364end , { desc =':previous' } ) 365 366vim . keymap . set ( 'n' , ']a' , function () 367-- count doesn't work with :next, must use range. See #30641. 368cmd ( { cmd ='next' , range ={ vim . v . count1 } } ) 369end , { desc =':next' } ) 370 371vim . keymap . set ( 'n' , '[A' , function () 372if vim . v . count ~= 0 then 373cmd ( { cmd ='argument' , count =vim . v . count } ) 374else 375cmd ( { cmd ='rewind' } ) 376end 377end , { desc =':rewind' } ) 378 379vim . keymap . set ( 'n' , ']A' , function () 380if vim . v . count ~= 0 then 381cmd ( { cmd ='argument' , count =vim . v . count } ) 382else 383cmd ( { cmd ='last' } ) 384end 385end , { desc =':last' } ) 386 387-- Tags 388vim . keymap . set ( 'n' , '[t' , function () 389-- count doesn't work with :tprevious, must use range. See #30641. 390cmd ( { cmd ='tprevious' , range ={ vim . v . count1 } } ) 391end , { desc =':tprevious' } ) 392 393vim . keymap . set ( 'n' , ']t' , function () 394-- count doesn't work with :tnext, must use range. See #30641. 395cmd ( { cmd ='tnext' , range ={ vim . v . count1 } } ) 396end , { desc =':tnext' } ) 397 398vim . keymap . set ( 'n' , '[T' , function () 399-- count doesn't work with :trewind, must use range. See #30641. 400cmd ( { cmd ='trewind' , range =vim . v . count ~= 0 and { vim . v . count } or nil } ) 401end , { desc =':trewind' } ) 402 403vim . keymap . set ( 'n' , ']T' , function () 404-- :tlast does not accept a count, so use :trewind if count given 405if vim . v . count ~= 0 then 406cmd ( { cmd ='trewind' , range ={ vim . v . count } } ) 407else 408cmd ( { cmd ='tlast' } ) 409end 410end , { desc =':tlast' } ) 411 412vim . keymap . set ( 'n' , '[<C-T>' , function () 413-- count doesn't work with :ptprevious, must use range. See #30641. 414cmd ( { cmd ='ptprevious' , range ={ vim . v . count1 } } ) 415end , { desc =':ptprevious' } ) 416 417vim . keymap . set ( 'n' , ']<C-T>' , function () 418-- count doesn't work with :ptnext, must use range. See #30641. 419cmd ( { cmd ='ptnext' , range ={ vim . v . count1 } } ) 420end , { desc =':ptnext' } ) 421 422-- Buffers 423vim . keymap . set ( 'n' , '[b' , function () 424cmd ( { cmd ='bprevious' , count =vim . v . count1 } ) 425end , { desc =':bprevious' } ) 426 427vim . keymap . set ( 'n' , ']b' , function () 428cmd ( { cmd ='bnext' , count =vim . v . count1 } ) 429end , { desc =':bnext' } ) 430 431vim . keymap . set ( 'n' , '[B' , function () 432if vim . v . count ~= 0 then 433cmd ( { cmd ='buffer' , count =vim . v . count } ) 434else 435cmd ( { cmd ='brewind' } ) 436end 437end , { desc =':brewind' } ) 438 439vim . keymap . set ( 'n' , ']B' , function () 440if vim . v . count ~= 0 then 441cmd ( { cmd ='buffer' , count =vim . v . count } ) 442else 443cmd ( { cmd ='blast' } ) 444end 445end , { desc =':blast' } ) 446 447-- Add empty lines 448vim . keymap . set ( 'n' , '[<Space>' , function () 449vim . go . operatorfunc =require ( 'vim._core.util' ). space_above 450return 'g@l' 451end , { expr =true , desc ='Add empty line above cursor' } ) 452 453vim . keymap . set ( 'n' , ']<Space>' , function () 454vim . go . operatorfunc =require ( 'vim._core.util' ). space_below 455return 'g@l' 456end , { expr =true , desc ='Add empty line below cursor' } ) 457end 458 459--- "Incremental selection" mappings (treesitter + LSP fallback). 460do 461vim . keymap . set ( { 'x' } , '[n' , function () 462vim . treesitter . select ( 'prev' , vim . v . count1 ) 463end , { desc ='Select previous node' } ) 464 465vim . keymap . set ( { 'x' } , ']n' , function () 466vim . treesitter . select ( 'next' , vim . v . count1 ) 467end , { desc ='Select next node' } ) 468 469vim . keymap . set ( { 'x' } , '[N' , function () 470vim . treesitter . select ( 'extend_prev' , vim . v . count1 ) 471end , { desc ='Select previous sibling node' } ) 472 473vim . keymap . set ( { 'x' } , ']N' , function () 474vim . treesitter . select ( 'extend_next' , vim . v . count1 ) 475end , { desc ='Select next sibling node' } ) 476 477vim . keymap . set ( { 'x' , 'o' } , 'an' , function () 478if vim . treesitter . get_parser ( nil , nil , { error =false } ) then 479vim . treesitter . select ( 'parent' , vim . v . count1 ) 480else 481vim . lsp . buf . selection_range ( vim . v . count1 ) 482end 483end , { desc ='Select parent (outer) node' } ) 484 485vim . keymap . set ( { 'x' , 'o' } , 'in' , function () 486if vim . treesitter . get_parser ( nil , nil , { error =false } ) then 487vim . treesitter . select ( 'child' , vim . v . count1 ) 488else 489vim . lsp . buf . selection_range ( - vim . v . count1 ) 490end 491end , { desc ='Select child (inner) node' } ) 492end 493end 494 495--- Default menus 496do 497--- Right click popup menu 498vim . cmd ( [[ 499amenu PopUp.Open\ in\ web\ browser gx 500anoremenu PopUp.Inspect <Cmd>Inspect<CR> 501anoremenu PopUp.Go\ to\ definition <Cmd>lua vim.lsp.buf.definition()<CR> 502anoremenu PopUp.Show\ Diagnostics <Cmd>lua vim.diagnostic.open_float()<CR> 503anoremenu PopUp.Show\ All\ Diagnostics <Cmd>lua vim.diagnostic.setqflist()<CR> 504anoremenu PopUp.Configure\ Diagnostics <Cmd>help vim.diagnostic.config()<CR> 505anoremenu PopUp.-1- <Nop> 506vnoremenu PopUp.Cut "+x 507vnoremenu PopUp.Copy "+y 508anoremenu PopUp.Paste "+gP 509vnoremenu PopUp.Paste "+P 510vnoremenu PopUp.Delete "_x 511nnoremenu PopUp.Select\ All ggVG 512vnoremenu PopUp.Select\ All gg0oG$ 513inoremenu PopUp.Select\ All <C-Home><C-O>VG 514anoremenu PopUp.-2- <Nop> 515anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR> 516]] ) 517 518local function enable_ctx_menu () 519vim . cmd ( [[ 520amenu disable PopUp.Go\ to\ definition 521amenu disable PopUp.Open\ in\ web\ browser 522amenu disable PopUp.Show\ Diagnostics 523amenu disable PopUp.Show\ All\ Diagnostics 524amenu disable PopUp.Configure\ Diagnostics 525]] ) 526 527local url =require ( 'vim.ui' ). _get_urls ()[ 1 ] 528if url and vim . startswith ( url , 'http' ) then 529vim . cmd ( [[amenu enable PopUp.Open\ in\ web\ browser]] ) 530elseif vim . lsp . get_clients ( { bufnr =0 } )[ 1 ] then 531vim . cmd ( [[anoremenu enable PopUp.Go\ to\ definition]] ) 532end 533 534local lnum =vim . fn . getcurpos ()[ 2 ] - 1 ---@type integer 535local diagnostic =false 536if next ( vim . diagnostic . get ( 0 , { lnum =lnum } )) ~= nil then 537diagnostic =true 538vim . cmd ( [[anoremenu enable PopUp.Show\ Diagnostics]] ) 539end 540 541if diagnostic or next ( vim . diagnostic . count ( 0 )) ~= nil then 542vim . cmd ( [[ 543anoremenu enable PopUp.Show\ All\ Diagnostics 544anoremenu enable PopUp.Configure\ Diagnostics 545]] ) 546end 547end 548 549local nvim_popupmenu_augroup =vim . api . nvim_create_augroup ( 'nvim.popupmenu' ) 550nvim_on ( 'MenuPopup' , nvim_popupmenu_augroup , { 551pattern ='*' , 552desc ='Mouse popup menu' , 553-- nested = true, 554} , function () 555enable_ctx_menu () 556end ) 557end 558 559--- Default autocommands. See |default-autocmds| 560do 561-- Warn if $NVIM_LOG_FILE or $XDG_STATE_HOME are inaccessible. #38039 562if vim . v . vim_did_enter then 563require ( 'vim._core.log' ). check_log_file () 564else 565nvim_on ( 'VimEnter' , nil , { once =true } , function () 566require ( 'vim._core.log' ). check_log_file () 567end ) 568end 569 570local nvim_terminal_augroup =vim . api . nvim_create_augroup ( 'nvim.terminal' ) 571vim . api . nvim_create_autocmd ( 'BufReadCmd' , { 572pattern ='term://*' , 573group =nvim_terminal_augroup , 574desc ='Treat term:// buffers as terminal buffers' , 575nested =true , 576command ="if !exists('b:term_title')|call jobstart(matchstr(expand(\"<amatch>\"), '\\c\\mterm://\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), {'term': v:true, 'cwd': expand(get(matchlist(expand(\"<amatch>\"), '\\c\\mterm://\\(.\\{-}\\)//'), 1, ''))})" , 577} ) 578 579nvim_on ( { 'TermClose' } , nvim_terminal_augroup , { 580nested =true , 581desc ='Automatically close terminal buffers when started with no arguments and exiting without an error' , 582} , function ( ev ) 583if vim . v . event . status ~= 0 then 584return 585end 586local info =vim . api . nvim_get_chan_info ( vim . bo [ ev . buf ]. channel ) 587local argv =info . argv or {} 588if table . concat ( argv , ' ' ) == vim . o . shell then 589vim . api . nvim_buf_delete ( ev . buf , { force =true } ) 590end 591end ) 592 593local nvim_terminal_exitmsg_ns =vim . api . nvim_create_namespace ( 'nvim.terminal.exitmsg' ) 594 595--- @param buf integer 596--- @param msg string 597--- @param pos integer 598local function set_terminal_exitmsg ( buf , msg , pos ) 599vim . api . nvim_buf_set_extmark ( buf , nvim_terminal_exitmsg_ns , pos , 0 , { 600virt_text ={ { msg , nil } } , 601virt_text_pos ='overlay' , 602} ) 603end 604 605nvim_on ( 'TermClose' , nvim_terminal_augroup , { 606nested =true , 607desc ='Displays the "[Process exited]" virtual text' , 608} , function ( ev ) 609if not vim . api . nvim_buf_is_valid ( ev . buf ) then 610return 611end 612 613local buf =vim . bo [ ev . buf ] 614local pos =ev . data . pos ---@type integer 615local buf_has_exitmsg =# ( 616vim . api . nvim_buf_get_extmarks ( ev . buf , nvim_terminal_exitmsg_ns , 0 , - 1 ) 617) > 0 618 619-- `nvim_open_term` buffers do not have an attached 'channel'. 620local msg =buf . channel == 0 and '[Terminal closed]' 621or ( '[Process exited %d]' ): format ( vim . v . event . status ) 622 623if buf . buftype ~= 'terminal' or buf_has_exitmsg then 624-- TermClose may be queued before TermOpen if process exits before `terminal_open` is called. 625-- Don't display the msg now, let TermOpen display it. 626nvim_on ( 'TermOpen' , nil , { 627buf =ev . buf , 628once =true , 629} , function () 630set_terminal_exitmsg ( ev . buf , msg , pos ) 631end ) 632return 633end 634set_terminal_exitmsg ( ev . buf , msg , pos ) 635end ) 636 637nvim_on ( 'TermRequest' , nvim_terminal_augroup , { 638desc ='Handles OSC foreground/background color requests' , 639} , function ( ev ) 640--- @type integer 641local channel =vim . bo [ ev . buf ]. channel 642if channel == 0 then 643return 644end 645local fg_request =ev . data . sequence == '\027]10;?' 646local bg_request =ev . data . sequence == '\027]11;?' 647if fg_request or bg_request then 648-- WARN: This does not return the actual foreground/background color, 649-- but rather returns: 650-- - fg=white/bg=black when Nvim option 'background' is 'dark' 651-- - fg=black/bg=white when Nvim option 'background' is 'light' 652local red , green , blue =0 , 0 , 0 653local bg_option_dark =vim . o . background == 'dark' 654if ( fg_request and bg_option_dark ) or ( bg_request and not bg_option_dark ) then 655red , green , blue =65535 , 65535 , 65535 656end 657local command =fg_request and 10 or 11 658local data = 659string . format ( '\027]%d;rgb:%04x/%04x/%04x%s' , command , red , green , blue , ev . data . terminator ) 660vim . api . nvim_chan_send ( channel , data ) 661end 662end ) 663 664local nvim_terminal_prompt_ns =vim . api . nvim_create_namespace ( 'nvim.terminal.prompt' ) 665nvim_on ( 'TermRequest' , nvim_terminal_augroup , { 666desc ='Mark shell prompts indicated by OSC 133 sequences for navigation' , 667} , function ( ev ) 668if string . match ( ev . data . sequence , '^\027]133;A' ) then 669local lnum =ev . data . cursor [ 1 ] ---@type integer 670if lnum >= 1 then 671vim . api . nvim_buf_set_extmark ( 672ev . buf , 673nvim_terminal_prompt_ns , 674lnum - 1 , 6750 , 676{ right_gravity =false } 677) 678end 679end 680end ) 681 682---@param ns integer 683---@param win integer 684---@param buf integer 685---@param count integer 686local function jump_to_prompt ( ns , win , buf , count ) 687local row , col =unpack ( vim . api . nvim_win_get_cursor ( win )) 688local start =- 1 689local end_ ---@type 0|-1 690if count > 0 then 691start =row 692end_ =- 1 693elseif count < 0 then 694-- Subtract 2 because row is 1-based, but extmarks are 0-based 695start =row - 2 696end_ =0 697end 698 699if start < 0 then 700return 701end 702 703local extmarks =vim . api . nvim_buf_get_extmarks ( 704buf , 705ns , 706{ start , col } , 707end_ , 708{ limit =math . abs ( count ) } 709) 710if # extmarks > 0 then 711local extmark =assert ( extmarks [ math . min ( # extmarks , math . abs ( count ))]) 712vim . api . nvim_win_set_cursor ( win , { extmark [ 2 ] + 1 , extmark [ 3 ] } ) 713end 714end 715 716nvim_on ( 'TermOpen' , nvim_terminal_augroup , { 717desc ='Default settings for :terminal buffers' , 718} , function ( ev ) 719vim . bo [ ev . buf ]. modifiable =false 720vim . bo [ ev . buf ]. undolevels =- 1 721vim . bo [ ev . buf ]. scrollback =vim . o . scrollback < 0 and 10000 or math . max ( 1 , vim . o . scrollback ) 722vim . bo [ ev . buf ]. textwidth =0 723vim . wo [ 0 ][ 0 ]. wrap =false 724vim . wo [ 0 ][ 0 ]. list =false 725vim . wo [ 0 ][ 0 ]. number =false 726vim . wo [ 0 ][ 0 ]. relativenumber =false 727vim . wo [ 0 ][ 0 ]. signcolumn ='no' 728vim . wo [ 0 ][ 0 ]. foldcolumn ='0' 729 730-- This is gross. Proper list options support when? 731local winhl =vim . o . winhighlight 732if winhl ~= '' then 733winhl =winhl .. ',' 734end 735vim . wo [ 0 ][ 0 ]. winhighlight =winhl .. 'StatusLine:StatusLineTerm,StatusLineNC:StatusLineTermNC' 736 737vim . keymap . set ( { 'n' , 'x' , 'o' } , '[[' , function () 738jump_to_prompt ( nvim_terminal_prompt_ns , 0 , ev . buf , - vim . v . count1 ) 739end , { buf =ev . buf , desc ='Jump [count] shell prompts backward' } ) 740vim . keymap . set ( { 'n' , 'x' , 'o' } , ']]' , function () 741jump_to_prompt ( nvim_terminal_prompt_ns , 0 , ev . buf , vim . v . count1 ) 742end , { buf =ev . buf , desc ='Jump [count] shell prompts forward' } ) 743 744-- If the terminal buffer is being reused, clear the previous exit msg 745vim . api . nvim_buf_clear_namespace ( ev . buf , nvim_terminal_exitmsg_ns , 0 , - 1 ) 746end ) 747 748vim . api . nvim_create_autocmd ( 'CmdwinEnter' , { 749pattern ='[:>]' , 750desc ='Limit syntax sync to maxlines=1 in the command window' , 751group =vim . api . nvim_create_augroup ( 'nvim.cmdwin' ), 752command ='syntax sync minlines=1 maxlines=1' , 753} ) 754 755nvim_on ( 'SwapExists' , vim . api . nvim_create_augroup ( 'nvim.swapfile' ), { 756pattern ='*' , 757desc ='Skip the swapfile prompt when the swapfile is owned by a running Nvim process' , 758} , function () 759local info =vim . fn . swapinfo ( vim . v . swapname ) 760local passwd =vim . uv . os_get_passwd () 761local user =passwd and passwd . username 762local iswin =1 == vim . fn . has ( 'win32' ) 763if info . error or info . pid <= 0 or ( not iswin and ( not user or info . user ~= user )) then 764vim . v . swapchoice ='' -- Show the prompt. 765return 766end 767vim . v . swapchoice ='e' -- Choose "(E)dit". 768vim . notify ( 769( 'W325: Ignoring swapfile from Nvim process %d' ): format ( info . pid ), 770vim . log . levels . WARN , 771{ _truncate =true } 772) 773end ) 774 775-- Check if a TTY is attached 776local tty =nil 777for _ , ui in ipairs ( vim . api . nvim_list_uis ()) do 778if ui . stdout_tty then 779tty =ui 780break 781end 782end 783 784-- Shared TTY option detection used by two paths: the startup path (a TTY is 785-- present when Nvim starts) and the UIEnter path (a TTY attaches to a 786-- previously |--headless| server, e.g. behind |--remote-ui|). The helpers are 787-- hoisted here so both paths share one implementation instead of duplicating 788-- it. 789-- 790-- Precedence: never override an explicit user setting. For 'background', 791-- bg_user_set() treats only our own sets (SID_LUA, -8) as re-applicable; a 792-- user set (real script SID, ":set", or API client) is preserved. 793-- 'termguicolors' is guarded by `was_set` and is only ever enabled here. 794-- 795-- Limitation: 'background' is global, the OSC 11 query is broadcast to every 796-- attached terminal, and a |TermResponse| is not attributable to a UI, so the 797-- value reflects whichever terminal answers last (decided by response speed), 798-- not necessarily the most recently attached one. 799local group =vim . api . nvim_create_augroup ( 'nvim.tty' ) 800 801--- Set an option after startup (so that OptionSet is fired), but only if not 802--- already set by the user. 803--- 804--- @param option string Option name 805--- @param value any Option value 806--- @param force boolean? Always set the value, even if already set 807local function setoption ( option , value , force ) 808if not force and vim . api . nvim_get_option_info2 ( option ). was_set then 809-- Don't do anything if option is already set 810return 811end 812 813-- Wait until Nvim is finished starting to set the option to ensure the 814-- OptionSet event fires. 815if vim . v . vim_did_enter == 1 then 816--- @diagnostic disable-next-line:no-unknown 817vim . o [ option ] =value 818else 819nvim_on ( 'VimEnter' , group , { 820once =true , 821nested =true , 822} , function () 823setoption ( option , value , force ) 824end ) 825end 826end 827 828--- Script ID (SID) used for our own automatic 'background' sets. Lets 829--- bg_user_set() distinguish a user set from our detection. 830local sid_lua =- 8 831 832--- True if 'background' was set by the user, not by our detection (sid_lua). 833local function bg_user_set () 834local info =vim . api . nvim_get_option_info2 ( 'background' ) 835return info . was_set and info . last_set_sid ~= sid_lua 836end 837 838--- Parse a string of hex characters as a color. 839--- 840--- The string can contain 1 to 4 hex characters. The returned value is 841--- between 0.0 and 1.0 (inclusive) representing the intensity of the color. 842--- 843--- For instance, if only a single hex char "a" is used, then this function 844--- returns 0.625 (10 / 16), while a value of "aa" would return 0.664 (170 / 845--- 256). 846--- 847--- @param c string Color as a string of hex chars 848--- @return number? Intensity of the color 849local function parsecolor ( c ) 850if # c == 0 or # c > 4 then 851return nil 852end 853 854local val =vim . _tointeger ( c , 16 ) 855if not val then 856return nil 857end 858 859local max =vim . _assert_integer ( string . rep ( 'f' , # c ), 16 ) 860return val / max 861end 862 863--- Parse an OSC 11 response 864--- 865--- Either of the two formats below are accepted: 866--- 867--- OSC 11 ; rgb:<red>/<green>/<blue> 868--- 869--- or 870--- 871--- OSC 11 ; rgba:<red>/<green>/<blue>/<alpha> 872--- 873--- where 874--- 875--- <red>, <green>, <blue>, <alpha> := h | hh | hhh | hhhh 876--- 877--- The alpha component is ignored, if present. 878--- 879--- @param resp string OSC 11 response 880--- @return string? Red component 881--- @return string? Green component 882--- @return string? Blue component 883local function parseosc11 ( resp ) 884local r , g , b 885r , g , b =resp : match ( '^\027%]11;rgb:(%x+)/(%x+)/(%x+)$' ) 886if not r and not g and not b then 887local a 888r , g , b , a =resp : match ( '^\027%]11;rgba:(%x+)/(%x+)/(%x+)/(%x+)$' ) 889if not a or # a > 4 then 890return nil , nil , nil 891end 892end 893 894if r and g and b and # r <= 4 and # g <= 4 and # b <= 4 then 895return r , g , b 896end 897 898return nil , nil , nil 899end 900 901--- Guess value of 'background' based on terminal color. 902--- 903--- We write Operating System Command (OSC) 11 to the terminal to request the 904--- terminal's background color. We then wait for a response. If the response 905--- matches `rgba:RRRR/GGGG/BBBB/AAAA` where R, G, B, and A are hex digits, then 906--- compute the luminance[1] of the RGB color and classify it as light/dark 907--- accordingly. Note that the color components may have anywhere from one to 908--- four hex digits, and require scaling accordingly as values out of 4, 8, 12, 909--- or 16 bits. Also note the A(lpha) component is optional, and is parsed but 910--- ignored in the calculations. 911--- 912--- [1] https://en.wikipedia.org/wiki/Luma_%28video%29 913--- 914--- In slow environments (e.g. SSH with high latency), this will increase 915--- startup time and produce a warning, so users may want to disable it. 916--- 917--- The OSC 11 handler is PERSISTENT (timeout=0) so it also reacts to runtime 918--- theme changes (a terminal in mode 2031 re-queries and forwards a fresh 919--- |TermResponse|). Its augroup is cleared on each call so only the 920--- most-recently-attached TUI's handler remains. 921--- 922--- @param sync boolean When true (a TTY is present at startup), also send a 923--- DSR probe and synchronously wait so 'background' is set before user config, 924--- warning (E1568) if the terminal never answers the DSR. 925--- @param chan integer 926local function detect_background ( sync , chan ) 927-- Re-create (clear) the handler's augroup on each call so only the 928-- most-recently-attached TUI's handler remains. 929local bg_group =vim . api . nvim_create_augroup ( 'nvim.tty.background' ) 930 931-- Send OSC 11 query. In the startup (sync) path also send a DSR probe: if 932-- the DSR response comes first, the terminal most likely doesn't support the 933-- bg color query, and we don't have to keep waiting for a bg response. #32109 934local osc11 ='\027]11;?\007' 935local dsr ='\027[5n' 936 937-- This handler updates 'background' anytime we receive an OSC 11 response 938-- from the terminal emulator. It is persistent (no built-in timeout) so it 939-- also reacts to runtime theme changes; the per-response bg_user_set() guard 940-- stops it once the user pins 'background'. 941local did_dsr_response =false 942vim . tty . request ( 943osc11 .. ( sync and dsr or '' ), 944{ group =bg_group , timeout =0 , chan =chan } , 945function ( resp ) 946-- DSR response that should come after the OSC 11 response if the terminal 947-- supports it. 948if sync and string . match ( resp , '^\027%[0n$' ) then 949did_dsr_response =true 950-- Don't stop listening: the bg response may come after the DSR response 951-- if the terminal handles requests out of sequence. In that case, the bg 952-- will simply be set later in the startup sequence. 953return 954end 955 956-- Never override an explicit user value: stop once the user pins it. 957if bg_user_set () then 958return true 959end 960 961local r , g , b =parseosc11 ( resp ) 962if r and g and b then 963local rr =parsecolor ( r ) 964local gg =parsecolor ( g ) 965local bb =parsecolor ( b ) 966 967if rr and gg and bb then 968local luminance =( 0.299 * rr ) + ( 0.587 * gg ) + ( 0.114 * bb ) 969local bg =luminance < 0.5 and 'dark' or 'light' 970vim . o . background =bg 971end 972end 973end 974) 975 976if not sync then 977return 978end 979 980-- Wait until detection of OSC 11 capabilities is complete to ensure 981-- background is automatically set before user config. 982if 983not vim . wait ( 100 , function () 984return did_dsr_response 985end , 1 ) 986-- Don't show the warning when running tests to avoid flakiness. 987and os . getenv ( 'NVIM_TEST' ) == nil 988then 989vim . notify ( 990"E1568: Terminal did not respond to DSR request for 'background' color. Startup may be slower. :help 'ttyfast'" , 991vim . log . levels . WARN , 992{ _truncate =true } 993) 994end 995end 996 997--- If the TUI (term_has_truecolor) detected that the host terminal supports truecolor, enable 998--- 'termguicolors'. Otherwise, query the terminal (using both XTGETTCAP and SGR + DECRQSS). If 999--- the terminal's response indicates that it does support truecolor enable 'termguicolors', 1000--- but only if the user has not already disabled it. 1001--- 1002--- @param ui table<string,any> The attached TTY UI (see |nvim_list_uis()|). 1003local function detect_termguicolors ( ui ) 1004local colorterm =os . getenv ( 'COLORTERM' ) 1005if ui . rgb or colorterm == 'truecolor' or colorterm == '24bit' then 1006-- The TUI was able to determine truecolor support or $COLORTERM explicitly indicates 1007-- truecolor support 1008setoption ( 'termguicolors' , true ) 1009elseif ( colorterm == nil or colorterm == '' ) and vim . o . ttyfast then 1010-- Neither the TUI nor $COLORTERM indicate that truecolor is supported, so query the 1011-- terminal 1012local caps ={} ---@type table<string, boolean> 1013vim . tty . query ( 1014{ 'Tc' , 'RGB' , 'setrgbf' , 'setrgbb' } , 1015{ group =group , chan =ui . chan } , 1016function ( cap , found ) 1017if not found then 1018return 1019end 1020 1021caps [ cap ] =true 1022if caps . Tc or caps . RGB or ( caps . setrgbf and caps . setrgbb ) then 1023setoption ( 'termguicolors' , true ) 1024end 1025end 1026) 1027 1028-- Arbitrary colors to set in the SGR sequence 1029local r =1 1030local g =2 1031local b =3 1032 1033-- Write SGR followed by DECRQSS. This sets the background color then 1034-- immediately asks the terminal what the background color is. If the 1035-- terminal responds to the DECRQSS with the same SGR sequence that we 1036-- sent then the terminal supports truecolor. 1037-- 1038-- Reset attributes first, as other code may have set attributes. 1039local payload =( '\027[0m\027[48;2;%d;%d;%dm%s' ): format ( r , g , b , '\027P$qm\027\\' ) 1040 1041vim . tty . request ( payload , { group =group , chan =ui . chan } , function ( resp ) 1042local decrqss =resp : match ( '^\027P1%$r([%d;:]+)m$' ) 1043if not decrqss then 1044return 1045end 1046 1047-- The DECRQSS SGR response first contains attributes separated by semicolons, followed by 1048-- the SGR itself with parameters separated by colons. Some terminals include "0" in the 1049-- attribute list unconditionally; others do not. Our SGR sequence did not set any 1050-- attributes, so there should be no attributes in the list. 1051local attrs =vim . split ( decrqss , ';' ) 1052if # attrs ~= 1 and ( # attrs ~= 2 or attrs [ 1 ] ~= '0' ) then 1053return 1054end 1055 1056-- The returned SGR sequence should begin with 48:2 1057local sgr =attrs [ # attrs ]: match ( '^48:2:([%d:]+)$' ) 1058if not sgr then 1059return 1060end 1061 1062-- The remaining elements of the SGR sequence should be the 3 colors we set. Some 1063-- terminals also include an additional parameter (which can even be empty!), so handle 1064-- those cases as well 1065local params =vim . split ( sgr , ':' ) 1066if # params ~= 3 and ( # params ~= 4 or ( params [ 1 ] ~= '' and params [ 1 ] ~= '1' )) then 1067return true 1068end 1069 1070if 1071vim . _tointeger ( params [ # params - 2 ]) == r 1072and vim . _tointeger ( params [ # params - 1 ]) == g 1073and vim . _tointeger ( params [ # params ]) == b 1074then 1075setoption ( 'termguicolors' , true ) 1076end 1077 1078return true 1079end ) 1080end 1081end 1082 1083if tty then 1084-- A TTY is present at startup. Detect synchronously so 'background' is set 1085-- before user config runs, and detect 'termguicolors'. This path owns the 1086-- startup TTY (including runtime reactivity), so the UIEnter path below is 1087-- not registered for it (avoids double-detection). 1088if vim . o . ttyfast then 1089detect_background ( true , tty . chan ) 1090end 1091 1092detect_termguicolors ( tty ) 1093require ( 'vim._core.mcursor' ). detect ( tty ) -- Kitty multicursor protocol. 1094 1095-- Show progress bars in supporting terminals 1096nvim_on ( 'Progress' , vim . api . nvim_create_augroup ( 'nvim.progress' ), { 1097desc ='Display native progress bars' , 1098} , function ( ev ) 1099if ev . data . status == 'running' then 1100if ev . data . percent ~= nil then 1101vim . api . nvim_ui_send ( string . format ( '\027]9;4;1;%d\027\\' , ev . data . percent )) 1102else 1103-- "Indeterminate" progress (unknown percent). 1104vim . api . nvim_ui_send ( string . format ( '\027]9;4;3\027\\' )) 1105end 1106else 1107vim . api . nvim_ui_send ( '\027]9;4;0;0\027\\' ) 1108end 1109end ) 1110end 1111 1112-- Re-detect terminal options when a UI attaches, not only at startup: a 1113-- |--headless| server (e.g. behind |--remote-ui|) has no UI when the block 1114-- above runs, and swapping a TUI between servers should pick up the current 1115-- terminal. Only handle TTYs that attach AFTER startup: if a TTY was present 1116-- at startup the block above already owns detection (incl. runtime 1117-- reactivity), so registering here too would double-detect. 1118if not tty then 1119--- The terminal UI that just attached (per |v:event| `chan`), or nil. 1120local function attaching_tty () 1121local chan =( vim . v . event or {} ). chan 1122for _ , ui in ipairs ( vim . api . nvim_list_uis ()) do 1123if ui . chan == chan then 1124return ui . stdout_tty and ui or nil 1125end 1126end 1127return nil 1128end 1129 1130nvim_on ( 'UIEnter' , vim . api . nvim_create_augroup ( 'nvim.tty.attach' ), {} , function () 1131local ui =attaching_tty () 1132if not ui then 1133return 1134end 1135 1136detect_termguicolors ( ui ) -- 'termguicolors' 1137require ( 'vim._core.mcursor' ). detect ( ui ) -- Kitty multicursor protocol. 1138 1139-- 'background': (re)query OSC 11. The persistent handler also reacts to 1140-- runtime theme changes (mode 2031 -> TUI re-queries -> |TermResponse|); 1141-- the per-response bg_user_set() guard preserves an explicit user value. 1142if vim . o . ttyfast then 1143detect_background ( false , ui . chan ) 1144end 1145end ) 1146end 1147end 1148 1149--- Default options 1150do 1151--- Default 'grepprg' to ripgrep if available. 1152if vim . fn . executable ( 'rg' ) == 1 then 1153-- Use -uu to make ripgrep not check ignore files/skip dot-files 1154vim . o . grepprg ='rg --vimgrep -uu ' 1155vim . o . grepformat ='%f:%l:%c:%m' 1156end 1157end