_defaults.lua 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. --- Default user commands
  2. do
  3. vim.api.nvim_create_user_command('Inspect', function(cmd)
  4. if cmd.bang then
  5. vim.print(vim.inspect_pos())
  6. else
  7. vim.show_pos()
  8. end
  9. end, { desc = 'Inspect highlights and extmarks at the cursor', bang = true })
  10. vim.api.nvim_create_user_command('InspectTree', function(cmd)
  11. if cmd.mods ~= '' or cmd.count ~= 0 then
  12. local count = cmd.count ~= 0 and cmd.count or ''
  13. local new = cmd.mods ~= '' and 'new' or 'vnew'
  14. vim.treesitter.inspect_tree({
  15. command = ('%s %s%s'):format(cmd.mods, count, new),
  16. })
  17. else
  18. vim.treesitter.inspect_tree()
  19. end
  20. end, { desc = 'Inspect treesitter language tree for buffer', count = true })
  21. vim.api.nvim_create_user_command('EditQuery', function(cmd)
  22. vim.treesitter.query.edit(cmd.fargs[1])
  23. end, { desc = 'Edit treesitter query', nargs = '?' })
  24. end
  25. --- Default mappings
  26. do
  27. --- Default maps for * and # in visual mode.
  28. ---
  29. --- See |v_star-default| and |v_#-default|
  30. do
  31. local function _visual_search(cmd)
  32. assert(cmd == '/' or cmd == '?')
  33. local chunks =
  34. vim.fn.getregion(vim.fn.getpos('.'), vim.fn.getpos('v'), { type = vim.fn.mode() })
  35. local esc_chunks = vim
  36. .iter(chunks)
  37. :map(function(v)
  38. return vim.fn.escape(v, cmd == '/' and [[/\]] or [[?\]])
  39. end)
  40. :totable()
  41. local esc_pat = table.concat(esc_chunks, [[\n]])
  42. local search_cmd = ([[%s\V%s%s]]):format(cmd, esc_pat, '\n')
  43. return '\27' .. search_cmd
  44. end
  45. vim.keymap.set('x', '*', function()
  46. return _visual_search('/')
  47. end, { desc = ':help v_star-default', expr = true, replace_keycodes = false })
  48. vim.keymap.set('x', '#', function()
  49. return _visual_search('?')
  50. end, { desc = ':help v_#-default', expr = true, replace_keycodes = false })
  51. end
  52. --- Map Y to y$. This mimics the behavior of D and C. See |Y-default|
  53. vim.keymap.set('n', 'Y', 'y$', { desc = ':help Y-default' })
  54. --- Use normal! <C-L> to prevent inserting raw <C-L> when using i_<C-O>. #17473
  55. ---
  56. --- See |CTRL-L-default|
  57. vim.keymap.set('n', '<C-L>', '<Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>', {
  58. desc = ':help CTRL-L-default',
  59. })
  60. --- Set undo points when deleting text in insert mode.
  61. ---
  62. --- See |i_CTRL-U-default| and |i_CTRL-W-default|
  63. vim.keymap.set('i', '<C-U>', '<C-G>u<C-U>', { desc = ':help i_CTRL-U-default' })
  64. vim.keymap.set('i', '<C-W>', '<C-G>u<C-W>', { desc = ':help i_CTRL-W-default' })
  65. --- Use the same flags as the previous substitution with &.
  66. ---
  67. --- Use : instead of <Cmd> so that ranges are supported. #19365
  68. ---
  69. --- See |&-default|
  70. vim.keymap.set('n', '&', ':&&<CR>', { desc = ':help &-default' })
  71. --- Use Q in Visual mode to execute a macro on each line of the selection. #21422
  72. --- This only make sense in linewise Visual mode. #28287
  73. ---
  74. --- Applies to @x and includes @@ too.
  75. vim.keymap.set(
  76. 'x',
  77. 'Q',
  78. "mode() ==# 'V' ? ':normal! @<C-R>=reg_recorded()<CR><CR>' : 'Q'",
  79. { silent = true, expr = true, desc = ':help v_Q-default' }
  80. )
  81. vim.keymap.set(
  82. 'x',
  83. '@',
  84. "mode() ==# 'V' ? ':normal! @'.getcharstr().'<CR>' : '@'",
  85. { silent = true, expr = true, desc = ':help v_@-default' }
  86. )
  87. --- Map |gx| to call |vim.ui.open| on the <cfile> at cursor.
  88. do
  89. local function do_open(uri)
  90. local cmd, err = vim.ui.open(uri)
  91. local rv = cmd and cmd:wait(1000) or nil
  92. if cmd and rv and rv.code ~= 0 then
  93. err = ('vim.ui.open: command %s (%d): %s'):format(
  94. (rv.code == 124 and 'timeout' or 'failed'),
  95. rv.code,
  96. vim.inspect(cmd.cmd)
  97. )
  98. end
  99. return err
  100. end
  101. local gx_desc =
  102. 'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)'
  103. vim.keymap.set({ 'n' }, 'gx', function()
  104. for _, url in ipairs(require('vim.ui')._get_urls()) do
  105. local err = do_open(url)
  106. if err then
  107. vim.notify(err, vim.log.levels.ERROR)
  108. end
  109. end
  110. end, { desc = gx_desc })
  111. vim.keymap.set({ 'x' }, 'gx', function()
  112. local lines =
  113. vim.fn.getregion(vim.fn.getpos('.'), vim.fn.getpos('v'), { type = vim.fn.mode() })
  114. -- Trim whitespace on each line and concatenate.
  115. local err = do_open(table.concat(vim.iter(lines):map(vim.trim):totable()))
  116. if err then
  117. vim.notify(err, vim.log.levels.ERROR)
  118. end
  119. end, { desc = gx_desc })
  120. end
  121. --- Default maps for built-in commenting.
  122. ---
  123. --- See |gc-default| and |gcc-default|.
  124. do
  125. local operator_rhs = function()
  126. return require('vim._comment').operator()
  127. end
  128. vim.keymap.set({ 'n', 'x' }, 'gc', operator_rhs, { expr = true, desc = 'Toggle comment' })
  129. local line_rhs = function()
  130. return require('vim._comment').operator() .. '_'
  131. end
  132. vim.keymap.set('n', 'gcc', line_rhs, { expr = true, desc = 'Toggle comment line' })
  133. local textobject_rhs = function()
  134. require('vim._comment').textobject()
  135. end
  136. vim.keymap.set({ 'o' }, 'gc', textobject_rhs, { desc = 'Comment textobject' })
  137. end
  138. --- Default maps for LSP functions.
  139. ---
  140. --- These are mapped unconditionally to avoid different behavior depending on whether an LSP
  141. --- client is attached. If no client is attached, or if a server does not support a capability, an
  142. --- error message is displayed rather than exhibiting different behavior.
  143. ---
  144. --- See |grr|, |grn|, |gra|, |gri|, |gO|, |i_CTRL-S|.
  145. do
  146. vim.keymap.set('n', 'grn', function()
  147. vim.lsp.buf.rename()
  148. end, { desc = 'vim.lsp.buf.rename()' })
  149. vim.keymap.set({ 'n', 'x' }, 'gra', function()
  150. vim.lsp.buf.code_action()
  151. end, { desc = 'vim.lsp.buf.code_action()' })
  152. vim.keymap.set('n', 'grr', function()
  153. vim.lsp.buf.references()
  154. end, { desc = 'vim.lsp.buf.references()' })
  155. vim.keymap.set('n', 'gri', function()
  156. vim.lsp.buf.implementation()
  157. end, { desc = 'vim.lsp.buf.implementation()' })
  158. vim.keymap.set('n', 'gO', function()
  159. vim.lsp.buf.document_symbol()
  160. end, { desc = 'vim.lsp.buf.document_symbol()' })
  161. vim.keymap.set({ 'i', 's' }, '<C-S>', function()
  162. vim.lsp.buf.signature_help()
  163. end, { desc = 'vim.lsp.buf.signature_help()' })
  164. end
  165. --- Map [d and ]d to move to the previous/next diagnostic. Map <C-W>d to open a floating window
  166. --- for the diagnostic under the cursor.
  167. ---
  168. --- See |[d-default|, |]d-default|, and |CTRL-W_d-default|.
  169. do
  170. vim.keymap.set('n', ']d', function()
  171. vim.diagnostic.jump({ count = vim.v.count1 })
  172. end, { desc = 'Jump to the next diagnostic in the current buffer' })
  173. vim.keymap.set('n', '[d', function()
  174. vim.diagnostic.jump({ count = -vim.v.count1 })
  175. end, { desc = 'Jump to the previous diagnostic in the current buffer' })
  176. vim.keymap.set('n', ']D', function()
  177. vim.diagnostic.jump({ count = math.huge, wrap = false })
  178. end, { desc = 'Jump to the last diagnostic in the current buffer' })
  179. vim.keymap.set('n', '[D', function()
  180. vim.diagnostic.jump({ count = -math.huge, wrap = false })
  181. end, { desc = 'Jump to the first diagnostic in the current buffer' })
  182. vim.keymap.set('n', '<C-W>d', function()
  183. vim.diagnostic.open_float()
  184. end, { desc = 'Show diagnostics under the cursor' })
  185. vim.keymap.set(
  186. 'n',
  187. '<C-W><C-D>',
  188. '<C-W>d',
  189. { remap = true, desc = 'Show diagnostics under the cursor' }
  190. )
  191. end
  192. --- vim-unimpaired style mappings. See: https://github.com/tpope/vim-unimpaired
  193. do
  194. --- Execute a command and print errors without a stacktrace.
  195. --- @param opts table Arguments to |nvim_cmd()|
  196. local function cmd(opts)
  197. local ok, err = pcall(vim.api.nvim_cmd, opts, {})
  198. if not ok then
  199. vim.api.nvim_err_writeln(err:sub(#'Vim:' + 1))
  200. end
  201. end
  202. -- Quickfix mappings
  203. vim.keymap.set('n', '[q', function()
  204. cmd({ cmd = 'cprevious', count = vim.v.count1 })
  205. end, { desc = ':cprevious' })
  206. vim.keymap.set('n', ']q', function()
  207. cmd({ cmd = 'cnext', count = vim.v.count1 })
  208. end, { desc = ':cnext' })
  209. vim.keymap.set('n', '[Q', function()
  210. cmd({ cmd = 'crewind', count = vim.v.count ~= 0 and vim.v.count or nil })
  211. end, { desc = ':crewind' })
  212. vim.keymap.set('n', ']Q', function()
  213. cmd({ cmd = 'clast', count = vim.v.count ~= 0 and vim.v.count or nil })
  214. end, { desc = ':clast' })
  215. vim.keymap.set('n', '[<C-Q>', function()
  216. cmd({ cmd = 'cpfile', count = vim.v.count1 })
  217. end, { desc = ':cpfile' })
  218. vim.keymap.set('n', ']<C-Q>', function()
  219. cmd({ cmd = 'cnfile', count = vim.v.count1 })
  220. end, { desc = ':cnfile' })
  221. -- Location list mappings
  222. vim.keymap.set('n', '[l', function()
  223. cmd({ cmd = 'lprevious', count = vim.v.count1 })
  224. end, { desc = ':lprevious' })
  225. vim.keymap.set('n', ']l', function()
  226. cmd({ cmd = 'lnext', count = vim.v.count1 })
  227. end, { desc = ':lnext' })
  228. vim.keymap.set('n', '[L', function()
  229. cmd({ cmd = 'lrewind', count = vim.v.count ~= 0 and vim.v.count or nil })
  230. end, { desc = ':lrewind' })
  231. vim.keymap.set('n', ']L', function()
  232. cmd({ cmd = 'llast', count = vim.v.count ~= 0 and vim.v.count or nil })
  233. end, { desc = ':llast' })
  234. vim.keymap.set('n', '[<C-L>', function()
  235. cmd({ cmd = 'lpfile', count = vim.v.count1 })
  236. end, { desc = ':lpfile' })
  237. vim.keymap.set('n', ']<C-L>', function()
  238. cmd({ cmd = 'lnfile', count = vim.v.count1 })
  239. end, { desc = ':lnfile' })
  240. -- Argument list
  241. vim.keymap.set('n', '[a', function()
  242. cmd({ cmd = 'previous', count = vim.v.count1 })
  243. end, { desc = ':previous' })
  244. vim.keymap.set('n', ']a', function()
  245. -- count doesn't work with :next, must use range. See #30641.
  246. cmd({ cmd = 'next', range = { vim.v.count1 } })
  247. end, { desc = ':next' })
  248. vim.keymap.set('n', '[A', function()
  249. if vim.v.count ~= 0 then
  250. cmd({ cmd = 'argument', count = vim.v.count })
  251. else
  252. cmd({ cmd = 'rewind' })
  253. end
  254. end, { desc = ':rewind' })
  255. vim.keymap.set('n', ']A', function()
  256. if vim.v.count ~= 0 then
  257. cmd({ cmd = 'argument', count = vim.v.count })
  258. else
  259. cmd({ cmd = 'last' })
  260. end
  261. end, { desc = ':last' })
  262. -- Tags
  263. vim.keymap.set('n', '[t', function()
  264. -- count doesn't work with :tprevious, must use range. See #30641.
  265. cmd({ cmd = 'tprevious', range = { vim.v.count1 } })
  266. end, { desc = ':tprevious' })
  267. vim.keymap.set('n', ']t', function()
  268. -- count doesn't work with :tnext, must use range. See #30641.
  269. cmd({ cmd = 'tnext', range = { vim.v.count1 } })
  270. end, { desc = ':tnext' })
  271. vim.keymap.set('n', '[T', function()
  272. -- count doesn't work with :trewind, must use range. See #30641.
  273. cmd({ cmd = 'trewind', range = vim.v.count ~= 0 and { vim.v.count } or nil })
  274. end, { desc = ':trewind' })
  275. vim.keymap.set('n', ']T', function()
  276. -- :tlast does not accept a count, so use :trewind if count given
  277. if vim.v.count ~= 0 then
  278. cmd({ cmd = 'trewind', range = { vim.v.count } })
  279. else
  280. cmd({ cmd = 'tlast' })
  281. end
  282. end, { desc = ':tlast' })
  283. vim.keymap.set('n', '[<C-T>', function()
  284. -- count doesn't work with :ptprevious, must use range. See #30641.
  285. cmd({ cmd = 'ptprevious', range = { vim.v.count1 } })
  286. end, { desc = ' :ptprevious' })
  287. vim.keymap.set('n', ']<C-T>', function()
  288. -- count doesn't work with :ptnext, must use range. See #30641.
  289. cmd({ cmd = 'ptnext', range = { vim.v.count1 } })
  290. end, { desc = ':ptnext' })
  291. -- Buffers
  292. vim.keymap.set('n', '[b', function()
  293. cmd({ cmd = 'bprevious', count = vim.v.count1 })
  294. end, { desc = ':bprevious' })
  295. vim.keymap.set('n', ']b', function()
  296. cmd({ cmd = 'bnext', count = vim.v.count1 })
  297. end, { desc = ':bnext' })
  298. vim.keymap.set('n', '[B', function()
  299. if vim.v.count ~= 0 then
  300. cmd({ cmd = 'buffer', count = vim.v.count })
  301. else
  302. cmd({ cmd = 'brewind' })
  303. end
  304. end, { desc = ':brewind' })
  305. vim.keymap.set('n', ']B', function()
  306. if vim.v.count ~= 0 then
  307. cmd({ cmd = 'buffer', count = vim.v.count })
  308. else
  309. cmd({ cmd = 'blast' })
  310. end
  311. end, { desc = ':blast' })
  312. -- Add empty lines
  313. vim.keymap.set('n', '[<Space>', function()
  314. -- TODO: update once it is possible to assign a Lua function to options #25672
  315. vim.go.operatorfunc = "v:lua.require'vim._buf'.space_above"
  316. return 'g@l'
  317. end, { expr = true, desc = 'Add empty line above cursor' })
  318. vim.keymap.set('n', ']<Space>', function()
  319. -- TODO: update once it is possible to assign a Lua function to options #25672
  320. vim.go.operatorfunc = "v:lua.require'vim._buf'.space_below"
  321. return 'g@l'
  322. end, { expr = true, desc = 'Add empty line below cursor' })
  323. end
  324. end
  325. --- Default menus
  326. do
  327. --- Right click popup menu
  328. vim.cmd([[
  329. anoremenu PopUp.Go\ to\ definition <Cmd>lua vim.lsp.buf.definition()<CR>
  330. amenu PopUp.Open\ in\ web\ browser gx
  331. anoremenu PopUp.Inspect <Cmd>Inspect<CR>
  332. anoremenu PopUp.-1- <Nop>
  333. vnoremenu PopUp.Cut "+x
  334. vnoremenu PopUp.Copy "+y
  335. anoremenu PopUp.Paste "+gP
  336. vnoremenu PopUp.Paste "+P
  337. vnoremenu PopUp.Delete "_x
  338. nnoremenu PopUp.Select\ All ggVG
  339. vnoremenu PopUp.Select\ All gg0oG$
  340. inoremenu PopUp.Select\ All <C-Home><C-O>VG
  341. anoremenu PopUp.-2- <Nop>
  342. anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR>
  343. ]])
  344. local function enable_ctx_menu(ctx)
  345. vim.cmd([[
  346. amenu disable PopUp.Go\ to\ definition
  347. amenu disable PopUp.Open\ in\ web\ browser
  348. ]])
  349. if ctx == 'url' then
  350. vim.cmd([[amenu enable PopUp.Open\ in\ web\ browser]])
  351. elseif ctx == 'lsp' then
  352. vim.cmd([[anoremenu enable PopUp.Go\ to\ definition]])
  353. end
  354. end
  355. local nvim_popupmenu_augroup = vim.api.nvim_create_augroup('nvim_popupmenu', {})
  356. vim.api.nvim_create_autocmd('MenuPopup', {
  357. pattern = '*',
  358. group = nvim_popupmenu_augroup,
  359. desc = 'Mouse popup menu',
  360. -- nested = true,
  361. callback = function()
  362. local urls = require('vim.ui')._get_urls()
  363. local url = vim.startswith(urls[1], 'http')
  364. local ctx = url and 'url' or (vim.lsp.get_clients({ bufnr = 0 })[1] and 'lsp' or nil)
  365. enable_ctx_menu(ctx)
  366. end,
  367. })
  368. end
  369. --- Default autocommands. See |default-autocmds|
  370. do
  371. local nvim_terminal_augroup = vim.api.nvim_create_augroup('nvim_terminal', {})
  372. vim.api.nvim_create_autocmd('BufReadCmd', {
  373. pattern = 'term://*',
  374. group = nvim_terminal_augroup,
  375. desc = 'Treat term:// buffers as terminal buffers',
  376. nested = true,
  377. 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, ''))})",
  378. })
  379. vim.api.nvim_create_autocmd({ 'TermClose' }, {
  380. group = nvim_terminal_augroup,
  381. nested = true,
  382. desc = 'Automatically close terminal buffers when started with no arguments and exiting without an error',
  383. callback = function(args)
  384. if vim.v.event.status ~= 0 then
  385. return
  386. end
  387. local info = vim.api.nvim_get_chan_info(vim.bo[args.buf].channel)
  388. local argv = info.argv or {}
  389. if table.concat(argv, ' ') == vim.o.shell then
  390. vim.api.nvim_buf_delete(args.buf, { force = true })
  391. end
  392. end,
  393. })
  394. vim.api.nvim_create_autocmd('TermRequest', {
  395. group = nvim_terminal_augroup,
  396. desc = 'Handles OSC foreground/background color requests',
  397. callback = function(args)
  398. --- @type integer
  399. local channel = vim.bo[args.buf].channel
  400. if channel == 0 then
  401. return
  402. end
  403. local fg_request = args.data == '\027]10;?'
  404. local bg_request = args.data == '\027]11;?'
  405. if fg_request or bg_request then
  406. -- WARN: This does not return the actual foreground/background color,
  407. -- but rather returns:
  408. -- - fg=white/bg=black when Nvim option 'background' is 'dark'
  409. -- - fg=black/bg=white when Nvim option 'background' is 'light'
  410. local red, green, blue = 0, 0, 0
  411. local bg_option_dark = vim.o.background == 'dark'
  412. if (fg_request and bg_option_dark) or (bg_request and not bg_option_dark) then
  413. red, green, blue = 65535, 65535, 65535
  414. end
  415. local command = fg_request and 10 or 11
  416. local data = string.format('\027]%d;rgb:%04x/%04x/%04x\007', command, red, green, blue)
  417. vim.api.nvim_chan_send(channel, data)
  418. end
  419. end,
  420. })
  421. vim.api.nvim_create_autocmd('TermOpen', {
  422. group = nvim_terminal_augroup,
  423. desc = 'Default settings for :terminal buffers',
  424. callback = function()
  425. vim.bo.modifiable = false
  426. vim.bo.undolevels = -1
  427. vim.bo.scrollback = vim.o.scrollback < 0 and 10000 or math.max(1, vim.o.scrollback)
  428. vim.bo.textwidth = 0
  429. vim.wo[0][0].wrap = false
  430. vim.wo[0][0].list = false
  431. vim.wo[0][0].number = false
  432. vim.wo[0][0].relativenumber = false
  433. vim.wo[0][0].signcolumn = 'no'
  434. vim.wo[0][0].foldcolumn = '0'
  435. -- This is gross. Proper list options support when?
  436. local winhl = vim.o.winhighlight
  437. if winhl ~= '' then
  438. winhl = winhl .. ','
  439. end
  440. vim.wo[0][0].winhighlight = winhl .. 'StatusLine:StatusLineTerm,StatusLineNC:StatusLineTermNC'
  441. end,
  442. })
  443. vim.api.nvim_create_autocmd('CmdwinEnter', {
  444. pattern = '[:>]',
  445. desc = 'Limit syntax sync to maxlines=1 in the command window',
  446. group = vim.api.nvim_create_augroup('nvim_cmdwin', {}),
  447. command = 'syntax sync minlines=1 maxlines=1',
  448. })
  449. vim.api.nvim_create_autocmd('SwapExists', {
  450. pattern = '*',
  451. desc = 'Skip the swapfile prompt when the swapfile is owned by a running Nvim process',
  452. group = vim.api.nvim_create_augroup('nvim_swapfile', {}),
  453. callback = function()
  454. local info = vim.fn.swapinfo(vim.v.swapname)
  455. local user = vim.uv.os_get_passwd().username
  456. local iswin = 1 == vim.fn.has('win32')
  457. if info.error or info.pid <= 0 or (not iswin and info.user ~= user) then
  458. vim.v.swapchoice = '' -- Show the prompt.
  459. return
  460. end
  461. vim.v.swapchoice = 'e' -- Choose "(E)dit".
  462. vim.notify(
  463. ('W325: Ignoring swapfile from Nvim process %d'):format(info.pid),
  464. vim.log.levels.WARN
  465. )
  466. end,
  467. })
  468. -- Only do the following when the TUI is attached
  469. local tty = nil
  470. for _, ui in ipairs(vim.api.nvim_list_uis()) do
  471. if ui.chan == 1 and ui.stdout_tty then
  472. tty = ui
  473. break
  474. end
  475. end
  476. if tty then
  477. local group = vim.api.nvim_create_augroup('nvim_tty', {})
  478. --- Set an option after startup (so that OptionSet is fired), but only if not
  479. --- already set by the user.
  480. ---
  481. --- @param option string Option name
  482. --- @param value any Option value
  483. --- @param force boolean? Always set the value, even if already set
  484. local function setoption(option, value, force)
  485. if not force and vim.api.nvim_get_option_info2(option, {}).was_set then
  486. -- Don't do anything if option is already set
  487. return
  488. end
  489. -- Wait until Nvim is finished starting to set the option to ensure the
  490. -- OptionSet event fires.
  491. if vim.v.vim_did_enter == 1 then
  492. --- @diagnostic disable-next-line:no-unknown
  493. vim.o[option] = value
  494. else
  495. vim.api.nvim_create_autocmd('VimEnter', {
  496. group = group,
  497. once = true,
  498. nested = true,
  499. callback = function()
  500. setoption(option, value, force)
  501. end,
  502. })
  503. end
  504. end
  505. --- Guess value of 'background' based on terminal color.
  506. ---
  507. --- We write Operating System Command (OSC) 11 to the terminal to request the
  508. --- terminal's background color. We then wait for a response. If the response
  509. --- matches `rgba:RRRR/GGGG/BBBB/AAAA` where R, G, B, and A are hex digits, then
  510. --- compute the luminance[1] of the RGB color and classify it as light/dark
  511. --- accordingly. Note that the color components may have anywhere from one to
  512. --- four hex digits, and require scaling accordingly as values out of 4, 8, 12,
  513. --- or 16 bits. Also note the A(lpha) component is optional, and is parsed but
  514. --- ignored in the calculations.
  515. ---
  516. --- [1] https://en.wikipedia.org/wiki/Luma_%28video%29
  517. do
  518. --- Parse a string of hex characters as a color.
  519. ---
  520. --- The string can contain 1 to 4 hex characters. The returned value is
  521. --- between 0.0 and 1.0 (inclusive) representing the intensity of the color.
  522. ---
  523. --- For instance, if only a single hex char "a" is used, then this function
  524. --- returns 0.625 (10 / 16), while a value of "aa" would return 0.664 (170 /
  525. --- 256).
  526. ---
  527. --- @param c string Color as a string of hex chars
  528. --- @return number? Intensity of the color
  529. local function parsecolor(c)
  530. if #c == 0 or #c > 4 then
  531. return nil
  532. end
  533. local val = tonumber(c, 16)
  534. if not val then
  535. return nil
  536. end
  537. local max = tonumber(string.rep('f', #c), 16)
  538. return val / max
  539. end
  540. --- Parse an OSC 11 response
  541. ---
  542. --- Either of the two formats below are accepted:
  543. ---
  544. --- OSC 11 ; rgb:<red>/<green>/<blue>
  545. ---
  546. --- or
  547. ---
  548. --- OSC 11 ; rgba:<red>/<green>/<blue>/<alpha>
  549. ---
  550. --- where
  551. ---
  552. --- <red>, <green>, <blue>, <alpha> := h | hh | hhh | hhhh
  553. ---
  554. --- The alpha component is ignored, if present.
  555. ---
  556. --- @param resp string OSC 11 response
  557. --- @return string? Red component
  558. --- @return string? Green component
  559. --- @return string? Blue component
  560. local function parseosc11(resp)
  561. local r, g, b
  562. r, g, b = resp:match('^\027%]11;rgb:(%x+)/(%x+)/(%x+)$')
  563. if not r and not g and not b then
  564. local a
  565. r, g, b, a = resp:match('^\027%]11;rgba:(%x+)/(%x+)/(%x+)/(%x+)$')
  566. if not a or #a > 4 then
  567. return nil, nil, nil
  568. end
  569. end
  570. if r and g and b and #r <= 4 and #g <= 4 and #b <= 4 then
  571. return r, g, b
  572. end
  573. return nil, nil, nil
  574. end
  575. -- This autocommand updates the value of 'background' anytime we receive
  576. -- an OSC 11 response from the terminal emulator. If the user has set
  577. -- 'background' explictly then we will delete this autocommand,
  578. -- effectively disabling automatic background setting.
  579. local force = false
  580. local id = vim.api.nvim_create_autocmd('TermResponse', {
  581. group = group,
  582. nested = true,
  583. desc = "Update the value of 'background' automatically based on the terminal emulator's background color",
  584. callback = function(args)
  585. local resp = args.data ---@type string
  586. local r, g, b = parseosc11(resp)
  587. if r and g and b then
  588. local rr = parsecolor(r)
  589. local gg = parsecolor(g)
  590. local bb = parsecolor(b)
  591. if rr and gg and bb then
  592. local luminance = (0.299 * rr) + (0.587 * gg) + (0.114 * bb)
  593. local bg = luminance < 0.5 and 'dark' or 'light'
  594. setoption('background', bg, force)
  595. -- On the first query response, don't force setting the option in
  596. -- case the user has already set it manually. If they have, then
  597. -- this autocommand will be deleted. If they haven't, then we do
  598. -- want to force setting the option to override the value set by
  599. -- this autocommand.
  600. if not force then
  601. force = true
  602. end
  603. end
  604. end
  605. end,
  606. })
  607. vim.api.nvim_create_autocmd('VimEnter', {
  608. group = group,
  609. nested = true,
  610. once = true,
  611. callback = function()
  612. if vim.api.nvim_get_option_info2('background', {}).was_set then
  613. vim.api.nvim_del_autocmd(id)
  614. end
  615. end,
  616. })
  617. io.stdout:write('\027]11;?\007')
  618. end
  619. --- If the TUI (term_has_truecolor) was able to determine that the host
  620. --- terminal supports truecolor, enable 'termguicolors'. Otherwise, query the
  621. --- terminal (using both XTGETTCAP and SGR + DECRQSS). If the terminal's
  622. --- response indicates that it does support truecolor enable 'termguicolors',
  623. --- but only if the user has not already disabled it.
  624. do
  625. local colorterm = os.getenv('COLORTERM')
  626. if tty.rgb or colorterm == 'truecolor' or colorterm == '24bit' then
  627. -- The TUI was able to determine truecolor support or $COLORTERM explicitly indicates
  628. -- truecolor support
  629. setoption('termguicolors', true)
  630. elseif colorterm == nil or colorterm == '' then
  631. -- Neither the TUI nor $COLORTERM indicate that truecolor is supported, so query the
  632. -- terminal
  633. local caps = {} ---@type table<string, boolean>
  634. require('vim.termcap').query({ 'Tc', 'RGB', 'setrgbf', 'setrgbb' }, function(cap, found)
  635. if not found then
  636. return
  637. end
  638. caps[cap] = true
  639. if caps.Tc or caps.RGB or (caps.setrgbf and caps.setrgbb) then
  640. setoption('termguicolors', true)
  641. end
  642. end)
  643. local timer = assert(vim.uv.new_timer())
  644. -- Arbitrary colors to set in the SGR sequence
  645. local r = 1
  646. local g = 2
  647. local b = 3
  648. local id = vim.api.nvim_create_autocmd('TermResponse', {
  649. group = group,
  650. nested = true,
  651. callback = function(args)
  652. local resp = args.data ---@type string
  653. local decrqss = resp:match('^\027P1%$r([%d;:]+)m$')
  654. if decrqss then
  655. -- The DECRQSS SGR response first contains attributes separated by
  656. -- semicolons, followed by the SGR itself with parameters separated
  657. -- by colons. Some terminals include "0" in the attribute list
  658. -- unconditionally; others do not. Our SGR sequence did not set any
  659. -- attributes, so there should be no attributes in the list.
  660. local attrs = vim.split(decrqss, ';')
  661. if #attrs ~= 1 and (#attrs ~= 2 or attrs[1] ~= '0') then
  662. return false
  663. end
  664. -- The returned SGR sequence should begin with 48:2
  665. local sgr = attrs[#attrs]:match('^48:2:([%d:]+)$')
  666. if not sgr then
  667. return false
  668. end
  669. -- The remaining elements of the SGR sequence should be the 3 colors
  670. -- we set. Some terminals also include an additional parameter
  671. -- (which can even be empty!), so handle those cases as well
  672. local params = vim.split(sgr, ':')
  673. if #params ~= 3 and (#params ~= 4 or (params[1] ~= '' and params[1] ~= '1')) then
  674. return true
  675. end
  676. if
  677. tonumber(params[#params - 2]) == r
  678. and tonumber(params[#params - 1]) == g
  679. and tonumber(params[#params]) == b
  680. then
  681. setoption('termguicolors', true)
  682. end
  683. return true
  684. end
  685. end,
  686. })
  687. -- Write SGR followed by DECRQSS. This sets the background color then
  688. -- immediately asks the terminal what the background color is. If the
  689. -- terminal responds to the DECRQSS with the same SGR sequence that we
  690. -- sent then the terminal supports truecolor.
  691. local decrqss = '\027P$qm\027\\'
  692. if os.getenv('TMUX') then
  693. decrqss = string.format('\027Ptmux;%s\027\\', decrqss:gsub('\027', '\027\027'))
  694. end
  695. -- Reset attributes first, as other code may have set attributes.
  696. io.stdout:write(string.format('\027[0m\027[48;2;%d;%d;%dm%s', r, g, b, decrqss))
  697. timer:start(1000, 0, function()
  698. -- Delete the autocommand if no response was received
  699. vim.schedule(function()
  700. -- Suppress error if autocommand has already been deleted
  701. pcall(vim.api.nvim_del_autocmd, id)
  702. end)
  703. if not timer:is_closing() then
  704. timer:close()
  705. end
  706. end)
  707. end
  708. end
  709. end
  710. end
  711. --- Default options
  712. do
  713. --- Default 'grepprg' to ripgrep if available.
  714. if vim.fn.executable('rg') == 1 then
  715. -- Use -uu to make ripgrep not check ignore files/skip dot-files
  716. vim.o.grepprg = 'rg --vimgrep -uu '
  717. vim.o.grepformat = '%f:%l:%c:%m'
  718. end
  719. end