_editor.lua 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. -- Nvim-Lua stdlib: the `vim` module (:help lua-stdlib)
  2. --
  3. -- Lua code lives in one of three places:
  4. -- 1. runtime/lua/vim/ (the runtime): For "nice to have" features, e.g. the
  5. -- `inspect` and `lpeg` modules.
  6. -- 2. runtime/lua/vim/shared.lua: pure lua functions which always
  7. -- are available. Used in the test runner, as well as worker threads
  8. -- and processes launched from Nvim.
  9. -- 3. runtime/lua/vim/_editor.lua: Code which directly interacts with
  10. -- the Nvim editor state. Only available in the main thread.
  11. --
  12. -- Guideline: "If in doubt, put it in the runtime".
  13. --
  14. -- Most functions should live directly in `vim.`, not in submodules.
  15. --
  16. -- Compatibility with Vim's `if_lua` is explicitly a non-goal.
  17. --
  18. -- Reference (#6580):
  19. -- - https://github.com/luafun/luafun
  20. -- - https://github.com/rxi/lume
  21. -- - http://leafo.net/lapis/reference/utilities.html
  22. -- - https://github.com/torch/paths
  23. -- - https://github.com/bakpakin/Fennel (pretty print, repl)
  24. -- - https://github.com/howl-editor/howl/tree/master/lib/howl/util
  25. local vim = assert(vim)
  26. -- These are for loading runtime modules lazily since they aren't available in
  27. -- the nvim binary as specified in executor.c
  28. for k, v in pairs({
  29. treesitter = true,
  30. filetype = true,
  31. F = true,
  32. lsp = true,
  33. highlight = true,
  34. diagnostic = true,
  35. keymap = true,
  36. ui = true,
  37. health = true,
  38. fs = true,
  39. }) do
  40. vim._submodules[k] = v
  41. end
  42. vim.log = {
  43. levels = {
  44. TRACE = 0,
  45. DEBUG = 1,
  46. INFO = 2,
  47. WARN = 3,
  48. ERROR = 4,
  49. OFF = 5,
  50. },
  51. }
  52. -- Internal-only until comments in #8107 are addressed.
  53. -- Returns:
  54. -- {errcode}, {output}
  55. function vim._system(cmd)
  56. local out = vim.fn.system(cmd)
  57. local err = vim.v.shell_error
  58. return err, out
  59. end
  60. -- Gets process info from the `ps` command.
  61. -- Used by nvim_get_proc() as a fallback.
  62. function vim._os_proc_info(pid)
  63. if pid == nil or pid <= 0 or type(pid) ~= 'number' then
  64. error('invalid pid')
  65. end
  66. local cmd = { 'ps', '-p', pid, '-o', 'comm=' }
  67. local err, name = vim._system(cmd)
  68. if 1 == err and vim.trim(name) == '' then
  69. return {} -- Process not found.
  70. elseif 0 ~= err then
  71. error('command failed: ' .. vim.fn.string(cmd))
  72. end
  73. local _, ppid = vim._system({ 'ps', '-p', pid, '-o', 'ppid=' })
  74. -- Remove trailing whitespace.
  75. name = vim.trim(name):gsub('^.*/', '')
  76. ppid = tonumber(ppid) or -1
  77. return {
  78. name = name,
  79. pid = pid,
  80. ppid = ppid,
  81. }
  82. end
  83. -- Gets process children from the `pgrep` command.
  84. -- Used by nvim_get_proc_children() as a fallback.
  85. function vim._os_proc_children(ppid)
  86. if ppid == nil or ppid <= 0 or type(ppid) ~= 'number' then
  87. error('invalid ppid')
  88. end
  89. local cmd = { 'pgrep', '-P', ppid }
  90. local err, rv = vim._system(cmd)
  91. if 1 == err and vim.trim(rv) == '' then
  92. return {} -- Process not found.
  93. elseif 0 ~= err then
  94. error('command failed: ' .. vim.fn.string(cmd))
  95. end
  96. local children = {}
  97. for s in rv:gmatch('%S+') do
  98. local i = tonumber(s)
  99. if i ~= nil then
  100. table.insert(children, i)
  101. end
  102. end
  103. return children
  104. end
  105. --- Gets a human-readable representation of the given object.
  106. ---
  107. ---@see https://github.com/kikito/inspect.lua
  108. ---@see https://github.com/mpeterv/vinspect
  109. local function inspect(object, options) -- luacheck: no unused
  110. error(object, options) -- Stub for gen_vimdoc.py
  111. end
  112. do
  113. local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false
  114. --- Paste handler, invoked by |nvim_paste()| when a conforming UI
  115. --- (such as the |TUI|) pastes text into the editor.
  116. ---
  117. --- Example: To remove ANSI color codes when pasting:
  118. --- <pre>
  119. --- vim.paste = (function(overridden)
  120. --- return function(lines, phase)
  121. --- for i,line in ipairs(lines) do
  122. --- -- Scrub ANSI color codes from paste input.
  123. --- lines[i] = line:gsub('\27%[[0-9;mK]+', '')
  124. --- end
  125. --- overridden(lines, phase)
  126. --- end
  127. --- end)(vim.paste)
  128. --- </pre>
  129. ---
  130. ---@see |paste|
  131. ---
  132. ---@param lines |readfile()|-style list of lines to paste. |channel-lines|
  133. ---@param phase -1: "non-streaming" paste: the call contains all lines.
  134. --- If paste is "streamed", `phase` indicates the stream state:
  135. --- - 1: starts the paste (exactly once)
  136. --- - 2: continues the paste (zero or more times)
  137. --- - 3: ends the paste (exactly once)
  138. ---@returns false if client should cancel the paste.
  139. function vim.paste(lines, phase)
  140. local now = vim.loop.now()
  141. local is_first_chunk = phase < 2
  142. local is_last_chunk = phase == -1 or phase == 3
  143. if is_first_chunk then -- Reset flags.
  144. tdots, tick, got_line1, undo_started, trailing_nl = now, 0, false, false, false
  145. end
  146. if #lines == 0 then
  147. lines = { '' }
  148. end
  149. if #lines == 1 and lines[1] == '' and not is_last_chunk then
  150. -- An empty chunk can cause some edge cases in streamed pasting,
  151. -- so don't do anything unless it is the last chunk.
  152. return true
  153. end
  154. -- Note: mode doesn't always start with "c" in cmdline mode, so use getcmdtype() instead.
  155. if vim.fn.getcmdtype() ~= '' then -- cmdline-mode: paste only 1 line.
  156. if not got_line1 then
  157. got_line1 = (#lines > 1)
  158. -- Escape control characters
  159. local line1 = lines[1]:gsub('(%c)', '\022%1')
  160. -- nvim_input() is affected by mappings,
  161. -- so use nvim_feedkeys() with "n" flag to ignore mappings.
  162. -- "t" flag is also needed so the pasted text is saved in cmdline history.
  163. vim.api.nvim_feedkeys(line1, 'nt', true)
  164. end
  165. return true
  166. end
  167. local mode = vim.api.nvim_get_mode().mode
  168. if undo_started then
  169. vim.api.nvim_command('undojoin')
  170. end
  171. if mode:find('^i') or mode:find('^n?t') then -- Insert mode or Terminal buffer
  172. vim.api.nvim_put(lines, 'c', false, true)
  173. elseif phase < 2 and mode:find('^R') and not mode:find('^Rv') then -- Replace mode
  174. -- TODO: implement Replace mode streamed pasting
  175. -- TODO: support Virtual Replace mode
  176. local nchars = 0
  177. for _, line in ipairs(lines) do
  178. nchars = nchars + line:len()
  179. end
  180. local row, col = unpack(vim.api.nvim_win_get_cursor(0))
  181. local bufline = vim.api.nvim_buf_get_lines(0, row - 1, row, true)[1]
  182. local firstline = lines[1]
  183. firstline = bufline:sub(1, col) .. firstline
  184. lines[1] = firstline
  185. lines[#lines] = lines[#lines] .. bufline:sub(col + nchars + 1, bufline:len())
  186. vim.api.nvim_buf_set_lines(0, row - 1, row, false, lines)
  187. elseif mode:find('^[nvV\22sS\19]') then -- Normal or Visual or Select mode
  188. if mode:find('^n') then -- Normal mode
  189. -- When there was a trailing new line in the previous chunk,
  190. -- the cursor is on the first character of the next line,
  191. -- so paste before the cursor instead of after it.
  192. vim.api.nvim_put(lines, 'c', not trailing_nl, false)
  193. else -- Visual or Select mode
  194. vim.api.nvim_command([[exe "silent normal! \<Del>"]])
  195. local del_start = vim.fn.getpos("'[")
  196. local cursor_pos = vim.fn.getpos('.')
  197. if mode:find('^[VS]') then -- linewise
  198. if cursor_pos[2] < del_start[2] then -- replacing lines at eof
  199. -- create a new line
  200. vim.api.nvim_put({ '' }, 'l', true, true)
  201. end
  202. vim.api.nvim_put(lines, 'c', false, false)
  203. else
  204. -- paste after cursor when replacing text at eol, otherwise paste before cursor
  205. vim.api.nvim_put(lines, 'c', cursor_pos[3] < del_start[3], false)
  206. end
  207. end
  208. -- put cursor at the end of the text instead of one character after it
  209. vim.fn.setpos('.', vim.fn.getpos("']"))
  210. trailing_nl = lines[#lines] == ''
  211. else -- Don't know what to do in other modes
  212. return false
  213. end
  214. undo_started = true
  215. if phase ~= -1 and (now - tdots >= 100) then
  216. local dots = ('.'):rep(tick % 4)
  217. tdots = now
  218. tick = tick + 1
  219. -- Use :echo because Lua print('') is a no-op, and we want to clear the
  220. -- message when there are zero dots.
  221. vim.api.nvim_command(('echo "%s"'):format(dots))
  222. end
  223. if is_last_chunk then
  224. vim.api.nvim_command('redraw' .. (tick > 1 and '|echo ""' or ''))
  225. end
  226. return true -- Paste will not continue if not returning `true`.
  227. end
  228. end
  229. --- Defers callback `cb` until the Nvim API is safe to call.
  230. ---
  231. ---@see |lua-loop-callbacks|
  232. ---@see |vim.schedule()|
  233. ---@see |vim.in_fast_event()|
  234. function vim.schedule_wrap(cb)
  235. return function(...)
  236. local args = vim.F.pack_len(...)
  237. vim.schedule(function()
  238. cb(vim.F.unpack_len(args))
  239. end)
  240. end
  241. end
  242. -- vim.fn.{func}(...)
  243. vim.fn = setmetatable({}, {
  244. __index = function(t, key)
  245. local _fn
  246. if vim.api[key] ~= nil then
  247. _fn = function()
  248. error(string.format('Tried to call API function with vim.fn: use vim.api.%s instead', key))
  249. end
  250. else
  251. _fn = function(...)
  252. return vim.call(key, ...)
  253. end
  254. end
  255. t[key] = _fn
  256. return _fn
  257. end,
  258. })
  259. vim.funcref = function(viml_func_name)
  260. return vim.fn[viml_func_name]
  261. end
  262. --- Execute Vim script commands.
  263. ---
  264. --- Note that `vim.cmd` can be indexed with a command name to return a callable function to the
  265. --- command.
  266. ---
  267. --- Example:
  268. --- <pre>
  269. --- vim.cmd('echo 42')
  270. --- vim.cmd([[
  271. --- augroup My_group
  272. --- autocmd!
  273. --- autocmd FileType c setlocal cindent
  274. --- augroup END
  275. --- ]])
  276. ---
  277. --- -- Ex command :echo "foo"
  278. --- -- Note string literals need to be double quoted.
  279. --- vim.cmd('echo "foo"')
  280. --- vim.cmd { cmd = 'echo', args = { '"foo"' } }
  281. --- vim.cmd.echo({ args = { '"foo"' } })
  282. --- vim.cmd.echo('"foo"')
  283. ---
  284. --- -- Ex command :write! myfile.txt
  285. --- vim.cmd('write! myfile.txt')
  286. --- vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
  287. --- vim.cmd.write { args = { "myfile.txt" }, bang = true }
  288. --- vim.cmd.write { "myfile.txt", bang = true }
  289. ---
  290. --- -- Ex command :colorscheme blue
  291. --- vim.cmd('colorscheme blue')
  292. --- vim.cmd.colorscheme('blue')
  293. --- </pre>
  294. ---
  295. ---@param command string|table Command(s) to execute.
  296. --- If a string, executes multiple lines of Vim script at once. In this
  297. --- case, it is an alias to |nvim_exec()|, where `output` is set to
  298. --- false. Thus it works identical to |:source|.
  299. --- If a table, executes a single command. In this case, it is an alias
  300. --- to |nvim_cmd()| where `opts` is empty.
  301. ---@see |ex-cmd-index|
  302. function vim.cmd(command) -- luacheck: no unused
  303. error(command) -- Stub for gen_vimdoc.py
  304. end
  305. local VIM_CMD_ARG_MAX = 20
  306. vim.cmd = setmetatable({}, {
  307. __call = function(_, command)
  308. if type(command) == 'table' then
  309. return vim.api.nvim_cmd(command, {})
  310. else
  311. return vim.api.nvim_exec(command, false)
  312. end
  313. end,
  314. __index = function(t, command)
  315. t[command] = function(...)
  316. local opts
  317. if select('#', ...) == 1 and type(select(1, ...)) == 'table' then
  318. opts = select(1, ...)
  319. -- Move indexed positions in opts to opt.args
  320. if opts[1] and not opts.args then
  321. opts.args = {}
  322. for i = 1, VIM_CMD_ARG_MAX do
  323. if not opts[i] then
  324. break
  325. end
  326. opts.args[i] = opts[i]
  327. opts[i] = nil
  328. end
  329. end
  330. else
  331. opts = { args = { ... } }
  332. end
  333. opts.cmd = command
  334. return vim.api.nvim_cmd(opts, {})
  335. end
  336. return t[command]
  337. end,
  338. })
  339. -- These are the vim.env/v/g/o/bo/wo variable magic accessors.
  340. do
  341. local validate = vim.validate
  342. --@private
  343. local function make_dict_accessor(scope, handle)
  344. validate({
  345. scope = { scope, 's' },
  346. })
  347. local mt = {}
  348. function mt:__newindex(k, v)
  349. return vim._setvar(scope, handle or 0, k, v)
  350. end
  351. function mt:__index(k)
  352. if handle == nil and type(k) == 'number' then
  353. return make_dict_accessor(scope, k)
  354. end
  355. return vim._getvar(scope, handle or 0, k)
  356. end
  357. return setmetatable({}, mt)
  358. end
  359. vim.g = make_dict_accessor('g', false)
  360. vim.v = make_dict_accessor('v', false)
  361. vim.b = make_dict_accessor('b')
  362. vim.w = make_dict_accessor('w')
  363. vim.t = make_dict_accessor('t')
  364. end
  365. --- Get a table of lines with start, end columns for a region marked by two points
  366. ---
  367. ---@param bufnr number of buffer
  368. ---@param pos1 (line, column) tuple marking beginning of region
  369. ---@param pos2 (line, column) tuple marking end of region
  370. ---@param regtype type of selection, see |setreg()|
  371. ---@param inclusive boolean indicating whether the selection is end-inclusive
  372. ---@return region lua table of the form {linenr = {startcol,endcol}}
  373. function vim.region(bufnr, pos1, pos2, regtype, inclusive)
  374. if not vim.api.nvim_buf_is_loaded(bufnr) then
  375. vim.fn.bufload(bufnr)
  376. end
  377. -- check that region falls within current buffer
  378. local buf_line_count = vim.api.nvim_buf_line_count(bufnr)
  379. pos1[1] = math.min(pos1[1], buf_line_count - 1)
  380. pos2[1] = math.min(pos2[1], buf_line_count - 1)
  381. -- in case of block selection, columns need to be adjusted for non-ASCII characters
  382. -- TODO: handle double-width characters
  383. local bufline
  384. if regtype:byte() == 22 then
  385. bufline = vim.api.nvim_buf_get_lines(bufnr, pos1[1], pos1[1] + 1, true)[1]
  386. pos1[2] = vim.str_utfindex(bufline, pos1[2])
  387. end
  388. local region = {}
  389. for l = pos1[1], pos2[1] do
  390. local c1, c2
  391. if regtype:byte() == 22 then -- block selection: take width from regtype
  392. c1 = pos1[2]
  393. c2 = c1 + regtype:sub(2)
  394. -- and adjust for non-ASCII characters
  395. bufline = vim.api.nvim_buf_get_lines(bufnr, l, l + 1, true)[1]
  396. if c1 < #bufline then
  397. c1 = vim.str_byteindex(bufline, c1)
  398. end
  399. if c2 < #bufline then
  400. c2 = vim.str_byteindex(bufline, c2)
  401. end
  402. else
  403. c1 = (l == pos1[1]) and pos1[2] or 0
  404. c2 = (l == pos2[1]) and (pos2[2] + (inclusive and 1 or 0)) or -1
  405. end
  406. table.insert(region, l, { c1, c2 })
  407. end
  408. return region
  409. end
  410. --- Defers calling `fn` until `timeout` ms passes.
  411. ---
  412. --- Use to do a one-shot timer that calls `fn`
  413. --- Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are
  414. --- safe to call.
  415. ---@param fn Callback to call once `timeout` expires
  416. ---@param timeout Number of milliseconds to wait before calling `fn`
  417. ---@return timer luv timer object
  418. function vim.defer_fn(fn, timeout)
  419. vim.validate({ fn = { fn, 'c', true } })
  420. local timer = vim.loop.new_timer()
  421. timer:start(
  422. timeout,
  423. 0,
  424. vim.schedule_wrap(function()
  425. if not timer:is_closing() then
  426. timer:close()
  427. end
  428. fn()
  429. end)
  430. )
  431. return timer
  432. end
  433. --- Display a notification to the user.
  434. ---
  435. --- This function can be overridden by plugins to display notifications using a
  436. --- custom provider (such as the system notification provider). By default,
  437. --- writes to |:messages|.
  438. ---
  439. ---@param msg string Content of the notification to show to the user.
  440. ---@param level number|nil One of the values from |vim.log.levels|.
  441. ---@param opts table|nil Optional parameters. Unused by default.
  442. function vim.notify(msg, level, opts) -- luacheck: no unused args
  443. if level == vim.log.levels.ERROR then
  444. vim.api.nvim_err_writeln(msg)
  445. elseif level == vim.log.levels.WARN then
  446. vim.api.nvim_echo({ { msg, 'WarningMsg' } }, true, {})
  447. else
  448. vim.api.nvim_echo({ { msg } }, true, {})
  449. end
  450. end
  451. do
  452. local notified = {}
  453. --- Display a notification only one time.
  454. ---
  455. --- Like |vim.notify()|, but subsequent calls with the same message will not
  456. --- display a notification.
  457. ---
  458. ---@param msg string Content of the notification to show to the user.
  459. ---@param level number|nil One of the values from |vim.log.levels|.
  460. ---@param opts table|nil Optional parameters. Unused by default.
  461. ---@return boolean true if message was displayed, else false
  462. function vim.notify_once(msg, level, opts)
  463. if not notified[msg] then
  464. vim.notify(msg, level, opts)
  465. notified[msg] = true
  466. return true
  467. end
  468. return false
  469. end
  470. end
  471. ---@private
  472. function vim.register_keystroke_callback()
  473. error('vim.register_keystroke_callback is deprecated, instead use: vim.on_key')
  474. end
  475. local on_key_cbs = {}
  476. --- Adds Lua function {fn} with namespace id {ns_id} as a listener to every,
  477. --- yes every, input key.
  478. ---
  479. --- The Nvim command-line option |-w| is related but does not support callbacks
  480. --- and cannot be toggled dynamically.
  481. ---
  482. ---@param fn function: Callback function. It should take one string argument.
  483. --- On each key press, Nvim passes the key char to fn(). |i_CTRL-V|
  484. --- If {fn} is nil, it removes the callback for the associated {ns_id}
  485. ---@param ns_id number? Namespace ID. If nil or 0, generates and returns a new
  486. --- |nvim_create_namespace()| id.
  487. ---
  488. ---@return number Namespace id associated with {fn}. Or count of all callbacks
  489. ---if on_key() is called without arguments.
  490. ---
  491. ---@note {fn} will be removed if an error occurs while calling.
  492. ---@note {fn} will not be cleared by |nvim_buf_clear_namespace()|
  493. ---@note {fn} will receive the keys after mappings have been evaluated
  494. function vim.on_key(fn, ns_id)
  495. if fn == nil and ns_id == nil then
  496. return #on_key_cbs
  497. end
  498. vim.validate({
  499. fn = { fn, 'c', true },
  500. ns_id = { ns_id, 'n', true },
  501. })
  502. if ns_id == nil or ns_id == 0 then
  503. ns_id = vim.api.nvim_create_namespace('')
  504. end
  505. on_key_cbs[ns_id] = fn
  506. return ns_id
  507. end
  508. --- Executes the on_key callbacks.
  509. ---@private
  510. function vim._on_key(char)
  511. local failed_ns_ids = {}
  512. local failed_messages = {}
  513. for k, v in pairs(on_key_cbs) do
  514. local ok, err_msg = pcall(v, char)
  515. if not ok then
  516. vim.on_key(nil, k)
  517. table.insert(failed_ns_ids, k)
  518. table.insert(failed_messages, err_msg)
  519. end
  520. end
  521. if failed_ns_ids[1] then
  522. error(
  523. string.format(
  524. "Error executing 'on_key' with ns_ids '%s'\n Messages: %s",
  525. table.concat(failed_ns_ids, ', '),
  526. table.concat(failed_messages, '\n')
  527. )
  528. )
  529. end
  530. end
  531. --- Generate a list of possible completions for the string.
  532. --- String starts with ^ and then has the pattern.
  533. ---
  534. --- 1. Can we get it to just return things in the global namespace with that name prefix
  535. --- 2. Can we get it to return things from global namespace even with `print(` in front.
  536. function vim._expand_pat(pat, env)
  537. env = env or _G
  538. pat = string.sub(pat, 2, #pat)
  539. if pat == '' then
  540. local result = vim.tbl_keys(env)
  541. table.sort(result)
  542. return result, 0
  543. end
  544. -- TODO: We can handle spaces in [] ONLY.
  545. -- We should probably do that at some point, just for cooler completion.
  546. -- TODO: We can suggest the variable names to go in []
  547. -- This would be difficult as well.
  548. -- Probably just need to do a smarter match than just `:match`
  549. -- Get the last part of the pattern
  550. local last_part = pat:match('[%w.:_%[%]\'"]+$')
  551. if not last_part then
  552. return {}, 0
  553. end
  554. local parts, search_index = vim._expand_pat_get_parts(last_part)
  555. local match_part = string.sub(last_part, search_index, #last_part)
  556. local prefix_match_pat = string.sub(pat, 1, #pat - #match_part) or ''
  557. local final_env = env
  558. for _, part in ipairs(parts) do
  559. if type(final_env) ~= 'table' then
  560. return {}, 0
  561. end
  562. local key
  563. -- Normally, we just have a string
  564. -- Just attempt to get the string directly from the environment
  565. if type(part) == 'string' then
  566. key = part
  567. else
  568. -- However, sometimes you want to use a variable, and complete on it
  569. -- With this, you have the power.
  570. -- MY_VAR = "api"
  571. -- vim[MY_VAR]
  572. -- -> _G[MY_VAR] -> "api"
  573. local result_key = part[1]
  574. if not result_key then
  575. return {}, 0
  576. end
  577. local result = rawget(env, result_key)
  578. if result == nil then
  579. return {}, 0
  580. end
  581. key = result
  582. end
  583. local field = rawget(final_env, key)
  584. if field == nil then
  585. local mt = getmetatable(final_env)
  586. if mt and type(mt.__index) == 'table' then
  587. field = rawget(mt.__index, key)
  588. elseif final_env == vim and vim._submodules[key] then
  589. field = vim[key]
  590. end
  591. end
  592. final_env = field
  593. if not final_env then
  594. return {}, 0
  595. end
  596. end
  597. local keys = {}
  598. ---@private
  599. local function insert_keys(obj)
  600. for k, _ in pairs(obj) do
  601. if type(k) == 'string' and string.sub(k, 1, string.len(match_part)) == match_part then
  602. keys[k] = true
  603. end
  604. end
  605. end
  606. if type(final_env) == 'table' then
  607. insert_keys(final_env)
  608. end
  609. local mt = getmetatable(final_env)
  610. if mt and type(mt.__index) == 'table' then
  611. insert_keys(mt.__index)
  612. end
  613. if final_env == vim then
  614. insert_keys(vim._submodules)
  615. end
  616. keys = vim.tbl_keys(keys)
  617. table.sort(keys)
  618. return keys, #prefix_match_pat
  619. end
  620. vim._expand_pat_get_parts = function(lua_string)
  621. local parts = {}
  622. local accumulator, search_index = '', 1
  623. local in_brackets, bracket_end = false, -1
  624. local string_char = nil
  625. for idx = 1, #lua_string do
  626. local s = lua_string:sub(idx, idx)
  627. if not in_brackets and (s == '.' or s == ':') then
  628. table.insert(parts, accumulator)
  629. accumulator = ''
  630. search_index = idx + 1
  631. elseif s == '[' then
  632. in_brackets = true
  633. table.insert(parts, accumulator)
  634. accumulator = ''
  635. search_index = idx + 1
  636. elseif in_brackets then
  637. if idx == bracket_end then
  638. in_brackets = false
  639. search_index = idx + 1
  640. if string_char == 'VAR' then
  641. table.insert(parts, { accumulator })
  642. accumulator = ''
  643. string_char = nil
  644. end
  645. elseif not string_char then
  646. bracket_end = string.find(lua_string, ']', idx, true)
  647. if s == '"' or s == "'" then
  648. string_char = s
  649. elseif s ~= ' ' then
  650. string_char = 'VAR'
  651. accumulator = s
  652. end
  653. elseif string_char then
  654. if string_char ~= s then
  655. accumulator = accumulator .. s
  656. else
  657. table.insert(parts, accumulator)
  658. accumulator = ''
  659. string_char = nil
  660. end
  661. end
  662. else
  663. accumulator = accumulator .. s
  664. end
  665. end
  666. parts = vim.tbl_filter(function(val)
  667. return #val > 0
  668. end, parts)
  669. return parts, search_index
  670. end
  671. ---Prints given arguments in human-readable format.
  672. ---Example:
  673. ---<pre>
  674. --- -- Print highlight group Normal and store it's contents in a variable.
  675. --- local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true))
  676. ---</pre>
  677. ---@see |vim.inspect()|
  678. ---@return given arguments.
  679. function vim.pretty_print(...)
  680. local objects = {}
  681. for i = 1, select('#', ...) do
  682. local v = select(i, ...)
  683. table.insert(objects, vim.inspect(v))
  684. end
  685. print(table.concat(objects, ' '))
  686. return ...
  687. end
  688. function vim._cs_remote(rcid, server_addr, connect_error, args)
  689. local function connection_failure_errmsg(consequence)
  690. local explanation
  691. if server_addr == '' then
  692. explanation = 'No server specified with --server'
  693. else
  694. explanation = "Failed to connect to '" .. server_addr .. "'"
  695. if connect_error ~= '' then
  696. explanation = explanation .. ': ' .. connect_error
  697. end
  698. end
  699. return 'E247: ' .. explanation .. '. ' .. consequence
  700. end
  701. local f_silent = false
  702. local f_tab = false
  703. local subcmd = string.sub(args[1], 10)
  704. if subcmd == 'tab' then
  705. f_tab = true
  706. elseif subcmd == 'silent' then
  707. f_silent = true
  708. elseif
  709. subcmd == 'wait'
  710. or subcmd == 'wait-silent'
  711. or subcmd == 'tab-wait'
  712. or subcmd == 'tab-wait-silent'
  713. then
  714. return { errmsg = 'E5600: Wait commands not yet implemented in nvim' }
  715. elseif subcmd == 'tab-silent' then
  716. f_tab = true
  717. f_silent = true
  718. elseif subcmd == 'send' then
  719. if rcid == 0 then
  720. return { errmsg = connection_failure_errmsg('Send failed.') }
  721. end
  722. vim.fn.rpcrequest(rcid, 'nvim_input', args[2])
  723. return { should_exit = true, tabbed = false }
  724. elseif subcmd == 'expr' then
  725. if rcid == 0 then
  726. return { errmsg = connection_failure_errmsg('Send expression failed.') }
  727. end
  728. print(vim.fn.rpcrequest(rcid, 'nvim_eval', args[2]))
  729. return { should_exit = true, tabbed = false }
  730. elseif subcmd ~= '' then
  731. return { errmsg = 'Unknown option argument: ' .. args[1] }
  732. end
  733. if rcid == 0 then
  734. if not f_silent then
  735. vim.notify(connection_failure_errmsg('Editing locally'), vim.log.levels.WARN)
  736. end
  737. else
  738. local command = {}
  739. if f_tab then
  740. table.insert(command, 'tab')
  741. end
  742. table.insert(command, 'drop')
  743. for i = 2, #args do
  744. table.insert(command, vim.fn.fnameescape(args[i]))
  745. end
  746. vim.fn.rpcrequest(rcid, 'nvim_command', table.concat(command, ' '))
  747. end
  748. return {
  749. should_exit = rcid ~= 0,
  750. tabbed = f_tab,
  751. }
  752. end
  753. --- Display a deprecation notification to the user.
  754. ---
  755. ---@param name string Deprecated function.
  756. ---@param alternative string|nil Preferred alternative function.
  757. ---@param version string Version in which the deprecated function will
  758. --- be removed.
  759. ---@param plugin string|nil Plugin name that the function will be removed
  760. --- from. Defaults to "Nvim".
  761. ---@param backtrace boolean|nil Prints backtrace. Defaults to true.
  762. function vim.deprecate(name, alternative, version, plugin, backtrace)
  763. local message = name .. ' is deprecated'
  764. plugin = plugin or 'Nvim'
  765. message = alternative and (message .. ', use ' .. alternative .. ' instead.') or message
  766. message = message
  767. .. ' See :h deprecated\nThis function will be removed in '
  768. .. plugin
  769. .. ' version '
  770. .. version
  771. if vim.notify_once(message, vim.log.levels.WARN) and backtrace ~= false then
  772. vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN)
  773. end
  774. end
  775. --- Create builtin mappings (incl. menus).
  776. --- Called once on startup.
  777. function vim._init_default_mappings()
  778. -- mappings
  779. --@private
  780. local function map(mode, lhs, rhs)
  781. vim.api.nvim_set_keymap(mode, lhs, rhs, { noremap = true, desc = 'Nvim builtin' })
  782. end
  783. map('n', 'Y', 'y$')
  784. -- Use normal! <C-L> to prevent inserting raw <C-L> when using i_<C-O>. #17473
  785. map('n', '<C-L>', '<Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>')
  786. map('i', '<C-U>', '<C-G>u<C-U>')
  787. map('i', '<C-W>', '<C-G>u<C-W>')
  788. map('x', '*', 'y/\\V<C-R>"<CR>')
  789. map('x', '#', 'y?\\V<C-R>"<CR>')
  790. -- Use : instead of <Cmd> so that ranges are supported. #19365
  791. map('n', '&', ':&&<CR>')
  792. -- menus
  793. -- TODO VimScript, no l10n
  794. vim.cmd([[
  795. aunmenu *
  796. vnoremenu PopUp.Cut "+x
  797. vnoremenu PopUp.Copy "+y
  798. anoremenu PopUp.Paste "+gP
  799. vnoremenu PopUp.Paste "+P
  800. vnoremenu PopUp.Delete "_x
  801. nnoremenu PopUp.Select\ All ggVG
  802. vnoremenu PopUp.Select\ All gg0oG$
  803. inoremenu PopUp.Select\ All <C-Home><C-O>VG
  804. anoremenu PopUp.-1- <Nop>
  805. anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR>
  806. ]])
  807. end
  808. require('vim._meta')
  809. return vim