-- Nvim-Lua stdlib: the `vim` module (:help lua-stdlib) -- -- Lua code lives in one of three places: -- 1. runtime/lua/vim/ (the runtime): For "nice to have" features, e.g. the -- `inspect` and `lpeg` modules. -- 2. runtime/lua/vim/shared.lua: pure lua functions which always -- are available. Used in the test runner, as well as worker threads -- and processes launched from Nvim. -- 3. runtime/lua/vim/_editor.lua: Code which directly interacts with -- the Nvim editor state. Only available in the main thread. -- -- Guideline: "If in doubt, put it in the runtime". -- -- Most functions should live directly in `vim.`, not in submodules. -- -- Compatibility with Vim's `if_lua` is explicitly a non-goal. -- -- Reference (#6580): -- - https://github.com/luafun/luafun -- - https://github.com/rxi/lume -- - http://leafo.net/lapis/reference/utilities.html -- - https://github.com/torch/paths -- - https://github.com/bakpakin/Fennel (pretty print, repl) -- - https://github.com/howl-editor/howl/tree/master/lib/howl/util -- These are for loading runtime modules lazily since they aren't available in -- the nvim binary as specified in executor.c for k, v in pairs({ treesitter = true, filetype = true, F = true, lsp = true, highlight = true, diagnostic = true, keymap = true, ui = true, health = true, fs = true, }) do vim._submodules[k] = v end vim.log = { levels = { TRACE = 0, DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4, OFF = 5, }, } -- Internal-only until comments in #8107 are addressed. -- Returns: -- {errcode}, {output} function vim._system(cmd) local out = vim.fn.system(cmd) local err = vim.v.shell_error return err, out end -- Gets process info from the `ps` command. -- Used by nvim_get_proc() as a fallback. function vim._os_proc_info(pid) if pid == nil or pid <= 0 or type(pid) ~= 'number' then error('invalid pid') end local cmd = { 'ps', '-p', pid, '-o', 'comm=' } local err, name = vim._system(cmd) if 1 == err and vim.trim(name) == '' then return {} -- Process not found. elseif 0 ~= err then error('command failed: ' .. vim.fn.string(cmd)) end local _, ppid = vim._system({ 'ps', '-p', pid, '-o', 'ppid=' }) -- Remove trailing whitespace. name = vim.trim(name):gsub('^.*/', '') ppid = tonumber(ppid) or -1 return { name = name, pid = pid, ppid = ppid, } end -- Gets process children from the `pgrep` command. -- Used by nvim_get_proc_children() as a fallback. function vim._os_proc_children(ppid) if ppid == nil or ppid <= 0 or type(ppid) ~= 'number' then error('invalid ppid') end local cmd = { 'pgrep', '-P', ppid } local err, rv = vim._system(cmd) if 1 == err and vim.trim(rv) == '' then return {} -- Process not found. elseif 0 ~= err then error('command failed: ' .. vim.fn.string(cmd)) end local children = {} for s in rv:gmatch('%S+') do local i = tonumber(s) if i ~= nil then table.insert(children, i) end end return children end --- Gets a human-readable representation of the given object. --- ---@see https://github.com/kikito/inspect.lua ---@see https://github.com/mpeterv/vinspect local function inspect(object, options) -- luacheck: no unused error(object, options) -- Stub for gen_vimdoc.py end do local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false --- Paste handler, invoked by |nvim_paste()| when a conforming UI --- (such as the |TUI|) pastes text into the editor. --- --- Example: To remove ANSI color codes when pasting: ---
--- vim.paste = (function(overridden) --- return function(lines, phase) --- for i,line in ipairs(lines) do --- -- Scrub ANSI color codes from paste input. --- lines[i] = line:gsub('\27%[[0-9;mK]+', '') --- end --- overridden(lines, phase) --- end --- end)(vim.paste) ------ ---@see |paste| ---@alias paste_phase -1 | 1 | 2 | 3 --- ---@param lines string[] # |readfile()|-style list of lines to paste. |channel-lines| ---@param phase paste_phase -1: "non-streaming" paste: the call contains all lines. --- If paste is "streamed", `phase` indicates the stream state: --- - 1: starts the paste (exactly once) --- - 2: continues the paste (zero or more times) --- - 3: ends the paste (exactly once) ---@returns boolean # false if client should cancel the paste. function vim.paste(lines, phase) local now = vim.loop.now() local is_first_chunk = phase < 2 local is_last_chunk = phase == -1 or phase == 3 if is_first_chunk then -- Reset flags. tdots, tick, got_line1, undo_started, trailing_nl = now, 0, false, false, false end if #lines == 0 then lines = { '' } end if #lines == 1 and lines[1] == '' and not is_last_chunk then -- An empty chunk can cause some edge cases in streamed pasting, -- so don't do anything unless it is the last chunk. return true end -- Note: mode doesn't always start with "c" in cmdline mode, so use getcmdtype() instead. if vim.fn.getcmdtype() ~= '' then -- cmdline-mode: paste only 1 line. if not got_line1 then got_line1 = (#lines > 1) -- Escape control characters local line1 = lines[1]:gsub('(%c)', '\022%1') -- nvim_input() is affected by mappings, -- so use nvim_feedkeys() with "n" flag to ignore mappings. vim.api.nvim_feedkeys(line1, 'n', true) end return true end local mode = vim.api.nvim_get_mode().mode if undo_started then vim.api.nvim_command('undojoin') end if mode:find('^i') or mode:find('^n?t') then -- Insert mode or Terminal buffer vim.api.nvim_put(lines, 'c', false, true) elseif phase < 2 and mode:find('^R') and not mode:find('^Rv') then -- Replace mode -- TODO: implement Replace mode streamed pasting -- TODO: support Virtual Replace mode local nchars = 0 for _, line in ipairs(lines) do nchars = nchars + line:len() end local row, col = unpack(vim.api.nvim_win_get_cursor(0)) local bufline = vim.api.nvim_buf_get_lines(0, row - 1, row, true)[1] local firstline = lines[1] firstline = bufline:sub(1, col) .. firstline lines[1] = firstline lines[#lines] = lines[#lines] .. bufline:sub(col + nchars + 1, bufline:len()) vim.api.nvim_buf_set_lines(0, row - 1, row, false, lines) elseif mode:find('^[nvV\22sS\19]') then -- Normal or Visual or Select mode if mode:find('^n') then -- Normal mode -- When there was a trailing new line in the previous chunk, -- the cursor is on the first character of the next line, -- so paste before the cursor instead of after it. vim.api.nvim_put(lines, 'c', not trailing_nl, false) else -- Visual or Select mode vim.api.nvim_command([[exe "silent normal! \
--- vim.cmd('echo 42') --- vim.cmd([[ --- augroup My_group --- autocmd! --- autocmd FileType c setlocal cindent --- augroup END --- ]]) --- --- -- Ex command :echo "foo" --- -- Note string literals need to be double quoted. --- vim.cmd('echo "foo"') --- vim.cmd { cmd = 'echo', args = { '"foo"' } } --- vim.cmd.echo({ args = { '"foo"' } }) --- vim.cmd.echo('"foo"') --- --- -- Ex command :write! myfile.txt --- vim.cmd('write! myfile.txt') --- vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true } --- vim.cmd.write { args = { "myfile.txt" }, bang = true } --- vim.cmd.write { "myfile.txt", bang = true } --- --- -- Ex command :colorscheme blue --- vim.cmd('colorscheme blue') --- vim.cmd.colorscheme('blue') ------ ---@param command string|table Command(s) to execute. --- If a string, executes multiple lines of Vim script at once. In this --- case, it is an alias to |nvim_exec()|, where `output` is set to --- false. Thus it works identical to |:source|. --- If a table, executes a single command. In this case, it is an alias --- to |nvim_cmd()| where `opts` is empty. ---@see |ex-cmd-index| function vim.cmd(command) -- luacheck: no unused error(command) -- Stub for gen_vimdoc.py end local VIM_CMD_ARG_MAX = 20 vim.cmd = setmetatable({}, { __call = function(_, command) if type(command) == 'table' then return vim.api.nvim_cmd(command, {}) else return vim.api.nvim_exec(command, false) end end, __index = function(t, command) t[command] = function(...) local opts if select('#', ...) == 1 and type(select(1, ...)) == 'table' then opts = select(1, ...) -- Move indexed positions in opts to opt.args if opts[1] and not opts.args then opts.args = {} for i = 1, VIM_CMD_ARG_MAX do if not opts[i] then break end opts.args[i] = opts[i] opts[i] = nil end end else opts = { args = { ... } } end opts.cmd = command return vim.api.nvim_cmd(opts, {}) end return t[command] end, }) -- These are the vim.env/v/g/o/bo/wo variable magic accessors. do local validate = vim.validate --@private local function make_dict_accessor(scope, handle) validate({ scope = { scope, 's' }, }) local mt = {} function mt:__newindex(k, v) return vim._setvar(scope, handle or 0, k, v) end function mt:__index(k) if handle == nil and type(k) == 'number' then return make_dict_accessor(scope, k) end return vim._getvar(scope, handle or 0, k) end return setmetatable({}, mt) end vim.g = make_dict_accessor('g', false) vim.v = make_dict_accessor('v', false) vim.b = make_dict_accessor('b') vim.w = make_dict_accessor('w') vim.t = make_dict_accessor('t') end --- Get a table of lines with start, end columns for a region marked by two points --- ---@param bufnr number of buffer ---@param pos1 integer[] (line, column) tuple marking beginning of region ---@param pos2 integer[] (line, column) tuple marking end of region ---@param regtype string type of selection, see |setreg()| ---@param inclusive boolean indicating whether the selection is end-inclusive ---@return table
--- -- Print highlight group Normal and store it's contents in a variable. --- local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) ------@see |vim.inspect()| ---@return any # given arguments. function vim.pretty_print(...) local objects = {} for i = 1, select('#', ...) do local v = select(i, ...) table.insert(objects, vim.inspect(v)) end print(table.concat(objects, ' ')) return ... end function vim._cs_remote(rcid, server_addr, connect_error, args) local function connection_failure_errmsg(consequence) local explanation if server_addr == '' then explanation = 'No server specified with --server' else explanation = "Failed to connect to '" .. server_addr .. "'" if connect_error ~= '' then explanation = explanation .. ': ' .. connect_error end end return 'E247: ' .. explanation .. '. ' .. consequence end local f_silent = false local f_tab = false local subcmd = string.sub(args[1], 10) if subcmd == 'tab' then f_tab = true elseif subcmd == 'silent' then f_silent = true elseif subcmd == 'wait' or subcmd == 'wait-silent' or subcmd == 'tab-wait' or subcmd == 'tab-wait-silent' then return { errmsg = 'E5600: Wait commands not yet implemented in nvim' } elseif subcmd == 'tab-silent' then f_tab = true f_silent = true elseif subcmd == 'send' then if rcid == 0 then return { errmsg = connection_failure_errmsg('Send failed.') } end vim.fn.rpcrequest(rcid, 'nvim_input', args[2]) return { should_exit = true, tabbed = false } elseif subcmd == 'expr' then if rcid == 0 then return { errmsg = connection_failure_errmsg('Send expression failed.') } end print(vim.fn.rpcrequest(rcid, 'nvim_eval', args[2])) return { should_exit = true, tabbed = false } elseif subcmd ~= '' then return { errmsg = 'Unknown option argument: ' .. args[1] } end if rcid == 0 then if not f_silent then vim.notify(connection_failure_errmsg('Editing locally'), vim.log.levels.WARN) end else local command = {} if f_tab then table.insert(command, 'tab') end table.insert(command, 'drop') for i = 2, #args do table.insert(command, vim.fn.fnameescape(args[i])) end vim.fn.rpcrequest(rcid, 'nvim_command', table.concat(command, ' ')) end return { should_exit = rcid ~= 0, tabbed = f_tab, } end --- Display a deprecation notification to the user. --- ---@param name string Deprecated function. ---@param alternative string|nil Preferred alternative function. ---@param version string Version in which the deprecated function will --- be removed. ---@param plugin string|nil Plugin name that the function will be removed --- from. Defaults to "Nvim". ---@param backtrace boolean|nil Prints backtrace. Defaults to true. function vim.deprecate(name, alternative, version, plugin, backtrace) local message = name .. ' is deprecated' plugin = plugin or 'Nvim' message = alternative and (message .. ', use ' .. alternative .. ' instead.') or message message = message .. ' See :h deprecated\nThis function will be removed in ' .. plugin .. ' version ' .. version if vim.notify_once(message, vim.log.levels.WARN) and backtrace ~= false then vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN) end end --- Create builtin mappings (incl. menus). --- Called once on startup. function vim._init_default_mappings() -- mappings --@private local function map(mode, lhs, rhs) vim.api.nvim_set_keymap(mode, lhs, rhs, { noremap = true, desc = 'Nvim builtin' }) end map('n', 'Y', 'y$') -- Use normal!