_editor.lua 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. -- Nvim-Lua stdlib: the `vim` module (:help lua-stdlib)
  2. --
  3. -- Lua code lives in one of four places:
  4. -- 1. Plugins! Not everything needs to live on "vim.*". Plugins are the correct model for
  5. -- non-essential features which the user may want to disable or replace with a third-party
  6. -- plugin. Examples: "editorconfig", "comment".
  7. -- - "opt-out": runtime/plugin/*.lua
  8. -- - "opt-in": runtime/pack/dist/opt/
  9. -- 2. runtime/lua/vim/ (the runtime): Lazy-loaded modules. Examples: `inspect`, `lpeg`.
  10. -- 3. runtime/lua/vim/shared.lua: pure Lua functions which always are available. Used in the test
  11. -- runner, as well as worker threads and processes launched from Nvim.
  12. -- 4. runtime/lua/vim/_editor.lua: Eager-loaded code which directly interacts with the Nvim
  13. -- editor state. Only available in the main thread.
  14. --
  15. -- The top level "vim.*" namespace is for fundamental Lua and editor features. Use submodules for
  16. -- everything else (but avoid excessive "nesting"), or plugins (see above).
  17. --
  18. -- Compatibility with Vim's `if_lua` is explicitly a non-goal.
  19. --
  20. -- Reference (#6580):
  21. -- - https://github.com/luafun/luafun
  22. -- - https://github.com/rxi/lume
  23. -- - http://leafo.net/lapis/reference/utilities.html
  24. -- - https://github.com/bakpakin/Fennel (pretty print, repl)
  25. -- These are for loading runtime modules lazily since they aren't available in
  26. -- the nvim binary as specified in executor.c
  27. for k, v in pairs({
  28. treesitter = true,
  29. filetype = true,
  30. loader = true,
  31. func = true,
  32. F = true,
  33. lsp = true,
  34. hl = true,
  35. diagnostic = true,
  36. keymap = true,
  37. ui = true,
  38. health = true,
  39. secure = true,
  40. snippet = true,
  41. _watch = true,
  42. }) do
  43. vim._submodules[k] = v
  44. end
  45. -- There are things which have special rules in vim._init_packages
  46. -- for legacy reasons (uri) or for performance (_inspector).
  47. -- most new things should go into a submodule namespace ( vim.foobar.do_thing() )
  48. vim._extra = {
  49. uri_from_fname = true,
  50. uri_from_bufnr = true,
  51. uri_to_fname = true,
  52. uri_to_bufnr = true,
  53. show_pos = true,
  54. inspect_pos = true,
  55. }
  56. --- @nodoc
  57. vim.log = {
  58. --- @enum vim.log.levels
  59. levels = {
  60. TRACE = 0,
  61. DEBUG = 1,
  62. INFO = 2,
  63. WARN = 3,
  64. ERROR = 4,
  65. OFF = 5,
  66. },
  67. }
  68. local utfs = {
  69. ['utf-8'] = true,
  70. ['utf-16'] = true,
  71. ['utf-32'] = true,
  72. }
  73. -- TODO(lewis6991): document that the signature is system({cmd}, [{opts},] {on_exit})
  74. --- Runs a system command or throws an error if {cmd} cannot be run.
  75. ---
  76. --- Examples:
  77. ---
  78. --- ```lua
  79. --- local on_exit = function(obj)
  80. --- print(obj.code)
  81. --- print(obj.signal)
  82. --- print(obj.stdout)
  83. --- print(obj.stderr)
  84. --- end
  85. ---
  86. --- -- Runs asynchronously:
  87. --- vim.system({'echo', 'hello'}, { text = true }, on_exit)
  88. ---
  89. --- -- Runs synchronously:
  90. --- local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
  91. --- -- { code = 0, signal = 0, stdout = 'hello\n', stderr = '' }
  92. ---
  93. --- ```
  94. ---
  95. --- See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system
  96. --- throws an error if {cmd} cannot be run.
  97. ---
  98. --- @param cmd (string[]) Command to execute
  99. --- @param opts vim.SystemOpts? Options:
  100. --- - cwd: (string) Set the current working directory for the sub-process.
  101. --- - env: table<string,string> Set environment variables for the new process. Inherits the
  102. --- current environment with `NVIM` set to |v:servername|.
  103. --- - clear_env: (boolean) `env` defines the job environment exactly, instead of merging current
  104. --- environment.
  105. --- - stdin: (string|string[]|boolean) If `true`, then a pipe to stdin is opened and can be written
  106. --- to via the `write()` method to SystemObj. If string or string[] then will be written to stdin
  107. --- and closed. Defaults to `false`.
  108. --- - stdout: (boolean|function)
  109. --- Handle output from stdout. When passed as a function must have the signature `fun(err: string, data: string)`.
  110. --- Defaults to `true`
  111. --- - stderr: (boolean|function)
  112. --- Handle output from stderr. When passed as a function must have the signature `fun(err: string, data: string)`.
  113. --- Defaults to `true`.
  114. --- - text: (boolean) Handle stdout and stderr as text. Replaces `\r\n` with `\n`.
  115. --- - timeout: (integer) Run the command with a time limit. Upon timeout the process is sent the
  116. --- TERM signal (15) and the exit code is set to 124.
  117. --- - detach: (boolean) If true, spawn the child process in a detached state - this will make it
  118. --- a process group leader, and will effectively enable the child to keep running after the
  119. --- parent exits. Note that the child process will still keep the parent's event loop alive
  120. --- unless the parent process calls |uv.unref()| on the child's process handle.
  121. ---
  122. --- @param on_exit? fun(out: vim.SystemCompleted) Called when subprocess exits. When provided, the command runs
  123. --- asynchronously. Receives SystemCompleted object, see return of SystemObj:wait().
  124. ---
  125. --- @return vim.SystemObj Object with the fields:
  126. --- - cmd (string[]) Command name and args
  127. --- - pid (integer) Process ID
  128. --- - wait (fun(timeout: integer|nil): SystemCompleted) Wait for the process to complete. Upon
  129. --- timeout the process is sent the KILL signal (9) and the exit code is set to 124. Cannot
  130. --- be called in |api-fast|.
  131. --- - SystemCompleted is an object with the fields:
  132. --- - code: (integer)
  133. --- - signal: (integer)
  134. --- - stdout: (string), nil if stdout argument is passed
  135. --- - stderr: (string), nil if stderr argument is passed
  136. --- - kill (fun(signal: integer|string))
  137. --- - write (fun(data: string|nil)) Requires `stdin=true`. Pass `nil` to close the stream.
  138. --- - is_closing (fun(): boolean)
  139. function vim.system(cmd, opts, on_exit)
  140. if type(opts) == 'function' then
  141. on_exit = opts
  142. opts = nil
  143. end
  144. return require('vim._system').run(cmd, opts, on_exit)
  145. end
  146. -- Gets process info from the `ps` command.
  147. -- Used by nvim_get_proc() as a fallback.
  148. function vim._os_proc_info(pid)
  149. if pid == nil or pid <= 0 or type(pid) ~= 'number' then
  150. error('invalid pid')
  151. end
  152. local cmd = { 'ps', '-p', pid, '-o', 'comm=' }
  153. local r = vim.system(cmd):wait()
  154. local name = assert(r.stdout)
  155. if r.code == 1 and vim.trim(name) == '' then
  156. return {} -- Process not found.
  157. elseif r.code ~= 0 then
  158. error('command failed: ' .. vim.fn.string(cmd))
  159. end
  160. local ppid_string = assert(vim.system({ 'ps', '-p', pid, '-o', 'ppid=' }):wait().stdout)
  161. -- Remove trailing whitespace.
  162. name = vim.trim(name):gsub('^.*/', '')
  163. local ppid = tonumber(ppid_string) or -1
  164. return {
  165. name = name,
  166. pid = pid,
  167. ppid = ppid,
  168. }
  169. end
  170. -- Gets process children from the `pgrep` command.
  171. -- Used by nvim_get_proc_children() as a fallback.
  172. function vim._os_proc_children(ppid)
  173. if ppid == nil or ppid <= 0 or type(ppid) ~= 'number' then
  174. error('invalid ppid')
  175. end
  176. local cmd = { 'pgrep', '-P', ppid }
  177. local r = vim.system(cmd):wait()
  178. if r.code == 1 and vim.trim(r.stdout) == '' then
  179. return {} -- Process not found.
  180. elseif r.code ~= 0 then
  181. error('command failed: ' .. vim.fn.string(cmd))
  182. end
  183. local children = {}
  184. for s in r.stdout:gmatch('%S+') do
  185. local i = tonumber(s)
  186. if i ~= nil then
  187. table.insert(children, i)
  188. end
  189. end
  190. return children
  191. end
  192. --- @nodoc
  193. --- @class vim.inspect.Opts
  194. --- @field depth? integer
  195. --- @field newline? string
  196. --- @field process? fun(item:any, path: string[]): any
  197. --- Gets a human-readable representation of the given object.
  198. ---
  199. ---@see |vim.print()|
  200. ---@see https://github.com/kikito/inspect.lua
  201. ---@see https://github.com/mpeterv/vinspect
  202. ---@return string
  203. ---@overload fun(x: any, opts?: vim.inspect.Opts): string
  204. vim.inspect = vim.inspect
  205. do
  206. local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false
  207. --- Paste handler, invoked by |nvim_paste()|.
  208. ---
  209. --- Note: This is provided only as a "hook", don't call it directly; call |nvim_paste()| instead,
  210. --- which arranges redo (dot-repeat) and invokes `vim.paste`.
  211. ---
  212. --- Example: To remove ANSI color codes when pasting:
  213. ---
  214. --- ```lua
  215. --- vim.paste = (function(overridden)
  216. --- return function(lines, phase)
  217. --- for i,line in ipairs(lines) do
  218. --- -- Scrub ANSI color codes from paste input.
  219. --- lines[i] = line:gsub('\27%[[0-9;mK]+', '')
  220. --- end
  221. --- return overridden(lines, phase)
  222. --- end
  223. --- end)(vim.paste)
  224. --- ```
  225. ---
  226. ---@see |paste|
  227. ---
  228. ---@param lines string[] # |readfile()|-style list of lines to paste. |channel-lines|
  229. ---@param phase (-1|1|2|3) -1: "non-streaming" paste: the call contains all lines.
  230. --- If paste is "streamed", `phase` indicates the stream state:
  231. --- - 1: starts the paste (exactly once)
  232. --- - 2: continues the paste (zero or more times)
  233. --- - 3: ends the paste (exactly once)
  234. ---@return boolean result false if client should cancel the paste.
  235. function vim.paste(lines, phase)
  236. local now = vim.uv.now()
  237. local is_first_chunk = phase < 2
  238. local is_last_chunk = phase == -1 or phase == 3
  239. if is_first_chunk then -- Reset flags.
  240. tdots, tick, got_line1, undo_started, trailing_nl = now, 0, false, false, false
  241. end
  242. if #lines == 0 then
  243. lines = { '' }
  244. end
  245. if #lines == 1 and lines[1] == '' and not is_last_chunk then
  246. -- An empty chunk can cause some edge cases in streamed pasting,
  247. -- so don't do anything unless it is the last chunk.
  248. return true
  249. end
  250. -- Note: mode doesn't always start with "c" in cmdline mode, so use getcmdtype() instead.
  251. if vim.fn.getcmdtype() ~= '' then -- cmdline-mode: paste only 1 line.
  252. if not got_line1 then
  253. got_line1 = (#lines > 1)
  254. -- Escape control characters
  255. local line1 = lines[1]:gsub('(%c)', '\022%1')
  256. -- nvim_input() is affected by mappings,
  257. -- so use nvim_feedkeys() with "n" flag to ignore mappings.
  258. -- "t" flag is also needed so the pasted text is saved in cmdline history.
  259. vim.api.nvim_feedkeys(line1, 'nt', true)
  260. end
  261. return true
  262. end
  263. local mode = vim.api.nvim_get_mode().mode
  264. if undo_started then
  265. vim.api.nvim_command('undojoin')
  266. end
  267. if mode:find('^i') or mode:find('^n?t') then -- Insert mode or Terminal buffer
  268. vim.api.nvim_put(lines, 'c', false, true)
  269. elseif phase < 2 and mode:find('^R') and not mode:find('^Rv') then -- Replace mode
  270. -- TODO: implement Replace mode streamed pasting
  271. -- TODO: support Virtual Replace mode
  272. local nchars = 0
  273. for _, line in ipairs(lines) do
  274. nchars = nchars + line:len()
  275. end
  276. --- @type integer, integer
  277. local row, col = unpack(vim.api.nvim_win_get_cursor(0))
  278. local bufline = vim.api.nvim_buf_get_lines(0, row - 1, row, true)[1]
  279. local firstline = lines[1]
  280. firstline = bufline:sub(1, col) .. firstline
  281. lines[1] = firstline
  282. lines[#lines] = lines[#lines] .. bufline:sub(col + nchars + 1, bufline:len())
  283. vim.api.nvim_buf_set_lines(0, row - 1, row, false, lines)
  284. elseif mode:find('^[nvV\22sS\19]') then -- Normal or Visual or Select mode
  285. if mode:find('^n') then -- Normal mode
  286. -- When there was a trailing new line in the previous chunk,
  287. -- the cursor is on the first character of the next line,
  288. -- so paste before the cursor instead of after it.
  289. vim.api.nvim_put(lines, 'c', not trailing_nl, false)
  290. else -- Visual or Select mode
  291. vim.api.nvim_command([[exe "silent normal! \<Del>"]])
  292. local del_start = vim.fn.getpos("'[")
  293. local cursor_pos = vim.fn.getpos('.')
  294. if mode:find('^[VS]') then -- linewise
  295. if cursor_pos[2] < del_start[2] then -- replacing lines at eof
  296. -- create a new line
  297. vim.api.nvim_put({ '' }, 'l', true, true)
  298. end
  299. vim.api.nvim_put(lines, 'c', false, false)
  300. else
  301. -- paste after cursor when replacing text at eol, otherwise paste before cursor
  302. vim.api.nvim_put(lines, 'c', cursor_pos[3] < del_start[3], false)
  303. end
  304. end
  305. -- put cursor at the end of the text instead of one character after it
  306. vim.fn.setpos('.', vim.fn.getpos("']"))
  307. trailing_nl = lines[#lines] == ''
  308. else -- Don't know what to do in other modes
  309. return false
  310. end
  311. undo_started = true
  312. if phase ~= -1 and (now - tdots >= 100) then
  313. local dots = ('.'):rep(tick % 4)
  314. tdots = now
  315. tick = tick + 1
  316. -- Use :echo because Lua print('') is a no-op, and we want to clear the
  317. -- message when there are zero dots.
  318. vim.api.nvim_command(('echo "%s"'):format(dots))
  319. end
  320. if is_last_chunk then
  321. vim.api.nvim_command('redraw' .. (tick > 1 and '|echo ""' or ''))
  322. end
  323. return true -- Paste will not continue if not returning `true`.
  324. end
  325. end
  326. --- Returns a function which calls {fn} via |vim.schedule()|.
  327. ---
  328. --- The returned function passes all arguments to {fn}.
  329. ---
  330. --- Example:
  331. ---
  332. --- ```lua
  333. --- function notify_readable(_err, readable)
  334. --- vim.notify("readable? " .. tostring(readable))
  335. --- end
  336. --- vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable))
  337. --- ```
  338. ---
  339. ---@see |lua-loop-callbacks|
  340. ---@see |vim.schedule()|
  341. ---@see |vim.in_fast_event()|
  342. ---@param fn function
  343. ---@return function
  344. function vim.schedule_wrap(fn)
  345. return function(...)
  346. local args = vim.F.pack_len(...)
  347. vim.schedule(function()
  348. fn(vim.F.unpack_len(args))
  349. end)
  350. end
  351. end
  352. -- vim.fn.{func}(...)
  353. ---@nodoc
  354. vim.fn = setmetatable({}, {
  355. --- @param t table<string,function>
  356. --- @param key string
  357. --- @return function
  358. __index = function(t, key)
  359. local _fn --- @type function
  360. if vim.api[key] ~= nil then
  361. _fn = function()
  362. error(string.format('Tried to call API function with vim.fn: use vim.api.%s instead', key))
  363. end
  364. else
  365. _fn = function(...)
  366. return vim.call(key, ...)
  367. end
  368. end
  369. t[key] = _fn
  370. return _fn
  371. end,
  372. })
  373. --- @private
  374. vim.funcref = function(viml_func_name)
  375. return vim.fn[viml_func_name]
  376. end
  377. local VIM_CMD_ARG_MAX = 20
  378. --- Executes Vimscript (|Ex-commands|).
  379. ---
  380. --- Note that `vim.cmd` can be indexed with a command name to return a callable function to the
  381. --- command.
  382. ---
  383. --- Example:
  384. ---
  385. --- ```lua
  386. --- vim.cmd('echo 42')
  387. --- vim.cmd([[
  388. --- augroup My_group
  389. --- autocmd!
  390. --- autocmd FileType c setlocal cindent
  391. --- augroup END
  392. --- ]])
  393. ---
  394. --- -- Ex command :echo "foo"
  395. --- -- Note string literals need to be double quoted.
  396. --- vim.cmd('echo "foo"')
  397. --- vim.cmd { cmd = 'echo', args = { '"foo"' } }
  398. --- vim.cmd.echo({ args = { '"foo"' } })
  399. --- vim.cmd.echo('"foo"')
  400. ---
  401. --- -- Ex command :write! myfile.txt
  402. --- vim.cmd('write! myfile.txt')
  403. --- vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
  404. --- vim.cmd.write { args = { "myfile.txt" }, bang = true }
  405. --- vim.cmd.write { "myfile.txt", bang = true }
  406. ---
  407. --- -- Ex command :colorscheme blue
  408. --- vim.cmd('colorscheme blue')
  409. --- vim.cmd.colorscheme('blue')
  410. --- ```
  411. ---
  412. ---@diagnostic disable-next-line: undefined-doc-param
  413. ---@param command string|table Command(s) to execute.
  414. --- If a string, executes multiple lines of Vimscript at once. In this
  415. --- case, it is an alias to |nvim_exec2()|, where `opts.output` is set
  416. --- to false. Thus it works identical to |:source|.
  417. --- If a table, executes a single command. In this case, it is an alias
  418. --- to |nvim_cmd()| where `opts` is empty.
  419. ---@see |ex-cmd-index|
  420. vim.cmd = setmetatable({}, {
  421. __call = function(_, command)
  422. if type(command) == 'table' then
  423. return vim.api.nvim_cmd(command, {})
  424. else
  425. vim.api.nvim_exec2(command, {})
  426. return ''
  427. end
  428. end,
  429. --- @param t table<string,function>
  430. __index = function(t, command)
  431. t[command] = function(...)
  432. local opts --- @type vim.api.keyset.cmd
  433. if select('#', ...) == 1 and type(select(1, ...)) == 'table' then
  434. --- @type vim.api.keyset.cmd
  435. opts = select(1, ...)
  436. -- Move indexed positions in opts to opt.args
  437. if opts[1] and not opts.args then
  438. opts.args = {}
  439. for i = 1, VIM_CMD_ARG_MAX do
  440. if not opts[i] then
  441. break
  442. end
  443. opts.args[i] = opts[i]
  444. --- @diagnostic disable-next-line: no-unknown
  445. opts[i] = nil
  446. end
  447. end
  448. else
  449. opts = { args = { ... } }
  450. end
  451. opts.cmd = command
  452. return vim.api.nvim_cmd(opts, {})
  453. end
  454. return t[command]
  455. end,
  456. })
  457. --- @class (private) vim.var_accessor
  458. --- @field [string] any
  459. --- @field [integer] vim.var_accessor
  460. -- These are the vim.env/v/g/o/bo/wo variable magic accessors.
  461. do
  462. --- @param scope string
  463. --- @param handle? false|integer
  464. --- @return vim.var_accessor
  465. local function make_dict_accessor(scope, handle)
  466. vim.validate('scope', scope, 'string')
  467. local mt = {}
  468. function mt:__newindex(k, v)
  469. return vim._setvar(scope, handle or 0, k, v)
  470. end
  471. function mt:__index(k)
  472. if handle == nil and type(k) == 'number' then
  473. return make_dict_accessor(scope, k)
  474. end
  475. return vim._getvar(scope, handle or 0, k)
  476. end
  477. return setmetatable({}, mt)
  478. end
  479. vim.g = make_dict_accessor('g', false)
  480. vim.v = make_dict_accessor('v', false) --[[@as vim.v]]
  481. vim.b = make_dict_accessor('b')
  482. vim.w = make_dict_accessor('w')
  483. vim.t = make_dict_accessor('t')
  484. end
  485. --- @deprecated
  486. --- Gets a dict of line segment ("chunk") positions for the region from `pos1` to `pos2`.
  487. ---
  488. --- Input and output positions are byte positions, (0,0)-indexed. "End of line" column
  489. --- position (for example, |linewise| visual selection) is returned as |v:maxcol| (big number).
  490. ---
  491. ---@param bufnr integer Buffer number, or 0 for current buffer
  492. ---@param pos1 integer[]|string Start of region as a (line, column) tuple or |getpos()|-compatible string
  493. ---@param pos2 integer[]|string End of region as a (line, column) tuple or |getpos()|-compatible string
  494. ---@param regtype string [setreg()]-style selection type
  495. ---@param inclusive boolean Controls whether the ending column is inclusive (see also 'selection').
  496. ---@return table region Dict of the form `{linenr = {startcol,endcol}}`. `endcol` is exclusive, and
  497. ---whole lines are returned as `{startcol,endcol} = {0,-1}`.
  498. function vim.region(bufnr, pos1, pos2, regtype, inclusive)
  499. vim.deprecate('vim.region', 'vim.fn.getregionpos()', '0.13')
  500. if not vim.api.nvim_buf_is_loaded(bufnr) then
  501. vim.fn.bufload(bufnr)
  502. end
  503. if type(pos1) == 'string' then
  504. local pos = vim.fn.getpos(pos1)
  505. pos1 = { pos[2] - 1, pos[3] - 1 }
  506. end
  507. if type(pos2) == 'string' then
  508. local pos = vim.fn.getpos(pos2)
  509. pos2 = { pos[2] - 1, pos[3] - 1 }
  510. end
  511. if pos1[1] > pos2[1] or (pos1[1] == pos2[1] and pos1[2] > pos2[2]) then
  512. pos1, pos2 = pos2, pos1 --- @type [integer, integer], [integer, integer]
  513. end
  514. -- getpos() may return {0,0,0,0}
  515. if pos1[1] < 0 or pos1[2] < 0 then
  516. return {}
  517. end
  518. -- check that region falls within current buffer
  519. local buf_line_count = vim.api.nvim_buf_line_count(bufnr)
  520. pos1[1] = math.min(pos1[1], buf_line_count - 1)
  521. pos2[1] = math.min(pos2[1], buf_line_count - 1)
  522. -- in case of block selection, columns need to be adjusted for non-ASCII characters
  523. -- TODO: handle double-width characters
  524. if regtype:byte() == 22 then
  525. local bufline = vim.api.nvim_buf_get_lines(bufnr, pos1[1], pos1[1] + 1, true)[1]
  526. pos1[2] = vim.str_utfindex(bufline, 'utf-32', pos1[2])
  527. end
  528. local region = {}
  529. for l = pos1[1], pos2[1] do
  530. local c1 --- @type number
  531. local c2 --- @type number
  532. if regtype:byte() == 22 then -- block selection: take width from regtype
  533. c1 = pos1[2]
  534. c2 = c1 + tonumber(regtype:sub(2))
  535. -- and adjust for non-ASCII characters
  536. local bufline = vim.api.nvim_buf_get_lines(bufnr, l, l + 1, true)[1]
  537. local utflen = vim.str_utfindex(bufline, 'utf-32', #bufline)
  538. if c1 <= utflen then
  539. c1 = assert(tonumber(vim.str_byteindex(bufline, 'utf-32', c1)))
  540. else
  541. c1 = #bufline + 1
  542. end
  543. if c2 <= utflen then
  544. c2 = assert(tonumber(vim.str_byteindex(bufline, 'utf-32', c2)))
  545. else
  546. c2 = #bufline + 1
  547. end
  548. elseif regtype == 'V' then -- linewise selection, always return whole line
  549. c1 = 0
  550. c2 = -1
  551. else
  552. c1 = (l == pos1[1]) and pos1[2] or 0
  553. if inclusive and l == pos2[1] then
  554. local bufline = vim.api.nvim_buf_get_lines(bufnr, pos2[1], pos2[1] + 1, true)[1]
  555. pos2[2] = vim.fn.byteidx(bufline, vim.fn.charidx(bufline, pos2[2]) + 1)
  556. end
  557. c2 = (l == pos2[1]) and pos2[2] or -1
  558. end
  559. table.insert(region, l, { c1, c2 })
  560. end
  561. return region
  562. end
  563. --- Defers calling {fn} until {timeout} ms passes.
  564. ---
  565. --- Use to do a one-shot timer that calls {fn}
  566. --- Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are
  567. --- safe to call.
  568. ---@param fn function Callback to call once `timeout` expires
  569. ---@param timeout integer Number of milliseconds to wait before calling `fn`
  570. ---@return table timer luv timer object
  571. function vim.defer_fn(fn, timeout)
  572. vim.validate('fn', fn, 'callable', true)
  573. local timer = assert(vim.uv.new_timer())
  574. timer:start(
  575. timeout,
  576. 0,
  577. vim.schedule_wrap(function()
  578. if not timer:is_closing() then
  579. timer:close()
  580. end
  581. fn()
  582. end)
  583. )
  584. return timer
  585. end
  586. --- Displays a notification to the user.
  587. ---
  588. --- This function can be overridden by plugins to display notifications using
  589. --- a custom provider (such as the system notification provider). By default,
  590. --- writes to |:messages|.
  591. ---@param msg string Content of the notification to show to the user.
  592. ---@param level integer|nil One of the values from |vim.log.levels|.
  593. ---@param opts table|nil Optional parameters. Unused by default.
  594. ---@diagnostic disable-next-line: unused-local
  595. function vim.notify(msg, level, opts) -- luacheck: no unused args
  596. local chunks = { { msg, level == vim.log.levels.WARN and 'WarningMsg' or nil } }
  597. vim.api.nvim_echo(chunks, true, { err = level == vim.log.levels.ERROR })
  598. end
  599. do
  600. local notified = {} --- @type table<string,true>
  601. --- Displays a notification only one time.
  602. ---
  603. --- Like |vim.notify()|, but subsequent calls with the same message will not
  604. --- display a notification.
  605. ---
  606. ---@param msg string Content of the notification to show to the user.
  607. ---@param level integer|nil One of the values from |vim.log.levels|.
  608. ---@param opts table|nil Optional parameters. Unused by default.
  609. ---@return boolean true if message was displayed, else false
  610. function vim.notify_once(msg, level, opts)
  611. if not notified[msg] then
  612. vim.notify(msg, level, opts)
  613. notified[msg] = true
  614. return true
  615. end
  616. return false
  617. end
  618. end
  619. local on_key_cbs = {} --- @type table<integer,[function, table]>
  620. --- Adds Lua function {fn} with namespace id {ns_id} as a listener to every,
  621. --- yes every, input key.
  622. ---
  623. --- The Nvim command-line option |-w| is related but does not support callbacks
  624. --- and cannot be toggled dynamically.
  625. ---
  626. ---@note {fn} will be removed on error.
  627. ---@note {fn} won't be invoked recursively, i.e. if {fn} itself consumes input,
  628. --- it won't be invoked for those keys.
  629. ---@note {fn} will not be cleared by |nvim_buf_clear_namespace()|
  630. ---
  631. ---@param fn nil|fun(key: string, typed: string): string? Function invoked for every input key,
  632. --- after mappings have been applied but before further processing. Arguments
  633. --- {key} and {typed} are raw keycodes, where {key} is the key after mappings
  634. --- are applied, and {typed} is the key(s) before mappings are applied.
  635. --- {typed} may be empty if {key} is produced by non-typed key(s) or by the
  636. --- same typed key(s) that produced a previous {key}.
  637. --- If {fn} returns an empty string, {key} is discarded/ignored.
  638. --- When {fn} is `nil`, the callback associated with namespace {ns_id} is removed.
  639. ---@param ns_id integer? Namespace ID. If nil or 0, generates and returns a
  640. --- new |nvim_create_namespace()| id.
  641. ---@param opts table? Optional parameters
  642. ---
  643. ---@see |keytrans()|
  644. ---
  645. ---@return integer Namespace id associated with {fn}. Or count of all callbacks
  646. ---if on_key() is called without arguments.
  647. function vim.on_key(fn, ns_id, opts)
  648. if fn == nil and ns_id == nil then
  649. return vim.tbl_count(on_key_cbs)
  650. end
  651. vim.validate('fn', fn, 'callable', true)
  652. vim.validate('ns_id', ns_id, 'number', true)
  653. vim.validate('opts', opts, 'table', true)
  654. opts = opts or {}
  655. if ns_id == nil or ns_id == 0 then
  656. ns_id = vim.api.nvim_create_namespace('')
  657. end
  658. on_key_cbs[ns_id] = fn and { fn, opts }
  659. return ns_id
  660. end
  661. --- Executes the on_key callbacks.
  662. ---@private
  663. function vim._on_key(buf, typed_buf)
  664. local failed = {} ---@type [integer, string][]
  665. local discard = false
  666. for k, v in pairs(on_key_cbs) do
  667. local fn = v[1]
  668. --- @type boolean, any
  669. local ok, rv = xpcall(function()
  670. return fn(buf, typed_buf)
  671. end, debug.traceback)
  672. if ok and rv ~= nil then
  673. if type(rv) == 'string' and #rv == 0 then
  674. discard = true
  675. -- break -- Without break deliver to all callbacks even when it eventually discards.
  676. -- "break" does not make sense unless callbacks are sorted by ???.
  677. else
  678. ok = false
  679. rv = 'return string must be empty'
  680. end
  681. end
  682. if not ok then
  683. vim.on_key(nil, k)
  684. table.insert(failed, { k, rv })
  685. end
  686. end
  687. if #failed > 0 then
  688. local errmsg = ''
  689. for _, v in ipairs(failed) do
  690. errmsg = errmsg .. string.format('\nWith ns_id %d: %s', v[1], v[2])
  691. end
  692. error(errmsg)
  693. end
  694. return discard
  695. end
  696. --- Convert UTF-32, UTF-16 or UTF-8 {index} to byte index.
  697. --- If {strict_indexing} is false
  698. --- then then an out of range index will return byte length
  699. --- instead of throwing an error.
  700. ---
  701. --- Invalid UTF-8 and NUL is treated like in |vim.str_utfindex()|.
  702. --- An {index} in the middle of a UTF-16 sequence is rounded upwards to
  703. --- the end of that sequence.
  704. ---@param s string
  705. ---@param encoding "utf-8"|"utf-16"|"utf-32"
  706. ---@param index integer
  707. ---@param strict_indexing? boolean # default: true
  708. ---@return integer
  709. function vim.str_byteindex(s, encoding, index, strict_indexing)
  710. if type(encoding) == 'number' then
  711. -- Legacy support for old API
  712. -- Parameters: ~
  713. -- • {str} (`string`)
  714. -- • {index} (`integer`)
  715. -- • {use_utf16} (`boolean?`)
  716. vim.deprecate(
  717. 'vim.str_byteindex',
  718. 'vim.str_byteindex(s, encoding, index, strict_indexing)',
  719. '1.0'
  720. )
  721. local old_index = encoding
  722. local use_utf16 = index or false
  723. return vim._str_byteindex(s, old_index, use_utf16) or error('index out of range')
  724. end
  725. -- Avoid vim.validate for performance.
  726. if type(s) ~= 'string' or type(index) ~= 'number' then
  727. vim.validate('s', s, 'string')
  728. vim.validate('index', index, 'number')
  729. end
  730. local len = #s
  731. if index == 0 or len == 0 then
  732. return 0
  733. end
  734. if not utfs[encoding] then
  735. vim.validate('encoding', encoding, function(v)
  736. return utfs[v], 'invalid encoding'
  737. end)
  738. end
  739. if strict_indexing ~= nil and type(strict_indexing) ~= 'boolean' then
  740. vim.validate('strict_indexing', strict_indexing, 'boolean', true)
  741. end
  742. if strict_indexing == nil then
  743. strict_indexing = true
  744. end
  745. if encoding == 'utf-8' then
  746. if index > len then
  747. return strict_indexing and error('index out of range') or len
  748. end
  749. return index
  750. end
  751. return vim._str_byteindex(s, index, encoding == 'utf-16')
  752. or strict_indexing and error('index out of range')
  753. or len
  754. end
  755. --- Convert byte index to UTF-32, UTF-16 or UTF-8 indices. If {index} is not
  756. --- supplied, the length of the string is used. All indices are zero-based.
  757. ---
  758. --- If {strict_indexing} is false then an out of range index will return string
  759. --- length instead of throwing an error.
  760. --- Invalid UTF-8 bytes, and embedded surrogates are counted as one code point
  761. --- each. An {index} in the middle of a UTF-8 sequence is rounded upwards to the end of
  762. --- that sequence.
  763. ---@param s string
  764. ---@param encoding "utf-8"|"utf-16"|"utf-32"
  765. ---@param index? integer
  766. ---@param strict_indexing? boolean # default: true
  767. ---@return integer
  768. function vim.str_utfindex(s, encoding, index, strict_indexing)
  769. if encoding == nil or type(encoding) == 'number' then
  770. -- Legacy support for old API
  771. -- Parameters: ~
  772. -- • {str} (`string`)
  773. -- • {index} (`integer?`)
  774. vim.deprecate(
  775. 'vim.str_utfindex',
  776. 'vim.str_utfindex(s, encoding, index, strict_indexing)',
  777. '1.0'
  778. )
  779. local old_index = encoding
  780. local col32, col16 = vim._str_utfindex(s, old_index) --[[@as integer,integer]]
  781. if not col32 or not col16 then
  782. error('index out of range')
  783. end
  784. -- Return (multiple): ~
  785. -- (`integer`) UTF-32 index
  786. -- (`integer`) UTF-16 index
  787. --- @diagnostic disable-next-line: redundant-return-value
  788. return col32, col16
  789. end
  790. if type(s) ~= 'string' or (index ~= nil and type(index) ~= 'number') then
  791. vim.validate('s', s, 'string')
  792. vim.validate('index', index, 'number', true)
  793. end
  794. if not index then
  795. index = math.huge
  796. strict_indexing = false
  797. end
  798. if index == 0 then
  799. return 0
  800. end
  801. if not utfs[encoding] then
  802. vim.validate('encoding', encoding, function(v)
  803. return utfs[v], 'invalid encoding'
  804. end)
  805. end
  806. if strict_indexing ~= nil and type(strict_indexing) ~= 'boolean' then
  807. vim.validate('strict_indexing', strict_indexing, 'boolean', true)
  808. end
  809. if strict_indexing == nil then
  810. strict_indexing = true
  811. end
  812. if encoding == 'utf-8' then
  813. local len = #s
  814. return index <= len and index or (strict_indexing and error('index out of range') or len)
  815. end
  816. local col32, col16 = vim._str_utfindex(s, index) --[[@as integer?,integer?]]
  817. local col = encoding == 'utf-16' and col16 or col32
  818. if col then
  819. return col
  820. end
  821. if strict_indexing then
  822. error('index out of range')
  823. end
  824. local max32, max16 = vim._str_utfindex(s)--[[@as integer integer]]
  825. return encoding == 'utf-16' and max16 or max32
  826. end
  827. --- Generates a list of possible completions for the str
  828. --- String has the pattern.
  829. ---
  830. --- 1. Can we get it to just return things in the global namespace with that name prefix
  831. --- 2. Can we get it to return things from global namespace even with `print(` in front.
  832. ---
  833. --- @param pat string
  834. --- @return any[], integer
  835. function vim._expand_pat(pat, env)
  836. env = env or _G
  837. if pat == '' then
  838. local result = vim.tbl_keys(env)
  839. table.sort(result)
  840. return result, 0
  841. end
  842. -- TODO: We can handle spaces in [] ONLY.
  843. -- We should probably do that at some point, just for cooler completion.
  844. -- TODO: We can suggest the variable names to go in []
  845. -- This would be difficult as well.
  846. -- Probably just need to do a smarter match than just `:match`
  847. -- Get the last part of the pattern
  848. local last_part = pat:match('[%w.:_%[%]\'"]+$')
  849. if not last_part then
  850. return {}, 0
  851. end
  852. local parts, search_index = vim._expand_pat_get_parts(last_part)
  853. local match_part = string.sub(last_part, search_index, #last_part)
  854. local prefix_match_pat = string.sub(pat, 1, #pat - #match_part) or ''
  855. local final_env = env
  856. for _, part in ipairs(parts) do
  857. if type(final_env) ~= 'table' then
  858. return {}, 0
  859. end
  860. local key --- @type any
  861. -- Normally, we just have a string
  862. -- Just attempt to get the string directly from the environment
  863. if type(part) == 'string' then
  864. key = part
  865. else
  866. -- However, sometimes you want to use a variable, and complete on it
  867. -- With this, you have the power.
  868. -- MY_VAR = "api"
  869. -- vim[MY_VAR]
  870. -- -> _G[MY_VAR] -> "api"
  871. local result_key = part[1]
  872. if not result_key then
  873. return {}, 0
  874. end
  875. local result = rawget(env, result_key)
  876. if result == nil then
  877. return {}, 0
  878. end
  879. key = result
  880. end
  881. local field = rawget(final_env, key)
  882. if field == nil then
  883. local mt = getmetatable(final_env)
  884. if mt and type(mt.__index) == 'table' then
  885. field = rawget(mt.__index, key)
  886. elseif final_env == vim and (vim._submodules[key] or vim._extra[key]) then
  887. field = vim[key] --- @type any
  888. end
  889. end
  890. final_env = field
  891. if not final_env then
  892. return {}, 0
  893. end
  894. end
  895. local keys = {} --- @type table<string,true>
  896. --- @param obj table<any,any>
  897. local function insert_keys(obj)
  898. for k, _ in pairs(obj) do
  899. if
  900. type(k) == 'string'
  901. and string.sub(k, 1, string.len(match_part)) == match_part
  902. and k:match('^[_%w]+$') ~= nil -- filter out invalid identifiers for field, e.g. 'foo#bar'
  903. then
  904. keys[k] = true
  905. end
  906. end
  907. end
  908. ---@param acc table<string,any>
  909. local function _fold_to_map(acc, k, v)
  910. acc[k] = (v or true)
  911. return acc
  912. end
  913. if type(final_env) == 'table' then
  914. insert_keys(final_env)
  915. end
  916. local mt = getmetatable(final_env)
  917. if mt and type(mt.__index) == 'table' then
  918. insert_keys(mt.__index)
  919. end
  920. if final_env == vim then
  921. insert_keys(vim._submodules)
  922. insert_keys(vim._extra)
  923. end
  924. -- Completion for dict accessors (special vim variables and vim.fn)
  925. if mt and vim.tbl_contains({ vim.g, vim.t, vim.w, vim.b, vim.v, vim.fn }, final_env) then
  926. local prefix, type = unpack(
  927. vim.fn == final_env and { '', 'function' }
  928. or vim.g == final_env and { 'g:', 'var' }
  929. or vim.t == final_env and { 't:', 'var' }
  930. or vim.w == final_env and { 'w:', 'var' }
  931. or vim.b == final_env and { 'b:', 'var' }
  932. or vim.v == final_env and { 'v:', 'var' }
  933. or { nil, nil }
  934. )
  935. assert(prefix and type, "Can't resolve final_env")
  936. local vars = vim.fn.getcompletion(prefix .. match_part, type) --- @type string[]
  937. insert_keys(vim
  938. .iter(vars)
  939. :map(function(s) ---@param s string
  940. s = s:gsub('[()]+$', '') -- strip '(' and ')' for function completions
  941. return s:sub(#prefix + 1) -- strip the prefix, e.g., 'g:foo' => 'foo'
  942. end)
  943. :fold({}, _fold_to_map))
  944. end
  945. -- Completion for option accessors (full names only)
  946. if
  947. mt
  948. and vim.tbl_contains(
  949. { vim.o, vim.go, vim.bo, vim.wo, vim.opt, vim.opt_local, vim.opt_global },
  950. final_env
  951. )
  952. then
  953. --- @type fun(option_name: string, option: vim.api.keyset.get_option_info): boolean
  954. local filter = function(_, _)
  955. return true
  956. end
  957. if vim.bo == final_env then
  958. filter = function(_, option)
  959. return option.scope == 'buf'
  960. end
  961. elseif vim.wo == final_env then
  962. filter = function(_, option)
  963. return option.scope == 'win'
  964. end
  965. end
  966. --- @type table<string, vim.api.keyset.get_option_info>
  967. local options = vim.api.nvim_get_all_options_info()
  968. insert_keys(vim.iter(options):filter(filter):fold({}, _fold_to_map))
  969. end
  970. keys = vim.tbl_keys(keys)
  971. table.sort(keys)
  972. return keys, #prefix_match_pat
  973. end
  974. --- @param lua_string string
  975. --- @return (string|string[])[], integer
  976. vim._expand_pat_get_parts = function(lua_string)
  977. local parts = {}
  978. local accumulator, search_index = '', 1
  979. local in_brackets = false
  980. local bracket_end = -1 --- @type integer?
  981. local string_char = nil
  982. for idx = 1, #lua_string do
  983. local s = lua_string:sub(idx, idx)
  984. if not in_brackets and (s == '.' or s == ':') then
  985. table.insert(parts, accumulator)
  986. accumulator = ''
  987. search_index = idx + 1
  988. elseif s == '[' then
  989. in_brackets = true
  990. table.insert(parts, accumulator)
  991. accumulator = ''
  992. search_index = idx + 1
  993. elseif in_brackets then
  994. if idx == bracket_end then
  995. in_brackets = false
  996. search_index = idx + 1
  997. if string_char == 'VAR' then
  998. table.insert(parts, { accumulator })
  999. accumulator = ''
  1000. string_char = nil
  1001. end
  1002. elseif not string_char then
  1003. bracket_end = string.find(lua_string, ']', idx, true)
  1004. if s == '"' or s == "'" then
  1005. string_char = s
  1006. elseif s ~= ' ' then
  1007. string_char = 'VAR'
  1008. accumulator = s
  1009. end
  1010. elseif string_char then
  1011. if string_char ~= s then
  1012. accumulator = accumulator .. s
  1013. else
  1014. table.insert(parts, accumulator)
  1015. accumulator = ''
  1016. string_char = nil
  1017. end
  1018. end
  1019. else
  1020. accumulator = accumulator .. s
  1021. end
  1022. end
  1023. --- @param val any[]
  1024. parts = vim.tbl_filter(function(val)
  1025. return #val > 0
  1026. end, parts)
  1027. return parts, search_index
  1028. end
  1029. do
  1030. -- Ideally we should just call complete() inside omnifunc, though there are
  1031. -- some bugs, so fake the two-step dance for now.
  1032. local matches --- @type any[]
  1033. --- Omnifunc for completing Lua values from the runtime Lua interpreter,
  1034. --- similar to the builtin completion for the `:lua` command.
  1035. ---
  1036. --- Activate using `set omnifunc=v:lua.vim.lua_omnifunc` in a Lua buffer.
  1037. --- @param find_start 1|0
  1038. function vim.lua_omnifunc(find_start, _)
  1039. if find_start == 1 then
  1040. local line = vim.api.nvim_get_current_line()
  1041. local prefix = string.sub(line, 1, vim.api.nvim_win_get_cursor(0)[2])
  1042. local pos
  1043. matches, pos = vim._expand_pat(prefix)
  1044. return (#matches > 0 and pos) or -1
  1045. else
  1046. return matches
  1047. end
  1048. end
  1049. end
  1050. --- "Pretty prints" the given arguments and returns them unmodified.
  1051. ---
  1052. --- Example:
  1053. ---
  1054. --- ```lua
  1055. --- local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
  1056. --- ```
  1057. ---
  1058. --- @see |vim.inspect()|
  1059. --- @see |:=|
  1060. --- @param ... any
  1061. --- @return any # given arguments.
  1062. function vim.print(...)
  1063. local msg = {}
  1064. for i = 1, select('#', ...) do
  1065. local o = select(i, ...)
  1066. if type(o) == 'string' then
  1067. table.insert(msg, o)
  1068. else
  1069. table.insert(msg, vim.inspect(o, { newline = '\n', indent = ' ' }))
  1070. end
  1071. end
  1072. print(table.concat(msg, '\n'))
  1073. return ...
  1074. end
  1075. --- Translates keycodes.
  1076. ---
  1077. --- Example:
  1078. ---
  1079. --- ```lua
  1080. --- local k = vim.keycode
  1081. --- vim.g.mapleader = k'<bs>'
  1082. --- ```
  1083. ---
  1084. --- @param str string String to be converted.
  1085. --- @return string
  1086. --- @see |nvim_replace_termcodes()|
  1087. function vim.keycode(str)
  1088. return vim.api.nvim_replace_termcodes(str, true, true, true)
  1089. end
  1090. --- @param server_addr string
  1091. --- @param connect_error string
  1092. function vim._cs_remote(rcid, server_addr, connect_error, args)
  1093. --- @return string
  1094. local function connection_failure_errmsg(consequence)
  1095. local explanation --- @type string
  1096. if server_addr == '' then
  1097. explanation = 'No server specified with --server'
  1098. else
  1099. explanation = "Failed to connect to '" .. server_addr .. "'"
  1100. if connect_error ~= '' then
  1101. explanation = explanation .. ': ' .. connect_error
  1102. end
  1103. end
  1104. return 'E247: ' .. explanation .. '. ' .. consequence
  1105. end
  1106. local f_silent = false
  1107. local f_tab = false
  1108. local subcmd = string.sub(args[1], 10)
  1109. if subcmd == 'tab' then
  1110. f_tab = true
  1111. elseif subcmd == 'silent' then
  1112. f_silent = true
  1113. elseif
  1114. subcmd == 'wait'
  1115. or subcmd == 'wait-silent'
  1116. or subcmd == 'tab-wait'
  1117. or subcmd == 'tab-wait-silent'
  1118. then
  1119. return { errmsg = 'E5600: Wait commands not yet implemented in Nvim' }
  1120. elseif subcmd == 'tab-silent' then
  1121. f_tab = true
  1122. f_silent = true
  1123. elseif subcmd == 'send' then
  1124. if rcid == 0 then
  1125. return { errmsg = connection_failure_errmsg('Send failed.') }
  1126. end
  1127. vim.rpcrequest(rcid, 'nvim_input', args[2])
  1128. return { should_exit = true, tabbed = false }
  1129. elseif subcmd == 'expr' then
  1130. if rcid == 0 then
  1131. return { errmsg = connection_failure_errmsg('Send expression failed.') }
  1132. end
  1133. local res = tostring(vim.rpcrequest(rcid, 'nvim_eval', args[2]))
  1134. return { result = res, should_exit = true, tabbed = false }
  1135. elseif subcmd ~= '' then
  1136. return { errmsg = 'Unknown option argument: ' .. tostring(args[1]) }
  1137. end
  1138. if rcid == 0 then
  1139. if not f_silent then
  1140. vim.notify(connection_failure_errmsg('Editing locally'), vim.log.levels.WARN)
  1141. end
  1142. else
  1143. local command = {}
  1144. if f_tab then
  1145. table.insert(command, 'tab')
  1146. end
  1147. table.insert(command, 'drop')
  1148. for i = 2, #args do
  1149. table.insert(command, vim.fn.fnameescape(args[i]))
  1150. end
  1151. vim.fn.rpcrequest(rcid, 'nvim_command', table.concat(command, ' '))
  1152. end
  1153. return {
  1154. should_exit = rcid ~= 0,
  1155. tabbed = f_tab,
  1156. }
  1157. end
  1158. do
  1159. local function truncated_echo(msg)
  1160. -- Truncate message to avoid hit-enter-prompt
  1161. local max_width = vim.o.columns * math.max(vim.o.cmdheight - 1, 0) + vim.v.echospace
  1162. local msg_truncated = string.sub(msg, 1, max_width)
  1163. vim.api.nvim_echo({ { msg_truncated, 'WarningMsg' } }, true, {})
  1164. end
  1165. local notified = false
  1166. function vim._truncated_echo_once(msg)
  1167. if not notified then
  1168. truncated_echo(msg)
  1169. notified = true
  1170. return true
  1171. end
  1172. return false
  1173. end
  1174. end
  1175. --- This is basically the same as debug.traceback(), except the full paths are shown.
  1176. local function traceback()
  1177. local level = 4
  1178. local backtrace = { 'stack traceback:' }
  1179. while true do
  1180. local info = debug.getinfo(level, 'Sl')
  1181. if not info then
  1182. break
  1183. end
  1184. local msg = (' %s:%s'):format(info.source:sub(2), info.currentline)
  1185. table.insert(backtrace, msg)
  1186. level = level + 1
  1187. end
  1188. return table.concat(backtrace, '\n')
  1189. end
  1190. --- Shows a deprecation message to the user.
  1191. ---
  1192. ---@param name string Deprecated feature (function, API, etc.).
  1193. ---@param alternative string|nil Suggested alternative feature.
  1194. ---@param version string Version when the deprecated function will be removed.
  1195. ---@param plugin string|nil Name of the plugin that owns the deprecated feature.
  1196. --- Defaults to "Nvim".
  1197. ---@param backtrace boolean|nil Prints backtrace. Defaults to true.
  1198. ---
  1199. ---@return string|nil # Deprecated message, or nil if no message was shown.
  1200. function vim.deprecate(name, alternative, version, plugin, backtrace)
  1201. plugin = plugin or 'Nvim'
  1202. if plugin == 'Nvim' then
  1203. require('vim.deprecated.health').add(name, version, traceback(), alternative)
  1204. -- Show a warning only if feature is hard-deprecated (see MAINTAIN.md).
  1205. -- Example: if removal `version` is 0.12 (soft-deprecated since 0.10-dev), show warnings
  1206. -- starting at 0.11, including 0.11-dev.
  1207. local major, minor = version:match('(%d+)%.(%d+)')
  1208. major, minor = tonumber(major), tonumber(minor)
  1209. local nvim_major = 0 --- Current Nvim major version.
  1210. -- We can't "subtract" from a major version, so:
  1211. -- * Always treat `major > nvim_major` as soft-deprecation.
  1212. -- * Compare `minor - 1` if `major == nvim_major`.
  1213. if major > nvim_major then
  1214. return -- Always soft-deprecation (see MAINTAIN.md).
  1215. end
  1216. local hard_deprecated_since = string.format('nvim-%d.%d', major, minor - 1)
  1217. if major == nvim_major and vim.fn.has(hard_deprecated_since) == 0 then
  1218. return
  1219. end
  1220. local msg = ('%s is deprecated. Run ":checkhealth vim.deprecated" for more information'):format(
  1221. name
  1222. )
  1223. local displayed = vim._truncated_echo_once(msg)
  1224. return displayed and msg or nil
  1225. else
  1226. vim.validate('name', name, 'string')
  1227. vim.validate('alternative', alternative, 'string', true)
  1228. vim.validate('version', version, 'string', true)
  1229. vim.validate('plugin', plugin, 'string', true)
  1230. local msg = ('%s is deprecated'):format(name)
  1231. msg = alternative and ('%s, use %s instead.'):format(msg, alternative) or (msg .. '.')
  1232. msg = ('%s\nFeature will be removed in %s %s'):format(msg, plugin, version)
  1233. local displayed = vim.notify_once(msg, vim.log.levels.WARN)
  1234. if displayed and backtrace ~= false then
  1235. vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN)
  1236. end
  1237. return displayed and msg or nil
  1238. end
  1239. end
  1240. require('vim._options')
  1241. -- Remove at Nvim 1.0
  1242. ---@deprecated
  1243. vim.loop = vim.uv
  1244. -- Deprecated. Remove at Nvim 2.0
  1245. vim.highlight = vim._defer_deprecated_module('vim.highlight', 'vim.hl')
  1246. return vim