robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
39.6 KiB1157 linesraw
1-- Default user-commands, autocmds, mappings, menus.
2
3local nvim_on = require('vim._core.util').nvim_on
4
5--- Default user commands
6do
7  vim.api.nvim_create_user_command('Inspect', function(cmd)
8    if cmd.bang then
9      vim.print(vim.inspect_pos())
10    else
11      vim.show_pos()
12    end
13  end, { desc = 'Inspect highlights and extmarks at the cursor', bang = true })
14
15  vim.api.nvim_create_user_command('InspectTree', function(cmd)
16    local opts = { lang = cmd.fargs[1] }
17
18    if cmd.mods ~= '' or cmd.count ~= 0 then
19      local count = cmd.count ~= 0 and cmd.count or ''
20      local new = cmd.mods ~= '' and 'new' or 'vnew'
21
22      opts.command = ('%s %s%s'):format(cmd.mods, count, new)
23    end
24
25    vim.treesitter.inspect_tree(opts)
26  end, { desc = 'Inspect treesitter language tree for buffer', count = true, nargs = '?' })
27
28  vim.api.nvim_create_user_command('EditQuery', function(cmd)
29    vim.treesitter.query.edit(cmd.fargs[1])
30  end, {
31    desc = 'Edit treesitter query',
32    nargs = '?',
33    complete = function()
34      return vim.treesitter.language._complete()
35    end,
36  })
37
38  vim.api.nvim_create_user_command('Open', function(cmd)
39    if #cmd.fargs == 0 then
40      local current_file = vim.fn.expand('%')
41      if current_file ~= '' then
42        vim.ui.open(current_file)
43      end
44    else
45      vim.ui.open(assert(cmd.fargs[1]))
46    end
47  end, {
48    desc = 'Open file with system default handler. See :help vim.ui.open()',
49    nargs = '?',
50    complete = '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|
59  do
60    --- @param forward 0|1
61    local function _visual_search(forward)
62      local pos = vim.fn.getpos('.')
63      local vpos = vim.fn.getpos('v')
64      local mode = vim.fn.mode()
65      local chunks = vim.fn.getregion(pos, vpos, { type = mode })
66      local esc_chunks = vim
67        .iter(chunks)
68        :map(function(v)
69          return vim.fn.escape(v, [[\]])
70        end)
71        :totable()
72      local esc_pat = table.concat(esc_chunks, [[\n]])
73      if #esc_pat == 0 then
74        vim.api.nvim_echo({ { 'E348: No string under cursor' } }, true, { err = true })
75        return '<Esc>'
76      end
77      local search = [[\V]] .. esc_pat
78
79      vim.fn.setreg('/', search)
80      vim.fn.histadd('/', search)
81      vim.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
85      local count = vim.v.count1
86      if forward == 0 then
87        local _, line, col, _ = unpack(pos)
88        local _, vline, vcol, _ = unpack(vpos)
89        if
90          line > vline
91          or mode == 'v' and line == vline and col > vcol
92          or mode == 'V' and col ~= 1
93          or mode == '\22' and col > vcol
94        then
95          count = count + 1
96        end
97      end
98      return '<Esc>' .. count .. 'n'
99    end
100
101    vim.keymap.set('x', '*', function()
102      return _visual_search(1)
103    end, { desc = ':help v_star-default', expr = true })
104    vim.keymap.set('x', '#', function()
105      return _visual_search(0)
106    end, { desc = ':help v_#-default', expr = true })
107  end
108
109  --- Map Y to y$. This mimics the behavior of D and C. See |Y-default|
110  vim.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|
115  vim.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|
127  vim.keymap.set('i', '<C-U>', '<C-G>u<C-U>', { desc = ':help i_CTRL-U-default' })
128  vim.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|
135  vim.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.
141  vim.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.
149  do
150    --- @param uri string
151    local function do_open(uri)
152      local cmd, err = vim.ui.open(uri)
153      local rv = cmd and cmd:wait(1000) or nil
154      if cmd and rv and rv.code ~= 0 then
155        err = ('vim.ui.open: command %s (%d): %s'):format(
156          (rv.code == 124 and 'timeout' or 'failed'),
157          rv.code,
158          vim.inspect(cmd.cmd)
159        )
160      end
161      return err
162    end
163
164    local gx_desc =
165      'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)'
166    vim.keymap.set({ 'n' }, 'gx', function()
167      for _, url in ipairs(require('vim.ui')._get_urls()) do
168        local err = do_open(url)
169        if err then
170          vim.notify(err, vim.log.levels.ERROR)
171        end
172      end
173    end, { desc = gx_desc })
174    vim.keymap.set({ 'x' }, 'gx', function()
175      local lines =
176        vim.fn.getregion(vim.fn.getpos('.'), vim.fn.getpos('v'), { type = vim.fn.mode() })
177      -- Trim whitespace on each line and concatenate.
178      local err = do_open(table.concat(vim.iter(lines):map(vim.trim):totable()))
179      if err then
180        vim.notify(err, vim.log.levels.ERROR)
181      end
182    end, { desc = gx_desc })
183  end
184
185  --- Default maps for built-in commenting.
186  ---
187  --- See |gc-default| and |gcc-default|.
188  do
189    local operator_rhs = function()
190      return require('vim._comment').operator()
191    end
192    vim.keymap.set({ 'n', 'x' }, 'gc', operator_rhs, { expr = true, desc = 'Toggle comment' })
193
194    local line_rhs = function()
195      return require('vim._comment').operator() .. '_'
196    end
197    vim.keymap.set('n', 'gcc', line_rhs, { expr = true, desc = 'Toggle comment line' })
198
199    local textobject_rhs = function()
200      require('vim._comment').textobject()
201    end
202    vim.keymap.set({ 'o' }, 'gc', textobject_rhs, { desc = 'Comment textobject' })
203  end
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|.
212  do
213    vim.keymap.set('n', 'grn', function()
214      vim.lsp.buf.rename()
215    end, { desc = 'vim.lsp.buf.rename()' })
216
217    vim.keymap.set({ 'n', 'x' }, 'gra', function()
218      vim.lsp.buf.code_action()
219    end, { desc = 'vim.lsp.buf.code_action()' })
220
221    vim.keymap.set('n', 'grx', function()
222      vim.lsp.codelens.run()
223    end, { desc = 'vim.lsp.codelens.run()' })
224
225    vim.keymap.set('n', 'grr', function()
226      vim.lsp.buf.references()
227    end, { desc = 'vim.lsp.buf.references()' })
228
229    vim.keymap.set('n', 'gri', function()
230      vim.lsp.buf.implementation()
231    end, { desc = 'vim.lsp.buf.implementation()' })
232
233    vim.keymap.set('n', 'grt', function()
234      vim.lsp.buf.type_definition()
235    end, { desc = 'vim.lsp.buf.type_definition()' })
236
237    vim.keymap.set('n', 'gO', function()
238      vim.lsp.buf.document_symbol()
239    end, { desc = 'vim.lsp.buf.document_symbol()' })
240
241    vim.keymap.set({ 'i', 's' }, '<C-S>', function()
242      vim.lsp.buf.signature_help()
243    end, { desc = 'vim.lsp.buf.signature_help()' })
244  end
245
246  do
247    ---@param direction vim.snippet.Direction
248    ---@param key string
249    local function set_snippet_jump(direction, key)
250      vim.keymap.set({ 'i', 's' }, key, function()
251        if vim.snippet.active({ direction = direction }) then
252          return string.format('<Cmd>lua vim.snippet.jump(%d)<CR>', direction)
253        else
254          return key
255        end
256      end, {
257        desc = 'vim.snippet.jump if active, otherwise ' .. key,
258        expr = true,
259        silent = true,
260      })
261    end
262
263    set_snippet_jump(1, '<Tab>')
264    set_snippet_jump(-1, '<S-Tab>')
265  end
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|.
271  do
272    vim.keymap.set('n', ']d', function()
273      vim.diagnostic.jump({ count = vim.v.count1 })
274    end, { desc = 'Jump to the next diagnostic in the current buffer' })
275
276    vim.keymap.set('n', '[d', function()
277      vim.diagnostic.jump({ count = -vim.v.count1 })
278    end, { desc = 'Jump to the previous diagnostic in the current buffer' })
279
280    vim.keymap.set('n', ']D', function()
281      vim.diagnostic.jump({ count = vim._maxint, wrap = false })
282    end, { desc = 'Jump to the last diagnostic in the current buffer' })
283
284    vim.keymap.set('n', '[D', function()
285      vim.diagnostic.jump({ count = -vim._maxint, wrap = false })
286    end, { desc = 'Jump to the first diagnostic in the current buffer' })
287
288    vim.keymap.set('n', '<C-W>d', function()
289      vim.diagnostic.open_float()
290    end, { desc = 'Show diagnostics under the cursor' })
291
292    vim.keymap.set(
293      'n',
294      '<C-W><C-D>',
295      '<C-W>d',
296      { remap = true, desc = 'Show diagnostics under the cursor' }
297    )
298  end
299
300  --- Execute a command and print errors without a stacktrace.
301  --- @param opts vim.api.keyset.cmd Arguments to |nvim_cmd()|
302  local function cmd(opts)
303    local ok, err = pcall(vim.api.nvim_cmd, opts, {})
304    if not ok then
305      vim.api.nvim_echo({ { require('vim._core.util').cmd_errmsg(err) } }, true, { err = true })
306    end
307  end
308
309  --- vim-unimpaired style mappings. See: https://github.com/tpope/vim-unimpaired
310  do
311    -- Quickfix mappings
312    vim.keymap.set('n', '[q', function()
313      cmd({ cmd = 'cprevious', count = vim.v.count1 })
314    end, { desc = ':cprevious' })
315
316    vim.keymap.set('n', ']q', function()
317      cmd({ cmd = 'cnext', count = vim.v.count1 })
318    end, { desc = ':cnext' })
319
320    vim.keymap.set('n', '[Q', function()
321      cmd({ cmd = 'crewind', count = vim.v.count ~= 0 and vim.v.count or nil })
322    end, { desc = ':crewind' })
323
324    vim.keymap.set('n', ']Q', function()
325      cmd({ cmd = 'clast', count = vim.v.count ~= 0 and vim.v.count or nil })
326    end, { desc = ':clast' })
327
328    vim.keymap.set('n', '[<C-Q>', function()
329      cmd({ cmd = 'cpfile', count = vim.v.count1 })
330    end, { desc = ':cpfile' })
331
332    vim.keymap.set('n', ']<C-Q>', function()
333      cmd({ cmd = 'cnfile', count = vim.v.count1 })
334    end, { desc = ':cnfile' })
335
336    -- Location list mappings
337    vim.keymap.set('n', '[l', function()
338      cmd({ cmd = 'lprevious', count = vim.v.count1 })
339    end, { desc = ':lprevious' })
340
341    vim.keymap.set('n', ']l', function()
342      cmd({ cmd = 'lnext', count = vim.v.count1 })
343    end, { desc = ':lnext' })
344
345    vim.keymap.set('n', '[L', function()
346      cmd({ cmd = 'lrewind', count = vim.v.count ~= 0 and vim.v.count or nil })
347    end, { desc = ':lrewind' })
348
349    vim.keymap.set('n', ']L', function()
350      cmd({ cmd = 'llast', count = vim.v.count ~= 0 and vim.v.count or nil })
351    end, { desc = ':llast' })
352
353    vim.keymap.set('n', '[<C-L>', function()
354      cmd({ cmd = 'lpfile', count = vim.v.count1 })
355    end, { desc = ':lpfile' })
356
357    vim.keymap.set('n', ']<C-L>', function()
358      cmd({ cmd = 'lnfile', count = vim.v.count1 })
359    end, { desc = ':lnfile' })
360
361    -- Argument list
362    vim.keymap.set('n', '[a', function()
363      cmd({ cmd = 'previous', count = vim.v.count1 })
364    end, { desc = ':previous' })
365
366    vim.keymap.set('n', ']a', function()
367      -- count doesn't work with :next, must use range. See #30641.
368      cmd({ cmd = 'next', range = { vim.v.count1 } })
369    end, { desc = ':next' })
370
371    vim.keymap.set('n', '[A', function()
372      if vim.v.count ~= 0 then
373        cmd({ cmd = 'argument', count = vim.v.count })
374      else
375        cmd({ cmd = 'rewind' })
376      end
377    end, { desc = ':rewind' })
378
379    vim.keymap.set('n', ']A', function()
380      if vim.v.count ~= 0 then
381        cmd({ cmd = 'argument', count = vim.v.count })
382      else
383        cmd({ cmd = 'last' })
384      end
385    end, { desc = ':last' })
386
387    -- Tags
388    vim.keymap.set('n', '[t', function()
389      -- count doesn't work with :tprevious, must use range. See #30641.
390      cmd({ cmd = 'tprevious', range = { vim.v.count1 } })
391    end, { desc = ':tprevious' })
392
393    vim.keymap.set('n', ']t', function()
394      -- count doesn't work with :tnext, must use range. See #30641.
395      cmd({ cmd = 'tnext', range = { vim.v.count1 } })
396    end, { desc = ':tnext' })
397
398    vim.keymap.set('n', '[T', function()
399      -- count doesn't work with :trewind, must use range. See #30641.
400      cmd({ cmd = 'trewind', range = vim.v.count ~= 0 and { vim.v.count } or nil })
401    end, { desc = ':trewind' })
402
403    vim.keymap.set('n', ']T', function()
404      -- :tlast does not accept a count, so use :trewind if count given
405      if vim.v.count ~= 0 then
406        cmd({ cmd = 'trewind', range = { vim.v.count } })
407      else
408        cmd({ cmd = 'tlast' })
409      end
410    end, { desc = ':tlast' })
411
412    vim.keymap.set('n', '[<C-T>', function()
413      -- count doesn't work with :ptprevious, must use range. See #30641.
414      cmd({ cmd = 'ptprevious', range = { vim.v.count1 } })
415    end, { desc = ':ptprevious' })
416
417    vim.keymap.set('n', ']<C-T>', function()
418      -- count doesn't work with :ptnext, must use range. See #30641.
419      cmd({ cmd = 'ptnext', range = { vim.v.count1 } })
420    end, { desc = ':ptnext' })
421
422    -- Buffers
423    vim.keymap.set('n', '[b', function()
424      cmd({ cmd = 'bprevious', count = vim.v.count1 })
425    end, { desc = ':bprevious' })
426
427    vim.keymap.set('n', ']b', function()
428      cmd({ cmd = 'bnext', count = vim.v.count1 })
429    end, { desc = ':bnext' })
430
431    vim.keymap.set('n', '[B', function()
432      if vim.v.count ~= 0 then
433        cmd({ cmd = 'buffer', count = vim.v.count })
434      else
435        cmd({ cmd = 'brewind' })
436      end
437    end, { desc = ':brewind' })
438
439    vim.keymap.set('n', ']B', function()
440      if vim.v.count ~= 0 then
441        cmd({ cmd = 'buffer', count = vim.v.count })
442      else
443        cmd({ cmd = 'blast' })
444      end
445    end, { desc = ':blast' })
446
447    -- Add empty lines
448    vim.keymap.set('n', '[<Space>', function()
449      vim.go.operatorfunc = require('vim._core.util').space_above
450      return 'g@l'
451    end, { expr = true, desc = 'Add empty line above cursor' })
452
453    vim.keymap.set('n', ']<Space>', function()
454      vim.go.operatorfunc = require('vim._core.util').space_below
455      return 'g@l'
456    end, { expr = true, desc = 'Add empty line below cursor' })
457  end
458
459  --- "Incremental selection" mappings (treesitter + LSP fallback).
460  do
461    vim.keymap.set({ 'x' }, '[n', function()
462      vim.treesitter.select('prev', vim.v.count1)
463    end, { desc = 'Select previous node' })
464
465    vim.keymap.set({ 'x' }, ']n', function()
466      vim.treesitter.select('next', vim.v.count1)
467    end, { desc = 'Select next node' })
468
469    vim.keymap.set({ 'x' }, '[N', function()
470      vim.treesitter.select('extend_prev', vim.v.count1)
471    end, { desc = 'Select previous sibling node' })
472
473    vim.keymap.set({ 'x' }, ']N', function()
474      vim.treesitter.select('extend_next', vim.v.count1)
475    end, { desc = 'Select next sibling node' })
476
477    vim.keymap.set({ 'x', 'o' }, 'an', function()
478      if vim.treesitter.get_parser(nil, nil, { error = false }) then
479        vim.treesitter.select('parent', vim.v.count1)
480      else
481        vim.lsp.buf.selection_range(vim.v.count1)
482      end
483    end, { desc = 'Select parent (outer) node' })
484
485    vim.keymap.set({ 'x', 'o' }, 'in', function()
486      if vim.treesitter.get_parser(nil, nil, { error = false }) then
487        vim.treesitter.select('child', vim.v.count1)
488      else
489        vim.lsp.buf.selection_range(-vim.v.count1)
490      end
491    end, { desc = 'Select child (inner) node' })
492  end
493end
494
495--- Default menus
496do
497  --- Right click popup menu
498  vim.cmd([[
499    amenu     PopUp.Open\ in\ web\ browser  gx
500    anoremenu PopUp.Inspect                 <Cmd>Inspect<CR>
501    anoremenu PopUp.Go\ to\ definition      <Cmd>lua vim.lsp.buf.definition()<CR>
502    anoremenu PopUp.Show\ Diagnostics       <Cmd>lua vim.diagnostic.open_float()<CR>
503    anoremenu PopUp.Show\ All\ Diagnostics  <Cmd>lua vim.diagnostic.setqflist()<CR>
504    anoremenu PopUp.Configure\ Diagnostics  <Cmd>help vim.diagnostic.config()<CR>
505    anoremenu PopUp.-1-                     <Nop>
506    vnoremenu PopUp.Cut                     "+x
507    vnoremenu PopUp.Copy                    "+y
508    anoremenu PopUp.Paste                   "+gP
509    vnoremenu PopUp.Paste                   "+P
510    vnoremenu PopUp.Delete                  "_x
511    nnoremenu PopUp.Select\ All             ggVG
512    vnoremenu PopUp.Select\ All             gg0oG$
513    inoremenu PopUp.Select\ All             <C-Home><C-O>VG
514    anoremenu PopUp.-2-                     <Nop>
515    anoremenu PopUp.How-to\ disable\ mouse  <Cmd>help disable-mouse<CR>
516  ]])
517
518  local function enable_ctx_menu()
519    vim.cmd([[
520      amenu disable PopUp.Go\ to\ definition
521      amenu disable PopUp.Open\ in\ web\ browser
522      amenu disable PopUp.Show\ Diagnostics
523      amenu disable PopUp.Show\ All\ Diagnostics
524      amenu disable PopUp.Configure\ Diagnostics
525    ]])
526
527    local url = require('vim.ui')._get_urls()[1]
528    if url and vim.startswith(url, 'http') then
529      vim.cmd([[amenu enable PopUp.Open\ in\ web\ browser]])
530    elseif vim.lsp.get_clients({ bufnr = 0 })[1] then
531      vim.cmd([[anoremenu enable PopUp.Go\ to\ definition]])
532    end
533
534    local lnum = vim.fn.getcurpos()[2] - 1 ---@type integer
535    local diagnostic = false
536    if next(vim.diagnostic.get(0, { lnum = lnum })) ~= nil then
537      diagnostic = true
538      vim.cmd([[anoremenu enable PopUp.Show\ Diagnostics]])
539    end
540
541    if diagnostic or next(vim.diagnostic.count(0)) ~= nil then
542      vim.cmd([[
543        anoremenu enable PopUp.Show\ All\ Diagnostics
544        anoremenu enable PopUp.Configure\ Diagnostics
545      ]])
546    end
547  end
548
549  local nvim_popupmenu_augroup = vim.api.nvim_create_augroup('nvim.popupmenu')
550  nvim_on('MenuPopup', nvim_popupmenu_augroup, {
551    pattern = '*',
552    desc = 'Mouse popup menu',
553    -- nested = true,
554  }, function()
555    enable_ctx_menu()
556  end)
557end
558
559--- Default autocommands. See |default-autocmds|
560do
561  -- Warn if $NVIM_LOG_FILE or $XDG_STATE_HOME are inaccessible. #38039
562  if vim.v.vim_did_enter then
563    require('vim._core.log').check_log_file()
564  else
565    nvim_on('VimEnter', nil, { once = true }, function()
566      require('vim._core.log').check_log_file()
567    end)
568  end
569
570  local nvim_terminal_augroup = vim.api.nvim_create_augroup('nvim.terminal')
571  vim.api.nvim_create_autocmd('BufReadCmd', {
572    pattern = 'term://*',
573    group = nvim_terminal_augroup,
574    desc = 'Treat term:// buffers as terminal buffers',
575    nested = true,
576    command = "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
579  nvim_on({ 'TermClose' }, nvim_terminal_augroup, {
580    nested = true,
581    desc = 'Automatically close terminal buffers when started with no arguments and exiting without an error',
582  }, function(ev)
583    if vim.v.event.status ~= 0 then
584      return
585    end
586    local info = vim.api.nvim_get_chan_info(vim.bo[ev.buf].channel)
587    local argv = info.argv or {}
588    if table.concat(argv, ' ') == vim.o.shell then
589      vim.api.nvim_buf_delete(ev.buf, { force = true })
590    end
591  end)
592
593  local 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
598  local function set_terminal_exitmsg(buf, msg, pos)
599    vim.api.nvim_buf_set_extmark(buf, nvim_terminal_exitmsg_ns, pos, 0, {
600      virt_text = { { msg, nil } },
601      virt_text_pos = 'overlay',
602    })
603  end
604
605  nvim_on('TermClose', nvim_terminal_augroup, {
606    nested = true,
607    desc = 'Displays the "[Process exited]" virtual text',
608  }, function(ev)
609    if not vim.api.nvim_buf_is_valid(ev.buf) then
610      return
611    end
612
613    local buf = vim.bo[ev.buf]
614    local pos = ev.data.pos ---@type integer
615    local buf_has_exitmsg = #(
616        vim.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'.
620    local msg = buf.channel == 0 and '[Terminal closed]'
621      or ('[Process exited %d]'):format(vim.v.event.status)
622
623    if 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.
626      nvim_on('TermOpen', nil, {
627        buf = ev.buf,
628        once = true,
629      }, function()
630        set_terminal_exitmsg(ev.buf, msg, pos)
631      end)
632      return
633    end
634    set_terminal_exitmsg(ev.buf, msg, pos)
635  end)
636
637  nvim_on('TermRequest', nvim_terminal_augroup, {
638    desc = 'Handles OSC foreground/background color requests',
639  }, function(ev)
640    --- @type integer
641    local channel = vim.bo[ev.buf].channel
642    if channel == 0 then
643      return
644    end
645    local fg_request = ev.data.sequence == '\027]10;?'
646    local bg_request = ev.data.sequence == '\027]11;?'
647    if 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'
652      local red, green, blue = 0, 0, 0
653      local bg_option_dark = vim.o.background == 'dark'
654      if (fg_request and bg_option_dark) or (bg_request and not bg_option_dark) then
655        red, green, blue = 65535, 65535, 65535
656      end
657      local command = fg_request and 10 or 11
658      local data =
659        string.format('\027]%d;rgb:%04x/%04x/%04x%s', command, red, green, blue, ev.data.terminator)
660      vim.api.nvim_chan_send(channel, data)
661    end
662  end)
663
664  local nvim_terminal_prompt_ns = vim.api.nvim_create_namespace('nvim.terminal.prompt')
665  nvim_on('TermRequest', nvim_terminal_augroup, {
666    desc = 'Mark shell prompts indicated by OSC 133 sequences for navigation',
667  }, function(ev)
668    if string.match(ev.data.sequence, '^\027]133;A') then
669      local lnum = ev.data.cursor[1] ---@type integer
670      if lnum >= 1 then
671        vim.api.nvim_buf_set_extmark(
672          ev.buf,
673          nvim_terminal_prompt_ns,
674          lnum - 1,
675          0,
676          { right_gravity = false }
677        )
678      end
679    end
680  end)
681
682  ---@param ns integer
683  ---@param win integer
684  ---@param buf integer
685  ---@param count integer
686  local function jump_to_prompt(ns, win, buf, count)
687    local row, col = unpack(vim.api.nvim_win_get_cursor(win))
688    local start = -1
689    local end_ ---@type 0|-1
690    if count > 0 then
691      start = row
692      end_ = -1
693    elseif count < 0 then
694      -- Subtract 2 because row is 1-based, but extmarks are 0-based
695      start = row - 2
696      end_ = 0
697    end
698
699    if start < 0 then
700      return
701    end
702
703    local extmarks = vim.api.nvim_buf_get_extmarks(
704      buf,
705      ns,
706      { start, col },
707      end_,
708      { limit = math.abs(count) }
709    )
710    if #extmarks > 0 then
711      local extmark = assert(extmarks[math.min(#extmarks, math.abs(count))])
712      vim.api.nvim_win_set_cursor(win, { extmark[2] + 1, extmark[3] })
713    end
714  end
715
716  nvim_on('TermOpen', nvim_terminal_augroup, {
717    desc = 'Default settings for :terminal buffers',
718  }, function(ev)
719    vim.bo[ev.buf].modifiable = false
720    vim.bo[ev.buf].undolevels = -1
721    vim.bo[ev.buf].scrollback = vim.o.scrollback < 0 and 10000 or math.max(1, vim.o.scrollback)
722    vim.bo[ev.buf].textwidth = 0
723    vim.wo[0][0].wrap = false
724    vim.wo[0][0].list = false
725    vim.wo[0][0].number = false
726    vim.wo[0][0].relativenumber = false
727    vim.wo[0][0].signcolumn = 'no'
728    vim.wo[0][0].foldcolumn = '0'
729
730    -- This is gross. Proper list options support when?
731    local winhl = vim.o.winhighlight
732    if winhl ~= '' then
733      winhl = winhl .. ','
734    end
735    vim.wo[0][0].winhighlight = winhl .. 'StatusLine:StatusLineTerm,StatusLineNC:StatusLineTermNC'
736
737    vim.keymap.set({ 'n', 'x', 'o' }, '[[', function()
738      jump_to_prompt(nvim_terminal_prompt_ns, 0, ev.buf, -vim.v.count1)
739    end, { buf = ev.buf, desc = 'Jump [count] shell prompts backward' })
740    vim.keymap.set({ 'n', 'x', 'o' }, ']]', function()
741      jump_to_prompt(nvim_terminal_prompt_ns, 0, ev.buf, vim.v.count1)
742    end, { buf = ev.buf, desc = 'Jump [count] shell prompts forward' })
743
744    -- If the terminal buffer is being reused, clear the previous exit msg
745    vim.api.nvim_buf_clear_namespace(ev.buf, nvim_terminal_exitmsg_ns, 0, -1)
746  end)
747
748  vim.api.nvim_create_autocmd('CmdwinEnter', {
749    pattern = '[:>]',
750    desc = 'Limit syntax sync to maxlines=1 in the command window',
751    group = vim.api.nvim_create_augroup('nvim.cmdwin'),
752    command = 'syntax sync minlines=1 maxlines=1',
753  })
754
755  nvim_on('SwapExists', vim.api.nvim_create_augroup('nvim.swapfile'), {
756    pattern = '*',
757    desc = 'Skip the swapfile prompt when the swapfile is owned by a running Nvim process',
758  }, function()
759    local info = vim.fn.swapinfo(vim.v.swapname)
760    local passwd = vim.uv.os_get_passwd()
761    local user = passwd and passwd.username
762    local iswin = 1 == vim.fn.has('win32')
763    if info.error or info.pid <= 0 or (not iswin and (not user or info.user ~= user)) then
764      vim.v.swapchoice = '' -- Show the prompt.
765      return
766    end
767    vim.v.swapchoice = 'e' -- Choose "(E)dit".
768    vim.notify(
769      ('W325: Ignoring swapfile from Nvim process %d'):format(info.pid),
770      vim.log.levels.WARN,
771      { _truncate = true }
772    )
773  end)
774
775  -- Check if a TTY is attached
776  local tty = nil
777  for _, ui in ipairs(vim.api.nvim_list_uis()) do
778    if ui.stdout_tty then
779      tty = ui
780      break
781    end
782  end
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.
799  local 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
807  local function setoption(option, value, force)
808    if not force and vim.api.nvim_get_option_info2(option).was_set then
809      -- Don't do anything if option is already set
810      return
811    end
812
813    -- Wait until Nvim is finished starting to set the option to ensure the
814    -- OptionSet event fires.
815    if vim.v.vim_did_enter == 1 then
816      --- @diagnostic disable-next-line:no-unknown
817      vim.o[option] = value
818    else
819      nvim_on('VimEnter', group, {
820        once = true,
821        nested = true,
822      }, function()
823        setoption(option, value, force)
824      end)
825    end
826  end
827
828  --- Script ID (SID) used for our own automatic 'background' sets. Lets
829  --- bg_user_set() distinguish a user set from our detection.
830  local sid_lua = -8
831
832  --- True if 'background' was set by the user, not by our detection (sid_lua).
833  local function bg_user_set()
834    local info = vim.api.nvim_get_option_info2('background')
835    return info.was_set and info.last_set_sid ~= sid_lua
836  end
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
849  local function parsecolor(c)
850    if #c == 0 or #c > 4 then
851      return nil
852    end
853
854    local val = vim._tointeger(c, 16)
855    if not val then
856      return nil
857    end
858
859    local max = vim._assert_integer(string.rep('f', #c), 16)
860    return val / max
861  end
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
883  local function parseosc11(resp)
884    local r, g, b
885    r, g, b = resp:match('^\027%]11;rgb:(%x+)/(%x+)/(%x+)$')
886    if not r and not g and not b then
887      local a
888      r, g, b, a = resp:match('^\027%]11;rgba:(%x+)/(%x+)/(%x+)/(%x+)$')
889      if not a or #a > 4 then
890        return nil, nil, nil
891      end
892    end
893
894    if r and g and b and #r <= 4 and #g <= 4 and #b <= 4 then
895      return r, g, b
896    end
897
898    return nil, nil, nil
899  end
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
926  local 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.
929    local 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
934    local osc11 = '\027]11;?\007'
935    local 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'.
941    local did_dsr_response = false
942    vim.tty.request(
943      osc11 .. (sync and dsr or ''),
944      { group = bg_group, timeout = 0, chan = chan },
945      function(resp)
946        -- DSR response that should come after the OSC 11 response if the terminal
947        -- supports it.
948        if sync and string.match(resp, '^\027%[0n$') then
949          did_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.
953          return
954        end
955
956        -- Never override an explicit user value: stop once the user pins it.
957        if bg_user_set() then
958          return true
959        end
960
961        local r, g, b = parseosc11(resp)
962        if r and g and b then
963          local rr = parsecolor(r)
964          local gg = parsecolor(g)
965          local bb = parsecolor(b)
966
967          if rr and gg and bb then
968            local luminance = (0.299 * rr) + (0.587 * gg) + (0.114 * bb)
969            local bg = luminance < 0.5 and 'dark' or 'light'
970            vim.o.background = bg
971          end
972        end
973      end
974    )
975
976    if not sync then
977      return
978    end
979
980    -- Wait until detection of OSC 11 capabilities is complete to ensure
981    -- background is automatically set before user config.
982    if
983      not vim.wait(100, function()
984        return did_dsr_response
985      end, 1)
986      -- Don't show the warning when running tests to avoid flakiness.
987      and os.getenv('NVIM_TEST') == nil
988    then
989      vim.notify(
990        "E1568: Terminal did not respond to DSR request for 'background' color. Startup may be slower. :help 'ttyfast'",
991        vim.log.levels.WARN,
992        { _truncate = true }
993      )
994    end
995  end
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()|).
1003  local function detect_termguicolors(ui)
1004    local colorterm = os.getenv('COLORTERM')
1005    if 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
1008      setoption('termguicolors', true)
1009    elseif (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
1012      local caps = {} ---@type table<string, boolean>
1013      vim.tty.query(
1014        { 'Tc', 'RGB', 'setrgbf', 'setrgbb' },
1015        { group = group, chan = ui.chan },
1016        function(cap, found)
1017          if not found then
1018            return
1019          end
1020
1021          caps[cap] = true
1022          if caps.Tc or caps.RGB or (caps.setrgbf and caps.setrgbb) then
1023            setoption('termguicolors', true)
1024          end
1025        end
1026      )
1027
1028      -- Arbitrary colors to set in the SGR sequence
1029      local r = 1
1030      local g = 2
1031      local 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.
1039      local payload = ('\027[0m\027[48;2;%d;%d;%dm%s'):format(r, g, b, '\027P$qm\027\\')
1040
1041      vim.tty.request(payload, { group = group, chan = ui.chan }, function(resp)
1042        local decrqss = resp:match('^\027P1%$r([%d;:]+)m$')
1043        if not decrqss then
1044          return
1045        end
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.
1051        local attrs = vim.split(decrqss, ';')
1052        if #attrs ~= 1 and (#attrs ~= 2 or attrs[1] ~= '0') then
1053          return
1054        end
1055
1056        -- The returned SGR sequence should begin with 48:2
1057        local sgr = attrs[#attrs]:match('^48:2:([%d:]+)$')
1058        if not sgr then
1059          return
1060        end
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
1065        local params = vim.split(sgr, ':')
1066        if #params ~= 3 and (#params ~= 4 or (params[1] ~= '' and params[1] ~= '1')) then
1067          return true
1068        end
1069
1070        if
1071          vim._tointeger(params[#params - 2]) == r
1072          and vim._tointeger(params[#params - 1]) == g
1073          and vim._tointeger(params[#params]) == b
1074        then
1075          setoption('termguicolors', true)
1076        end
1077
1078        return true
1079      end)
1080    end
1081  end
1082
1083  if 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).
1088    if vim.o.ttyfast then
1089      detect_background(true, tty.chan)
1090    end
1091
1092    detect_termguicolors(tty)
1093    require('vim._core.mcursor').detect(tty) -- Kitty multicursor protocol.
1094
1095    -- Show progress bars in supporting terminals
1096    nvim_on('Progress', vim.api.nvim_create_augroup('nvim.progress'), {
1097      desc = 'Display native progress bars',
1098    }, function(ev)
1099      if ev.data.status == 'running' then
1100        if ev.data.percent ~= nil then
1101          vim.api.nvim_ui_send(string.format('\027]9;4;1;%d\027\\', ev.data.percent))
1102        else
1103          -- "Indeterminate" progress (unknown percent).
1104          vim.api.nvim_ui_send(string.format('\027]9;4;3\027\\'))
1105        end
1106      else
1107        vim.api.nvim_ui_send('\027]9;4;0;0\027\\')
1108      end
1109    end)
1110  end
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.
1118  if not tty then
1119    --- The terminal UI that just attached (per |v:event| `chan`), or nil.
1120    local function attaching_tty()
1121      local chan = (vim.v.event or {}).chan
1122      for _, ui in ipairs(vim.api.nvim_list_uis()) do
1123        if ui.chan == chan then
1124          return ui.stdout_tty and ui or nil
1125        end
1126      end
1127      return nil
1128    end
1129
1130    nvim_on('UIEnter', vim.api.nvim_create_augroup('nvim.tty.attach'), {}, function()
1131      local ui = attaching_tty()
1132      if not ui then
1133        return
1134      end
1135
1136      detect_termguicolors(ui) -- 'termguicolors'
1137      require('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.
1142      if vim.o.ttyfast then
1143        detect_background(false, ui.chan)
1144      end
1145    end)
1146  end
1147end
1148
1149--- Default options
1150do
1151  --- Default 'grepprg' to ripgrep if available.
1152  if vim.fn.executable('rg') == 1 then
1153    -- Use -uu to make ripgrep not check ignore files/skip dot-files
1154    vim.o.grepprg = 'rg --vimgrep -uu '
1155    vim.o.grepformat = '%f:%l:%c:%m'
1156  end
1157end