diff options
author | Josh Rahm <joshuarahm@gmail.com> | 2023-11-29 22:39:54 +0000 |
---|---|---|
committer | Josh Rahm <joshuarahm@gmail.com> | 2023-11-29 22:39:54 +0000 |
commit | 21cb7d04c387e4198ca8098a884c78b56ffcf4c2 (patch) | |
tree | 84fe5690df1551f0bb2bdfe1a13aacd29ebc1de7 /runtime/lua/vim | |
parent | d9c904f85a23a496df4eb6be42aa43f007b22d50 (diff) | |
parent | 4a8bf24ac690004aedf5540fa440e788459e5e34 (diff) | |
download | rneovim-colorcolchar.tar.gz rneovim-colorcolchar.tar.bz2 rneovim-colorcolchar.zip |
Merge remote-tracking branch 'upstream/master' into colorcolcharcolorcolchar
Diffstat (limited to 'runtime/lua/vim')
79 files changed, 41248 insertions, 5686 deletions
diff --git a/runtime/lua/vim/F.lua b/runtime/lua/vim/F.lua index 3e370c0a84..5ed60ca8ab 100644 --- a/runtime/lua/vim/F.lua +++ b/runtime/lua/vim/F.lua @@ -1,18 +1,30 @@ local F = {} ---- Returns {a} if it is not nil, otherwise returns {b}. +--- Returns the first argument which is not nil. --- ----@generic A ----@generic B +--- If all arguments are nil, returns nil. --- ----@param a A ----@param b B ----@return A | B -function F.if_nil(a, b) - if a == nil then - return b +--- Examples: +--- +--- ```lua +--- local a = nil +--- local b = nil +--- local c = 42 +--- local d = true +--- assert(vim.F.if_nil(a, b, c, d) == 42) +--- ``` +--- +---@param ... any +---@return any +function F.if_nil(...) + local nargs = select('#', ...) + for i = 1, nargs do + local v = select(i, ...) + if v ~= nil then + return v + end end - return a + return nil end -- Use in combination with pcall diff --git a/runtime/lua/vim/_defaults.lua b/runtime/lua/vim/_defaults.lua new file mode 100644 index 0000000000..cc872dea83 --- /dev/null +++ b/runtime/lua/vim/_defaults.lua @@ -0,0 +1,314 @@ +--- Default mappings +do + --- Default maps for * and # in visual mode. + --- + --- See |v_star-default| and |v_#-default| + do + local function region_chunks(region) + local chunks = {} + local maxcol = vim.v.maxcol + for line, cols in vim.spairs(region) do + local endcol = cols[2] == maxcol and -1 or cols[2] + local chunk = vim.api.nvim_buf_get_text(0, line, cols[1], line, endcol, {})[1] + table.insert(chunks, chunk) + end + return chunks + end + + local function _visual_search(cmd) + assert(cmd == '/' or cmd == '?') + local region = vim.region( + 0, + '.', + 'v', + vim.api.nvim_get_mode().mode:sub(1, 1), + vim.o.selection == 'inclusive' + ) + local chunks = region_chunks(region) + local esc_chunks = vim + .iter(chunks) + :map(function(v) + return vim.fn.escape(v, cmd == '/' and [[/\]] or [[?\]]) + end) + :totable() + local esc_pat = table.concat(esc_chunks, [[\n]]) + local search_cmd = ([[%s\V%s%s]]):format(cmd, esc_pat, '\n') + return '\27' .. search_cmd + end + + vim.keymap.set('x', '*', function() + return _visual_search('/') + end, { desc = ':help v_star-default', expr = true, silent = true }) + vim.keymap.set('x', '#', function() + return _visual_search('?') + end, { desc = ':help v_#-default', expr = true, silent = true }) + end + + --- Map Y to y$. This mimics the behavior of D and C. See |Y-default| + vim.keymap.set('n', 'Y', 'y$', { desc = ':help Y-default' }) + + --- Use normal! <C-L> to prevent inserting raw <C-L> when using i_<C-O>. #17473 + --- + --- See |CTRL-L-default| + vim.keymap.set('n', '<C-L>', '<Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>', { + desc = ':help CTRL-L-default', + }) + + --- Set undo points when deleting text in insert mode. + --- + --- See |i_CTRL-U-default| and |i_CTRL-W-default| + vim.keymap.set('i', '<C-U>', '<C-G>u<C-U>', { desc = ':help i_CTRL-U-default' }) + vim.keymap.set('i', '<C-W>', '<C-G>u<C-W>', { desc = ':help i_CTRL-W-default' }) + + --- Use the same flags as the previous substitution with &. + --- + --- Use : instead of <Cmd> so that ranges are supported. #19365 + --- + --- See |&-default| + vim.keymap.set('n', '&', ':&&<CR>', { desc = ':help &-default' }) + + --- Map |gx| to call |vim.ui.open| on the identifier under the cursor + do + -- TODO: use vim.region() when it lands... #13896 #16843 + local function get_visual_selection() + local save_a = vim.fn.getreginfo('a') + vim.cmd([[norm! "ay]]) + local selection = vim.fn.getreg('a', 1) + vim.fn.setreg('a', save_a) + return selection + end + + local function do_open(uri) + local _, err = vim.ui.open(uri) + if err then + vim.notify(err, vim.log.levels.ERROR) + end + end + + local gx_desc = + 'Opens filepath or URI under cursor with the system handler (file explorer, web browser, …)' + vim.keymap.set({ 'n' }, 'gx', function() + do_open(vim.fn.expand('<cfile>')) + end, { desc = gx_desc }) + vim.keymap.set({ 'x' }, 'gx', function() + do_open(get_visual_selection()) + end, { desc = gx_desc }) + end +end + +--- Default menus +do + --- Right click popup menu + -- TODO VimScript, no l10n + vim.cmd([[ + aunmenu * + vnoremenu PopUp.Cut "+x + vnoremenu PopUp.Copy "+y + anoremenu PopUp.Paste "+gP + vnoremenu PopUp.Paste "+P + vnoremenu PopUp.Delete "_x + nnoremenu PopUp.Select\ All ggVG + vnoremenu PopUp.Select\ All gg0oG$ + inoremenu PopUp.Select\ All <C-Home><C-O>VG + anoremenu PopUp.-1- <Nop> + anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR> + ]]) +end + +--- Default autocommands. See |default-autocmds| +do + local nvim_terminal_augroup = vim.api.nvim_create_augroup('nvim_terminal', {}) + vim.api.nvim_create_autocmd('BufReadCmd', { + pattern = 'term://*', + group = nvim_terminal_augroup, + desc = 'Treat term:// buffers as terminal buffers', + nested = true, + command = "if !exists('b:term_title')|call termopen(matchstr(expand(\"<amatch>\"), '\\c\\mterm://\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), {'cwd': expand(get(matchlist(expand(\"<amatch>\"), '\\c\\mterm://\\(.\\{-}\\)//'), 1, ''))})", + }) + + vim.api.nvim_create_autocmd({ 'TermClose' }, { + group = nvim_terminal_augroup, + desc = 'Automatically close terminal buffers when started with no arguments and exiting without an error', + callback = function(args) + if vim.v.event.status == 0 then + local info = vim.api.nvim_get_chan_info(vim.bo[args.buf].channel) + local argv = info.argv or {} + if #argv == 1 and argv[1] == vim.o.shell then + vim.cmd({ cmd = 'bdelete', args = { args.buf }, bang = true }) + end + end + end, + }) + + vim.api.nvim_create_autocmd('CmdwinEnter', { + pattern = '[:>]', + desc = 'Limit syntax sync to maxlines=1 in the command window', + group = vim.api.nvim_create_augroup('nvim_cmdwin', {}), + command = 'syntax sync minlines=1 maxlines=1', + }) + + vim.api.nvim_create_autocmd('SwapExists', { + pattern = '*', + desc = 'Skip the swapfile prompt when the swapfile is owned by a running Nvim process', + group = vim.api.nvim_create_augroup('nvim_swapfile', {}), + callback = function() + local info = vim.fn.swapinfo(vim.v.swapname) + local user = vim.uv.os_get_passwd().username + local iswin = 1 == vim.fn.has('win32') + if info.error or info.pid <= 0 or (not iswin and info.user ~= user) then + vim.v.swapchoice = '' -- Show the prompt. + return + end + vim.v.swapchoice = 'e' -- Choose "(E)dit". + vim.notify(('W325: Ignoring swapfile from Nvim process %d'):format(info.pid)) + end, + }) +end + +--- Guess value of 'background' based on terminal color. +--- +--- We write Operating System Command (OSC) 11 to the terminal to request the +--- terminal's background color. We then wait for a response. If the response +--- matches `rgba:RRRR/GGGG/BBBB/AAAA` where R, G, B, and A are hex digits, then +--- compute the luminance[1] of the RGB color and classify it as light/dark +--- accordingly. Note that the color components may have anywhere from one to +--- four hex digits, and require scaling accordingly as values out of 4, 8, 12, +--- or 16 bits. Also note the A(lpha) component is optional, and is parsed but +--- ignored in the calculations. +--- +--- [1] https://en.wikipedia.org/wiki/Luma_%28video%29 +do + --- Parse a string of hex characters as a color. + --- + --- The string can contain 1 to 4 hex characters. The returned value is + --- between 0.0 and 1.0 (inclusive) representing the intensity of the color. + --- + --- For instance, if only a single hex char "a" is used, then this function + --- returns 0.625 (10 / 16), while a value of "aa" would return 0.664 (170 / + --- 256). + --- + --- @param c string Color as a string of hex chars + --- @return number? Intensity of the color + local function parsecolor(c) + if #c == 0 or #c > 4 then + return nil + end + + local val = tonumber(c, 16) + if not val then + return nil + end + + local max = tonumber(string.rep('f', #c), 16) + return val / max + end + + --- Parse an OSC 11 response + --- + --- Either of the two formats below are accepted: + --- + --- OSC 11 ; rgb:<red>/<green>/<blue> + --- + --- or + --- + --- OSC 11 ; rgba:<red>/<green>/<blue>/<alpha> + --- + --- where + --- + --- <red>, <green>, <blue>, <alpha> := h | hh | hhh | hhhh + --- + --- The alpha component is ignored, if present. + --- + --- @param resp string OSC 11 response + --- @return string? Red component + --- @return string? Green component + --- @return string? Blue component + local function parseosc11(resp) + local r, g, b + r, g, b = resp:match('^\027%]11;rgb:(%x+)/(%x+)/(%x+)$') + if not r and not g and not b then + local a + r, g, b, a = resp:match('^\027%]11;rgba:(%x+)/(%x+)/(%x+)/(%x+)$') + if not a or #a > 4 then + return nil, nil, nil + end + end + + if r and g and b and #r <= 4 and #g <= 4 and #b <= 4 then + return r, g, b + end + + return nil, nil, nil + end + + local tty = false + for _, ui in ipairs(vim.api.nvim_list_uis()) do + if ui.chan == 1 and ui.stdout_tty then + tty = true + break + end + end + + if tty then + local timer = assert(vim.uv.new_timer()) + + ---@param bg string New value of the 'background' option + local function setbg(bg) + if vim.api.nvim_get_option_info2('background', {}).was_set then + -- Don't do anything if 'background' is already set + return + end + + -- Wait until Nvim is finished starting to set 'background' to ensure the + -- OptionSet event fires. + if vim.v.vim_did_enter == 1 then + if vim.o.background ~= bg then + vim.o.background = bg + end + else + vim.api.nvim_create_autocmd('VimEnter', { + once = true, + nested = true, + callback = function() + setbg(bg) + end, + }) + end + end + + local id = vim.api.nvim_create_autocmd('TermResponse', { + nested = true, + callback = function(args) + local resp = args.data ---@type string + local r, g, b = parseosc11(resp) + if r and g and b then + local rr = parsecolor(r) + local gg = parsecolor(g) + local bb = parsecolor(b) + + if rr and gg and bb then + local luminance = (0.299 * rr) + (0.587 * gg) + (0.114 * bb) + local bg = luminance < 0.5 and 'dark' or 'light' + setbg(bg) + end + + return true + end + end, + }) + + io.stdout:write('\027]11;?\027\\') + + timer:start(1000, 0, function() + -- No response received. Delete the autocommand + vim.schedule(function() + -- Suppress error if autocommand has already been deleted + pcall(vim.api.nvim_del_autocmd, id) + end) + + if not timer:is_closing() then + timer:close() + end + end) + end +end diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua index da8764fbd4..6cccbe8313 100644 --- a/runtime/lua/vim/_editor.lua +++ b/runtime/lua/vim/_editor.lua @@ -3,7 +3,7 @@ -- 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 +-- 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 @@ -28,6 +28,8 @@ for k, v in pairs({ treesitter = true, filetype = true, + loader = true, + func = true, F = true, lsp = true, highlight = true, @@ -35,12 +37,26 @@ for k, v in pairs({ keymap = true, ui = true, health = true, - fs = true, secure = true, + snippet = true, + _watch = true, }) do vim._submodules[k] = v end +-- There are things which have special rules in vim._init_packages +-- for legacy reasons (uri) or for performance (_inspector). +-- most new things should go into a submodule namespace ( vim.foobar.do_thing() ) +vim._extra = { + uri_from_fname = true, + uri_from_bufnr = true, + uri_to_fname = true, + uri_to_bufnr = true, + show_pos = true, + inspect_pos = true, +} + +--- @private vim.log = { levels = { TRACE = 0, @@ -52,13 +68,78 @@ vim.log = { }, } --- 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 +-- TODO(lewis6991): document that the signature is system({cmd}, [{opts},] {on_exit}) +--- Runs a system command or throws an error if {cmd} cannot be run. +--- +--- Examples: +--- +--- ```lua +--- +--- local on_exit = function(obj) +--- print(obj.code) +--- print(obj.signal) +--- print(obj.stdout) +--- print(obj.stderr) +--- end +--- +--- -- Runs asynchronously: +--- vim.system({'echo', 'hello'}, { text = true }, on_exit) +--- +--- -- Runs synchronously: +--- local obj = vim.system({'echo', 'hello'}, { text = true }):wait() +--- -- { code = 0, signal = 0, stdout = 'hello', stderr = '' } +--- +--- ``` +--- +--- See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system +--- throws an error if {cmd} cannot be run. +--- +--- @param cmd (string[]) Command to execute +--- @param opts (SystemOpts|nil) Options: +--- - cwd: (string) Set the current working directory for the sub-process. +--- - env: table<string,string> Set environment variables for the new process. Inherits the +--- current environment with `NVIM` set to |v:servername|. +--- - clear_env: (boolean) `env` defines the job environment exactly, instead of merging current +--- environment. +--- - stdin: (string|string[]|boolean) If `true`, then a pipe to stdin is opened and can be written +--- to via the `write()` method to SystemObj. If string or string[] then will be written to stdin +--- and closed. Defaults to `false`. +--- - stdout: (boolean|function) +--- Handle output from stdout. When passed as a function must have the signature `fun(err: string, data: string)`. +--- Defaults to `true` +--- - stderr: (boolean|function) +--- Handle output from stderr. When passed as a function must have the signature `fun(err: string, data: string)`. +--- Defaults to `true`. +--- - text: (boolean) Handle stdout and stderr as text. Replaces `\r\n` with `\n`. +--- - timeout: (integer) Run the command with a time limit. Upon timeout the process is sent the +--- TERM signal (15) and the exit code is set to 124. +--- - detach: (boolean) If true, spawn the child process in a detached state - this will make it +--- a process group leader, and will effectively enable the child to keep running after the +--- parent exits. Note that the child process will still keep the parent's event loop alive +--- unless the parent process calls |uv.unref()| on the child's process handle. +--- +--- @param on_exit (function|nil) Called when subprocess exits. When provided, the command runs +--- asynchronously. Receives SystemCompleted object, see return of SystemObj:wait(). +--- +--- @return vim.SystemObj Object with the fields: +--- - pid (integer) Process ID +--- - wait (fun(timeout: integer|nil): SystemCompleted) Wait for the process to complete. Upon +--- timeout the process is sent the KILL signal (9) and the exit code is set to 124. Cannot +--- be called in |api-fast|. +--- - SystemCompleted is an object with the fields: +--- - code: (integer) +--- - signal: (integer) +--- - stdout: (string), nil if stdout argument is passed +--- - stderr: (string), nil if stderr argument is passed +--- - kill (fun(signal: integer|string)) +--- - write (fun(data: string|nil)) Requires `stdin=true`. Pass `nil` to close the stream. +--- - is_closing (fun(): boolean) +function vim.system(cmd, opts, on_exit) + if type(opts) == 'function' then + on_exit = opts + opts = nil + end + return require('vim._system').run(cmd, opts, on_exit) end -- Gets process info from the `ps` command. @@ -68,13 +149,14 @@ function vim._os_proc_info(pid) 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 + local r = vim.system(cmd):wait() + local name = assert(r.stdout) + if r.code == 1 and vim.trim(name) == '' then return {} -- Process not found. - elseif 0 ~= err then + elseif r.code ~= 0 then error('command failed: ' .. vim.fn.string(cmd)) end - local _, ppid = vim._system({ 'ps', '-p', pid, '-o', 'ppid=' }) + local ppid = assert(vim.system({ 'ps', '-p', pid, '-o', 'ppid=' }):wait().stdout) -- Remove trailing whitespace. name = vim.trim(name):gsub('^.*/', '') ppid = tonumber(ppid) or -1 @@ -92,14 +174,14 @@ function vim._os_proc_children(ppid) error('invalid ppid') end local cmd = { 'pgrep', '-P', ppid } - local err, rv = vim._system(cmd) - if 1 == err and vim.trim(rv) == '' then + local r = vim.system(cmd):wait() + if r.code == 1 and vim.trim(r.stdout) == '' then return {} -- Process not found. - elseif 0 ~= err then + elseif r.code ~= 0 then error('command failed: ' .. vim.fn.string(cmd)) end local children = {} - for s in rv:gmatch('%S+') do + for s in r.stdout:gmatch('%S+') do local i = tonumber(s) if i ~= nil then table.insert(children, i) @@ -110,11 +192,11 @@ end --- Gets a human-readable representation of the given object. --- +---@see |vim.print()| ---@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 +---@return string +vim.inspect = vim.inspect do local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false @@ -123,7 +205,8 @@ do --- (such as the |TUI|) pastes text into the editor. --- --- Example: To remove ANSI color codes when pasting: - --- <pre>lua + --- + --- ```lua --- vim.paste = (function(overridden) --- return function(lines, phase) --- for i,line in ipairs(lines) do @@ -133,7 +216,7 @@ do --- overridden(lines, phase) --- end --- end)(vim.paste) - --- </pre> + --- ``` --- ---@see |paste| ---@alias paste_phase -1 | 1 | 2 | 3 @@ -144,9 +227,9 @@ do --- - 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. + ---@return boolean result false if client should cancel the paste. function vim.paste(lines, phase) - local now = vim.loop.now() + local now = vim.uv.now() local is_first_chunk = phase < 2 local is_last_chunk = phase == -1 or phase == 3 if is_first_chunk then -- Reset flags. @@ -236,23 +319,35 @@ do end end ---- Defers callback `cb` until the Nvim API is safe to call. +--- Returns a function which calls {fn} via |vim.schedule()|. +--- +--- The returned function passes all arguments to {fn}. +--- +--- Example: +--- +--- ```lua +--- function notify_readable(_err, readable) +--- vim.notify("readable? " .. tostring(readable)) +--- end +--- vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable)) +--- ``` --- ---@see |lua-loop-callbacks| ---@see |vim.schedule()| ---@see |vim.in_fast_event()| ----@param cb function +---@param fn function ---@return function -function vim.schedule_wrap(cb) +function vim.schedule_wrap(fn) return function(...) local args = vim.F.pack_len(...) vim.schedule(function() - cb(vim.F.unpack_len(args)) + fn(vim.F.unpack_len(args)) end) end end -- vim.fn.{func}(...) +---@private vim.fn = setmetatable({}, { __index = function(t, key) local _fn @@ -270,62 +365,61 @@ vim.fn = setmetatable({}, { end, }) +--- @private vim.funcref = function(viml_func_name) return vim.fn[viml_func_name] end ---- Execute Vim script commands. +local VIM_CMD_ARG_MAX = 20 + +--- Executes Vim script commands. --- --- Note that `vim.cmd` can be indexed with a command name to return a callable function to the --- command. --- --- Example: ---- <pre>lua ---- 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') ---- </pre> +--- +--- ```lua +--- 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|. +--- case, it is an alias to |nvim_exec2()|, where `opts.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) + vim.api.nvim_exec2(command, {}) + return '' end end, __index = function(t, command) @@ -355,11 +449,17 @@ vim.cmd = setmetatable({}, { end, }) +--- @class vim.var_accessor +--- @field [string] any +--- @field [integer] vim.var_accessor + -- These are the vim.env/v/g/o/bo/wo variable magic accessors. do local validate = vim.validate - --@private + --- @param scope string + --- @param handle? false|integer + --- @return vim.var_accessor local function make_dict_accessor(scope, handle) validate({ scope = { scope, 's' }, @@ -384,19 +484,41 @@ do vim.t = make_dict_accessor('t') end ---- Get a table of lines with start, end columns for a region marked by two points +--- Gets a dict of line segment ("chunk") positions for the region from `pos1` to `pos2`. +--- +--- Input and output positions are byte positions, (0,0)-indexed. "End of line" column +--- position (for example, |linewise| visual selection) is returned as |v:maxcol| (big number). --- ----@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 region Table of the form `{linenr = {startcol,endcol}}` +---@param bufnr integer Buffer number, or 0 for current buffer +---@param pos1 integer[]|string Start of region as a (line, column) tuple or |getpos()|-compatible string +---@param pos2 integer[]|string End of region as a (line, column) tuple or |getpos()|-compatible string +---@param regtype string \|setreg()|-style selection type +---@param inclusive boolean Controls whether the ending column is inclusive (see also 'selection'). +---@return table region Dict of the form `{linenr = {startcol,endcol}}`. `endcol` is exclusive, and +---whole lines are returned as `{startcol,endcol} = {0,-1}`. function vim.region(bufnr, pos1, pos2, regtype, inclusive) if not vim.api.nvim_buf_is_loaded(bufnr) then vim.fn.bufload(bufnr) end + if type(pos1) == 'string' then + local pos = vim.fn.getpos(pos1) + pos1 = { pos[2] - 1, pos[3] - 1 } + end + if type(pos2) == 'string' then + local pos = vim.fn.getpos(pos2) + pos2 = { pos[2] - 1, pos[3] - 1 } + end + + if pos1[1] > pos2[1] or (pos1[1] == pos2[1] and pos1[2] > pos2[2]) then + pos1, pos2 = pos2, pos1 + end + + -- getpos() may return {0,0,0,0} + if pos1[1] < 0 or pos1[2] < 0 then + return {} + end + -- check that region falls within current buffer local buf_line_count = vim.api.nvim_buf_line_count(bufnr) pos1[1] = math.min(pos1[1], buf_line_count - 1) @@ -404,9 +526,8 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive) -- in case of block selection, columns need to be adjusted for non-ASCII characters -- TODO: handle double-width characters - local bufline if regtype:byte() == 22 then - bufline = vim.api.nvim_buf_get_lines(bufnr, pos1[1], pos1[1] + 1, true)[1] + local bufline = vim.api.nvim_buf_get_lines(bufnr, pos1[1], pos1[1] + 1, true)[1] pos1[2] = vim.str_utfindex(bufline, pos1[2]) end @@ -417,7 +538,7 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive) c1 = pos1[2] c2 = c1 + regtype:sub(2) -- and adjust for non-ASCII characters - bufline = vim.api.nvim_buf_get_lines(bufnr, l, l + 1, true)[1] + local bufline = vim.api.nvim_buf_get_lines(bufnr, l, l + 1, true)[1] local utflen = vim.str_utfindex(bufline, #bufline) if c1 <= utflen then c1 = vim.str_byteindex(bufline, c1) @@ -429,18 +550,25 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive) else c2 = #bufline + 1 end + elseif regtype == 'V' then -- linewise selection, always return whole line + c1 = 0 + c2 = -1 else c1 = (l == pos1[1]) and pos1[2] or 0 - c2 = (l == pos2[1]) and (pos2[2] + (inclusive and 1 or 0)) or -1 + if inclusive and l == pos2[1] then + local bufline = vim.api.nvim_buf_get_lines(bufnr, pos2[1], pos2[1] + 1, true)[1] + pos2[2] = vim.fn.byteidx(bufline, vim.fn.charidx(bufline, pos2[2]) + 1) + end + c2 = (l == pos2[1]) and pos2[2] or -1 end table.insert(region, l, { c1, c2 }) end return region end ---- Defers calling `fn` until `timeout` ms passes. +--- Defers calling {fn} until {timeout} ms passes. --- ---- Use to do a one-shot timer that calls `fn` +--- Use to do a one-shot timer that calls {fn} --- Note: The {fn} is |vim.schedule_wrap()|ped automatically, so API functions are --- safe to call. ---@param fn function Callback to call once `timeout` expires @@ -448,7 +576,7 @@ end ---@return table timer luv timer object function vim.defer_fn(fn, timeout) vim.validate({ fn = { fn, 'c', true } }) - local timer = vim.loop.new_timer() + local timer = vim.uv.new_timer() timer:start( timeout, 0, @@ -464,14 +592,14 @@ function vim.defer_fn(fn, timeout) return timer end ---- Display a notification to the user. +--- Displays a notification to the user. --- --- This function can be overridden by plugins to display notifications using a --- custom provider (such as the system notification provider). By default, --- writes to |:messages|. --- ---@param msg string Content of the notification to show to the user. ----@param level number|nil One of the values from |vim.log.levels|. +---@param level integer|nil One of the values from |vim.log.levels|. ---@param opts table|nil Optional parameters. Unused by default. function vim.notify(msg, level, opts) -- luacheck: no unused args if level == vim.log.levels.ERROR then @@ -486,13 +614,13 @@ end do local notified = {} - --- Display a notification only one time. + --- Displays a notification only one time. --- --- Like |vim.notify()|, but subsequent calls with the same message will not --- display a notification. --- ---@param msg string Content of the notification to show to the user. - ---@param level number|nil One of the values from |vim.log.levels|. + ---@param level integer|nil One of the values from |vim.log.levels|. ---@param opts table|nil Optional parameters. Unused by default. ---@return boolean true if message was displayed, else false function vim.notify_once(msg, level, opts) @@ -505,11 +633,6 @@ do end end ----@private -function vim.register_keystroke_callback() - error('vim.register_keystroke_callback is deprecated, instead use: vim.on_key') -end - local on_key_cbs = {} --- Adds Lua function {fn} with namespace id {ns_id} as a listener to every, @@ -518,21 +641,20 @@ local on_key_cbs = {} --- The Nvim command-line option |-w| is related but does not support callbacks --- and cannot be toggled dynamically. --- ----@param fn function: Callback function. It should take one string argument. ---- On each key press, Nvim passes the key char to fn(). |i_CTRL-V| ---- If {fn} is nil, it removes the callback for the associated {ns_id} ----@param ns_id number? Namespace ID. If nil or 0, generates and returns a new ---- |nvim_create_namespace()| id. ---- ----@return number Namespace id associated with {fn}. Or count of all callbacks ----if on_key() is called without arguments. ---- ----@note {fn} will be removed if an error occurs while calling. +---@note {fn} will be removed on error. ---@note {fn} will not be cleared by |nvim_buf_clear_namespace()| ---@note {fn} will receive the keys after mappings have been evaluated +--- +---@param fn fun(key: string) Function invoked on every key press. |i_CTRL-V| +--- Returning nil removes the callback associated with namespace {ns_id}. +---@param ns_id integer? Namespace ID. If nil or 0, generates and returns a +--- new |nvim_create_namespace()| id. +--- +---@return integer Namespace id associated with {fn}. Or count of all callbacks +---if on_key() is called without arguments. function vim.on_key(fn, ns_id) if fn == nil and ns_id == nil then - return #on_key_cbs + return vim.tbl_count(on_key_cbs) end vim.validate({ @@ -573,16 +695,14 @@ function vim._on_key(char) end end ---- Generate a list of possible completions for the string. ---- String starts with ^ and then has the pattern. +--- Generates a list of possible completions for the string. +--- String has the pattern. --- --- 1. Can we get it to just return things in the global namespace with that name prefix --- 2. Can we get it to return things from global namespace even with `print(` in front. function vim._expand_pat(pat, env) env = env or _G - pat = string.sub(pat, 2, #pat) - if pat == '' then local result = vim.tbl_keys(env) table.sort(result) @@ -643,7 +763,7 @@ function vim._expand_pat(pat, env) local mt = getmetatable(final_env) if mt and type(mt.__index) == 'table' then field = rawget(mt.__index, key) - elseif final_env == vim and vim._submodules[key] then + elseif final_env == vim and (vim._submodules[key] or vim._extra[key]) then field = vim[key] end end @@ -655,7 +775,6 @@ function vim._expand_pat(pat, env) end local keys = {} - ---@private local function insert_keys(obj) for k, _ in pairs(obj) do if type(k) == 'string' and string.sub(k, 1, string.len(match_part)) == match_part then @@ -673,6 +792,7 @@ function vim._expand_pat(pat, env) end if final_env == vim then insert_keys(vim._submodules) + insert_keys(vim._extra) end keys = vim.tbl_keys(keys) @@ -744,25 +864,80 @@ vim._expand_pat_get_parts = function(lua_string) return parts, search_index end ----Prints given arguments in human-readable format. ----Example: ----<pre>lua ---- -- 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)) ----</pre> ----@see |vim.inspect()| ----@return any # given arguments. +do + -- Ideally we should just call complete() inside omnifunc, though there are + -- some bugs, so fake the two-step dance for now. + local matches + + --- Omnifunc for completing Lua values from the runtime Lua interpreter, + --- similar to the builtin completion for the `:lua` command. + --- + --- Activate using `set omnifunc=v:lua.vim.lua_omnifunc` in a Lua buffer. + function vim.lua_omnifunc(find_start, _) + if find_start == 1 then + local line = vim.api.nvim_get_current_line() + local prefix = string.sub(line, 1, vim.api.nvim_win_get_cursor(0)[2]) + local pos + matches, pos = vim._expand_pat(prefix) + return (#matches > 0 and pos) or -1 + else + return matches + end + end +end + +---@private function vim.pretty_print(...) - local objects = {} + vim.deprecate('vim.pretty_print', 'vim.print', '0.10') + return vim.print(...) +end + +--- "Pretty prints" the given arguments and returns them unmodified. +--- +--- Example: +--- +--- ```lua +--- local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' })) +--- ``` +--- +--- @see |vim.inspect()| +--- @see |:=| +--- @return any # given arguments. +function vim.print(...) + if vim.in_fast_event() then + print(...) + return ... + end + for i = 1, select('#', ...) do - local v = select(i, ...) - table.insert(objects, vim.inspect(v)) + local o = select(i, ...) + if type(o) == 'string' then + vim.api.nvim_out_write(o) + else + vim.api.nvim_out_write(vim.inspect(o, { newline = '\n', indent = ' ' })) + end + vim.api.nvim_out_write('\n') end - print(table.concat(objects, ' ')) return ... end +--- Translates keycodes. +--- +--- Example: +--- +--- ```lua +--- local k = vim.keycode +--- vim.g.mapleader = k'<bs>' +--- ``` +--- +--- @param str string String to be converted. +--- @return string +--- @see |nvim_replace_termcodes()| +function vim.keycode(str) + return vim.api.nvim_replace_termcodes(str, true, true, true) +end + function vim._cs_remote(rcid, server_addr, connect_error, args) local function connection_failure_errmsg(consequence) local explanation @@ -791,7 +966,7 @@ function vim._cs_remote(rcid, server_addr, connect_error, args) or subcmd == 'tab-wait' or subcmd == 'tab-wait-silent' then - return { errmsg = 'E5600: Wait commands not yet implemented in nvim' } + return { errmsg = 'E5600: Wait commands not yet implemented in Nvim' } elseif subcmd == 'tab-silent' then f_tab = true f_silent = true @@ -799,14 +974,14 @@ function vim._cs_remote(rcid, server_addr, connect_error, args) if rcid == 0 then return { errmsg = connection_failure_errmsg('Send failed.') } end - vim.fn.rpcrequest(rcid, 'nvim_input', args[2]) + vim.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 } + local res = tostring(vim.rpcrequest(rcid, 'nvim_eval', args[2])) + return { result = res, should_exit = true, tabbed = false } elseif subcmd ~= '' then return { errmsg = 'Unknown option argument: ' .. args[1] } end @@ -833,67 +1008,37 @@ function vim._cs_remote(rcid, server_addr, connect_error, args) } end ---- Display a deprecation notification to the user. +--- Shows a deprecation message 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 name string Deprecated feature (function, API, etc.). +---@param alternative string|nil Suggested alternative feature. +---@param version string Version when the deprecated function will be removed. +---@param plugin string|nil Name of the plugin that owns the deprecated feature. +--- Defaults to "Nvim". ---@param backtrace boolean|nil Prints backtrace. Defaults to true. +--- +---@return string|nil # Deprecated message, or nil if no message was shown. function vim.deprecate(name, alternative, version, plugin, backtrace) - local message = name .. ' is deprecated' + local msg = ('%s is deprecated'):format(name) 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 + msg = alternative and ('%s, use %s instead.'):format(msg, alternative) or msg + msg = ('%s%s\nThis feature will be removed in %s version %s'):format( + msg, + (plugin == 'Nvim' and ' :help deprecated' or ''), + plugin, + version + ) + local displayed = vim.notify_once(msg, vim.log.levels.WARN) + if displayed and backtrace ~= false then vim.notify(debug.traceback('', 2):sub(2), vim.log.levels.WARN) end + return displayed and msg or nil 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! <C-L> to prevent inserting raw <C-L> when using i_<C-O>. #17473 - map('n', '<C-L>', '<Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>') - map('i', '<C-U>', '<C-G>u<C-U>') - map('i', '<C-W>', '<C-G>u<C-W>') - map('x', '*', 'y/\\V<C-R>"<CR>') - map('x', '#', 'y?\\V<C-R>"<CR>') - -- Use : instead of <Cmd> so that ranges are supported. #19365 - map('n', '&', ':&&<CR>') - - -- menus - - -- TODO VimScript, no l10n - vim.cmd([[ - aunmenu * - vnoremenu PopUp.Cut "+x - vnoremenu PopUp.Copy "+y - anoremenu PopUp.Paste "+gP - vnoremenu PopUp.Paste "+P - vnoremenu PopUp.Delete "_x - nnoremenu PopUp.Select\ All ggVG - vnoremenu PopUp.Select\ All gg0oG$ - inoremenu PopUp.Select\ All <C-Home><C-O>VG - anoremenu PopUp.-1- <Nop> - anoremenu PopUp.How-to\ disable\ mouse <Cmd>help disable-mouse<CR> - ]]) -end +require('vim._options') -require('vim._meta') +-- Remove at Nvim 1.0 +---@deprecated +vim.loop = vim.uv return vim diff --git a/runtime/lua/vim/_init_packages.lua b/runtime/lua/vim/_init_packages.lua index 0c4ee8636d..4a961970cc 100644 --- a/runtime/lua/vim/_init_packages.lua +++ b/runtime/lua/vim/_init_packages.lua @@ -42,13 +42,23 @@ function vim._load_package(name) return nil end --- Insert vim._load_package after the preloader at position 2 -table.insert(package.loaders, 2, vim._load_package) +-- TODO(bfredl): dedicated state for this? +if vim.api then + -- Insert vim._load_package after the preloader at position 2 + table.insert(package.loaders, 2, vim._load_package) +end -- builtin functions which always should be available require('vim.shared') -vim._submodules = { inspect = true } +vim._submodules = { + inspect = true, + version = true, + fs = true, + iter = true, + re = true, + text = true, +} -- These are for loading runtime modules in the vim namespace lazily. setmetatable(vim, { @@ -78,6 +88,6 @@ function vim.empty_dict() end -- only on main thread: functions for interacting with editor state -if not vim.is_thread() then +if vim.api and not vim.is_thread() then require('vim._editor') end diff --git a/runtime/lua/vim/_inspector.lua b/runtime/lua/vim/_inspector.lua index f46a525910..3f7b9d2c23 100644 --- a/runtime/lua/vim/_inspector.lua +++ b/runtime/lua/vim/_inspector.lua @@ -2,7 +2,7 @@ ---@field syntax boolean include syntax based highlight groups (defaults to true) ---@field treesitter boolean include treesitter based highlight groups (defaults to true) ---@field extmarks boolean|"all" include extmarks. When `all`, then extmarks without a `hl_group` will also be included (defaults to true) ----@field semantic_tokens boolean include semantic tokens (defaults to true) +---@field semantic_tokens boolean include semantic token highlights (defaults to true) local defaults = { syntax = true, treesitter = true, @@ -14,15 +14,15 @@ local defaults = { --- ---Can also be pretty-printed with `:Inspect!`. *:Inspect!* --- ----@param bufnr? number defaults to the current buffer ----@param row? number row to inspect, 0-based. Defaults to the row of the current cursor ----@param col? number col to inspect, 0-based. Defaults to the col of the current cursor +---@param bufnr? integer defaults to the current buffer +---@param row? integer row to inspect, 0-based. Defaults to the row of the current cursor +---@param col? integer col to inspect, 0-based. Defaults to the col of the current cursor ---@param filter? InspectorFilter (table|nil) a table with key-value pairs to filter the items --- - syntax (boolean): include syntax based highlight groups (defaults to true) --- - treesitter (boolean): include treesitter based highlight groups (defaults to true) --- - extmarks (boolean|"all"): include extmarks. When `all`, then extmarks without a `hl_group` will also be included (defaults to true) --- - semantic_tokens (boolean): include semantic tokens (defaults to true) ----@return {treesitter:table,syntax:table,extmarks:table,semantic_tokens:table,buffer:number,col:number,row:number} (table) a table with the following key-value pairs. Items are in "traversal order": +---@return {treesitter:table,syntax:table,extmarks:table,semantic_tokens:table,buffer:integer,col:integer,row:integer} (table) a table with the following key-value pairs. Items are in "traversal order": --- - treesitter: a list of treesitter captures --- - syntax: a list of syntax groups --- - semantic_tokens: a list of semantic tokens @@ -56,7 +56,6 @@ function vim.inspect_pos(bufnr, row, col, filter) } -- resolve hl links - ---@private local function resolve_hl(data) if data.hl_group then local hlid = vim.api.nvim_get_hl_id_by_name(data.hl_group) @@ -69,59 +68,67 @@ function vim.inspect_pos(bufnr, row, col, filter) -- treesitter if filter.treesitter then for _, capture in pairs(vim.treesitter.get_captures_at_pos(bufnr, row, col)) do - capture.hl_group = '@' .. capture.capture - table.insert(results.treesitter, resolve_hl(capture)) + capture.hl_group = '@' .. capture.capture .. '.' .. capture.lang + results.treesitter[#results.treesitter + 1] = resolve_hl(capture) end end -- syntax - if filter.syntax then - for _, i1 in ipairs(vim.fn.synstack(row + 1, col + 1)) do - table.insert(results.syntax, resolve_hl({ hl_group = vim.fn.synIDattr(i1, 'name') })) - end + if filter.syntax and vim.api.nvim_buf_is_valid(bufnr) then + vim.api.nvim_buf_call(bufnr, function() + for _, i1 in ipairs(vim.fn.synstack(row + 1, col + 1)) do + results.syntax[#results.syntax + 1] = + resolve_hl({ hl_group = vim.fn.synIDattr(i1, 'name') }) + end + end) end - -- semantic tokens + -- namespace id -> name map + local nsmap = {} + for name, id in pairs(vim.api.nvim_get_namespaces()) do + nsmap[id] = name + end + + --- Convert an extmark tuple into a table + local function to_map(extmark) + extmark = { + id = extmark[1], + row = extmark[2], + col = extmark[3], + opts = resolve_hl(extmark[4]), + } + extmark.ns_id = extmark.opts.ns_id + extmark.ns = nsmap[extmark.ns_id] or '' + extmark.end_row = extmark.opts.end_row or extmark.row -- inclusive + extmark.end_col = extmark.opts.end_col or (extmark.col + 1) -- exclusive + return extmark + end + + --- Check if an extmark overlaps this position + local function is_here(extmark) + return (row >= extmark.row and row <= extmark.end_row) -- within the rows of the extmark + and (row > extmark.row or col >= extmark.col) -- either not the first row, or in range of the col + and (row < extmark.end_row or col < extmark.end_col) -- either not in the last row or in range of the col + end + + -- all extmarks at this position + local extmarks = vim.api.nvim_buf_get_extmarks(bufnr, -1, 0, -1, { details = true }) + extmarks = vim.tbl_map(to_map, extmarks) + extmarks = vim.tbl_filter(is_here, extmarks) + if filter.semantic_tokens then - for _, token in ipairs(vim.lsp.semantic_tokens.get_at_pos(bufnr, row, col) or {}) do - token.hl_groups = { - type = resolve_hl({ hl_group = '@' .. token.type }), - modifiers = vim.tbl_map(function(modifier) - return resolve_hl({ hl_group = '@' .. modifier }) - end, token.modifiers or {}), - } - table.insert(results.semantic_tokens, token) - end + results.semantic_tokens = vim.tbl_filter(function(extmark) + return extmark.ns:find('vim_lsp_semantic_tokens') == 1 + end, extmarks) end - -- extmarks if filter.extmarks then - for ns, nsid in pairs(vim.api.nvim_get_namespaces()) do - if ns:find('vim_lsp_semantic_tokens') ~= 1 then - local extmarks = vim.api.nvim_buf_get_extmarks(bufnr, nsid, 0, -1, { details = true }) - for _, extmark in ipairs(extmarks) do - extmark = { - ns_id = nsid, - ns = ns, - id = extmark[1], - row = extmark[2], - col = extmark[3], - opts = resolve_hl(extmark[4]), - } - local end_row = extmark.opts.end_row or extmark.row -- inclusive - local end_col = extmark.opts.end_col or (extmark.col + 1) -- exclusive - if - (filter.extmarks == 'all' or extmark.opts.hl_group) -- filter hl_group - and (row >= extmark.row and row <= end_row) -- within the rows of the extmark - and (row > extmark.row or col >= extmark.col) -- either not the first row, or in range of the col - and (row < end_row or col < end_col) -- either not in the last row or in range of the col - then - table.insert(results.extmarks, extmark) - end - end - end - end + results.extmarks = vim.tbl_filter(function(extmark) + return extmark.ns:find('vim_lsp_semantic_tokens') ~= 1 + and (filter.extmarks == 'all' or extmark.opts.hl_group) + end, extmarks) end + return results end @@ -129,26 +136,23 @@ end --- ---Can also be shown with `:Inspect`. *:Inspect* --- ----@param bufnr? number defaults to the current buffer ----@param row? number row to inspect, 0-based. Defaults to the row of the current cursor ----@param col? number col to inspect, 0-based. Defaults to the col of the current cursor +---@param bufnr? integer defaults to the current buffer +---@param row? integer row to inspect, 0-based. Defaults to the row of the current cursor +---@param col? integer col to inspect, 0-based. Defaults to the col of the current cursor ---@param filter? InspectorFilter (table|nil) see |vim.inspect_pos()| function vim.show_pos(bufnr, row, col, filter) local items = vim.inspect_pos(bufnr, row, col, filter) local lines = { {} } - ---@private local function append(str, hl) table.insert(lines[#lines], { str, hl }) end - ---@private local function nl() table.insert(lines, {}) end - ---@private local function item(data, comment) append(' - ') append(data.hl_group, data.hl_group) @@ -174,16 +178,17 @@ function vim.show_pos(bufnr, row, col, filter) nl() end + -- semantic tokens if #items.semantic_tokens > 0 then append('Semantic Tokens', 'Title') nl() - for _, token in ipairs(items.semantic_tokens) do - local client = vim.lsp.get_client_by_id(token.client_id) - client = client and (' (' .. client.name .. ')') or '' - item(token.hl_groups.type, 'type' .. client) - for _, modifier in ipairs(token.hl_groups.modifiers) do - item(modifier, 'modifier' .. client) - end + local sorted_marks = vim.fn.sort(items.semantic_tokens, function(left, right) + local left_first = left.opts.priority < right.opts.priority + or left.opts.priority == right.opts.priority and left.opts.hl_group < right.opts.hl_group + return left_first and -1 or 1 + end) + for _, extmark in ipairs(sorted_marks) do + item(extmark.opts, 'priority: ' .. extmark.opts.priority) end nl() end @@ -197,6 +202,7 @@ function vim.show_pos(bufnr, row, col, filter) end nl() end + -- extmarks if #items.extmarks > 0 then append('Extmarks', 'Title') diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua index 104f29c4c0..e3b99f6b3d 100644 --- a/runtime/lua/vim/_meta.lua +++ b/runtime/lua/vim/_meta.lua @@ -1,540 +1,32 @@ -local a = vim.api - --- TODO(tjdevries): Improve option metadata so that this doesn't have to be hardcoded. --- Can be done in a separate PR. -local key_value_options = { - fillchars = true, - fcs = true, - listchars = true, - lcs = true, - winhighlight = true, - winhl = true, -} - ---- Convert a vimoption_T style dictionary to the correct OptionType associated with it. ----@return string -local function get_option_metatype(name, info) - if info.type == 'string' then - if info.flaglist then - return 'set' - elseif info.commalist then - if key_value_options[name] then - return 'map' - end - return 'array' - end - return 'string' - end - return info.type -end - -local options_info = setmetatable({}, { - __index = function(t, k) - local info = a.nvim_get_option_info(k) - info.metatype = get_option_metatype(k, info) - rawset(t, k, info) - return rawget(t, k) - end, -}) - -vim.env = setmetatable({}, { - __index = function(_, k) - local v = vim.fn.getenv(k) - if v == vim.NIL then - return nil - end - return v - end, - - __newindex = function(_, k, v) - vim.fn.setenv(k, v) - end, -}) - -local function opt_validate(option_name, target_scope) - local scope = options_info[option_name].scope - if scope ~= target_scope then - local scope_to_string = { buf = 'buffer', win = 'window' } - error( - string.format( - [['%s' is a %s option, not a %s option. See ":help %s"]], - option_name, - scope_to_string[scope] or scope, - scope_to_string[target_scope] or target_scope, - option_name - ) - ) - end -end - -local function new_opt_accessor(handle, scope) - return setmetatable({}, { - __index = function(_, k) - if handle == nil and type(k) == 'number' then - return new_opt_accessor(k, scope) - end - opt_validate(k, scope) - return a.nvim_get_option_value(k, { [scope] = handle or 0 }) - end, - - __newindex = function(_, k, v) - opt_validate(k, scope) - return a.nvim_set_option_value(k, v, { [scope] = handle or 0 }) - end, - }) -end - -vim.bo = new_opt_accessor(nil, 'buf') -vim.wo = new_opt_accessor(nil, 'win') - --- vim global option --- this ONLY sets the global option. like `setglobal` -vim.go = setmetatable({}, { - __index = function(_, k) - return a.nvim_get_option_value(k, { scope = 'global' }) - end, - __newindex = function(_, k, v) - return a.nvim_set_option_value(k, v, { scope = 'global' }) - end, -}) - --- vim `set` style options. --- it has no additional metamethod magic. -vim.o = setmetatable({}, { - __index = function(_, k) - return a.nvim_get_option_value(k, {}) - end, - __newindex = function(_, k, v) - return a.nvim_set_option_value(k, v, {}) - end, -}) - ----@brief [[ ---- vim.opt, vim.opt_local and vim.opt_global implementation ---- ---- To be used as helpers for working with options within neovim. ---- For information on how to use, see :help vim.opt ---- ----@brief ]] - ---- Preserves the order and does not mutate the original list -local function remove_duplicate_values(t) - local result, seen = {}, {} - for _, v in ipairs(t) do - if not seen[v] then - table.insert(result, v) - end - - seen[v] = true - end - - return result -end - --- Check whether the OptionTypes is allowed for vim.opt --- If it does not match, throw an error which indicates which option causes the error. -local function assert_valid_value(name, value, types) - local type_of_value = type(value) - for _, valid_type in ipairs(types) do - if valid_type == type_of_value then - return - end - end - - error( - string.format( - "Invalid option type '%s' for '%s', should be %s", - type_of_value, - name, - table.concat(types, ' or ') - ) - ) -end - -local function passthrough(_, x) - return x -end - -local function tbl_merge(left, right) - return vim.tbl_extend('force', left, right) -end - -local function tbl_remove(t, value) - if type(value) == 'string' then - t[value] = nil - else - for _, v in ipairs(value) do - t[v] = nil - end - end - - return t -end - -local valid_types = { - boolean = { 'boolean' }, - number = { 'number' }, - string = { 'string' }, - set = { 'string', 'table' }, - array = { 'string', 'table' }, - map = { 'string', 'table' }, -} - --- Map of functions to take a Lua style value and convert to vimoption_T style value. --- Each function takes (info, lua_value) -> vim_value -local to_vim_value = { - boolean = passthrough, - number = passthrough, - string = passthrough, - - set = function(info, value) - if type(value) == 'string' then - return value - end - - if info.flaglist and info.commalist then - local keys = {} - for k, v in pairs(value) do - if v then - table.insert(keys, k) - end - end - - table.sort(keys) - return table.concat(keys, ',') - else - local result = '' - for k, v in pairs(value) do - if v then - result = result .. k - end - end - - return result - end - end, - - array = function(info, value) - if type(value) == 'string' then - return value - end - if not info.allows_duplicates then - value = remove_duplicate_values(value) - end - return table.concat(value, ',') - end, - - map = function(_, value) - if type(value) == 'string' then - return value - end - - local result = {} - for opt_key, opt_value in pairs(value) do - table.insert(result, string.format('%s:%s', opt_key, opt_value)) - end - - table.sort(result) - return table.concat(result, ',') - end, -} - ---- Convert a lua value to a vimoption_T value -local function convert_value_to_vim(name, info, value) - if value == nil then - return vim.NIL - end - - assert_valid_value(name, value, valid_types[info.metatype]) - - return to_vim_value[info.metatype](info, value) -end - --- Map of OptionType to functions that take vimoption_T values and convert to lua values. --- Each function takes (info, vim_value) -> lua_value -local to_lua_value = { - boolean = passthrough, - number = passthrough, - string = passthrough, - - array = function(info, value) - if type(value) == 'table' then - if not info.allows_duplicates then - value = remove_duplicate_values(value) - end - - return value - end - - -- Empty strings mean that there is nothing there, - -- so empty table should be returned. - if value == '' then - return {} - end - - -- Handles unescaped commas in a list. - if string.find(value, ',,,') then - local left, right = unpack(vim.split(value, ',,,')) - - local result = {} - vim.list_extend(result, vim.split(left, ',')) - table.insert(result, ',') - vim.list_extend(result, vim.split(right, ',')) - - table.sort(result) - - return result - end - - if string.find(value, ',^,,', 1, true) then - local left, right = unpack(vim.split(value, ',^,,', true)) - - local result = {} - vim.list_extend(result, vim.split(left, ',')) - table.insert(result, '^,') - vim.list_extend(result, vim.split(right, ',')) - - table.sort(result) - - return result - end - - return vim.split(value, ',') - end, - - set = function(info, value) - if type(value) == 'table' then - return value - end - - -- Empty strings mean that there is nothing there, - -- so empty table should be returned. - if value == '' then - return {} - end - - assert(info.flaglist, 'That is the only one I know how to handle') - - if info.flaglist and info.commalist then - local split_value = vim.split(value, ',') - local result = {} - for _, v in ipairs(split_value) do - result[v] = true - end - - return result - else - local result = {} - for i = 1, #value do - result[value:sub(i, i)] = true - end - - return result - end - end, - - map = function(info, raw_value) - if type(raw_value) == 'table' then - return raw_value - end - - assert(info.commalist, 'Only commas are supported currently') - - local result = {} - - local comma_split = vim.split(raw_value, ',') - for _, key_value_str in ipairs(comma_split) do - local key, value = unpack(vim.split(key_value_str, ':')) - key = vim.trim(key) - - result[key] = value - end - - return result - end, -} - ---- Converts a vimoption_T style value to a Lua value -local function convert_value_to_lua(info, option_value) - return to_lua_value[info.metatype](info, option_value) -end - -local prepend_methods = { - number = function() - error("The '^' operator is not currently supported for") - end, - - string = function(left, right) - return right .. left - end, - - array = function(left, right) - for i = #right, 1, -1 do - table.insert(left, 1, right[i]) - end - - return left - end, - - map = tbl_merge, - set = tbl_merge, -} - ---- Handles the '^' operator -local function prepend_value(info, current, new) - return prepend_methods[info.metatype]( - convert_value_to_lua(info, current), - convert_value_to_lua(info, new) - ) -end - -local add_methods = { - number = function(left, right) - return left + right - end, - - string = function(left, right) - return left .. right - end, - - array = function(left, right) - for _, v in ipairs(right) do - table.insert(left, v) - end - - return left - end, - - map = tbl_merge, - set = tbl_merge, -} - ---- Handles the '+' operator -local function add_value(info, current, new) - return add_methods[info.metatype]( - convert_value_to_lua(info, current), - convert_value_to_lua(info, new) - ) -end - -local function remove_one_item(t, val) - if vim.tbl_islist(t) then - local remove_index = nil - for i, v in ipairs(t) do - if v == val then - remove_index = i - end - end - - if remove_index then - table.remove(t, remove_index) - end - else - t[val] = nil - end -end - -local remove_methods = { - number = function(left, right) - return left - right - end, - - string = function() - error('Subtraction not supported for strings.') - end, - - array = function(left, right) - if type(right) == 'string' then - remove_one_item(left, right) - else - for _, v in ipairs(right) do - remove_one_item(left, v) - end - end - - return left - end, - - map = tbl_remove, - set = tbl_remove, -} - ---- Handles the '-' operator -local function remove_value(info, current, new) - return remove_methods[info.metatype](convert_value_to_lua(info, current), new) -end - -local function create_option_accessor(scope) - local option_mt - - local function make_option(name, value) - local info = assert(options_info[name], 'Not a valid option name: ' .. name) - - if type(value) == 'table' and getmetatable(value) == option_mt then - assert(name == value._name, "must be the same value, otherwise that's weird.") - - value = value._value - end - - return setmetatable({ - _name = name, - _value = value, - _info = info, - }, option_mt) - end - - option_mt = { - -- To set a value, instead use: - -- opt[my_option] = value - _set = function(self) - local value = convert_value_to_vim(self._name, self._info, self._value) - a.nvim_set_option_value(self._name, value, { scope = scope }) - end, - - get = function(self) - return convert_value_to_lua(self._info, self._value) - end, - - append = function(self, right) - self._value = add_value(self._info, self._value, right) - self:_set() - end, - - __add = function(self, right) - return make_option(self._name, add_value(self._info, self._value, right)) - end, - - prepend = function(self, right) - self._value = prepend_value(self._info, self._value, right) - self:_set() - end, - - __pow = function(self, right) - return make_option(self._name, prepend_value(self._info, self._value, right)) - end, - - remove = function(self, right) - self._value = remove_value(self._info, self._value, right) - self:_set() - end, - - __sub = function(self, right) - return make_option(self._name, remove_value(self._info, self._value, right)) - end, - } - option_mt.__index = option_mt - - return setmetatable({}, { - __index = function(_, k) - return make_option(k, a.nvim_get_option_value(k, {})) - end, - - __newindex = function(_, k, v) - make_option(k, v):_set() - end, - }) -end - -vim.opt = create_option_accessor() -vim.opt_local = create_option_accessor('local') -vim.opt_global = create_option_accessor('global') +--- @meta + +---@type uv +vim.uv = ... + +--- The following modules are loaded specially in _init_packages.lua + +vim.F = require('vim.F') +vim._watch = require('vim._watch') +vim.diagnostic = require('vim.diagnostic') +vim.filetype = require('vim.filetype') +vim.fs = require('vim.fs') +vim.func = require('vim.func') +vim.health = require('vim.health') +vim.highlight = require('vim.highlight') +vim.iter = require('vim.iter') +vim.keymap = require('vim.keymap') +vim.loader = require('vim.loader') +vim.lsp = require('vim.lsp') +vim.re = require('vim.re') +vim.secure = require('vim.secure') +vim.snippet = require('vim.snippet') +vim.treesitter = require('vim.treesitter') +vim.ui = require('vim.ui') +vim.version = require('vim.version') + +local uri = require('vim.uri') + +vim.uri_from_fname = uri.uri_from_fname +vim.uri_from_bufnr = uri.uri_from_bufnr +vim.uri_to_fname = uri.uri_to_fname +vim.uri_to_bufnr = uri.uri_to_bufnr diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua new file mode 100644 index 0000000000..49269ba631 --- /dev/null +++ b/runtime/lua/vim/_meta/api.lua @@ -0,0 +1,2102 @@ +--- @meta _ +-- THIS FILE IS GENERATED +-- DO NOT EDIT +error('Cannot require a meta file') + +vim.api = {} + +--- @private +--- @param buffer integer +--- @param keys boolean +--- @param dot boolean +--- @return string +function vim.api.nvim__buf_debug_extmarks(buffer, keys, dot) end + +--- @private +--- @param buffer integer +--- @param first integer +--- @param last integer +function vim.api.nvim__buf_redraw_range(buffer, first, last) end + +--- @private +--- @param buffer integer +--- @return table<string,any> +function vim.api.nvim__buf_stats(buffer) end + +--- @private +--- @return string +function vim.api.nvim__get_lib_dir() end + +--- @private +--- Find files in runtime directories +--- +--- @param pat any[] pattern of files to search for +--- @param all boolean whether to return all matches or only the first +--- @param opts vim.api.keyset.runtime is_lua: only search Lua subdirs +--- @return string[] +function vim.api.nvim__get_runtime(pat, all, opts) end + +--- @private +--- Returns object given as argument. +--- This API function is used for testing. One should not rely on its presence +--- in plugins. +--- +--- @param obj any Object to return. +--- @return any +function vim.api.nvim__id(obj) end + +--- @private +--- Returns array given as argument. +--- This API function is used for testing. One should not rely on its presence +--- in plugins. +--- +--- @param arr any[] Array to return. +--- @return any[] +function vim.api.nvim__id_array(arr) end + +--- @private +--- Returns dictionary given as argument. +--- This API function is used for testing. One should not rely on its presence +--- in plugins. +--- +--- @param dct table<string,any> Dictionary to return. +--- @return table<string,any> +function vim.api.nvim__id_dictionary(dct) end + +--- @private +--- Returns floating-point value given as argument. +--- This API function is used for testing. One should not rely on its presence +--- in plugins. +--- +--- @param flt number Value to return. +--- @return number +function vim.api.nvim__id_float(flt) end + +--- @private +--- @param grid integer +--- @param row integer +--- @param col integer +--- @return any[] +function vim.api.nvim__inspect_cell(grid, row, col) end + +--- @private +--- For testing. The condition in schar_cache_clear_if_full is hard to reach, +--- so this function can be used to force a cache clear in a test. +--- +function vim.api.nvim__invalidate_glyph_cache() end + +--- @private +--- @return any[] +function vim.api.nvim__runtime_inspect() end + +--- @private +--- @param path string +function vim.api.nvim__screenshot(path) end + +--- @private +--- Gets internal stats. +--- +--- @return table<string,any> +function vim.api.nvim__stats() end + +--- @private +--- @param str string +--- @return any +function vim.api.nvim__unpack(str) end + +--- Adds a highlight to buffer. +--- Useful for plugins that dynamically generate highlights to a buffer (like +--- a semantic highlighter or linter). The function adds a single highlight to +--- a buffer. Unlike `matchaddpos()` highlights follow changes to line +--- numbering (as lines are inserted/removed above the highlighted line), like +--- signs and marks do. +--- Namespaces are used for batch deletion/updating of a set of highlights. To +--- create a namespace, use `nvim_create_namespace()` which returns a +--- namespace id. Pass it in to this function as `ns_id` to add highlights to +--- the namespace. All highlights in the same namespace can then be cleared +--- with single call to `nvim_buf_clear_namespace()`. If the highlight never +--- will be deleted by an API call, pass `ns_id = -1`. +--- As a shorthand, `ns_id = 0` can be used to create a new namespace for the +--- highlight, the allocated id is then returned. If `hl_group` is the empty +--- string no highlight is added, but a new `ns_id` is still returned. This is +--- supported for backwards compatibility, new code should use +--- `nvim_create_namespace()` to create a new empty namespace. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param ns_id integer namespace to use or -1 for ungrouped highlight +--- @param hl_group string Name of the highlight group to use +--- @param line integer Line to highlight (zero-indexed) +--- @param col_start integer Start of (byte-indexed) column range to highlight +--- @param col_end integer End of (byte-indexed) column range to highlight, or -1 to +--- highlight to end of line +--- @return integer +function vim.api.nvim_buf_add_highlight(buffer, ns_id, hl_group, line, col_start, col_end) end + +--- Activates buffer-update events on a channel, or as Lua callbacks. +--- Example (Lua): capture buffer updates in a global `events` variable (use +--- "vim.print(events)" to see its contents): +--- +--- ```lua +--- events = {} +--- vim.api.nvim_buf_attach(0, false, { +--- on_lines = function(...) +--- table.insert(events, {...}) +--- end, +--- }) +--- ``` +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param send_buffer boolean True if the initial notification should contain the +--- whole buffer: first notification will be +--- `nvim_buf_lines_event`. Else the first notification +--- will be `nvim_buf_changedtick_event`. Not for Lua +--- callbacks. +--- @param opts table<string,function> Optional parameters. +--- • on_lines: Lua callback invoked on change. Return `true` to detach. Args: +--- • the string "lines" +--- • buffer handle +--- • b:changedtick +--- • first line that changed (zero-indexed) +--- • last line that was changed +--- • last line in the updated range +--- • byte count of previous contents +--- • deleted_codepoints (if `utf_sizes` is true) +--- • deleted_codeunits (if `utf_sizes` is true) +--- +--- • on_bytes: Lua callback invoked on change. This +--- callback receives more granular information about the +--- change compared to on_lines. Return `true` to detach. Args: +--- • the string "bytes" +--- • buffer handle +--- • b:changedtick +--- • start row of the changed text (zero-indexed) +--- • start column of the changed text +--- • byte offset of the changed text (from the start of +--- the buffer) +--- • old end row of the changed text +--- • old end column of the changed text +--- • old end byte length of the changed text +--- • new end row of the changed text +--- • new end column of the changed text +--- • new end byte length of the changed text +--- +--- • on_changedtick: Lua callback invoked on changedtick +--- increment without text change. Args: +--- • the string "changedtick" +--- • buffer handle +--- • b:changedtick +--- +--- • on_detach: Lua callback invoked on detach. Args: +--- • the string "detach" +--- • buffer handle +--- +--- • on_reload: Lua callback invoked on reload. The entire +--- buffer content should be considered changed. Args: +--- • the string "reload" +--- • buffer handle +--- +--- • utf_sizes: include UTF-32 and UTF-16 size of the +--- replaced region, as args to `on_lines`. +--- • preview: also attach to command preview (i.e. +--- 'inccommand') events. +--- @return boolean +function vim.api.nvim_buf_attach(buffer, send_buffer, opts) end + +--- call a function with buffer as temporary current buffer +--- This temporarily switches current buffer to "buffer". If the current +--- window already shows "buffer", the window is not switched If a window +--- inside the current tabpage (including a float) already shows the buffer +--- One of these windows will be set as current window temporarily. Otherwise +--- a temporary scratch window (called the "autocmd window" for historical +--- reasons) will be used. +--- This is useful e.g. to call Vimscript functions that only work with the +--- current buffer/window currently, like `termopen()`. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param fun function Function to call inside the buffer (currently Lua callable +--- only) +--- @return any +function vim.api.nvim_buf_call(buffer, fun) end + +--- @deprecated +--- @param buffer integer +--- @param ns_id integer +--- @param line_start integer +--- @param line_end integer +function vim.api.nvim_buf_clear_highlight(buffer, ns_id, line_start, line_end) end + +--- Clears `namespace`d objects (highlights, `extmarks`, virtual text) from a +--- region. +--- Lines are 0-indexed. `api-indexing` To clear the namespace in the entire +--- buffer, specify line_start=0 and line_end=-1. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param ns_id integer Namespace to clear, or -1 to clear all namespaces. +--- @param line_start integer Start of range of lines to clear +--- @param line_end integer End of range of lines to clear (exclusive) or -1 to +--- clear to end of buffer. +function vim.api.nvim_buf_clear_namespace(buffer, ns_id, line_start, line_end) end + +--- Creates a buffer-local command `user-commands`. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer. +--- @param name string +--- @param command any +--- @param opts vim.api.keyset.user_command +function vim.api.nvim_buf_create_user_command(buffer, name, command, opts) end + +--- Removes an `extmark`. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param ns_id integer Namespace id from `nvim_create_namespace()` +--- @param id integer Extmark id +--- @return boolean +function vim.api.nvim_buf_del_extmark(buffer, ns_id, id) end + +--- Unmaps a buffer-local `mapping` for the given mode. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param mode string +--- @param lhs string +function vim.api.nvim_buf_del_keymap(buffer, mode, lhs) end + +--- Deletes a named mark in the buffer. See `mark-motions`. +--- +--- @param buffer integer Buffer to set the mark on +--- @param name string Mark name +--- @return boolean +function vim.api.nvim_buf_del_mark(buffer, name) end + +--- Delete a buffer-local user-defined command. +--- Only commands created with `:command-buffer` or +--- `nvim_buf_create_user_command()` can be deleted with this function. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer. +--- @param name string Name of the command to delete. +function vim.api.nvim_buf_del_user_command(buffer, name) end + +--- Removes a buffer-scoped (b:) variable +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param name string Variable name +function vim.api.nvim_buf_del_var(buffer, name) end + +--- Deletes the buffer. See `:bwipeout` +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param opts table<string,any> Optional parameters. Keys: +--- • force: Force deletion and ignore unsaved changes. +--- • unload: Unloaded only, do not delete. See `:bunload` +function vim.api.nvim_buf_delete(buffer, opts) end + +--- Gets a changed tick of a buffer +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @return integer +function vim.api.nvim_buf_get_changedtick(buffer) end + +--- Gets a map of buffer-local `user-commands`. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param opts vim.api.keyset.get_commands Optional parameters. Currently not used. +--- @return table<string,any> +function vim.api.nvim_buf_get_commands(buffer, opts) end + +--- Gets the position (0-indexed) of an `extmark`. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param ns_id integer Namespace id from `nvim_create_namespace()` +--- @param id integer Extmark id +--- @param opts table<string,any> Optional parameters. Keys: +--- • details: Whether to include the details dict +--- • hl_name: Whether to include highlight group name instead +--- of id, true if omitted +--- @return integer[] +function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end + +--- Gets `extmarks` (including `signs`) in "traversal order" from a `charwise` +--- region defined by buffer positions (inclusive, 0-indexed `api-indexing`). +--- Region can be given as (row,col) tuples, or valid extmark ids (whose +--- positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1) +--- respectively, thus the following are equivalent: +--- +--- ```lua +--- vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -1, {}) +--- vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) +--- ``` +--- +--- If `end` is less than `start`, traversal works backwards. (Useful with +--- `limit`, to get the first marks prior to a given position.) +--- Note: when using extmark ranges (marks with a end_row/end_col position) +--- the `overlap` option might be useful. Otherwise only the start position of +--- an extmark will be considered. +--- Example: +--- +--- ```lua +--- local api = vim.api +--- local pos = api.nvim_win_get_cursor(0) +--- local ns = api.nvim_create_namespace('my-plugin') +--- -- Create new extmark at line 1, column 1. +--- local m1 = api.nvim_buf_set_extmark(0, ns, 0, 0, {}) +--- -- Create new extmark at line 3, column 1. +--- local m2 = api.nvim_buf_set_extmark(0, ns, 2, 0, {}) +--- -- Get extmarks only from line 3. +--- local ms = api.nvim_buf_get_extmarks(0, ns, {2,0}, {2,0}, {}) +--- -- Get all marks in this buffer + namespace. +--- local all = api.nvim_buf_get_extmarks(0, ns, 0, -1, {}) +--- vim.print(ms) +--- ``` +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param ns_id integer Namespace id from `nvim_create_namespace()` or -1 for all +--- namespaces +--- @param start any Start of range: a 0-indexed (row, col) or valid extmark id +--- (whose position defines the bound). `api-indexing` +--- @param end_ any End of range (inclusive): a 0-indexed (row, col) or valid +--- extmark id (whose position defines the bound). +--- `api-indexing` +--- @param opts vim.api.keyset.get_extmarks Optional parameters. Keys: +--- • limit: Maximum number of marks to return +--- • details: Whether to include the details dict +--- • hl_name: Whether to include highlight group name instead +--- of id, true if omitted +--- • overlap: Also include marks which overlap the range, even +--- if their start position is less than `start` +--- • type: Filter marks by type: "highlight", "sign", +--- "virt_text" and "virt_lines" +--- @return any[] +function vim.api.nvim_buf_get_extmarks(buffer, ns_id, start, end_, opts) end + +--- Gets a list of buffer-local `mapping` definitions. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param mode string Mode short-name ("n", "i", "v", ...) +--- @return table<string,any>[] +function vim.api.nvim_buf_get_keymap(buffer, mode) end + +--- Gets a line-range from the buffer. +--- Indexing is zero-based, end-exclusive. Negative indices are interpreted as +--- length+1+index: -1 refers to the index past the end. So to get the last +--- element use start=-2 and end=-1. +--- Out-of-bounds indices are clamped to the nearest valid value, unless +--- `strict_indexing` is set. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param start integer First line index +--- @param end_ integer Last line index, exclusive +--- @param strict_indexing boolean Whether out-of-bounds should be an error. +--- @return string[] +function vim.api.nvim_buf_get_lines(buffer, start, end_, strict_indexing) end + +--- Returns a `(row,col)` tuple representing the position of the named mark. +--- "End of line" column position is returned as `v:maxcol` (big number). See +--- `mark-motions`. +--- Marks are (1,0)-indexed. `api-indexing` +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param name string Mark name +--- @return integer[] +function vim.api.nvim_buf_get_mark(buffer, name) end + +--- Gets the full file name for the buffer +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @return string +function vim.api.nvim_buf_get_name(buffer) end + +--- @deprecated +--- @param buffer integer +--- @return integer +function vim.api.nvim_buf_get_number(buffer) end + +--- Returns the byte offset of a line (0-indexed). `api-indexing` +--- Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is one byte. +--- 'fileformat' and 'fileencoding' are ignored. The line index just after the +--- last line gives the total byte-count of the buffer. A final EOL byte is +--- counted if it would be written, see 'eol'. +--- Unlike `line2byte()`, throws error for out-of-bounds indexing. Returns -1 +--- for unloaded buffer. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param index integer Line index +--- @return integer +function vim.api.nvim_buf_get_offset(buffer, index) end + +--- @deprecated +--- @param buffer integer +--- @param name string +--- @return any +function vim.api.nvim_buf_get_option(buffer, name) end + +--- Gets a range from the buffer. +--- This differs from `nvim_buf_get_lines()` in that it allows retrieving only +--- portions of a line. +--- Indexing is zero-based. Row indices are end-inclusive, and column indices +--- are end-exclusive. +--- Prefer `nvim_buf_get_lines()` when retrieving entire lines. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param start_row integer First line index +--- @param start_col integer Starting column (byte offset) on first line +--- @param end_row integer Last line index, inclusive +--- @param end_col integer Ending column (byte offset) on last line, exclusive +--- @param opts table<string,any> Optional parameters. Currently unused. +--- @return string[] +function vim.api.nvim_buf_get_text(buffer, start_row, start_col, end_row, end_col, opts) end + +--- Gets a buffer-scoped (b:) variable. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param name string Variable name +--- @return any +function vim.api.nvim_buf_get_var(buffer, name) end + +--- Checks if a buffer is valid and loaded. See `api-buffer` for more info +--- about unloaded buffers. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @return boolean +function vim.api.nvim_buf_is_loaded(buffer) end + +--- Checks if a buffer is valid. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @return boolean +function vim.api.nvim_buf_is_valid(buffer) end + +--- Returns the number of lines in the given buffer. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @return integer +function vim.api.nvim_buf_line_count(buffer) end + +--- Creates or updates an `extmark`. +--- By default a new extmark is created when no id is passed in, but it is +--- also possible to create a new mark by passing in a previously unused id or +--- move an existing mark by passing in its id. The caller must then keep +--- track of existing and unused ids itself. (Useful over RPC, to avoid +--- waiting for the return value.) +--- Using the optional arguments, it is possible to use this to highlight a +--- range of text, and also to associate virtual text to the mark. +--- If present, the position defined by `end_col` and `end_row` should be +--- after the start position in order for the extmark to cover a range. An +--- earlier end position is not an error, but then it behaves like an empty +--- range (no highlighting). +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param ns_id integer Namespace id from `nvim_create_namespace()` +--- @param line integer Line where to place the mark, 0-based. `api-indexing` +--- @param col integer Column where to place the mark, 0-based. `api-indexing` +--- @param opts vim.api.keyset.set_extmark Optional parameters. +--- • id : id of the extmark to edit. +--- • end_row : ending line of the mark, 0-based inclusive. +--- • end_col : ending col of the mark, 0-based exclusive. +--- • hl_group : name of the highlight group used to highlight +--- this mark. +--- • hl_eol : when true, for a multiline highlight covering the +--- EOL of a line, continue the highlight for the rest of the +--- screen line (just like for diff and cursorline highlight). +--- • virt_text : virtual text to link to this mark. A list of +--- [text, highlight] tuples, each representing a text chunk +--- with specified highlight. `highlight` element can either +--- be a single highlight group, or an array of multiple +--- highlight groups that will be stacked (highest priority +--- last). A highlight group can be supplied either as a +--- string or as an integer, the latter which can be obtained +--- using `nvim_get_hl_id_by_name()`. +--- • virt_text_pos : position of virtual text. Possible values: +--- • "eol": right after eol character (default). +--- • "overlay": display over the specified column, without +--- shifting the underlying text. +--- • "right_align": display right aligned in the window. +--- • "inline": display at the specified column, and shift the +--- buffer text to the right as needed. +--- +--- • virt_text_win_col : position the virtual text at a fixed +--- window column (starting from the first text column of the +--- screen line) instead of "virt_text_pos". +--- • virt_text_hide : hide the virtual text when the background +--- text is selected or hidden because of scrolling with +--- 'nowrap' or 'smoothscroll'. Currently only affects +--- "overlay" virt_text. +--- • hl_mode : control how highlights are combined with the +--- highlights of the text. Currently only affects virt_text +--- highlights, but might affect `hl_group` in later versions. +--- • "replace": only show the virt_text color. This is the +--- default. +--- • "combine": combine with background text color. +--- • "blend": blend with background text color. Not supported +--- for "inline" virt_text. +--- +--- • virt_lines : virtual lines to add next to this mark This +--- should be an array over lines, where each line in turn is +--- an array over [text, highlight] tuples. In general, buffer +--- and window options do not affect the display of the text. +--- In particular 'wrap' and 'linebreak' options do not take +--- effect, so the number of extra screen lines will always +--- match the size of the array. However the 'tabstop' buffer +--- option is still used for hard tabs. By default lines are +--- placed below the buffer line containing the mark. +--- • virt_lines_above: place virtual lines above instead. +--- • virt_lines_leftcol: Place extmarks in the leftmost column +--- of the window, bypassing sign and number columns. +--- • ephemeral : for use with `nvim_set_decoration_provider()` +--- callbacks. The mark will only be used for the current +--- redraw cycle, and not be permantently stored in the +--- buffer. +--- • right_gravity : boolean that indicates the direction the +--- extmark will be shifted in when new text is inserted (true +--- for right, false for left). Defaults to true. +--- • end_right_gravity : boolean that indicates the direction +--- the extmark end position (if it exists) will be shifted in +--- when new text is inserted (true for right, false for +--- left). Defaults to false. +--- • undo_restore : Restore the exact position of the mark if +--- text around the mark was deleted and then restored by +--- undo. Defaults to true. +--- • invalidate : boolean that indicates whether to hide the +--- extmark if the entirety of its range is deleted. If +--- "undo_restore" is false, the extmark is deleted instead. +--- • priority: a priority value for the highlight group or sign +--- attribute. For example treesitter highlighting uses a +--- value of 100. +--- • strict: boolean that indicates extmark should not be +--- placed if the line or column value is past the end of the +--- buffer or end of the line respectively. Defaults to true. +--- • sign_text: string of length 1-2 used to display in the +--- sign column. Note: ranges are unsupported and decorations +--- are only applied to start_row +--- • sign_hl_group: name of the highlight group used to +--- highlight the sign column text. Note: ranges are +--- unsupported and decorations are only applied to start_row +--- • number_hl_group: name of the highlight group used to +--- highlight the number column. Note: ranges are unsupported +--- and decorations are only applied to start_row +--- • line_hl_group: name of the highlight group used to +--- highlight the whole line. Note: ranges are unsupported and +--- decorations are only applied to start_row +--- • cursorline_hl_group: name of the highlight group used to +--- highlight the line when the cursor is on the same line as +--- the mark and 'cursorline' is enabled. Note: ranges are +--- unsupported and decorations are only applied to start_row +--- • conceal: string which should be either empty or a single +--- character. Enable concealing similar to `:syn-conceal`. +--- When a character is supplied it is used as `:syn-cchar`. +--- "hl_group" is used as highlight for the cchar if provided, +--- otherwise it defaults to `hl-Conceal`. +--- • spell: boolean indicating that spell checking should be +--- performed within this extmark +--- • ui_watched: boolean that indicates the mark should be +--- drawn by a UI. When set, the UI will receive win_extmark +--- events. Note: the mark is positioned by virt_text +--- attributes. Can be used together with virt_text. +--- @return integer +function vim.api.nvim_buf_set_extmark(buffer, ns_id, line, col, opts) end + +--- Sets a buffer-local `mapping` for the given mode. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param mode string +--- @param lhs string +--- @param rhs string +--- @param opts vim.api.keyset.keymap +function vim.api.nvim_buf_set_keymap(buffer, mode, lhs, rhs, opts) end + +--- Sets (replaces) a line-range in the buffer. +--- Indexing is zero-based, end-exclusive. Negative indices are interpreted as +--- length+1+index: -1 refers to the index past the end. So to change or +--- delete the last element use start=-2 and end=-1. +--- To insert lines at a given index, set `start` and `end` to the same index. +--- To delete a range of lines, set `replacement` to an empty array. +--- Out-of-bounds indices are clamped to the nearest valid value, unless +--- `strict_indexing` is set. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param start integer First line index +--- @param end_ integer Last line index, exclusive +--- @param strict_indexing boolean Whether out-of-bounds should be an error. +--- @param replacement string[] Array of lines to use as replacement +function vim.api.nvim_buf_set_lines(buffer, start, end_, strict_indexing, replacement) end + +--- Sets a named mark in the given buffer, all marks are allowed +--- file/uppercase, visual, last change, etc. See `mark-motions`. +--- Marks are (1,0)-indexed. `api-indexing` +--- +--- @param buffer integer Buffer to set the mark on +--- @param name string Mark name +--- @param line integer Line number +--- @param col integer Column/row number +--- @param opts table<string,any> Optional parameters. Reserved for future use. +--- @return boolean +function vim.api.nvim_buf_set_mark(buffer, name, line, col, opts) end + +--- Sets the full file name for a buffer +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param name string Buffer name +function vim.api.nvim_buf_set_name(buffer, name) end + +--- @deprecated +--- @param buffer integer +--- @param name string +--- @param value any +function vim.api.nvim_buf_set_option(buffer, name, value) end + +--- Sets (replaces) a range in the buffer +--- This is recommended over `nvim_buf_set_lines()` when only modifying parts +--- of a line, as extmarks will be preserved on non-modified parts of the +--- touched lines. +--- Indexing is zero-based. Row indices are end-inclusive, and column indices +--- are end-exclusive. +--- To insert text at a given `(row, column)` location, use `start_row = +--- end_row = row` and `start_col = end_col = col`. To delete the text in a +--- range, use `replacement = {}`. +--- Prefer `nvim_buf_set_lines()` if you are only adding or deleting entire +--- lines. +--- Prefer `nvim_put()` if you want to insert text at the cursor position. +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param start_row integer First line index +--- @param start_col integer Starting column (byte offset) on first line +--- @param end_row integer Last line index, inclusive +--- @param end_col integer Ending column (byte offset) on last line, exclusive +--- @param replacement string[] Array of lines to use as replacement +function vim.api.nvim_buf_set_text(buffer, start_row, start_col, end_row, end_col, replacement) end + +--- Sets a buffer-scoped (b:) variable +--- +--- @param buffer integer Buffer handle, or 0 for current buffer +--- @param name string Variable name +--- @param value any Variable value +function vim.api.nvim_buf_set_var(buffer, name, value) end + +--- @deprecated +--- @param buffer integer +--- @param src_id integer +--- @param line integer +--- @param chunks any[] +--- @param opts table<string,any> +--- @return integer +function vim.api.nvim_buf_set_virtual_text(buffer, src_id, line, chunks, opts) end + +--- Calls a Vimscript `Dictionary-function` with the given arguments. +--- On execution error: fails with Vimscript error, updates v:errmsg. +--- +--- @param dict any Dictionary, or String evaluating to a Vimscript `self` dict +--- @param fn string Name of the function defined on the Vimscript dict +--- @param args any[] Function arguments packed in an Array +--- @return any +function vim.api.nvim_call_dict_function(dict, fn, args) end + +--- Calls a Vimscript function with the given arguments. +--- On execution error: fails with Vimscript error, updates v:errmsg. +--- +--- @param fn string Function to call +--- @param args any[] Function arguments packed in an Array +--- @return any +function vim.api.nvim_call_function(fn, args) end + +--- Send data to channel `id`. For a job, it writes it to the stdin of the +--- process. For the stdio channel `channel-stdio`, it writes to Nvim's +--- stdout. For an internal terminal instance (`nvim_open_term()`) it writes +--- directly to terminal output. See `channel-bytes` for more information. +--- This function writes raw data, not RPC messages. If the channel was +--- created with `rpc=true` then the channel expects RPC messages, use +--- `vim.rpcnotify()` and `vim.rpcrequest()` instead. +--- +--- @param chan integer id of the channel +--- @param data string data to write. 8-bit clean: can contain NUL bytes. +function vim.api.nvim_chan_send(chan, data) end + +--- Clears all autocommands selected by {opts}. To delete autocmds see +--- `nvim_del_autocmd()`. +--- +--- @param opts vim.api.keyset.clear_autocmds Parameters +--- • event: (string|table) Examples: +--- • event: "pat1" +--- • event: { "pat1" } +--- • event: { "pat1", "pat2", "pat3" } +--- +--- • pattern: (string|table) +--- • pattern or patterns to match exactly. +--- • For example, if you have `*.py` as that pattern for the +--- autocmd, you must pass `*.py` exactly to clear it. +--- `test.py` will not match the pattern. +--- +--- • defaults to clearing all patterns. +--- • NOTE: Cannot be used with {buffer} +--- +--- • buffer: (bufnr) +--- • clear only `autocmd-buflocal` autocommands. +--- • NOTE: Cannot be used with {pattern} +--- +--- • group: (string|int) The augroup name or id. +--- • NOTE: If not passed, will only delete autocmds not in any group. +function vim.api.nvim_clear_autocmds(opts) end + +--- Executes an Ex command. +--- Unlike `nvim_command()` this command takes a structured Dictionary instead +--- of a String. This allows for easier construction and manipulation of an Ex +--- command. This also allows for things such as having spaces inside a +--- command argument, expanding filenames in a command that otherwise doesn't +--- expand filenames, etc. Command arguments may also be Number, Boolean or +--- String. +--- The first argument may also be used instead of count for commands that +--- support it in order to make their usage simpler with `vim.cmd()`. For +--- example, instead of `vim.cmd.bdelete{ count = 2 }`, you may do +--- `vim.cmd.bdelete(2)`. +--- On execution error: fails with Vimscript error, updates v:errmsg. +--- +--- @param cmd vim.api.keyset.cmd Command to execute. Must be a Dictionary that can contain the +--- same values as the return value of `nvim_parse_cmd()` except +--- "addr", "nargs" and "nextcmd" which are ignored if provided. +--- All values except for "cmd" are optional. +--- @param opts vim.api.keyset.cmd_opts Optional parameters. +--- • output: (boolean, default false) Whether to return command +--- output. +--- @return string +function vim.api.nvim_cmd(cmd, opts) end + +--- Executes an Ex command. +--- On execution error: fails with Vimscript error, updates v:errmsg. +--- Prefer using `nvim_cmd()` or `nvim_exec2()` over this. To evaluate +--- multiple lines of Vim script or an Ex command directly, use +--- `nvim_exec2()`. To construct an Ex command using a structured format and +--- then execute it, use `nvim_cmd()`. To modify an Ex command before +--- evaluating it, use `nvim_parse_cmd()` in conjunction with `nvim_cmd()`. +--- +--- @param command string Ex command string +function vim.api.nvim_command(command) end + +--- @deprecated +--- @param command string +--- @return string +function vim.api.nvim_command_output(command) end + +--- Create or get an autocommand group `autocmd-groups`. +--- To get an existing group id, do: +--- +--- ```lua +--- local id = vim.api.nvim_create_augroup("MyGroup", { +--- clear = false +--- }) +--- ``` +--- +--- @param name string String: The name of the group +--- @param opts vim.api.keyset.create_augroup Dictionary Parameters +--- • clear (bool) optional: defaults to true. Clear existing +--- commands if the group already exists `autocmd-groups`. +--- @return integer +function vim.api.nvim_create_augroup(name, opts) end + +--- Creates an `autocommand` event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string). +--- Example using Lua callback: +--- +--- ```lua +--- vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { +--- pattern = {"*.c", "*.h"}, +--- callback = function(ev) +--- print(string.format('event fired: %s', vim.inspect(ev))) +--- end +--- }) +--- ``` +--- +--- Example using an Ex command as the handler: +--- +--- ```lua +--- vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { +--- pattern = {"*.c", "*.h"}, +--- command = "echo 'Entering a C or C++ file'", +--- }) +--- ``` +--- +--- Note: `pattern` is NOT automatically expanded (unlike with `:autocmd`), +--- thus names like "$HOME" and "~" must be expanded explicitly: +--- +--- ```lua +--- pattern = vim.fn.expand("~") .. "/some/path/*.py" +--- ``` +--- +--- @param event any (string|array) Event(s) that will trigger the handler +--- (`callback` or `command`). +--- @param opts vim.api.keyset.create_autocmd Options dict: +--- • group (string|integer) optional: autocommand group name or +--- id to match against. +--- • pattern (string|array) optional: pattern(s) to match +--- literally `autocmd-pattern`. +--- • buffer (integer) optional: buffer number for buffer-local +--- autocommands `autocmd-buflocal`. Cannot be used with +--- {pattern}. +--- • desc (string) optional: description (for documentation and +--- troubleshooting). +--- • callback (function|string) optional: Lua function (or +--- Vimscript function name, if string) called when the +--- event(s) is triggered. Lua callback can return true to +--- delete the autocommand, and receives a table argument with +--- these keys: +--- • id: (number) autocommand id +--- • event: (string) name of the triggered event +--- `autocmd-events` +--- • group: (number|nil) autocommand group id, if any +--- • match: (string) expanded value of `<amatch>` +--- • buf: (number) expanded value of `<abuf>` +--- • file: (string) expanded value of `<afile>` +--- • data: (any) arbitrary data passed from +--- `nvim_exec_autocmds()` +--- +--- • command (string) optional: Vim command to execute on event. +--- Cannot be used with {callback} +--- • once (boolean) optional: defaults to false. Run the +--- autocommand only once `autocmd-once`. +--- • nested (boolean) optional: defaults to false. Run nested +--- autocommands `autocmd-nested`. +--- @return integer +function vim.api.nvim_create_autocmd(event, opts) end + +--- Creates a new, empty, unnamed buffer. +--- +--- @param listed boolean Sets 'buflisted' +--- @param scratch boolean Creates a "throwaway" `scratch-buffer` for temporary work +--- (always 'nomodified'). Also sets 'nomodeline' on the +--- buffer. +--- @return integer +function vim.api.nvim_create_buf(listed, scratch) end + +--- Creates a new namespace or gets an existing one. *namespace* +--- Namespaces are used for buffer highlights and virtual text, see +--- `nvim_buf_add_highlight()` and `nvim_buf_set_extmark()`. +--- Namespaces can be named or anonymous. If `name` matches an existing +--- namespace, the associated id is returned. If `name` is an empty string a +--- new, anonymous namespace is created. +--- +--- @param name string Namespace name or empty string +--- @return integer +function vim.api.nvim_create_namespace(name) end + +--- Creates a global `user-commands` command. +--- For Lua usage see `lua-guide-commands-create`. +--- Example: +--- +--- ```vim +--- :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true}) +--- :SayHello +--- Hello world! +--- ``` +--- +--- @param name string Name of the new user command. Must begin with an uppercase +--- letter. +--- @param command any Replacement command to execute when this user command is +--- executed. When called from Lua, the command can also be a +--- Lua function. The function is called with a single table +--- argument that contains the following keys: +--- • name: (string) Command name +--- • args: (string) The args passed to the command, if any +--- `<args>` +--- • fargs: (table) The args split by unescaped whitespace +--- (when more than one argument is allowed), if any +--- `<f-args>` +--- • nargs: (string) Number of arguments `:command-nargs` +--- • bang: (boolean) "true" if the command was executed with a +--- ! modifier `<bang>` +--- • line1: (number) The starting line of the command range +--- `<line1>` +--- • line2: (number) The final line of the command range +--- `<line2>` +--- • range: (number) The number of items in the command range: +--- 0, 1, or 2 `<range>` +--- • count: (number) Any count supplied `<count>` +--- • reg: (string) The optional register, if specified `<reg>` +--- • mods: (string) Command modifiers, if any `<mods>` +--- • smods: (table) Command modifiers in a structured format. +--- Has the same structure as the "mods" key of +--- `nvim_parse_cmd()`. +--- @param opts vim.api.keyset.user_command Optional `command-attributes`. +--- • Set boolean attributes such as `:command-bang` or +--- `:command-bar` to true (but not `:command-buffer`, use +--- `nvim_buf_create_user_command()` instead). +--- • "complete" `:command-complete` also accepts a Lua +--- function which works like +--- `:command-completion-customlist`. +--- • Other parameters: +--- • desc: (string) Used for listing the command when a Lua +--- function is used for {command}. +--- • force: (boolean, default true) Override any previous +--- definition. +--- • preview: (function) Preview callback for 'inccommand' +--- `:command-preview` +function vim.api.nvim_create_user_command(name, command, opts) end + +--- Delete an autocommand group by id. +--- To get a group id one can use `nvim_get_autocmds()`. +--- NOTE: behavior differs from `:augroup-delete`. When deleting a group, +--- autocommands contained in this group will also be deleted and cleared. +--- This group will no longer exist. +--- +--- @param id integer Integer The id of the group. +function vim.api.nvim_del_augroup_by_id(id) end + +--- Delete an autocommand group by name. +--- NOTE: behavior differs from `:augroup-delete`. When deleting a group, +--- autocommands contained in this group will also be deleted and cleared. +--- This group will no longer exist. +--- +--- @param name string String The name of the group. +function vim.api.nvim_del_augroup_by_name(name) end + +--- Deletes an autocommand by id. +--- +--- @param id integer Integer Autocommand id returned by `nvim_create_autocmd()` +function vim.api.nvim_del_autocmd(id) end + +--- Deletes the current line. +--- +function vim.api.nvim_del_current_line() end + +--- Unmaps a global `mapping` for the given mode. +--- To unmap a buffer-local mapping, use `nvim_buf_del_keymap()`. +--- +--- @param mode string +--- @param lhs string +function vim.api.nvim_del_keymap(mode, lhs) end + +--- Deletes an uppercase/file named mark. See `mark-motions`. +--- +--- @param name string Mark name +--- @return boolean +function vim.api.nvim_del_mark(name) end + +--- Delete a user-defined command. +--- +--- @param name string Name of the command to delete. +function vim.api.nvim_del_user_command(name) end + +--- Removes a global (g:) variable. +--- +--- @param name string Variable name +function vim.api.nvim_del_var(name) end + +--- Echo a message. +--- +--- @param chunks any[] A list of [text, hl_group] arrays, each representing a text +--- chunk with specified highlight. `hl_group` element can be +--- omitted for no highlight. +--- @param history boolean if true, add to `message-history`. +--- @param opts vim.api.keyset.echo_opts Optional parameters. +--- • verbose: Message was printed as a result of 'verbose' +--- option if Nvim was invoked with -V3log_file, the message +--- will be redirected to the log_file and suppressed from +--- direct output. +function vim.api.nvim_echo(chunks, history, opts) end + +--- Writes a message to the Vim error buffer. Does not append "\n", the +--- message is buffered (won't display) until a linefeed is written. +--- +--- @param str string Message +function vim.api.nvim_err_write(str) end + +--- Writes a message to the Vim error buffer. Appends "\n", so the buffer is +--- flushed (and displayed). +--- +--- @param str string Message +function vim.api.nvim_err_writeln(str) end + +--- Evaluates a Vimscript `expression`. Dictionaries and Lists are recursively +--- expanded. +--- On execution error: fails with Vimscript error, updates v:errmsg. +--- +--- @param expr string Vimscript expression string +--- @return any +function vim.api.nvim_eval(expr) end + +--- Evaluates statusline string. +--- +--- @param str string Statusline string (see 'statusline'). +--- @param opts vim.api.keyset.eval_statusline Optional parameters. +--- • winid: (number) `window-ID` of the window to use as context +--- for statusline. +--- • maxwidth: (number) Maximum width of statusline. +--- • fillchar: (string) Character to fill blank spaces in the +--- statusline (see 'fillchars'). Treated as single-width even +--- if it isn't. +--- • highlights: (boolean) Return highlight information. +--- • use_winbar: (boolean) Evaluate winbar instead of statusline. +--- • use_tabline: (boolean) Evaluate tabline instead of +--- statusline. When true, {winid} is ignored. Mutually +--- exclusive with {use_winbar}. +--- • use_statuscol_lnum: (number) Evaluate statuscolumn for this +--- line number instead of statusline. +--- @return table<string,any> +function vim.api.nvim_eval_statusline(str, opts) end + +--- @deprecated +--- @param src string +--- @param output boolean +--- @return string +function vim.api.nvim_exec(src, output) end + +--- Executes Vimscript (multiline block of Ex commands), like anonymous +--- `:source`. +--- Unlike `nvim_command()` this function supports heredocs, script-scope +--- (s:), etc. +--- On execution error: fails with Vimscript error, updates v:errmsg. +--- +--- @param src string Vimscript code +--- @param opts vim.api.keyset.exec_opts Optional parameters. +--- • output: (boolean, default false) Whether to capture and +--- return all (non-error, non-shell `:!`) output. +--- @return table<string,any> +function vim.api.nvim_exec2(src, opts) end + +--- Execute all autocommands for {event} that match the corresponding {opts} +--- `autocmd-execute`. +--- +--- @param event any (String|Array) The event or events to execute +--- @param opts vim.api.keyset.exec_autocmds Dictionary of autocommand options: +--- • group (string|integer) optional: the autocommand group name +--- or id to match against. `autocmd-groups`. +--- • pattern (string|array) optional: defaults to "*" +--- `autocmd-pattern`. Cannot be used with {buffer}. +--- • buffer (integer) optional: buffer number +--- `autocmd-buflocal`. Cannot be used with {pattern}. +--- • modeline (bool) optional: defaults to true. Process the +--- modeline after the autocommands `<nomodeline>`. +--- • data (any): arbitrary data to send to the autocommand +--- callback. See `nvim_create_autocmd()` for details. +function vim.api.nvim_exec_autocmds(event, opts) end + +--- Sends input-keys to Nvim, subject to various quirks controlled by `mode` +--- flags. This is a blocking call, unlike `nvim_input()`. +--- On execution error: does not fail, but updates v:errmsg. +--- To input sequences like <C-o> use `nvim_replace_termcodes()` (typically +--- with escape_ks=false) to replace `keycodes`, then pass the result to +--- nvim_feedkeys(). +--- Example: +--- +--- ```vim +--- :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) +--- :call nvim_feedkeys(key, 'n', v:false) +--- ``` +--- +--- @param keys string to be typed +--- @param mode string behavior flags, see `feedkeys()` +--- @param escape_ks boolean If true, escape K_SPECIAL bytes in `keys`. This should be +--- false if you already used `nvim_replace_termcodes()`, and +--- true otherwise. +function vim.api.nvim_feedkeys(keys, mode, escape_ks) end + +--- Gets the option information for all options. +--- The dictionary has the full option names as keys and option metadata +--- dictionaries as detailed at `nvim_get_option_info2()`. +--- +--- @return table<string,any> +function vim.api.nvim_get_all_options_info() end + +--- Get all autocommands that match the corresponding {opts}. +--- These examples will get autocommands matching ALL the given criteria: +--- +--- ```lua +--- -- Matches all criteria +--- autocommands = vim.api.nvim_get_autocmds({ +--- group = "MyGroup", +--- event = {"BufEnter", "BufWinEnter"}, +--- pattern = {"*.c", "*.h"} +--- }) +--- +--- -- All commands from one group +--- autocommands = vim.api.nvim_get_autocmds({ +--- group = "MyGroup", +--- }) +--- ``` +--- +--- NOTE: When multiple patterns or events are provided, it will find all the +--- autocommands that match any combination of them. +--- +--- @param opts vim.api.keyset.get_autocmds Dictionary with at least one of the following: +--- • group (string|integer): the autocommand group name or id to +--- match against. +--- • event (string|array): event or events to match against +--- `autocmd-events`. +--- • pattern (string|array): pattern or patterns to match against +--- `autocmd-pattern`. Cannot be used with {buffer} +--- • buffer: Buffer number or list of buffer numbers for buffer +--- local autocommands `autocmd-buflocal`. Cannot be used with +--- {pattern} +--- @return any[] +function vim.api.nvim_get_autocmds(opts) end + +--- Gets information about a channel. +--- +--- @param chan integer +--- @return table<string,any> +function vim.api.nvim_get_chan_info(chan) end + +--- Returns the 24-bit RGB value of a `nvim_get_color_map()` color name or +--- "#rrggbb" hexadecimal string. +--- Example: +--- +--- ```vim +--- :echo nvim_get_color_by_name("Pink") +--- :echo nvim_get_color_by_name("#cbcbcb") +--- ``` +--- +--- @param name string Color name or "#rrggbb" string +--- @return integer +function vim.api.nvim_get_color_by_name(name) end + +--- Returns a map of color names and RGB values. +--- Keys are color names (e.g. "Aqua") and values are 24-bit RGB color values +--- (e.g. 65535). +--- +--- @return table<string,any> +function vim.api.nvim_get_color_map() end + +--- Gets a map of global (non-buffer-local) Ex commands. +--- Currently only `user-commands` are supported, not builtin Ex commands. +--- +--- @param opts vim.api.keyset.get_commands Optional parameters. Currently only supports {"builtin":false} +--- @return table<string,any> +function vim.api.nvim_get_commands(opts) end + +--- Gets a map of the current editor state. +--- +--- @param opts vim.api.keyset.context Optional parameters. +--- • types: List of `context-types` ("regs", "jumps", "bufs", +--- "gvars", …) to gather, or empty for "all". +--- @return table<string,any> +function vim.api.nvim_get_context(opts) end + +--- Gets the current buffer. +--- +--- @return integer +function vim.api.nvim_get_current_buf() end + +--- Gets the current line. +--- +--- @return string +function vim.api.nvim_get_current_line() end + +--- Gets the current tabpage. +--- +--- @return integer +function vim.api.nvim_get_current_tabpage() end + +--- Gets the current window. +--- +--- @return integer +function vim.api.nvim_get_current_win() end + +--- Gets all or specific highlight groups in a namespace. +--- +--- @param ns_id integer Get highlight groups for namespace ns_id +--- `nvim_get_namespaces()`. Use 0 to get global highlight groups +--- `:highlight`. +--- @param opts vim.api.keyset.get_highlight Options dict: +--- • name: (string) Get a highlight definition by name. +--- • id: (integer) Get a highlight definition by id. +--- • link: (boolean, default true) Show linked group name +--- instead of effective definition `:hi-link`. +--- • create: (boolean, default true) When highlight group +--- doesn't exist create it. +--- @return table<string,any> +function vim.api.nvim_get_hl(ns_id, opts) end + +--- @deprecated +--- @param hl_id integer +--- @param rgb boolean +--- @return table<string,any> +function vim.api.nvim_get_hl_by_id(hl_id, rgb) end + +--- @deprecated +--- @param name string +--- @param rgb boolean +--- @return table<string,any> +function vim.api.nvim_get_hl_by_name(name, rgb) end + +--- Gets a highlight group by name +--- similar to `hlID()`, but allocates a new ID if not present. +--- +--- @param name string +--- @return integer +function vim.api.nvim_get_hl_id_by_name(name) end + +--- Gets the active highlight namespace. +--- +--- @param opts vim.api.keyset.get_ns Optional parameters +--- • winid: (number) `window-ID` for retrieving a window's +--- highlight namespace. A value of -1 is returned when +--- `nvim_win_set_hl_ns()` has not been called for the window +--- (or was called with a namespace of -1). +--- @return integer +function vim.api.nvim_get_hl_ns(opts) end + +--- Gets a list of global (non-buffer-local) `mapping` definitions. +--- +--- @param mode string Mode short-name ("n", "i", "v", ...) +--- @return table<string,any>[] +function vim.api.nvim_get_keymap(mode) end + +--- Returns a `(row, col, buffer, buffername)` tuple representing the position +--- of the uppercase/file named mark. "End of line" column position is +--- returned as `v:maxcol` (big number). See `mark-motions`. +--- Marks are (1,0)-indexed. `api-indexing` +--- +--- @param name string Mark name +--- @param opts table<string,any> Optional parameters. Reserved for future use. +--- @return any[] +function vim.api.nvim_get_mark(name, opts) end + +--- Gets the current mode. `mode()` "blocking" is true if Nvim is waiting for +--- input. +--- +--- @return table<string,any> +function vim.api.nvim_get_mode() end + +--- Gets existing, non-anonymous `namespace`s. +--- +--- @return table<string,any> +function vim.api.nvim_get_namespaces() end + +--- @deprecated +--- @param name string +--- @return any +function vim.api.nvim_get_option(name) end + +--- @deprecated +--- @param name string +--- @return table<string,any> +function vim.api.nvim_get_option_info(name) end + +--- Gets the option information for one option from arbitrary buffer or window +--- Resulting dictionary has keys: +--- • name: Name of the option (like 'filetype') +--- • shortname: Shortened name of the option (like 'ft') +--- • type: type of option ("string", "number" or "boolean") +--- • default: The default value for the option +--- • was_set: Whether the option was set. +--- • last_set_sid: Last set script id (if any) +--- • last_set_linenr: line number where option was set +--- • last_set_chan: Channel where option was set (0 for local) +--- • scope: one of "global", "win", or "buf" +--- • global_local: whether win or buf option has a global value +--- • commalist: List of comma separated values +--- • flaglist: List of single char flags +--- +--- When {scope} is not provided, the last set information applies to the +--- local value in the current buffer or window if it is available, otherwise +--- the global value information is returned. This behavior can be disabled by +--- explicitly specifying {scope} in the {opts} table. +--- +--- @param name string Option name +--- @param opts vim.api.keyset.option Optional parameters +--- • scope: One of "global" or "local". Analogous to `:setglobal` +--- and `:setlocal`, respectively. +--- • win: `window-ID`. Used for getting window local options. +--- • buf: Buffer number. Used for getting buffer local options. +--- Implies {scope} is "local". +--- @return table<string,any> +function vim.api.nvim_get_option_info2(name, opts) end + +--- Gets the value of an option. The behavior of this function matches that of +--- `:set`: the local value of an option is returned if it exists; otherwise, +--- the global value is returned. Local values always correspond to the +--- current buffer or window, unless "buf" or "win" is set in {opts}. +--- +--- @param name string Option name +--- @param opts vim.api.keyset.option Optional parameters +--- • scope: One of "global" or "local". Analogous to `:setglobal` +--- and `:setlocal`, respectively. +--- • win: `window-ID`. Used for getting window local options. +--- • buf: Buffer number. Used for getting buffer local options. +--- Implies {scope} is "local". +--- • filetype: `filetype`. Used to get the default option for a +--- specific filetype. Cannot be used with any other option. +--- Note: this will trigger `ftplugin` and all `FileType` +--- autocommands for the corresponding filetype. +--- @return any +function vim.api.nvim_get_option_value(name, opts) end + +--- Gets info describing process `pid`. +--- +--- @param pid integer +--- @return any +function vim.api.nvim_get_proc(pid) end + +--- Gets the immediate children of process `pid`. +--- +--- @param pid integer +--- @return any[] +function vim.api.nvim_get_proc_children(pid) end + +--- Find files in runtime directories +--- "name" can contain wildcards. For example +--- nvim_get_runtime_file("colors/*.vim", true) will return all color scheme +--- files. Always use forward slashes (/) in the search pattern for +--- subdirectories regardless of platform. +--- It is not an error to not find any files. An empty array is returned then. +--- +--- @param name string pattern of files to search for +--- @param all boolean whether to return all matches or only the first +--- @return string[] +function vim.api.nvim_get_runtime_file(name, all) end + +--- Gets a global (g:) variable. +--- +--- @param name string Variable name +--- @return any +function vim.api.nvim_get_var(name) end + +--- Gets a v: variable. +--- +--- @param name string Variable name +--- @return any +function vim.api.nvim_get_vvar(name) end + +--- Queues raw user-input. Unlike `nvim_feedkeys()`, this uses a low-level +--- input buffer and the call is non-blocking (input is processed +--- asynchronously by the eventloop). +--- On execution error: does not fail, but updates v:errmsg. +--- +--- @param keys string to be typed +--- @return integer +function vim.api.nvim_input(keys) end + +--- Send mouse event from GUI. +--- Non-blocking: does not wait on any result, but queues the event to be +--- processed soon by the event loop. +--- +--- @param button string Mouse button: one of "left", "right", "middle", "wheel", +--- "move". +--- @param action string For ordinary buttons, one of "press", "drag", "release". +--- For the wheel, one of "up", "down", "left", "right". +--- Ignored for "move". +--- @param modifier string String of modifiers each represented by a single char. The +--- same specifiers are used as for a key press, except that +--- the "-" separator is optional, so "C-A-", "c-a" and "CA" +--- can all be used to specify Ctrl+Alt+click. +--- @param grid integer Grid number if the client uses `ui-multigrid`, else 0. +--- @param row integer Mouse row-position (zero-based, like redraw events) +--- @param col integer Mouse column-position (zero-based, like redraw events) +function vim.api.nvim_input_mouse(button, action, modifier, grid, row, col) end + +--- Gets the current list of buffer handles +--- Includes unlisted (unloaded/deleted) buffers, like `:ls!`. Use +--- `nvim_buf_is_loaded()` to check if a buffer is loaded. +--- +--- @return integer[] +function vim.api.nvim_list_bufs() end + +--- Get information about all open channels. +--- +--- @return any[] +function vim.api.nvim_list_chans() end + +--- Gets the paths contained in `runtime-search-path`. +--- +--- @return string[] +function vim.api.nvim_list_runtime_paths() end + +--- Gets the current list of tabpage handles. +--- +--- @return integer[] +function vim.api.nvim_list_tabpages() end + +--- Gets a list of dictionaries representing attached UIs. +--- +--- @return any[] +function vim.api.nvim_list_uis() end + +--- Gets the current list of window handles. +--- +--- @return integer[] +function vim.api.nvim_list_wins() end + +--- Sets the current editor state from the given `context` map. +--- +--- @param dict table<string,any> `Context` map. +--- @return any +function vim.api.nvim_load_context(dict) end + +--- Notify the user with a message +--- Relays the call to vim.notify . By default forwards your message in the +--- echo area but can be overridden to trigger desktop notifications. +--- +--- @param msg string Message to display to the user +--- @param log_level integer The log level +--- @param opts table<string,any> Reserved for future use. +--- @return any +function vim.api.nvim_notify(msg, log_level, opts) end + +--- Open a terminal instance in a buffer +--- By default (and currently the only option) the terminal will not be +--- connected to an external process. Instead, input send on the channel will +--- be echoed directly by the terminal. This is useful to display ANSI +--- terminal sequences returned as part of a rpc message, or similar. +--- Note: to directly initiate the terminal using the right size, display the +--- buffer in a configured window before calling this. For instance, for a +--- floating display, first create an empty buffer using `nvim_create_buf()`, +--- then display it using `nvim_open_win()`, and then call this function. Then +--- `nvim_chan_send()` can be called immediately to process sequences in a +--- virtual terminal having the intended size. +--- +--- @param buffer integer the buffer to use (expected to be empty) +--- @param opts table<string,function> Optional parameters. +--- • on_input: Lua callback for input sent, i e keypresses in +--- terminal mode. Note: keypresses are sent raw as they would +--- be to the pty master end. For instance, a carriage return +--- is sent as a "\r", not as a "\n". `textlock` applies. It +--- is possible to call `nvim_chan_send()` directly in the +--- callback however. ["input", term, bufnr, data] +--- @return integer +function vim.api.nvim_open_term(buffer, opts) end + +--- Open a new window. +--- Currently this is used to open floating and external windows. Floats are +--- windows that are drawn above the split layout, at some anchor position in +--- some other window. Floats can be drawn internally or by external GUI with +--- the `ui-multigrid` extension. External windows are only supported with +--- multigrid GUIs, and are displayed as separate top-level windows. +--- For a general overview of floats, see `api-floatwin`. +--- Exactly one of `external` and `relative` must be specified. The `width` +--- and `height` of the new window must be specified. +--- With relative=editor (row=0,col=0) refers to the top-left corner of the +--- screen-grid and (row=Lines-1,col=Columns-1) refers to the bottom-right +--- corner. Fractional values are allowed, but the builtin implementation +--- (used by non-multigrid UIs) will always round down to nearest integer. +--- Out-of-bounds values, and configurations that make the float not fit +--- inside the main editor, are allowed. The builtin implementation truncates +--- values so floats are fully within the main screen grid. External GUIs +--- could let floats hover outside of the main window like a tooltip, but this +--- should not be used to specify arbitrary WM screen positions. +--- Example (Lua): window-relative float +--- +--- ```lua +--- vim.api.nvim_open_win(0, false, +--- {relative='win', row=3, col=3, width=12, height=3}) +--- ``` +--- +--- Example (Lua): buffer-relative float (travels as buffer is scrolled) +--- +--- ```lua +--- vim.api.nvim_open_win(0, false, +--- {relative='win', width=12, height=3, bufpos={100,10}}) +--- }) +--- ``` +--- +--- @param buffer integer Buffer to display, or 0 for current buffer +--- @param enter boolean Enter the window (make it the current window) +--- @param config vim.api.keyset.float_config Map defining the window configuration. Keys: +--- • relative: Sets the window layout to "floating", placed at +--- (row,col) coordinates relative to: +--- • "editor" The global editor grid +--- • "win" Window given by the `win` field, or current +--- window. +--- • "cursor" Cursor position in current window. +--- • "mouse" Mouse position +--- +--- • win: `window-ID` for relative="win". +--- • anchor: Decides which corner of the float to place at +--- (row,col): +--- • "NW" northwest (default) +--- • "NE" northeast +--- • "SW" southwest +--- • "SE" southeast +--- +--- • width: Window width (in character cells). Minimum of 1. +--- • height: Window height (in character cells). Minimum of 1. +--- • bufpos: Places float relative to buffer text (only when +--- relative="win"). Takes a tuple of zero-indexed [line, +--- column]. `row` and `col` if given are applied relative to this position, else they +--- default to: +--- • `row=1` and `col=0` if `anchor` is "NW" or "NE" +--- • `row=0` and `col=0` if `anchor` is "SW" or "SE" (thus +--- like a tooltip near the buffer text). +--- +--- • row: Row position in units of "screen cell height", may be +--- fractional. +--- • col: Column position in units of "screen cell width", may +--- be fractional. +--- • focusable: Enable focus by user actions (wincmds, mouse +--- events). Defaults to true. Non-focusable windows can be +--- entered by `nvim_set_current_win()`. +--- • external: GUI should display the window as an external +--- top-level window. Currently accepts no other positioning +--- configuration together with this. +--- • zindex: Stacking order. floats with higher `zindex` go on top on floats with lower indices. Must be larger +--- than zero. The following screen elements have hard-coded +--- z-indices: +--- • 100: insert completion popupmenu +--- • 200: message scrollback +--- • 250: cmdline completion popupmenu (when +--- wildoptions+=pum) The default value for floats are 50. +--- In general, values below 100 are recommended, unless +--- there is a good reason to overshadow builtin elements. +--- +--- • style: (optional) Configure the appearance of the window. +--- Currently only supports one value: +--- • "minimal" Nvim will display the window with many UI +--- options disabled. This is useful when displaying a +--- temporary float where the text should not be edited. +--- Disables 'number', 'relativenumber', 'cursorline', +--- 'cursorcolumn', 'foldcolumn', 'spell' and 'list' +--- options. 'signcolumn' is changed to `auto` and +--- 'colorcolumn' is cleared. 'statuscolumn' is changed to +--- empty. The end-of-buffer region is hidden by setting +--- `eob` flag of 'fillchars' to a space char, and clearing +--- the `hl-EndOfBuffer` region in 'winhighlight'. +--- +--- • border: Style of (optional) window border. This can either +--- be a string or an array. The string values are +--- • "none": No border (default). +--- • "single": A single line box. +--- • "double": A double line box. +--- • "rounded": Like "single", but with rounded corners ("╭" +--- etc.). +--- • "solid": Adds padding by a single whitespace cell. +--- • "shadow": A drop shadow effect by blending with the +--- background. +--- • If it is an array, it should have a length of eight or +--- any divisor of eight. The array will specify the eight +--- chars building up the border in a clockwise fashion +--- starting with the top-left corner. As an example, the +--- double box style could be specified as [ "╔", "═" ,"╗", +--- "║", "╝", "═", "╚", "║" ]. If the number of chars are +--- less than eight, they will be repeated. Thus an ASCII +--- border could be specified as [ "/", "-", "\\", "|" ], or +--- all chars the same as [ "x" ]. An empty string can be +--- used to turn off a specific border, for instance, [ "", +--- "", "", ">", "", "", "", "<" ] will only make vertical +--- borders but not horizontal ones. By default, +--- `FloatBorder` highlight is used, which links to +--- `WinSeparator` when not defined. It could also be +--- specified by character: [ ["+", "MyCorner"], ["x", +--- "MyBorder"] ]. +--- +--- • title: Title (optional) in window border, string or list. +--- List should consist of `[text, highlight]` tuples. If +--- string, the default highlight group is `FloatTitle`. +--- • title_pos: Title position. Must be set with `title` +--- option. Value can be one of "left", "center", or "right". +--- Default is `"left"`. +--- • footer: Footer (optional) in window border, string or +--- list. List should consist of `[text, highlight]` tuples. +--- If string, the default highlight group is `FloatFooter`. +--- • footer_pos: Footer position. Must be set with `footer` +--- option. Value can be one of "left", "center", or "right". +--- Default is `"left"`. +--- • noautocmd: If true then no buffer-related autocommand +--- events such as `BufEnter`, `BufLeave` or `BufWinEnter` may +--- fire from calling this function. +--- • fixed: If true when anchor is NW or SW, the float window +--- would be kept fixed even if the window would be truncated. +--- • hide: If true the floating window will be hidden. +--- @return integer +function vim.api.nvim_open_win(buffer, enter, config) end + +--- Writes a message to the Vim output buffer. Does not append "\n", the +--- message is buffered (won't display) until a linefeed is written. +--- +--- @param str string Message +function vim.api.nvim_out_write(str) end + +--- Parse command line. +--- Doesn't check the validity of command arguments. +--- +--- @param str string Command line string to parse. Cannot contain "\n". +--- @param opts table<string,any> Optional parameters. Reserved for future use. +--- @return table<string,any> +function vim.api.nvim_parse_cmd(str, opts) end + +--- Parse a Vimscript expression. +--- +--- @param expr string Expression to parse. Always treated as a single line. +--- @param flags string Flags: +--- • "m" if multiple expressions in a row are allowed (only +--- the first one will be parsed), +--- • "E" if EOC tokens are not allowed (determines whether +--- they will stop parsing process or be recognized as an +--- operator/space, though also yielding an error). +--- • "l" when needing to start parsing with lvalues for +--- ":let" or ":for". Common flag sets: +--- • "m" to parse like for ":echo". +--- • "E" to parse like for "<C-r>=". +--- • empty string for ":call". +--- • "lm" to parse for ":let". +--- @param highlight boolean If true, return value will also include "highlight" key +--- containing array of 4-tuples (arrays) (Integer, Integer, +--- Integer, String), where first three numbers define the +--- highlighted region and represent line, starting column +--- and ending column (latter exclusive: one should highlight +--- region [start_col, end_col)). +--- @return table<string,any> +function vim.api.nvim_parse_expression(expr, flags, highlight) end + +--- Pastes at cursor, in any mode. +--- Invokes the `vim.paste` handler, which handles each mode appropriately. +--- Sets redo/undo. Faster than `nvim_input()`. Lines break at LF ("\n"). +--- Errors ('nomodifiable', `vim.paste()` failure, …) are reflected in `err` +--- but do not affect the return value (which is strictly decided by +--- `vim.paste()`). On error, subsequent calls are ignored ("drained") until +--- the next paste is initiated (phase 1 or -1). +--- +--- @param data string Multiline input. May be binary (containing NUL bytes). +--- @param crlf boolean Also break lines at CR and CRLF. +--- @param phase integer -1: paste in a single call (i.e. without streaming). To +--- "stream" a paste, call `nvim_paste` sequentially with these `phase` values: +--- • 1: starts the paste (exactly once) +--- • 2: continues the paste (zero or more times) +--- • 3: ends the paste (exactly once) +--- @return boolean +function vim.api.nvim_paste(data, crlf, phase) end + +--- Puts text at cursor, in any mode. +--- Compare `:put` and `p` which are always linewise. +--- +--- @param lines string[] `readfile()`-style list of lines. `channel-lines` +--- @param type string Edit behavior: any `getregtype()` result, or: +--- • "b" `blockwise-visual` mode (may include width, e.g. "b3") +--- • "c" `charwise` mode +--- • "l" `linewise` mode +--- • "" guess by contents, see `setreg()` +--- @param after boolean If true insert after cursor (like `p`), or before (like +--- `P`). +--- @param follow boolean If true place cursor at end of inserted text. +function vim.api.nvim_put(lines, type, after, follow) end + +--- Replaces terminal codes and `keycodes` (<CR>, <Esc>, ...) in a string with +--- the internal representation. +--- +--- @param str string String to be converted. +--- @param from_part boolean Legacy Vim parameter. Usually true. +--- @param do_lt boolean Also translate <lt>. Ignored if `special` is false. +--- @param special boolean Replace `keycodes`, e.g. <CR> becomes a "\r" char. +--- @return string +function vim.api.nvim_replace_termcodes(str, from_part, do_lt, special) end + +--- Selects an item in the completion popup menu. +--- If neither `ins-completion` nor `cmdline-completion` popup menu is active +--- this API call is silently ignored. Useful for an external UI using +--- `ui-popupmenu` to control the popup menu with the mouse. Can also be used +--- in a mapping; use <Cmd> `:map-cmd` or a Lua mapping to ensure the mapping +--- doesn't end completion mode. +--- +--- @param item integer Index (zero-based) of the item to select. Value of -1 +--- selects nothing and restores the original text. +--- @param insert boolean For `ins-completion`, whether the selection should be +--- inserted in the buffer. Ignored for `cmdline-completion`. +--- @param finish boolean Finish the completion and dismiss the popup menu. Implies +--- {insert}. +--- @param opts table<string,any> Optional parameters. Reserved for future use. +function vim.api.nvim_select_popupmenu_item(item, insert, finish, opts) end + +--- Sets the current buffer. +--- +--- @param buffer integer Buffer handle +function vim.api.nvim_set_current_buf(buffer) end + +--- Changes the global working directory. +--- +--- @param dir string Directory path +function vim.api.nvim_set_current_dir(dir) end + +--- Sets the current line. +--- +--- @param line string Line contents +function vim.api.nvim_set_current_line(line) end + +--- Sets the current tabpage. +--- +--- @param tabpage integer Tabpage handle +function vim.api.nvim_set_current_tabpage(tabpage) end + +--- Sets the current window. +--- +--- @param window integer Window handle +function vim.api.nvim_set_current_win(window) end + +--- Set or change decoration provider for a `namespace` +--- This is a very general purpose interface for having Lua callbacks being +--- triggered during the redraw code. +--- The expected usage is to set `extmarks` for the currently redrawn buffer. +--- `nvim_buf_set_extmark()` can be called to add marks on a per-window or +--- per-lines basis. Use the `ephemeral` key to only use the mark for the +--- current screen redraw (the callback will be called again for the next +--- redraw). +--- Note: this function should not be called often. Rather, the callbacks +--- themselves can be used to throttle unneeded callbacks. the `on_start` +--- callback can return `false` to disable the provider until the next redraw. +--- Similarly, return `false` in `on_win` will skip the `on_lines` calls for +--- that window (but any extmarks set in `on_win` will still be used). A +--- plugin managing multiple sources of decoration should ideally only set one +--- provider, and merge the sources internally. You can use multiple `ns_id` +--- for the extmarks set/modified inside the callback anyway. +--- Note: doing anything other than setting extmarks is considered +--- experimental. Doing things like changing options are not explicitly +--- forbidden, but is likely to have unexpected consequences (such as 100% CPU +--- consumption). doing `vim.rpcnotify` should be OK, but `vim.rpcrequest` is +--- quite dubious for the moment. +--- Note: It is not allowed to remove or update extmarks in 'on_line' +--- callbacks. +--- +--- @param ns_id integer Namespace id from `nvim_create_namespace()` +--- @param opts vim.api.keyset.set_decoration_provider Table of callbacks: +--- • on_start: called first on each screen redraw ["start", +--- tick] +--- • on_buf: called for each buffer being redrawn (before window +--- callbacks) ["buf", bufnr, tick] +--- • on_win: called when starting to redraw a specific window. +--- botline_guess is an approximation that does not exceed the +--- last line number. ["win", winid, bufnr, topline, +--- botline_guess] +--- • on_line: called for each buffer line being redrawn. (The +--- interaction with fold lines is subject to change) ["win", +--- winid, bufnr, row] +--- • on_end: called at the end of a redraw cycle ["end", tick] +function vim.api.nvim_set_decoration_provider(ns_id, opts) end + +--- Sets a highlight group. +--- +--- @param ns_id integer Namespace id for this highlight `nvim_create_namespace()`. +--- Use 0 to set a highlight group globally `:highlight`. +--- Highlights from non-global namespaces are not active by +--- default, use `nvim_set_hl_ns()` or `nvim_win_set_hl_ns()` to +--- activate them. +--- @param name string Highlight group name, e.g. "ErrorMsg" +--- @param val vim.api.keyset.highlight Highlight definition map, accepts the following keys: +--- • fg (or foreground): color name or "#RRGGBB", see note. +--- • bg (or background): color name or "#RRGGBB", see note. +--- • sp (or special): color name or "#RRGGBB" +--- • blend: integer between 0 and 100 +--- • bold: boolean +--- • standout: boolean +--- • underline: boolean +--- • undercurl: boolean +--- • underdouble: boolean +--- • underdotted: boolean +--- • underdashed: boolean +--- • strikethrough: boolean +--- • italic: boolean +--- • reverse: boolean +--- • nocombine: boolean +--- • link: name of another highlight group to link to, see +--- `:hi-link`. +--- • default: Don't override existing definition `:hi-default` +--- • ctermfg: Sets foreground of cterm color `ctermfg` +--- • ctermbg: Sets background of cterm color `ctermbg` +--- • cterm: cterm attribute map, like `highlight-args`. If not +--- set, cterm attributes will match those from the attribute +--- map documented above. +--- • force: if true force update the highlight group when it +--- exists. +function vim.api.nvim_set_hl(ns_id, name, val) end + +--- Set active namespace for highlights defined with `nvim_set_hl()`. This can +--- be set for a single window, see `nvim_win_set_hl_ns()`. +--- +--- @param ns_id integer the namespace to use +function vim.api.nvim_set_hl_ns(ns_id) end + +--- Set active namespace for highlights defined with `nvim_set_hl()` while +--- redrawing. +--- This function meant to be called while redrawing, primarily from +--- `nvim_set_decoration_provider()` on_win and on_line callbacks, which are +--- allowed to change the namespace during a redraw cycle. +--- +--- @param ns_id integer the namespace to activate +function vim.api.nvim_set_hl_ns_fast(ns_id) end + +--- Sets a global `mapping` for the given mode. +--- To set a buffer-local mapping, use `nvim_buf_set_keymap()`. +--- Unlike `:map`, leading/trailing whitespace is accepted as part of the +--- {lhs} or {rhs}. Empty {rhs} is `<Nop>`. `keycodes` are replaced as usual. +--- Example: +--- +--- ```vim +--- call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) +--- ``` +--- +--- is equivalent to: +--- +--- ```vim +--- nmap <nowait> <Space><NL> <Nop> +--- ``` +--- +--- @param mode string Mode short-name (map command prefix: "n", "i", "v", "x", …) or +--- "!" for `:map!`, or empty string for `:map`. "ia", "ca" or +--- "!a" for abbreviation in Insert mode, Cmdline mode, or both, +--- respectively +--- @param lhs string Left-hand-side `{lhs}` of the mapping. +--- @param rhs string Right-hand-side `{rhs}` of the mapping. +--- @param opts vim.api.keyset.keymap Optional parameters map: Accepts all `:map-arguments` as keys +--- except `<buffer>`, values are booleans (default false). Also: +--- • "noremap" disables `recursive_mapping`, like `:noremap` +--- • "desc" human-readable description. +--- • "callback" Lua function called in place of {rhs}. +--- • "replace_keycodes" (boolean) When "expr" is true, replace +--- keycodes in the resulting string (see +--- `nvim_replace_termcodes()`). Returning nil from the Lua +--- "callback" is equivalent to returning an empty string. +function vim.api.nvim_set_keymap(mode, lhs, rhs, opts) end + +--- @deprecated +--- @param name string +--- @param value any +function vim.api.nvim_set_option(name, value) end + +--- Sets the value of an option. The behavior of this function matches that of +--- `:set`: for global-local options, both the global and local value are set +--- unless otherwise specified with {scope}. +--- Note the options {win} and {buf} cannot be used together. +--- +--- @param name string Option name +--- @param value any New option value +--- @param opts vim.api.keyset.option Optional parameters +--- • scope: One of "global" or "local". Analogous to +--- `:setglobal` and `:setlocal`, respectively. +--- • win: `window-ID`. Used for setting window local option. +--- • buf: Buffer number. Used for setting buffer local option. +function vim.api.nvim_set_option_value(name, value, opts) end + +--- Sets a global (g:) variable. +--- +--- @param name string Variable name +--- @param value any Variable value +function vim.api.nvim_set_var(name, value) end + +--- Sets a v: variable, if it is not readonly. +--- +--- @param name string Variable name +--- @param value any Variable value +function vim.api.nvim_set_vvar(name, value) end + +--- Calculates the number of display cells occupied by `text`. Control +--- characters including <Tab> count as one cell. +--- +--- @param text string Some text +--- @return integer +function vim.api.nvim_strwidth(text) end + +--- Removes a tab-scoped (t:) variable +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @param name string Variable name +function vim.api.nvim_tabpage_del_var(tabpage, name) end + +--- Gets the tabpage number +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @return integer +function vim.api.nvim_tabpage_get_number(tabpage) end + +--- Gets a tab-scoped (t:) variable +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @param name string Variable name +--- @return any +function vim.api.nvim_tabpage_get_var(tabpage, name) end + +--- Gets the current window in a tabpage +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @return integer +function vim.api.nvim_tabpage_get_win(tabpage) end + +--- Checks if a tabpage is valid +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @return boolean +function vim.api.nvim_tabpage_is_valid(tabpage) end + +--- Gets the windows in a tabpage +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @return integer[] +function vim.api.nvim_tabpage_list_wins(tabpage) end + +--- Sets a tab-scoped (t:) variable +--- +--- @param tabpage integer Tabpage handle, or 0 for current tabpage +--- @param name string Variable name +--- @param value any Variable value +function vim.api.nvim_tabpage_set_var(tabpage, name, value) end + +--- Calls a function with window as temporary current window. +--- +--- @param window integer Window handle, or 0 for current window +--- @param fun function Function to call inside the window (currently Lua callable +--- only) +--- @return any +function vim.api.nvim_win_call(window, fun) end + +--- Closes the window (like `:close` with a `window-ID`). +--- +--- @param window integer Window handle, or 0 for current window +--- @param force boolean Behave like `:close!` The last window of a buffer with +--- unwritten changes can be closed. The buffer will become +--- hidden, even if 'hidden' is not set. +function vim.api.nvim_win_close(window, force) end + +--- Removes a window-scoped (w:) variable +--- +--- @param window integer Window handle, or 0 for current window +--- @param name string Variable name +function vim.api.nvim_win_del_var(window, name) end + +--- Gets the current buffer in a window +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer +function vim.api.nvim_win_get_buf(window) end + +--- Gets window configuration. +--- The returned value may be given to `nvim_open_win()`. +--- `relative` is empty for normal windows. +--- +--- @param window integer Window handle, or 0 for current window +--- @return table<string,any> +function vim.api.nvim_win_get_config(window) end + +--- Gets the (1,0)-indexed, buffer-relative cursor position for a given window +--- (different windows showing the same buffer have independent cursor +--- positions). `api-indexing` +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer[] +function vim.api.nvim_win_get_cursor(window) end + +--- Gets the window height +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer +function vim.api.nvim_win_get_height(window) end + +--- Gets the window number +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer +function vim.api.nvim_win_get_number(window) end + +--- @deprecated +--- @param window integer +--- @param name string +--- @return any +function vim.api.nvim_win_get_option(window, name) end + +--- Gets the window position in display cells. First position is zero. +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer[] +function vim.api.nvim_win_get_position(window) end + +--- Gets the window tabpage +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer +function vim.api.nvim_win_get_tabpage(window) end + +--- Gets a window-scoped (w:) variable +--- +--- @param window integer Window handle, or 0 for current window +--- @param name string Variable name +--- @return any +function vim.api.nvim_win_get_var(window, name) end + +--- Gets the window width +--- +--- @param window integer Window handle, or 0 for current window +--- @return integer +function vim.api.nvim_win_get_width(window) end + +--- Closes the window and hide the buffer it contains (like `:hide` with a +--- `window-ID`). +--- Like `:hide` the buffer becomes hidden unless another window is editing +--- it, or 'bufhidden' is `unload`, `delete` or `wipe` as opposed to `:close` +--- or `nvim_win_close()`, which will close the buffer. +--- +--- @param window integer Window handle, or 0 for current window +function vim.api.nvim_win_hide(window) end + +--- Checks if a window is valid +--- +--- @param window integer Window handle, or 0 for current window +--- @return boolean +function vim.api.nvim_win_is_valid(window) end + +--- Sets the current buffer in a window, without side effects +--- +--- @param window integer Window handle, or 0 for current window +--- @param buffer integer Buffer handle +function vim.api.nvim_win_set_buf(window, buffer) end + +--- Configures window layout. Currently only for floating and external windows +--- (including changing a split window to those layouts). +--- When reconfiguring a floating window, absent option keys will not be +--- changed. `row`/`col` and `relative` must be reconfigured together. +--- +--- @param window integer Window handle, or 0 for current window +--- @param config vim.api.keyset.float_config Map defining the window configuration, see `nvim_open_win()` +function vim.api.nvim_win_set_config(window, config) end + +--- Sets the (1,0)-indexed cursor position in the window. `api-indexing` This +--- scrolls the window even if it is not the current one. +--- +--- @param window integer Window handle, or 0 for current window +--- @param pos integer[] (row, col) tuple representing the new position +function vim.api.nvim_win_set_cursor(window, pos) end + +--- Sets the window height. +--- +--- @param window integer Window handle, or 0 for current window +--- @param height integer Height as a count of rows +function vim.api.nvim_win_set_height(window, height) end + +--- Set highlight namespace for a window. This will use highlights defined +--- with `nvim_set_hl()` for this namespace, but fall back to global +--- highlights (ns=0) when missing. +--- This takes precedence over the 'winhighlight' option. +--- +--- @param window integer +--- @param ns_id integer the namespace to use +function vim.api.nvim_win_set_hl_ns(window, ns_id) end + +--- @deprecated +--- @param window integer +--- @param name string +--- @param value any +function vim.api.nvim_win_set_option(window, name, value) end + +--- Sets a window-scoped (w:) variable +--- +--- @param window integer Window handle, or 0 for current window +--- @param name string Variable name +--- @param value any Variable value +function vim.api.nvim_win_set_var(window, name, value) end + +--- Sets the window width. This will only succeed if the screen is split +--- vertically. +--- +--- @param window integer Window handle, or 0 for current window +--- @param width integer Width as a count of columns +function vim.api.nvim_win_set_width(window, width) end + +--- Computes the number of screen lines occupied by a range of text in a given +--- window. Works for off-screen text and takes folds into account. +--- Diff filler or virtual lines above a line are counted as a part of that +--- line, unless the line is on "start_row" and "start_vcol" is specified. +--- Diff filler or virtual lines below the last buffer line are counted in the +--- result when "end_row" is omitted. +--- Line indexing is similar to `nvim_buf_get_text()`. +--- +--- @param window integer Window handle, or 0 for current window. +--- @param opts vim.api.keyset.win_text_height Optional parameters: +--- • start_row: Starting line index, 0-based inclusive. When +--- omitted start at the very top. +--- • end_row: Ending line index, 0-based inclusive. When +--- omitted end at the very bottom. +--- • start_vcol: Starting virtual column index on "start_row", +--- 0-based inclusive, rounded down to full screen lines. When +--- omitted include the whole line. +--- • end_vcol: Ending virtual column index on "end_row", +--- 0-based exclusive, rounded up to full screen lines. When +--- omitted include the whole line. +--- @return table<string,any> +function vim.api.nvim_win_text_height(window, opts) end diff --git a/runtime/lua/vim/_meta/api_keysets.lua b/runtime/lua/vim/_meta/api_keysets.lua new file mode 100644 index 0000000000..f69e5a92c7 --- /dev/null +++ b/runtime/lua/vim/_meta/api_keysets.lua @@ -0,0 +1,267 @@ +--- @meta _ +-- THIS FILE IS GENERATED +-- DO NOT EDIT +error('Cannot require a meta file') + +--- @class vim.api.keyset.clear_autocmds +--- @field buffer? integer +--- @field event? any +--- @field group? any +--- @field pattern? any + +--- @class vim.api.keyset.cmd +--- @field cmd? string +--- @field range? any[] +--- @field count? integer +--- @field reg? string +--- @field bang? boolean +--- @field args? any[] +--- @field magic? table<string,any> +--- @field mods? table<string,any> +--- @field nargs? any +--- @field addr? any +--- @field nextcmd? any + +--- @class vim.api.keyset.cmd_magic +--- @field file? boolean +--- @field bar? boolean + +--- @class vim.api.keyset.cmd_mods +--- @field silent? boolean +--- @field emsg_silent? boolean +--- @field unsilent? boolean +--- @field filter? table<string,any> +--- @field sandbox? boolean +--- @field noautocmd? boolean +--- @field browse? boolean +--- @field confirm? boolean +--- @field hide? boolean +--- @field horizontal? boolean +--- @field keepalt? boolean +--- @field keepjumps? boolean +--- @field keepmarks? boolean +--- @field keeppatterns? boolean +--- @field lockmarks? boolean +--- @field noswapfile? boolean +--- @field tab? integer +--- @field verbose? integer +--- @field vertical? boolean +--- @field split? string + +--- @class vim.api.keyset.cmd_mods_filter +--- @field pattern? string +--- @field force? boolean + +--- @class vim.api.keyset.cmd_opts +--- @field output? boolean + +--- @class vim.api.keyset.context +--- @field types? any[] + +--- @class vim.api.keyset.create_augroup +--- @field clear? any + +--- @class vim.api.keyset.create_autocmd +--- @field buffer? integer +--- @field callback? any +--- @field command? string +--- @field desc? string +--- @field group? any +--- @field nested? boolean +--- @field once? boolean +--- @field pattern? any + +--- @class vim.api.keyset.echo_opts +--- @field verbose? boolean + +--- @class vim.api.keyset.eval_statusline +--- @field winid? integer +--- @field maxwidth? integer +--- @field fillchar? string +--- @field highlights? boolean +--- @field use_winbar? boolean +--- @field use_tabline? boolean +--- @field use_statuscol_lnum? integer + +--- @class vim.api.keyset.exec_autocmds +--- @field buffer? integer +--- @field group? any +--- @field modeline? boolean +--- @field pattern? any +--- @field data? any + +--- @class vim.api.keyset.exec_opts +--- @field output? boolean + +--- @class vim.api.keyset.float_config +--- @field row? number +--- @field col? number +--- @field width? integer +--- @field height? integer +--- @field anchor? string +--- @field relative? string +--- @field win? integer +--- @field bufpos? any[] +--- @field external? boolean +--- @field focusable? boolean +--- @field zindex? integer +--- @field border? any +--- @field title? any +--- @field title_pos? string +--- @field footer? any +--- @field footer_pos? string +--- @field style? string +--- @field noautocmd? boolean +--- @field fixed? boolean +--- @field hide? boolean + +--- @class vim.api.keyset.get_autocmds +--- @field event? any +--- @field group? any +--- @field pattern? any +--- @field buffer? any + +--- @class vim.api.keyset.get_commands +--- @field builtin? boolean + +--- @class vim.api.keyset.get_extmarks +--- @field limit? integer +--- @field details? boolean +--- @field hl_name? boolean +--- @field overlap? boolean +--- @field type? string + +--- @class vim.api.keyset.get_highlight +--- @field id? integer +--- @field name? string +--- @field link? boolean +--- @field create? boolean + +--- @class vim.api.keyset.get_ns +--- @field winid? integer + +--- @class vim.api.keyset.highlight +--- @field bold? boolean +--- @field standout? boolean +--- @field strikethrough? boolean +--- @field underline? boolean +--- @field undercurl? boolean +--- @field underdouble? boolean +--- @field underdotted? boolean +--- @field underdashed? boolean +--- @field italic? boolean +--- @field reverse? boolean +--- @field altfont? boolean +--- @field nocombine? boolean +--- @field default? boolean +--- @field cterm? any +--- @field foreground? any +--- @field fg? any +--- @field background? any +--- @field bg? any +--- @field ctermfg? any +--- @field ctermbg? any +--- @field special? any +--- @field sp? any +--- @field link? any +--- @field global_link? any +--- @field fallback? boolean +--- @field blend? integer +--- @field fg_indexed? boolean +--- @field bg_indexed? boolean +--- @field force? boolean + +--- @class vim.api.keyset.highlight_cterm +--- @field bold? boolean +--- @field standout? boolean +--- @field strikethrough? boolean +--- @field underline? boolean +--- @field undercurl? boolean +--- @field underdouble? boolean +--- @field underdotted? boolean +--- @field underdashed? boolean +--- @field italic? boolean +--- @field reverse? boolean +--- @field altfont? boolean +--- @field nocombine? boolean + +--- @class vim.api.keyset.keymap +--- @field noremap? boolean +--- @field nowait? boolean +--- @field silent? boolean +--- @field script? boolean +--- @field expr? boolean +--- @field unique? boolean +--- @field callback? function +--- @field desc? string +--- @field replace_keycodes? boolean + +--- @class vim.api.keyset.option +--- @field scope? string +--- @field win? integer +--- @field buf? integer +--- @field filetype? string + +--- @class vim.api.keyset.runtime +--- @field is_lua? boolean +--- @field do_source? boolean + +--- @class vim.api.keyset.set_decoration_provider +--- @field on_start? function +--- @field on_buf? function +--- @field on_win? function +--- @field on_line? function +--- @field on_end? function +--- @field _on_hl_def? function +--- @field _on_spell_nav? function + +--- @class vim.api.keyset.set_extmark +--- @field id? integer +--- @field end_line? integer +--- @field end_row? integer +--- @field end_col? integer +--- @field hl_group? any +--- @field virt_text? any[] +--- @field virt_text_pos? string +--- @field virt_text_win_col? integer +--- @field virt_text_hide? boolean +--- @field hl_eol? boolean +--- @field hl_mode? string +--- @field invalidate? boolean +--- @field ephemeral? boolean +--- @field priority? integer +--- @field right_gravity? boolean +--- @field end_right_gravity? boolean +--- @field virt_lines? any[] +--- @field virt_lines_above? boolean +--- @field virt_lines_leftcol? boolean +--- @field strict? boolean +--- @field sign_text? string +--- @field sign_hl_group? any +--- @field number_hl_group? any +--- @field line_hl_group? any +--- @field cursorline_hl_group? any +--- @field conceal? string +--- @field spell? boolean +--- @field ui_watched? boolean +--- @field undo_restore? boolean + +--- @class vim.api.keyset.user_command +--- @field addr? any +--- @field bang? boolean +--- @field bar? boolean +--- @field complete? any +--- @field count? any +--- @field desc? any +--- @field force? boolean +--- @field keepscript? boolean +--- @field nargs? any +--- @field preview? any +--- @field range? any +--- @field register? boolean + +--- @class vim.api.keyset.win_text_height +--- @field start_row? integer +--- @field end_row? integer +--- @field start_vcol? integer +--- @field end_vcol? integer diff --git a/runtime/lua/vim/_meta/base64.lua b/runtime/lua/vim/_meta/base64.lua new file mode 100644 index 0000000000..f25b4af234 --- /dev/null +++ b/runtime/lua/vim/_meta/base64.lua @@ -0,0 +1,13 @@ +--- @meta + +--- Encode {str} using Base64. +--- +--- @param str string String to encode +--- @return string Encoded string +function vim.base64.encode(str) end + +--- Decode a Base64 encoded string. +--- +--- @param str string Base64 encoded string +--- @return string Decoded string +function vim.base64.decode(str) end diff --git a/runtime/lua/vim/_meta/builtin.lua b/runtime/lua/vim/_meta/builtin.lua new file mode 100644 index 0000000000..eeba356672 --- /dev/null +++ b/runtime/lua/vim/_meta/builtin.lua @@ -0,0 +1,289 @@ +---@meta + +-- luacheck: no unused args + +---@defgroup vim.builtin +--- +---@brief <pre>help +---vim.api.{func}({...}) *vim.api* +--- Invokes Nvim |API| function {func} with arguments {...}. +--- Example: call the "nvim_get_current_line()" API function: >lua +--- print(tostring(vim.api.nvim_get_current_line())) +--- +---vim.NIL *vim.NIL* +--- Special value representing NIL in |RPC| and |v:null| in Vimscript +--- conversion, and similar cases. Lua `nil` cannot be used as part of a Lua +--- table representing a Dictionary or Array, because it is treated as +--- missing: `{"foo", nil}` is the same as `{"foo"}`. +--- +---vim.type_idx *vim.type_idx* +--- Type index for use in |lua-special-tbl|. Specifying one of the values from +--- |vim.types| allows typing the empty table (it is unclear whether empty Lua +--- table represents empty list or empty array) and forcing integral numbers +--- to be |Float|. See |lua-special-tbl| for more details. +--- +---vim.val_idx *vim.val_idx* +--- Value index for tables representing |Float|s. A table representing +--- floating-point value 1.0 looks like this: >lua +--- { +--- [vim.type_idx] = vim.types.float, +--- [vim.val_idx] = 1.0, +--- } +---< See also |vim.type_idx| and |lua-special-tbl|. +--- +---vim.types *vim.types* +--- Table with possible values for |vim.type_idx|. Contains two sets of +--- key-value pairs: first maps possible values for |vim.type_idx| to +--- human-readable strings, second maps human-readable type names to values +--- for |vim.type_idx|. Currently contains pairs for `float`, `array` and +--- `dictionary` types. +--- +--- Note: One must expect that values corresponding to `vim.types.float`, +--- `vim.types.array` and `vim.types.dictionary` fall under only two following +--- assumptions: +--- 1. Value may serve both as a key and as a value in a table. Given the +--- properties of Lua tables this basically means “value is not `nil`”. +--- 2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the +--- same as `value`. +--- No other restrictions are put on types, and it is not guaranteed that +--- values corresponding to `vim.types.float`, `vim.types.array` and +--- `vim.types.dictionary` will not change or that `vim.types` table will only +--- contain values for these three types. +--- +--- *log_levels* *vim.log.levels* +---Log levels are one of the values defined in `vim.log.levels`: +--- +--- vim.log.levels.DEBUG +--- vim.log.levels.ERROR +--- vim.log.levels.INFO +--- vim.log.levels.TRACE +--- vim.log.levels.WARN +--- vim.log.levels.OFF +--- +---</pre> + +--- Returns true if the code is executing as part of a "fast" event handler, +--- where most of the API is disabled. These are low-level events (e.g. +--- |lua-loop-callbacks|) which can be invoked whenever Nvim polls for input. +--- When this is `false` most API functions are callable (but may be subject +--- to other restrictions such as |textlock|). +function vim.in_fast_event() end + +--- Creates a special empty table (marked with a metatable), which Nvim +--- converts to an empty dictionary when translating Lua values to Vimscript +--- or API types. Nvim by default converts an empty table `{}` without this +--- metatable to an list/array. +--- +--- Note: If numeric keys are present in the table, Nvim ignores the metatable +--- marker and converts the dict to a list/array anyway. +function vim.empty_dict() end + +--- Sends {event} to {channel} via |RPC| and returns immediately. If {channel} +--- is 0, the event is broadcast to all channels. +--- +--- This function also works in a fast callback |lua-loop-callbacks|. +--- @param channel integer +--- @param method string +--- @param args? any[] +--- @param ...? any +function vim.rpcnotify(channel, method, args, ...) end + +--- Sends a request to {channel} to invoke {method} via |RPC| and blocks until +--- a response is received. +--- +--- Note: NIL values as part of the return value is represented as |vim.NIL| +--- special value +--- @param channel integer +--- @param method string +--- @param args? any[] +--- @param ...? any +function vim.rpcrequest(channel, method, args, ...) end + +--- Compares strings case-insensitively. +--- @param a string +--- @param b string +--- @return 0|1|-1 +--- if strings are +--- equal, {a} is greater than {b} or {a} is lesser than {b}, respectively. +function vim.stricmp(a, b) end + +--- Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not +--- supplied, it defaults to false (use UTF-32). Returns the byte index. +--- +--- Invalid UTF-8 and NUL is treated like by |vim.str_byteindex()|. +--- An {index} in the middle of a UTF-16 sequence is rounded upwards to +--- the end of that sequence. +--- @param str string +--- @param index number +--- @param use_utf16? any +function vim.str_byteindex(str, index, use_utf16) end + +--- Gets a list of the starting byte positions of each UTF-8 codepoint in the given string. +--- +--- Embedded NUL bytes are treated as terminating the string. +--- @param str string +--- @return table +function vim.str_utf_pos(str) end + +--- Gets the distance (in bytes) from the starting byte of the codepoint (character) that {index} +--- points to. +--- +--- The result can be added to {index} to get the starting byte of a character. +--- +--- Examples: +--- +--- ```lua +--- -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8) +--- +--- -- Returns 0 because the index is pointing at the first byte of a character +--- vim.str_utf_start('æ', 1) +--- +--- -- Returns -1 because the index is pointing at the second byte of a character +--- vim.str_utf_start('æ', 2) +--- ``` +--- +--- @param str string +--- @param index number +--- @return number +function vim.str_utf_start(str, index) end + +--- Gets the distance (in bytes) from the last byte of the codepoint (character) that {index} points +--- to. +--- +--- Examples: +--- +--- ```lua +--- -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8) +--- +--- -- Returns 0 because the index is pointing at the last byte of a character +--- vim.str_utf_end('æ', 2) +--- +--- -- Returns 1 because the index is pointing at the penultimate byte of a character +--- vim.str_utf_end('æ', 1) +--- ``` +--- +--- @param str string +--- @param index number +--- @return number +function vim.str_utf_end(str, index) end + +--- Convert byte index to UTF-32 and UTF-16 indices. If {index} is not +--- supplied, the length of the string is used. All indices are zero-based. +--- +--- Embedded NUL bytes are treated as terminating the string. Invalid UTF-8 +--- bytes, and embedded surrogates are counted as one code point each. An +--- {index} in the middle of a UTF-8 sequence is rounded upwards to the end of +--- that sequence. +--- @param str string +--- @param index? number +--- @return integer UTF-32 index +--- @return integer UTF-16 index +function vim.str_utfindex(str, index) end + +--- The result is a String, which is the text {str} converted from +--- encoding {from} to encoding {to}. When the conversion fails `nil` is +--- returned. When some characters could not be converted they +--- are replaced with "?". +--- The encoding names are whatever the iconv() library function +--- can accept, see ":Man 3 iconv". +--- +--- @param str string Text to convert +--- @param from number Encoding of {str} +--- @param to number Target encoding +--- @param opts? table<string,any> +--- @return string|nil Converted string if conversion succeeds, `nil` otherwise. +function vim.iconv(str, from, to, opts) end + +--- Schedules {fn} to be invoked soon by the main event-loop. Useful +--- to avoid |textlock| or other temporary restrictions. +--- @param fn function +function vim.schedule(fn) end + +--- Wait for {time} in milliseconds until {callback} returns `true`. +--- +--- Executes {callback} immediately and at approximately {interval} +--- milliseconds (default 200). Nvim still processes other events during +--- this time. +--- +--- Cannot be called while in an |api-fast| event. +--- +--- Examples: +--- +--- ```lua +--- +--- --- +--- -- Wait for 100 ms, allowing other events to process +--- vim.wait(100, function() end) +--- +--- --- +--- -- Wait for 100 ms or until global variable set. +--- vim.wait(100, function() return vim.g.waiting_for_var end) +--- +--- --- +--- -- Wait for 1 second or until global variable set, checking every ~500 ms +--- vim.wait(1000, function() return vim.g.waiting_for_var end, 500) +--- +--- --- +--- -- Schedule a function to set a value in 100ms +--- vim.defer_fn(function() vim.g.timer_result = true end, 100) +--- +--- -- Would wait ten seconds if results blocked. Actually only waits 100 ms +--- if vim.wait(10000, function() return vim.g.timer_result end) then +--- print('Only waiting a little bit of time!') +--- end +--- ``` +--- +--- @param time integer Number of milliseconds to wait +--- @param callback? fun(): boolean Optional callback. Waits until {callback} returns true +--- @param interval? integer (Approximate) number of milliseconds to wait between polls +--- @param fast_only? boolean If true, only |api-fast| events will be processed. +--- @return boolean, nil|-1|-2 +--- - If {callback} returns `true` during the {time}: `true, nil` +--- - If {callback} never returns `true` during the {time}: `false, -1` +--- - If {callback} is interrupted during the {time}: `false, -2` +--- - If {callback} errors, the error is raised. +function vim.wait(time, callback, interval, fast_only) end + +--- Attach to ui events, similar to |nvim_ui_attach()| but receive events +--- as Lua callback. Can be used to implement screen elements like +--- popupmenu or message handling in Lua. +--- +--- {options} should be a dictionary-like table, where `ext_...` options should +--- be set to true to receive events for the respective external element. +--- +--- {callback} receives event name plus additional parameters. See |ui-popupmenu| +--- and the sections below for event format for respective events. +--- +--- WARNING: This api is considered experimental. Usability will vary for +--- different screen elements. In particular `ext_messages` behavior is subject +--- to further changes and usability improvements. This is expected to be +--- used to handle messages when setting 'cmdheight' to zero (which is +--- likewise experimental). +--- +--- Example (stub for a |ui-popupmenu| implementation): +--- +--- ```lua +--- ns = vim.api.nvim_create_namespace('my_fancy_pum') +--- +--- vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...) +--- if event == "popupmenu_show" then +--- local items, selected, row, col, grid = ... +--- print("display pum ", #items) +--- elseif event == "popupmenu_select" then +--- local selected = ... +--- print("selected", selected) +--- elseif event == "popupmenu_hide" then +--- print("FIN") +--- end +--- end) +--- ``` +--- +--- @param ns integer +--- @param options table<string, any> +--- @param callback fun() +function vim.ui_attach(ns, options, callback) end + +--- Detach a callback previously attached with |vim.ui_attach()| for the +--- given namespace {ns}. +--- @param ns integer +function vim.ui_detach(ns) end diff --git a/runtime/lua/vim/_meta/builtin_types.lua b/runtime/lua/vim/_meta/builtin_types.lua new file mode 100644 index 0000000000..ef0452c649 --- /dev/null +++ b/runtime/lua/vim/_meta/builtin_types.lua @@ -0,0 +1,129 @@ +--- @class vim.fn.sign +--- @field group string +--- @field id integer +--- @field lnum integer +--- @field name string +--- @field priority integer + +--- @class vim.fn.getbufinfo.dict +--- @field buflisted? 0|1 +--- @field bufloaded? 0|1 +--- @field bufmodified? 0|1 + +--- @class vim.fn.getbufinfo.ret.item +--- @field bufnr integer +--- @field changed 0|1 +--- @field changedtick integer +--- @field hidden 0|1 +--- @field lastused integer +--- @field linecount integer +--- @field listed 0|1 +--- @field lnum integer +--- @field loaded 0|1 +--- @field name string +--- @field signs vim.fn.sign[] +--- @field variables table<string,any> +--- @field windows integer[] + +--- @alias vim.fn.getjumplist.ret {[1]: vim.fn.getjumplist.ret.item[], [2]: integer} + +--- @class vim.fn.getjumplist.ret.item +--- @field bufnr integer +--- @field col integer +--- @field coladd integer +--- @field filename? string +--- @field lnum integer + +--- @class vim.fn.getmousepos.ret +--- @field screenrow integer +--- @field screencol integer +--- @field winid integer +--- @field winrow integer +--- @field wincol integer +--- @field line integer +--- @field column integer + +--- @class vim.fn.getwininfo.ret.item +--- @field botline integer +--- @field bufnr integer +--- @field height integer +--- @field loclist integer +--- @field quickfix integer +--- @field tabnr integer +--- @field terminal integer +--- @field textoff integer +--- @field topline integer +--- @field variables table<string,any> +--- @field width integer +--- @field winbar integer +--- @field wincol integer +--- @field winid integer +--- @field winnr integer +--- @field winrow integer + +--- @class vim.fn.sign_define.dict +--- @field text string +--- @field icon? string +--- @field linehl? string +--- @field numhl? string +--- @field texthl? string +--- @field culhl? string + +--- @class vim.fn.sign_getdefined.ret.item +--- @field name string +--- @field text string +--- @field icon? string +--- @field texthl? string +--- @field culhl? string +--- @field numhl? string +--- @field linehl? string + +--- @class vim.fn.sign_getplaced.dict +--- @field group? string +--- @field id? integer +--- @field lnum? string + +--- @class vim.fn.sign_getplaced.ret.item +--- @field buf integer +--- @field signs vim.fn.sign[] + +--- @class vim.fn.sign_place.dict +--- @field lnum? integer +--- @field priority? integer + +--- @class vim.fn.sign_placelist.list.item +--- @field buffer integer|string +--- @field group? string +--- @field id? integer +--- @field lnum integer +--- @field name string +--- @field priority? integer + +--- @class vim.fn.sign_unplace.dict +--- @field buffer? integer|string +--- @field id? integer + +--- @class vim.fn.sign_unplacelist.list.item +--- @field buffer? integer|string +--- @field group? string +--- @field id? integer + +--- @class vim.fn.winrestview.dict +--- @field col? integer +--- @field coladd? integer +--- @field curswant? integer +--- @field leftcol? integer +--- @field lnum? integer +--- @field skipcol? integer +--- @field topfill? integer +--- @field topline? integer + +--- @class vim.fn.winsaveview.ret +--- @field col integer +--- @field coladd integer +--- @field curswant integer +--- @field leftcol integer +--- @field lnum integer +--- @field skipcol integer +--- @field topfill integer +--- @field topline integer diff --git a/runtime/lua/vim/_meta/diff.lua b/runtime/lua/vim/_meta/diff.lua new file mode 100644 index 0000000000..f265139448 --- /dev/null +++ b/runtime/lua/vim/_meta/diff.lua @@ -0,0 +1,70 @@ +---@meta + +-- luacheck: no unused args + +--- Run diff on strings {a} and {b}. Any indices returned by this function, +--- either directly or via callback arguments, are 1-based. +--- +--- Examples: +--- +--- ```lua +--- vim.diff('a\n', 'b\nc\n') +--- -- => +--- -- @@ -1 +1,2 @@ +--- -- -a +--- -- +b +--- -- +c +--- +--- vim.diff('a\n', 'b\nc\n', {result_type = 'indices'}) +--- -- => +--- -- { +--- -- {1, 1, 1, 2} +--- -- } +--- ``` +--- +---@param a string First string to compare +---@param b string Second string to compare +---@param opts table<string,any> Optional parameters: +--- - `on_hunk` (callback): +--- Invoked for each hunk in the diff. Return a negative number +--- to cancel the callback for any remaining hunks. +--- Args: +--- - `start_a` (integer): Start line of hunk in {a}. +--- - `count_a` (integer): Hunk size in {a}. +--- - `start_b` (integer): Start line of hunk in {b}. +--- - `count_b` (integer): Hunk size in {b}. +--- - `result_type` (string): Form of the returned diff: +--- - "unified": (default) String in unified format. +--- - "indices": Array of hunk locations. +--- Note: This option is ignored if `on_hunk` is used. +--- - `linematch` (boolean|integer): Run linematch on the resulting hunks +--- from xdiff. When integer, only hunks upto this size in +--- lines are run through linematch. Requires `result_type = indices`, +--- ignored otherwise. +--- - `algorithm` (string): +--- Diff algorithm to use. Values: +--- - "myers" the default algorithm +--- - "minimal" spend extra time to generate the +--- smallest possible diff +--- - "patience" patience diff algorithm +--- - "histogram" histogram diff algorithm +--- - `ctxlen` (integer): Context length +--- - `interhunkctxlen` (integer): +--- Inter hunk context length +--- - `ignore_whitespace` (boolean): +--- Ignore whitespace +--- - `ignore_whitespace_change` (boolean): +--- Ignore whitespace change +--- - `ignore_whitespace_change_at_eol` (boolean) +--- Ignore whitespace change at end-of-line. +--- - `ignore_cr_at_eol` (boolean) +--- Ignore carriage return at end-of-line +--- - `ignore_blank_lines` (boolean) +--- Ignore blank lines +--- - `indent_heuristic` (boolean): +--- Use the indent heuristic for the internal +--- diff library. +--- +---@return string|table|nil +--- See {opts.result_type}. `nil` if {opts.on_hunk} is given. +function vim.diff(a, b, opts) end diff --git a/runtime/lua/vim/_meta/json.lua b/runtime/lua/vim/_meta/json.lua new file mode 100644 index 0000000000..e010086615 --- /dev/null +++ b/runtime/lua/vim/_meta/json.lua @@ -0,0 +1,39 @@ +---@meta + +---@nodoc +vim.json = {} + +-- luacheck: no unused args + +---@defgroup vim.json +--- +--- This module provides encoding and decoding of Lua objects to and +--- from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. + +--- Decodes (or "unpacks") the JSON-encoded {str} to a Lua object. +--- +--- - Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below). +--- - Decodes empty object as |vim.empty_dict()|. +--- - Decodes empty array as `{}` (empty Lua table). +--- +--- Example: +--- +--- ```lua +--- vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}')) +--- -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL } +--- ``` +--- +---@param str string Stringified JSON data. +---@param opts? table<string,any> Options table with keys: +--- - luanil: (table) Table with keys: +--- * object: (boolean) When true, converts `null` in JSON objects +--- to Lua `nil` instead of |vim.NIL|. +--- * array: (boolean) When true, converts `null` in JSON arrays +--- to Lua `nil` instead of |vim.NIL|. +---@return any +function vim.json.decode(str, opts) end + +--- Encodes (or "packs") Lua object {obj} as JSON in a Lua string. +---@param obj any +---@return string +function vim.json.encode(obj) end diff --git a/runtime/lua/vim/_meta/lpeg.lua b/runtime/lua/vim/_meta/lpeg.lua new file mode 100644 index 0000000000..42c9a6449e --- /dev/null +++ b/runtime/lua/vim/_meta/lpeg.lua @@ -0,0 +1,323 @@ +--- @meta + +-- These types were taken from https://github.com/LuaCATS/lpeg, with types being renamed to include +-- the vim namespace and with some descriptions made less verbose. + +--- *LPeg* is a new pattern-matching library for Lua, based on [Parsing Expression Grammars](https://bford.info/packrat/) (PEGs). +vim.lpeg = {} + +--- @class vim.lpeg.Pattern +--- @operator unm: vim.lpeg.Pattern +--- @operator add(vim.lpeg.Pattern): vim.lpeg.Pattern +--- @operator sub(vim.lpeg.Pattern): vim.lpeg.Pattern +--- @operator mul(vim.lpeg.Pattern): vim.lpeg.Pattern +--- @operator mul(vim.lpeg.Capture): vim.lpeg.Pattern +--- @operator div(string): vim.lpeg.Capture +--- @operator div(number): vim.lpeg.Capture +--- @operator div(table): vim.lpeg.Capture +--- @operator div(function): vim.lpeg.Capture +--- @operator pow(number): vim.lpeg.Pattern +--- @operator mod(function): nil +local Pattern = {} + +--- @alias vim.lpeg.Capture vim.lpeg.Pattern + +--- Matches the given `pattern` against the `subject` string. If the match succeeds, returns the index in the +--- subject of the first character after the match, or the captured values (if the pattern captured any value). +--- An optional numeric argument `init` makes the match start at that position in the subject string. As usual +--- in Lua libraries, a negative value counts from the end. Unlike typical pattern-matching functions, `match` +--- works only in anchored mode; that is, it tries to match the pattern with a prefix of the given subject +--- string (at position `init`), not with an arbitrary substring of the subject. So, if we want to find a +--- pattern anywhere in a string, we must either write a loop in Lua or write a pattern that +--- matches anywhere. +--- +--- Example: +--- ```lua +--- local pattern = lpeg.R("az") ^ 1 * -1 +--- assert(pattern:match("hello") == 6) +--- assert(lpeg.match(pattern, "hello") == 6) +--- assert(pattern:match("1 hello") == nil) +--- ``` +--- +--- @param pattern vim.lpeg.Pattern +--- @param subject string +--- @param init? integer +--- @return integer|vim.lpeg.Capture|nil +function vim.lpeg.match(pattern, subject, init) end + +--- Matches the given `pattern` against the `subject` string. If the match succeeds, returns the +--- index in the subject of the first character after the match, or the captured values (if the +--- pattern captured any value). An optional numeric argument `init` makes the match start at +--- that position in the subject string. As usual in Lua libraries, a negative value counts from the end. +--- Unlike typical pattern-matching functions, `match` works only in anchored mode; that is, it tries +--- to match the pattern with a prefix of the given subject string (at position `init`), not with +--- an arbitrary substring of the subject. So, if we want to find a pattern anywhere in a string, +--- we must either write a loop in Lua or write a pattern that matches anywhere. +--- +--- Example: +--- ```lua +--- local pattern = lpeg.R("az") ^ 1 * -1 +--- assert(pattern:match("hello") == 6) +--- assert(lpeg.match(pattern, "hello") == 6) +--- assert(pattern:match("1 hello") == nil) +--- ``` +--- +--- @param subject string +--- @param init? integer +--- @return integer|vim.lpeg.Capture|nil +function Pattern:match(subject, init) end + +--- Returns the string `"pattern"` if the given value is a pattern, otherwise `nil`. +--- +--- @return 'pattern'|nil +function vim.lpeg.type(value) end + +--- Returns a string with the running version of LPeg. +--- @return string +function vim.lpeg.version() end + +--- Sets a limit for the size of the backtrack stack used by LPeg to track calls and choices. +--- The default limit is `400`. Most well-written patterns need little backtrack levels and +--- therefore you seldom need to change this limit; before changing it you should try to rewrite +--- your pattern to avoid the need for extra space. Nevertheless, a few useful patterns may overflow. +--- Also, with recursive grammars, subjects with deep recursion may also need larger limits. +--- +--- @param max integer +function vim.lpeg.setmaxstack(max) end + +--- Converts the given value into a proper pattern. This following rules are applied: +--- * If the argument is a pattern, it is returned unmodified. +--- * If the argument is a string, it is translated to a pattern that matches the string literally. +--- * If the argument is a non-negative number `n`, the result is a pattern that matches exactly `n` characters. +--- * If the argument is a negative number `-n`, the result is a pattern that succeeds only if +--- the input string has less than `n` characters left: `lpeg.P(-n)` is equivalent to `-lpeg.P(n)` +--- (see the unary minus operation). +--- * If the argument is a boolean, the result is a pattern that always succeeds or always fails +--- (according to the boolean value), without consuming any input. +--- * If the argument is a table, it is interpreted as a grammar (see Grammars). +--- * If the argument is a function, returns a pattern equivalent to a match-time captureover the empty string. +--- +--- @param value vim.lpeg.Pattern|string|integer|boolean|table|function +--- @return vim.lpeg.Pattern +function vim.lpeg.P(value) end + +--- Returns a pattern that matches only if the input string at the current position is preceded by `patt`. +--- Pattern `patt` must match only strings with some fixed length, and it cannot contain captures. +--- Like the and predicate, this pattern never consumes any input, independently of success or failure. +--- +--- @param pattern vim.lpeg.Pattern +--- @return vim.lpeg.Pattern +function vim.lpeg.B(pattern) end + +--- Returns a pattern that matches any single character belonging to one of the given ranges. +--- Each `range` is a string `xy` of length 2, representing all characters with code between the codes of +--- `x` and `y` (both inclusive). As an example, the pattern `lpeg.R("09")` matches any digit, and +--- `lpeg.R("az", "AZ")` matches any ASCII letter. +--- +--- Example: +--- ```lua +--- local pattern = lpeg.R("az") ^ 1 * -1 +--- assert(pattern:match("hello") == 6) +--- ``` +--- +--- @param ... string +--- @return vim.lpeg.Pattern +function vim.lpeg.R(...) end + +--- Returns a pattern that matches any single character that appears in the given string (the `S` stands for Set). +--- As an example, the pattern `lpeg.S("+-*/")` matches any arithmetic operator. Note that, if `s` is a character +--- (that is, a string of length 1), then `lpeg.P(s)` is equivalent to `lpeg.S(s)` which is equivalent to +--- `lpeg.R(s..s)`. Note also that both `lpeg.S("")` and `lpeg.R()` are patterns that always fail. +--- +--- @param string string +--- @return vim.lpeg.Pattern +function vim.lpeg.S(string) end + +--- Creates a non-terminal (a variable) for a grammar. This operation creates a non-terminal (a variable) +--- for a grammar. The created non-terminal refers to the rule indexed by `v` in the enclosing grammar. +--- +--- Example: +--- ```lua +--- local b = lpeg.P({"(" * ((1 - lpeg.S "()") + lpeg.V(1)) ^ 0 * ")"}) +--- assert(b:match('((string))') == 11) +--- assert(b:match('(') == nil) +--- ``` +--- +--- @param v string|integer +--- @return vim.lpeg.Pattern +function vim.lpeg.V(v) end + +--- @class vim.lpeg.Locale +--- @field alnum userdata +--- @field alpha userdata +--- @field cntrl userdata +--- @field digit userdata +--- @field graph userdata +--- @field lower userdata +--- @field print userdata +--- @field punct userdata +--- @field space userdata +--- @field upper userdata +--- @field xdigit userdata + +--- Returns a table with patterns for matching some character classes according to the current locale. +--- The table has fields named `alnum`, `alpha`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, +--- `space`, `upper`, and `xdigit`, each one containing a correspondent pattern. Each pattern matches +--- any single character that belongs to its class. +--- If called with an argument `table`, then it creates those fields inside the given table and returns +--- that table. +--- +--- Example: +--- ```lua +--- lpeg.locale(lpeg) +--- local space = lpeg.space^0 +--- local name = lpeg.C(lpeg.alpha^1) * space +--- local sep = lpeg.S(",;") * space +--- local pair = lpeg.Cg(name * "=" * space * name) * sep^-1 +--- local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset) +--- local t = list:match("a=b, c = hi; next = pi") +--- assert(t.a == 'b') +--- assert(t.c == 'hi') +--- assert(t.next == 'pi') +--- local locale = lpeg.locale() +--- assert(type(locale.digit) == 'userdata') +--- ``` +--- +--- @param tab? table +--- @return vim.lpeg.Locale +function vim.lpeg.locale(tab) end + +--- Creates a simple capture, which captures the substring of the subject that matches `patt`. +--- The captured value is a string. If `patt` has other captures, their values are returned after this one. +--- +--- Example: +--- ```lua +--- local function split (s, sep) +--- sep = lpeg.P(sep) +--- local elem = lpeg.C((1 - sep)^0) +--- local p = elem * (sep * elem)^0 +--- return lpeg.match(p, s) +--- end +--- local a, b, c = split('a,b,c', ',') +--- assert(a == 'a') +--- assert(b == 'b') +--- assert(c == 'c') +--- ``` +--- +--- @param patt vim.lpeg.Pattern +--- @return vim.lpeg.Capture +function vim.lpeg.C(patt) end + +--- Creates an argument capture. This pattern matches the empty string and produces the value given as the +--- nth extra argument given in the call to `lpeg.match`. +--- @param n integer +--- @return vim.lpeg.Capture +function vim.lpeg.Carg(n) end + +--- Creates a back capture. This pattern matches the empty string and produces the values produced by the most recent +--- group capture named `name` (where `name` can be any Lua value). Most recent means the last complete outermost +--- group capture with the given name. A Complete capture means that the entire pattern corresponding to the capture +--- has matched. An Outermost capture means that the capture is not inside another complete capture. +--- In the same way that LPeg does not specify when it evaluates captures, it does not specify whether it reuses +--- values previously produced by the group or re-evaluates them. +--- +--- @param name any +--- @return vim.lpeg.Capture +function vim.lpeg.Cb(name) end + +--- Creates a constant capture. This pattern matches the empty string and produces all given values as its captured values. +--- +--- @param ... any +--- @return vim.lpeg.Capture +function vim.lpeg.Cc(...) end + +--- Creates a fold capture. If `patt` produces a list of captures C1 C2 ... Cn, this capture will produce the value +--- `func(...func(func(C1, C2), C3)...,Cn)`, that is, it will fold (or accumulate, or reduce) the captures from +--- `patt` using function `func`. This capture assumes that `patt` should produce at least one capture with at +--- least one value (of any type), which becomes the initial value of an accumulator. (If you need a specific +--- initial value, you may prefix a constant captureto `patt`.) For each subsequent capture, LPeg calls `func` +--- with this accumulator as the first argument and all values produced by the capture as extra arguments; +--- the first result from this call becomes the new value for the accumulator. The final value of the accumulator +--- becomes the captured value. +--- +--- Example: +--- ```lua +--- local number = lpeg.R("09") ^ 1 / tonumber +--- local list = number * ("," * number) ^ 0 +--- local function add(acc, newvalue) return acc + newvalue end +--- local sum = lpeg.Cf(list, add) +--- assert(sum:match("10,30,43") == 83) +--- ``` +--- +--- @param patt vim.lpeg.Pattern +--- @param func fun(acc, newvalue) +--- @return vim.lpeg.Capture +function vim.lpeg.Cf(patt, func) end + +--- Creates a group capture. It groups all values returned by `patt` into a single capture. +--- The group may be anonymous (if no name is given) or named with the given name (which +--- can be any non-nil Lua value). +--- +--- @param patt vim.lpeg.Pattern +--- @param name? string +--- @return vim.lpeg.Capture +function vim.lpeg.Cg(patt, name) end + +--- Creates a position capture. It matches the empty string and captures the position in the +--- subject where the match occurs. The captured value is a number. +--- +--- Example: +--- ```lua +--- local I = lpeg.Cp() +--- local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end +--- local match_start, match_end = anywhere("world"):match("hello world!") +--- assert(match_start == 7) +--- assert(match_end == 12) +--- ``` +--- +--- @return vim.lpeg.Capture +function vim.lpeg.Cp() end + +--- Creates a substitution capture. This function creates a substitution capture, which +--- captures the substring of the subject that matches `patt`, with substitutions. +--- For any capture inside `patt` with a value, the substring that matched the capture +--- is replaced by the capture value (which should be a string). The final captured +--- value is the string resulting from all replacements. +--- +--- Example: +--- ```lua +--- local function gsub (s, patt, repl) +--- patt = lpeg.P(patt) +--- patt = lpeg.Cs((patt / repl + 1)^0) +--- return lpeg.match(patt, s) +--- end +--- assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!') +--- ``` +--- +--- @param patt vim.lpeg.Pattern +--- @return vim.lpeg.Capture +function vim.lpeg.Cs(patt) end + +--- Creates a table capture. This capture returns a table with all values from all anonymous captures +--- made by `patt` inside this table in successive integer keys, starting at 1. +--- Moreover, for each named capture group created by `patt`, the first value of the group is put into +--- the table with the group name as its key. The captured value is only the table. +--- +--- @param patt vim.lpeg.Pattern|'' +--- @return vim.lpeg.Capture +function vim.lpeg.Ct(patt) end + +--- Creates a match-time capture. Unlike all other captures, this one is evaluated immediately when a match occurs +--- (even if it is part of a larger pattern that fails later). It forces the immediate evaluation of all its nested captures +--- and then calls `function`. The given function gets as arguments the entire subject, the current position +--- (after the match of `patt`), plus any capture values produced by `patt`. The first value returned by `function` +--- defines how the match happens. If the call returns a number, the match succeeds and the returned number +--- becomes the new current position. (Assuming a subject sand current position i, the returned number must be +--- in the range [i, len(s) + 1].) If the call returns true, the match succeeds without consuming any input +--- (so, to return true is equivalent to return i). If the call returns false, nil, or no value, the match fails. +--- Any extra values returned by the function become the values produced by the capture. +--- +--- @param patt vim.lpeg.Pattern +--- @param fn function +--- @return vim.lpeg.Capture +function vim.lpeg.Cmt(patt, fn) end diff --git a/runtime/lua/vim/_meta/misc.lua b/runtime/lua/vim/_meta/misc.lua new file mode 100644 index 0000000000..0d70e16314 --- /dev/null +++ b/runtime/lua/vim/_meta/misc.lua @@ -0,0 +1,15 @@ +---@meta + +-- luacheck: no unused args + +--- Invokes |vim-function| or |user-function| {func} with arguments {...}. +--- See also |vim.fn|. +--- Equivalent to: +--- +--- ```lua +--- vim.fn[func]({...}) +--- ``` +--- +--- @param func fun() +--- @param ... any +function vim.call(func, ...) end diff --git a/runtime/lua/vim/_meta/mpack.lua b/runtime/lua/vim/_meta/mpack.lua new file mode 100644 index 0000000000..54e097ad97 --- /dev/null +++ b/runtime/lua/vim/_meta/mpack.lua @@ -0,0 +1,15 @@ +--- @meta + +-- luacheck: no unused args + +--- @defgroup vim.mpack +--- +--- This module provides encoding and decoding of Lua objects to and +--- from msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. + +--- Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object. +--- @param str string +function vim.mpack.decode(str) end + +--- Encodes (or "packs") Lua object {obj} as msgpack in a Lua string. +function vim.mpack.encode(obj) end diff --git a/runtime/lua/vim/_meta/options.lua b/runtime/lua/vim/_meta/options.lua new file mode 100644 index 0000000000..d2bdab4d28 --- /dev/null +++ b/runtime/lua/vim/_meta/options.lua @@ -0,0 +1,7958 @@ +--- @meta _ +-- THIS FILE IS GENERATED +-- DO NOT EDIT +error('Cannot require a meta file') + +---@class vim.bo +---@field [integer] vim.bo +vim.bo = vim.bo + +---@class vim.wo +---@field [integer] vim.wo +vim.wo = vim.wo + +--- Allow CTRL-_ in Insert and Command-line mode. This is default off, to +--- avoid that users that accidentally type CTRL-_ instead of SHIFT-_ get +--- into reverse Insert mode, and don't know how to get out. See +--- 'revins'. +--- +--- @type boolean +vim.o.allowrevins = false +vim.o.ari = vim.o.allowrevins +vim.go.allowrevins = vim.o.allowrevins +vim.go.ari = vim.go.allowrevins + +--- Tells Vim what to do with characters with East Asian Width Class +--- Ambiguous (such as Euro, Registered Sign, Copyright Sign, Greek +--- letters, Cyrillic letters). +--- +--- There are currently two possible values: +--- "single": Use the same width as characters in US-ASCII. This is +--- expected by most users. +--- "double": Use twice the width of ASCII characters. +--- *E834* *E835* +--- The value "double" cannot be used if 'listchars' or 'fillchars' +--- contains a character that would be double width. These errors may +--- also be given when calling setcellwidths(). +--- +--- The values are overruled for characters specified with +--- `setcellwidths()`. +--- +--- There are a number of CJK fonts for which the width of glyphs for +--- those characters are solely based on how many octets they take in +--- legacy/traditional CJK encodings. In those encodings, Euro, +--- Registered sign, Greek/Cyrillic letters are represented by two octets, +--- therefore those fonts have "wide" glyphs for them. This is also +--- true of some line drawing characters used to make tables in text +--- file. Therefore, when a CJK font is used for GUI Vim or +--- Vim is running inside a terminal (emulators) that uses a CJK font +--- (or Vim is run inside an xterm invoked with "-cjkwidth" option.), +--- this option should be set to "double" to match the width perceived +--- by Vim with the width of glyphs in the font. Perhaps it also has +--- to be set to "double" under CJK MS-Windows when the system locale is +--- set to one of CJK locales. See Unicode Standard Annex #11 +--- (https://www.unicode.org/reports/tr11). +--- +--- @type string +vim.o.ambiwidth = "single" +vim.o.ambw = vim.o.ambiwidth +vim.go.ambiwidth = vim.o.ambiwidth +vim.go.ambw = vim.go.ambiwidth + +--- This option can be set to start editing Arabic text. +--- Setting this option will: +--- - Set the 'rightleft' option, unless 'termbidi' is set. +--- - Set the 'arabicshape' option, unless 'termbidi' is set. +--- - Set the 'keymap' option to "arabic"; in Insert mode CTRL-^ toggles +--- between typing English and Arabic key mapping. +--- - Set the 'delcombine' option +--- +--- Resetting this option will: +--- - Reset the 'rightleft' option. +--- - Disable the use of 'keymap' (without changing its value). +--- Note that 'arabicshape' and 'delcombine' are not reset (it is a global +--- option). +--- Also see `arabic.txt`. +--- +--- @type boolean +vim.o.arabic = false +vim.o.arab = vim.o.arabic +vim.wo.arabic = vim.o.arabic +vim.wo.arab = vim.wo.arabic + +--- When on and 'termbidi' is off, the required visual character +--- corrections that need to take place for displaying the Arabic language +--- take effect. Shaping, in essence, gets enabled; the term is a broad +--- one which encompasses: +--- a) the changing/morphing of characters based on their location +--- within a word (initial, medial, final and stand-alone). +--- b) the enabling of the ability to compose characters +--- c) the enabling of the required combining of some characters +--- When disabled the display shows each character's true stand-alone +--- form. +--- Arabic is a complex language which requires other settings, for +--- further details see `arabic.txt`. +--- +--- @type boolean +vim.o.arabicshape = true +vim.o.arshape = vim.o.arabicshape +vim.go.arabicshape = vim.o.arabicshape +vim.go.arshape = vim.go.arabicshape + +--- When on, Vim will change the current working directory whenever you +--- open a file, switch buffers, delete a buffer or open/close a window. +--- It will change to the directory containing the file which was opened +--- or selected. When a buffer has no name it also has no directory, thus +--- the current directory won't change when navigating to it. +--- Note: When this option is on some plugins may not work. +--- +--- @type boolean +vim.o.autochdir = false +vim.o.acd = vim.o.autochdir +vim.go.autochdir = vim.o.autochdir +vim.go.acd = vim.go.autochdir + +--- Copy indent from current line when starting a new line (typing <CR> +--- in Insert mode or when using the "o" or "O" command). If you do not +--- type anything on the new line except <BS> or CTRL-D and then type +--- <Esc>, CTRL-O or <CR>, the indent is deleted again. Moving the cursor +--- to another line has the same effect, unless the 'I' flag is included +--- in 'cpoptions'. +--- When autoindent is on, formatting (with the "gq" command or when you +--- reach 'textwidth' in Insert mode) uses the indentation of the first +--- line. +--- When 'smartindent' or 'cindent' is on the indent is changed in +--- a different way. +--- +--- @type boolean +vim.o.autoindent = true +vim.o.ai = vim.o.autoindent +vim.bo.autoindent = vim.o.autoindent +vim.bo.ai = vim.bo.autoindent + +--- When a file has been detected to have been changed outside of Vim and +--- it has not been changed inside of Vim, automatically read it again. +--- When the file has been deleted this is not done, so you have the text +--- from before it was deleted. When it appears again then it is read. +--- `timestamp` +--- If this option has a local value, use this command to switch back to +--- using the global value: +--- ``` +--- :set autoread< +--- ``` +--- +--- +--- @type boolean +vim.o.autoread = true +vim.o.ar = vim.o.autoread +vim.bo.autoread = vim.o.autoread +vim.bo.ar = vim.bo.autoread +vim.go.autoread = vim.o.autoread +vim.go.ar = vim.go.autoread + +--- Write the contents of the file, if it has been modified, on each +--- `:next`, `:rewind`, `:last`, `:first`, `:previous`, `:stop`, +--- `:suspend`, `:tag`, `:!`, `:make`, CTRL-] and CTRL-^ command; and when +--- a `:buffer`, CTRL-O, CTRL-I, '{A-Z0-9}, or `{A-Z0-9} command takes one +--- to another file. +--- A buffer is not written if it becomes hidden, e.g. when 'bufhidden' is +--- set to "hide" and `:next` is used. +--- Note that for some commands the 'autowrite' option is not used, see +--- 'autowriteall' for that. +--- Some buffers will not be written, specifically when 'buftype' is +--- "nowrite", "nofile", "terminal" or "prompt". +--- USE WITH CARE: If you make temporary changes to a buffer that you +--- don't want to be saved this option may cause it to be saved anyway. +--- Renaming the buffer with ":file {name}" may help avoid this. +--- +--- @type boolean +vim.o.autowrite = false +vim.o.aw = vim.o.autowrite +vim.go.autowrite = vim.o.autowrite +vim.go.aw = vim.go.autowrite + +--- Like 'autowrite', but also used for commands ":edit", ":enew", ":quit", +--- ":qall", ":exit", ":xit", ":recover" and closing the Vim window. +--- Setting this option also implies that Vim behaves like 'autowrite' has +--- been set. +--- +--- @type boolean +vim.o.autowriteall = false +vim.o.awa = vim.o.autowriteall +vim.go.autowriteall = vim.o.autowriteall +vim.go.awa = vim.go.autowriteall + +--- When set to "dark" or "light", adjusts the default color groups for +--- that background type. The `TUI` or other UI sets this on startup +--- (triggering `OptionSet`) if it can detect the background color. +--- +--- This option does NOT change the background color, it tells Nvim what +--- the "inherited" (terminal/GUI) background looks like. +--- See `:hi-normal` if you want to set the background color explicitly. +--- *g:colors_name* +--- When a color scheme is loaded (the "g:colors_name" variable is set) +--- setting 'background' will cause the color scheme to be reloaded. If +--- the color scheme adjusts to the value of 'background' this will work. +--- However, if the color scheme sets 'background' itself the effect may +--- be undone. First delete the "g:colors_name" variable when needed. +--- +--- Normally this option would be set in the vimrc file. Possibly +--- depending on the terminal name. Example: +--- ``` +--- :if $TERM ==# "xterm" +--- : set background=dark +--- :endif +--- ``` +--- When this option is set, the default settings for the highlight groups +--- will change. To use other settings, place ":highlight" commands AFTER +--- the setting of the 'background' option. +--- This option is also used in the "$VIMRUNTIME/syntax/syntax.vim" file +--- to select the colors for syntax highlighting. After changing this +--- option, you must load syntax.vim again to see the result. This can be +--- done with ":syntax on". +--- +--- @type string +vim.o.background = "dark" +vim.o.bg = vim.o.background +vim.go.background = vim.o.background +vim.go.bg = vim.go.background + +--- Influences the working of <BS>, <Del>, CTRL-W and CTRL-U in Insert +--- mode. This is a list of items, separated by commas. Each item allows +--- a way to backspace over something: +--- value effect ~ +--- indent allow backspacing over autoindent +--- eol allow backspacing over line breaks (join lines) +--- start allow backspacing over the start of insert; CTRL-W and CTRL-U +--- stop once at the start of insert. +--- nostop like start, except CTRL-W and CTRL-U do not stop at the start of +--- insert. +--- +--- When the value is empty, Vi compatible backspacing is used, none of +--- the ways mentioned for the items above are possible. +--- +--- @type string +vim.o.backspace = "indent,eol,start" +vim.o.bs = vim.o.backspace +vim.go.backspace = vim.o.backspace +vim.go.bs = vim.go.backspace + +--- Make a backup before overwriting a file. Leave it around after the +--- file has been successfully written. If you do not want to keep the +--- backup file, but you do want a backup while the file is being +--- written, reset this option and set the 'writebackup' option (this is +--- the default). If you do not want a backup file at all reset both +--- options (use this if your file system is almost full). See the +--- `backup-table` for more explanations. +--- When the 'backupskip' pattern matches, a backup is not made anyway. +--- When 'patchmode' is set, the backup may be renamed to become the +--- oldest version of a file. +--- +--- @type boolean +vim.o.backup = false +vim.o.bk = vim.o.backup +vim.go.backup = vim.o.backup +vim.go.bk = vim.go.backup + +--- When writing a file and a backup is made, this option tells how it's +--- done. This is a comma-separated list of words. +--- +--- The main values are: +--- "yes" make a copy of the file and overwrite the original one +--- "no" rename the file and write a new one +--- "auto" one of the previous, what works best +--- +--- Extra values that can be combined with the ones above are: +--- "breaksymlink" always break symlinks when writing +--- "breakhardlink" always break hardlinks when writing +--- +--- Making a copy and overwriting the original file: +--- - Takes extra time to copy the file. +--- + When the file has special attributes, is a (hard/symbolic) link or +--- has a resource fork, all this is preserved. +--- - When the file is a link the backup will have the name of the link, +--- not of the real file. +--- +--- Renaming the file and writing a new one: +--- + It's fast. +--- - Sometimes not all attributes of the file can be copied to the new +--- file. +--- - When the file is a link the new file will not be a link. +--- +--- The "auto" value is the middle way: When Vim sees that renaming the +--- file is possible without side effects (the attributes can be passed on +--- and the file is not a link) that is used. When problems are expected, +--- a copy will be made. +--- +--- The "breaksymlink" and "breakhardlink" values can be used in +--- combination with any of "yes", "no" and "auto". When included, they +--- force Vim to always break either symbolic or hard links by doing +--- exactly what the "no" option does, renaming the original file to +--- become the backup and writing a new file in its place. This can be +--- useful for example in source trees where all the files are symbolic or +--- hard links and any changes should stay in the local source tree, not +--- be propagated back to the original source. +--- *crontab* +--- One situation where "no" and "auto" will cause problems: A program +--- that opens a file, invokes Vim to edit that file, and then tests if +--- the open file was changed (through the file descriptor) will check the +--- backup file instead of the newly created file. "crontab -e" is an +--- example. +--- +--- When a copy is made, the original file is truncated and then filled +--- with the new text. This means that protection bits, owner and +--- symbolic links of the original file are unmodified. The backup file, +--- however, is a new file, owned by the user who edited the file. The +--- group of the backup is set to the group of the original file. If this +--- fails, the protection bits for the group are made the same as for +--- others. +--- +--- When the file is renamed, this is the other way around: The backup has +--- the same attributes of the original file, and the newly written file +--- is owned by the current user. When the file was a (hard/symbolic) +--- link, the new file will not! That's why the "auto" value doesn't +--- rename when the file is a link. The owner and group of the newly +--- written file will be set to the same ones as the original file, but +--- the system may refuse to do this. In that case the "auto" value will +--- again not rename the file. +--- +--- @type string +vim.o.backupcopy = "auto" +vim.o.bkc = vim.o.backupcopy +vim.bo.backupcopy = vim.o.backupcopy +vim.bo.bkc = vim.bo.backupcopy +vim.go.backupcopy = vim.o.backupcopy +vim.go.bkc = vim.go.backupcopy + +--- List of directories for the backup file, separated with commas. +--- - The backup file will be created in the first directory in the list +--- where this is possible. If none of the directories exist Nvim will +--- attempt to create the last directory in the list. +--- - Empty means that no backup file will be created ('patchmode' is +--- impossible!). Writing may fail because of this. +--- - A directory "." means to put the backup file in the same directory +--- as the edited file. +--- - A directory starting with "./" (or ".\" for MS-Windows) means to put +--- the backup file relative to where the edited file is. The leading +--- "." is replaced with the path name of the edited file. +--- ("." inside a directory name has no special meaning). +--- - Spaces after the comma are ignored, other spaces are considered part +--- of the directory name. To have a space at the start of a directory +--- name, precede it with a backslash. +--- - To include a comma in a directory name precede it with a backslash. +--- - A directory name may end in an '/'. +--- - For Unix and Win32, if a directory ends in two path separators "//", +--- the swap file name will be built from the complete path to the file +--- with all path separators changed to percent '%' signs. This will +--- ensure file name uniqueness in the backup directory. +--- On Win32, it is also possible to end with "\\". However, When a +--- separating comma is following, you must use "//", since "\\" will +--- include the comma in the file name. Therefore it is recommended to +--- use '//', instead of '\\'. +--- - Environment variables are expanded `:set_env`. +--- - Careful with '\' characters, type one before a space, type two to +--- get one in the option (see `option-backslash`), for example: +--- ``` +--- :set bdir=c:\\tmp,\ dir\\,with\\,commas,\\\ dir\ with\ spaces +--- ``` +--- +--- See also 'backup' and 'writebackup' options. +--- If you want to hide your backup files on Unix, consider this value: +--- ``` +--- :set backupdir=./.backup,~/.backup,.,/tmp +--- ``` +--- You must create a ".backup" directory in each directory and in your +--- home directory for this to work properly. +--- The use of `:set+=` and `:set-=` is preferred when adding or removing +--- directories from the list. This avoids problems when a future version +--- uses another default. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.backupdir = ".,$XDG_STATE_HOME/nvim/backup//" +vim.o.bdir = vim.o.backupdir +vim.go.backupdir = vim.o.backupdir +vim.go.bdir = vim.go.backupdir + +--- String which is appended to a file name to make the name of the +--- backup file. The default is quite unusual, because this avoids +--- accidentally overwriting existing files with a backup file. You might +--- prefer using ".bak", but make sure that you don't have files with +--- ".bak" that you want to keep. +--- Only normal file name characters can be used; `/\*?[|<>` are illegal. +--- +--- If you like to keep a lot of backups, you could use a BufWritePre +--- autocommand to change 'backupext' just before writing the file to +--- include a timestamp. +--- ``` +--- :au BufWritePre * let &bex = '-' .. strftime("%Y%b%d%X") .. '~' +--- ``` +--- Use 'backupdir' to put the backup in a different directory. +--- +--- @type string +vim.o.backupext = "~" +vim.o.bex = vim.o.backupext +vim.go.backupext = vim.o.backupext +vim.go.bex = vim.go.backupext + +--- A list of file patterns. When one of the patterns matches with the +--- name of the file which is written, no backup file is created. Both +--- the specified file name and the full path name of the file are used. +--- The pattern is used like with `:autocmd`, see `autocmd-pattern`. +--- Watch out for special characters, see `option-backslash`. +--- When $TMPDIR, $TMP or $TEMP is not defined, it is not used for the +--- default value. "/tmp/*" is only used for Unix. +--- +--- WARNING: Not having a backup file means that when Vim fails to write +--- your buffer correctly and then, for whatever reason, Vim exits, you +--- lose both the original file and what you were writing. Only disable +--- backups if you don't care about losing the file. +--- +--- Note that environment variables are not expanded. If you want to use +--- $HOME you must expand it explicitly, e.g.: +--- +--- ```vim +--- :let &backupskip = escape(expand('$HOME'), '\') .. '/tmp/*' +--- ``` +--- Note that the default also makes sure that "crontab -e" works (when a +--- backup would be made by renaming the original file crontab won't see +--- the newly created file). Also see 'backupcopy' and `crontab`. +--- +--- @type string +vim.o.backupskip = "/tmp/*" +vim.o.bsk = vim.o.backupskip +vim.go.backupskip = vim.o.backupskip +vim.go.bsk = vim.go.backupskip + +--- Specifies for which events the bell will not be rung. It is a comma- +--- separated list of items. For each item that is present, the bell +--- will be silenced. This is most useful to specify specific events in +--- insert mode to be silenced. +--- +--- item meaning when present ~ +--- all All events. +--- backspace When hitting <BS> or <Del> and deleting results in an +--- error. +--- cursor Fail to move around using the cursor keys or +--- <PageUp>/<PageDown> in `Insert-mode`. +--- complete Error occurred when using `i_CTRL-X_CTRL-K` or +--- `i_CTRL-X_CTRL-T`. +--- copy Cannot copy char from insert mode using `i_CTRL-Y` or +--- `i_CTRL-E`. +--- ctrlg Unknown Char after <C-G> in Insert mode. +--- error Other Error occurred (e.g. try to join last line) +--- (mostly used in `Normal-mode` or `Cmdline-mode`). +--- esc hitting <Esc> in `Normal-mode`. +--- hangul Ignored. +--- lang Calling the beep module for Lua/Mzscheme/TCL. +--- mess No output available for `g<`. +--- showmatch Error occurred for 'showmatch' function. +--- operator Empty region error `cpo-E`. +--- register Unknown register after <C-R> in `Insert-mode`. +--- shell Bell from shell output `:!`. +--- spell Error happened on spell suggest. +--- wildmode More matches in `cmdline-completion` available +--- (depends on the 'wildmode' setting). +--- +--- This is most useful to fine tune when in Insert mode the bell should +--- be rung. For Normal mode and Ex commands, the bell is often rung to +--- indicate that an error occurred. It can be silenced by adding the +--- "error" keyword. +--- +--- @type string +vim.o.belloff = "all" +vim.o.bo = vim.o.belloff +vim.go.belloff = vim.o.belloff +vim.go.bo = vim.go.belloff + +--- This option should be set before editing a binary file. You can also +--- use the `-b` Vim argument. When this option is switched on a few +--- options will be changed (also when it already was on): +--- 'textwidth' will be set to 0 +--- 'wrapmargin' will be set to 0 +--- 'modeline' will be off +--- 'expandtab' will be off +--- Also, 'fileformat' and 'fileformats' options will not be used, the +--- file is read and written like 'fileformat' was "unix" (a single <NL> +--- separates lines). +--- The 'fileencoding' and 'fileencodings' options will not be used, the +--- file is read without conversion. +--- NOTE: When you start editing a(nother) file while the 'bin' option is +--- on, settings from autocommands may change the settings again (e.g., +--- 'textwidth'), causing trouble when editing. You might want to set +--- 'bin' again when the file has been loaded. +--- The previous values of these options are remembered and restored when +--- 'bin' is switched from on to off. Each buffer has its own set of +--- saved option values. +--- To edit a file with 'binary' set you can use the `++bin` argument. +--- This avoids you have to do ":set bin", which would have effect for all +--- files you edit. +--- When writing a file the <EOL> for the last line is only written if +--- there was one in the original file (normally Vim appends an <EOL> to +--- the last line if there is none; this would make the file longer). See +--- the 'endofline' option. +--- +--- @type boolean +vim.o.binary = false +vim.o.bin = vim.o.binary +vim.bo.binary = vim.o.binary +vim.bo.bin = vim.bo.binary + +--- When writing a file and the following conditions are met, a BOM (Byte +--- Order Mark) is prepended to the file: +--- - this option is on +--- - the 'binary' option is off +--- - 'fileencoding' is "utf-8", "ucs-2", "ucs-4" or one of the little/big +--- endian variants. +--- Some applications use the BOM to recognize the encoding of the file. +--- Often used for UCS-2 files on MS-Windows. For other applications it +--- causes trouble, for example: "cat file1 file2" makes the BOM of file2 +--- appear halfway through the resulting file. Gcc doesn't accept a BOM. +--- When Vim reads a file and 'fileencodings' starts with "ucs-bom", a +--- check for the presence of the BOM is done and 'bomb' set accordingly. +--- Unless 'binary' is set, it is removed from the first line, so that you +--- don't see it when editing. When you don't change the options, the BOM +--- will be restored when writing the file. +--- +--- @type boolean +vim.o.bomb = false +vim.bo.bomb = vim.o.bomb + +--- This option lets you choose which characters might cause a line +--- break if 'linebreak' is on. Only works for ASCII characters. +--- +--- @type string +vim.o.breakat = " \t!@*-+;:,./?" +vim.o.brk = vim.o.breakat +vim.go.breakat = vim.o.breakat +vim.go.brk = vim.go.breakat + +--- Every wrapped line will continue visually indented (same amount of +--- space as the beginning of that line), thus preserving horizontal blocks +--- of text. +--- +--- @type boolean +vim.o.breakindent = false +vim.o.bri = vim.o.breakindent +vim.wo.breakindent = vim.o.breakindent +vim.wo.bri = vim.wo.breakindent + +--- Settings for 'breakindent'. It can consist of the following optional +--- items and must be separated by a comma: +--- min:{n} Minimum text width that will be kept after +--- applying 'breakindent', even if the resulting +--- text should normally be narrower. This prevents +--- text indented almost to the right window border +--- occupying lot of vertical space when broken. +--- (default: 20) +--- shift:{n} After applying 'breakindent', the wrapped line's +--- beginning will be shifted by the given number of +--- characters. It permits dynamic French paragraph +--- indentation (negative) or emphasizing the line +--- continuation (positive). +--- (default: 0) +--- sbr Display the 'showbreak' value before applying the +--- additional indent. +--- (default: off) +--- list:{n} Adds an additional indent for lines that match a +--- numbered or bulleted list (using the +--- 'formatlistpat' setting). +--- list:-1 Uses the length of a match with 'formatlistpat' +--- for indentation. +--- (default: 0) +--- column:{n} Indent at column {n}. Will overrule the other +--- sub-options. Note: an additional indent may be +--- added for the 'showbreak' setting. +--- (default: off) +--- +--- @type string +vim.o.breakindentopt = "" +vim.o.briopt = vim.o.breakindentopt +vim.wo.breakindentopt = vim.o.breakindentopt +vim.wo.briopt = vim.wo.breakindentopt + +--- Which directory to use for the file browser: +--- last Use same directory as with last file browser, where a +--- file was opened or saved. +--- buffer Use the directory of the related buffer. +--- current Use the current directory. +--- {path} Use the specified directory +--- +--- @type string +vim.o.browsedir = "" +vim.o.bsdir = vim.o.browsedir +vim.go.browsedir = vim.o.browsedir +vim.go.bsdir = vim.go.browsedir + +--- This option specifies what happens when a buffer is no longer +--- displayed in a window: +--- <empty> follow the global 'hidden' option +--- hide hide the buffer (don't unload it), even if 'hidden' is +--- not set +--- unload unload the buffer, even if 'hidden' is set; the +--- `:hide` command will also unload the buffer +--- delete delete the buffer from the buffer list, even if +--- 'hidden' is set; the `:hide` command will also delete +--- the buffer, making it behave like `:bdelete` +--- wipe wipe the buffer from the buffer list, even if +--- 'hidden' is set; the `:hide` command will also wipe +--- out the buffer, making it behave like `:bwipeout` +--- +--- CAREFUL: when "unload", "delete" or "wipe" is used changes in a buffer +--- are lost without a warning. Also, these values may break autocommands +--- that switch between buffers temporarily. +--- This option is used together with 'buftype' and 'swapfile' to specify +--- special kinds of buffers. See `special-buffers`. +--- +--- @type string +vim.o.bufhidden = "" +vim.o.bh = vim.o.bufhidden +vim.bo.bufhidden = vim.o.bufhidden +vim.bo.bh = vim.bo.bufhidden + +--- When this option is set, the buffer shows up in the buffer list. If +--- it is reset it is not used for ":bnext", "ls", the Buffers menu, etc. +--- This option is reset by Vim for buffers that are only used to remember +--- a file name or marks. Vim sets it when starting to edit a buffer. +--- But not when moving to a buffer with ":buffer". +--- +--- @type boolean +vim.o.buflisted = true +vim.o.bl = vim.o.buflisted +vim.bo.buflisted = vim.o.buflisted +vim.bo.bl = vim.bo.buflisted + +--- The value of this option specifies the type of a buffer: +--- <empty> normal buffer +--- acwrite buffer will always be written with `BufWriteCmd`s +--- help help buffer (do not set this manually) +--- nofile buffer is not related to a file, will not be written +--- nowrite buffer will not be written +--- quickfix list of errors `:cwindow` or locations `:lwindow` +--- terminal `terminal-emulator` buffer +--- prompt buffer where only the last line can be edited, meant +--- to be used by a plugin, see `prompt-buffer` +--- +--- This option is used together with 'bufhidden' and 'swapfile' to +--- specify special kinds of buffers. See `special-buffers`. +--- Also see `win_gettype()`, which returns the type of the window. +--- +--- Be careful with changing this option, it can have many side effects! +--- One such effect is that Vim will not check the timestamp of the file, +--- if the file is changed by another program this will not be noticed. +--- +--- A "quickfix" buffer is only used for the error list and the location +--- list. This value is set by the `:cwindow` and `:lwindow` commands and +--- you are not supposed to change it. +--- +--- "nofile" and "nowrite" buffers are similar: +--- both: The buffer is not to be written to disk, ":w" doesn't +--- work (":w filename" does work though). +--- both: The buffer is never considered to be `'modified'`. +--- There is no warning when the changes will be lost, for +--- example when you quit Vim. +--- both: A swap file is only created when using too much memory +--- (when 'swapfile' has been reset there is never a swap +--- file). +--- nofile only: The buffer name is fixed, it is not handled like a +--- file name. It is not modified in response to a `:cd` +--- command. +--- both: When using ":e bufname" and already editing "bufname" +--- the buffer is made empty and autocommands are +--- triggered as usual for `:edit`. +--- *E676* +--- "acwrite" implies that the buffer name is not related to a file, like +--- "nofile", but it will be written. Thus, in contrast to "nofile" and +--- "nowrite", ":w" does work and a modified buffer can't be abandoned +--- without saving. For writing there must be matching `BufWriteCmd|, +--- |FileWriteCmd` or `FileAppendCmd` autocommands. +--- +--- @type string +vim.o.buftype = "" +vim.o.bt = vim.o.buftype +vim.bo.buftype = vim.o.buftype +vim.bo.bt = vim.bo.buftype + +--- Specifies details about changing the case of letters. It may contain +--- these words, separated by a comma: +--- internal Use internal case mapping functions, the current +--- locale does not change the case mapping. When +--- "internal" is omitted, the towupper() and towlower() +--- system library functions are used when available. +--- keepascii For the ASCII characters (0x00 to 0x7f) use the US +--- case mapping, the current locale is not effective. +--- This probably only matters for Turkish. +--- +--- @type string +vim.o.casemap = "internal,keepascii" +vim.o.cmp = vim.o.casemap +vim.go.casemap = vim.o.casemap +vim.go.cmp = vim.go.casemap + +--- When on, `:cd`, `:tcd` and `:lcd` without an argument changes the +--- current working directory to the `$HOME` directory like in Unix. +--- When off, those commands just print the current directory name. +--- On Unix this option has no effect. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type boolean +vim.o.cdhome = false +vim.o.cdh = vim.o.cdhome +vim.go.cdhome = vim.o.cdhome +vim.go.cdh = vim.go.cdhome + +--- This is a list of directories which will be searched when using the +--- `:cd`, `:tcd` and `:lcd` commands, provided that the directory being +--- searched for has a relative path, not an absolute part starting with +--- "/", "./" or "../", the 'cdpath' option is not used then. +--- The 'cdpath' option's value has the same form and semantics as +--- `'path'`. Also see `file-searching`. +--- The default value is taken from $CDPATH, with a "," prepended to look +--- in the current directory first. +--- If the default value taken from $CDPATH is not what you want, include +--- a modified version of the following command in your vimrc file to +--- override it: +--- ``` +--- :let &cdpath = ',' .. substitute(substitute($CDPATH, '[, ]', '\\\0', 'g'), ':', ',', 'g') +--- ``` +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- (parts of 'cdpath' can be passed to the shell to expand file names). +--- +--- @type string +vim.o.cdpath = ",," +vim.o.cd = vim.o.cdpath +vim.go.cdpath = vim.o.cdpath +vim.go.cd = vim.go.cdpath + +--- The key used in Command-line Mode to open the command-line window. +--- Only non-printable keys are allowed. +--- The key can be specified as a single character, but it is difficult to +--- type. The preferred way is to use the <> notation. Examples: +--- ``` +--- :exe "set cedit=\\<C-Y>" +--- :exe "set cedit=\\<Esc>" +--- ``` +--- `Nvi` also has this option, but it only uses the first character. +--- See `cmdwin`. +--- +--- @type string +vim.o.cedit = "\6" +vim.go.cedit = vim.o.cedit + +--- `channel` connected to the buffer, or 0 if no channel is connected. +--- In a `:terminal` buffer this is the terminal channel. +--- Read-only. +--- +--- @type integer +vim.o.channel = 0 +vim.bo.channel = vim.o.channel + +--- An expression that is used for character encoding conversion. It is +--- evaluated when a file that is to be read or has been written has a +--- different encoding from what is desired. +--- 'charconvert' is not used when the internal iconv() function is +--- supported and is able to do the conversion. Using iconv() is +--- preferred, because it is much faster. +--- 'charconvert' is not used when reading stdin `--`, because there is no +--- file to convert from. You will have to save the text in a file first. +--- The expression must return zero, false or an empty string for success, +--- non-zero or true for failure. +--- See `encoding-names` for possible encoding names. +--- Additionally, names given in 'fileencodings' and 'fileencoding' are +--- used. +--- Conversion between "latin1", "unicode", "ucs-2", "ucs-4" and "utf-8" +--- is done internally by Vim, 'charconvert' is not used for this. +--- Also used for Unicode conversion. +--- Example: +--- ``` +--- set charconvert=CharConvert() +--- fun CharConvert() +--- system("recode " +--- \ .. v:charconvert_from .. ".." .. v:charconvert_to +--- \ .. " <" .. v:fname_in .. " >" .. v:fname_out) +--- return v:shell_error +--- endfun +--- ``` +--- The related Vim variables are: +--- v:charconvert_from name of the current encoding +--- v:charconvert_to name of the desired encoding +--- v:fname_in name of the input file +--- v:fname_out name of the output file +--- Note that v:fname_in and v:fname_out will never be the same. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.charconvert = "" +vim.o.ccv = vim.o.charconvert +vim.go.charconvert = vim.o.charconvert +vim.go.ccv = vim.go.charconvert + +--- Enables automatic C program indenting. See 'cinkeys' to set the keys +--- that trigger reindenting in insert mode and 'cinoptions' to set your +--- preferred indent style. +--- If 'indentexpr' is not empty, it overrules 'cindent'. +--- If 'lisp' is not on and both 'indentexpr' and 'equalprg' are empty, +--- the "=" operator indents using this algorithm rather than calling an +--- external program. +--- See `C-indenting`. +--- When you don't like the way 'cindent' works, try the 'smartindent' +--- option or 'indentexpr'. +--- +--- @type boolean +vim.o.cindent = false +vim.o.cin = vim.o.cindent +vim.bo.cindent = vim.o.cindent +vim.bo.cin = vim.bo.cindent + +--- A list of keys that, when typed in Insert mode, cause reindenting of +--- the current line. Only used if 'cindent' is on and 'indentexpr' is +--- empty. +--- For the format of this option see `cinkeys-format`. +--- See `C-indenting`. +--- +--- @type string +vim.o.cinkeys = "0{,0},0),0],:,0#,!^F,o,O,e" +vim.o.cink = vim.o.cinkeys +vim.bo.cinkeys = vim.o.cinkeys +vim.bo.cink = vim.bo.cinkeys + +--- The 'cinoptions' affect the way 'cindent' reindents lines in a C +--- program. See `cinoptions-values` for the values of this option, and +--- `C-indenting` for info on C indenting in general. +--- +--- @type string +vim.o.cinoptions = "" +vim.o.cino = vim.o.cinoptions +vim.bo.cinoptions = vim.o.cinoptions +vim.bo.cino = vim.bo.cinoptions + +--- Keywords that are interpreted as a C++ scope declaration by `cino-g`. +--- Useful e.g. for working with the Qt framework that defines additional +--- scope declarations "signals", "public slots" and "private slots": +--- ``` +--- set cinscopedecls+=signals,public\ slots,private\ slots +--- ``` +--- +--- +--- @type string +vim.o.cinscopedecls = "public,protected,private" +vim.o.cinsd = vim.o.cinscopedecls +vim.bo.cinscopedecls = vim.o.cinscopedecls +vim.bo.cinsd = vim.bo.cinscopedecls + +--- These keywords start an extra indent in the next line when +--- 'smartindent' or 'cindent' is set. For 'cindent' this is only done at +--- an appropriate place (inside {}). +--- Note that 'ignorecase' isn't used for 'cinwords'. If case doesn't +--- matter, include the keyword both the uppercase and lowercase: +--- "if,If,IF". +--- +--- @type string +vim.o.cinwords = "if,else,while,do,for,switch" +vim.o.cinw = vim.o.cinwords +vim.bo.cinwords = vim.o.cinwords +vim.bo.cinw = vim.bo.cinwords + +--- This option is a list of comma-separated names. +--- These names are recognized: +--- +--- *clipboard-unnamed* +--- unnamed When included, Vim will use the clipboard register "*" +--- for all yank, delete, change and put operations which +--- would normally go to the unnamed register. When a +--- register is explicitly specified, it will always be +--- used regardless of whether "unnamed" is in 'clipboard' +--- or not. The clipboard register can always be +--- explicitly accessed using the "* notation. Also see +--- `clipboard`. +--- +--- *clipboard-unnamedplus* +--- unnamedplus A variant of the "unnamed" flag which uses the +--- clipboard register "+" (`quoteplus`) instead of +--- register "*" for all yank, delete, change and put +--- operations which would normally go to the unnamed +--- register. When "unnamed" is also included to the +--- option, yank and delete operations (but not put) +--- will additionally copy the text into register +--- "*". See `clipboard`. +--- +--- @type string +vim.o.clipboard = "" +vim.o.cb = vim.o.clipboard +vim.go.clipboard = vim.o.clipboard +vim.go.cb = vim.go.clipboard + +--- Number of screen lines to use for the command-line. Helps avoiding +--- `hit-enter` prompts. +--- The value of this option is stored with the tab page, so that each tab +--- page can have a different value. +--- +--- When 'cmdheight' is zero, there is no command-line unless it is being +--- used. The command-line will cover the last line of the screen when +--- shown. +--- +--- WARNING: `cmdheight=0` is considered experimental. Expect some +--- unwanted behaviour. Some 'shortmess' flags and similar +--- mechanism might fail to take effect, causing unwanted hit-enter +--- prompts. Some informative messages, both from Nvim itself and +--- plugins, will not be displayed. +--- +--- @type integer +vim.o.cmdheight = 1 +vim.o.ch = vim.o.cmdheight +vim.go.cmdheight = vim.o.cmdheight +vim.go.ch = vim.go.cmdheight + +--- Number of screen lines to use for the command-line window. `cmdwin` +--- +--- @type integer +vim.o.cmdwinheight = 7 +vim.o.cwh = vim.o.cmdwinheight +vim.go.cmdwinheight = vim.o.cmdwinheight +vim.go.cwh = vim.go.cmdwinheight + +--- 'colorcolumn' is a comma-separated list of screen columns that are +--- highlighted with ColorColumn `hl-ColorColumn`. Useful to align +--- text. Will make screen redrawing slower. +--- The screen column can be an absolute number, or a number preceded with +--- '+' or '-', which is added to or subtracted from 'textwidth'. +--- ``` +--- :set cc=+1 " highlight column after 'textwidth' +--- :set cc=+1,+2,+3 " highlight three columns after 'textwidth' +--- :hi ColorColumn ctermbg=lightgrey guibg=lightgrey +--- ``` +--- +--- When 'textwidth' is zero then the items with '-' and '+' are not used. +--- A maximum of 256 columns are highlighted. +--- +--- @type string +vim.o.colorcolumn = "" +vim.o.cc = vim.o.colorcolumn +vim.wo.colorcolumn = vim.o.colorcolumn +vim.wo.cc = vim.wo.colorcolumn + +--- Number of columns of the screen. Normally this is set by the terminal +--- initialization and does not have to be set by hand. +--- When Vim is running in the GUI or in a resizable window, setting this +--- option will cause the window size to be changed. When you only want +--- to use the size for the GUI, put the command in your `ginit.vim` file. +--- When you set this option and Vim is unable to change the physical +--- number of columns of the display, the display may be messed up. For +--- the GUI it is always possible and Vim limits the number of columns to +--- what fits on the screen. You can use this command to get the widest +--- window possible: +--- ``` +--- :set columns=9999 +--- ``` +--- Minimum value is 12, maximum value is 10000. +--- +--- @type integer +vim.o.columns = 80 +vim.o.co = vim.o.columns +vim.go.columns = vim.o.columns +vim.go.co = vim.go.columns + +--- A comma-separated list of strings that can start a comment line. See +--- `format-comments`. See `option-backslash` about using backslashes to +--- insert a space. +--- +--- @type string +vim.o.comments = "s1:/*,mb:*,ex:*/,://,b:#,:%,:XCOMM,n:>,fb:-,fb:•" +vim.o.com = vim.o.comments +vim.bo.comments = vim.o.comments +vim.bo.com = vim.bo.comments + +--- A template for a comment. The "%s" in the value is replaced with the +--- comment text. For example, C uses "/*%s*/". Currently only used to +--- add markers for folding, see `fold-marker`. +--- +--- @type string +vim.o.commentstring = "" +vim.o.cms = vim.o.commentstring +vim.bo.commentstring = vim.o.commentstring +vim.bo.cms = vim.bo.commentstring + +--- This option specifies how keyword completion `ins-completion` works +--- when CTRL-P or CTRL-N are used. It is also used for whole-line +--- completion `i_CTRL-X_CTRL-L`. It indicates the type of completion +--- and the places to scan. It is a comma-separated list of flags: +--- . scan the current buffer ('wrapscan' is ignored) +--- w scan buffers from other windows +--- b scan other loaded buffers that are in the buffer list +--- u scan the unloaded buffers that are in the buffer list +--- U scan the buffers that are not in the buffer list +--- k scan the files given with the 'dictionary' option +--- kspell use the currently active spell checking `spell` +--- k{dict} scan the file {dict}. Several "k" flags can be given, +--- patterns are valid too. For example: +--- ``` +--- :set cpt=k/usr/dict/*,k~/spanish +--- ``` +--- s scan the files given with the 'thesaurus' option +--- s{tsr} scan the file {tsr}. Several "s" flags can be given, patterns +--- are valid too. +--- i scan current and included files +--- d scan current and included files for defined name or macro +--- `i_CTRL-X_CTRL-D` +--- ] tag completion +--- t same as "]" +--- f scan the buffer names (as opposed to buffer contents) +--- +--- Unloaded buffers are not loaded, thus their autocmds `:autocmd` are +--- not executed, this may lead to unexpected completions from some files +--- (gzipped files for example). Unloaded buffers are not scanned for +--- whole-line completion. +--- +--- As you can see, CTRL-N and CTRL-P can be used to do any 'iskeyword'- +--- based expansion (e.g., dictionary `i_CTRL-X_CTRL-K`, included patterns +--- `i_CTRL-X_CTRL-I`, tags `i_CTRL-X_CTRL-]` and normal expansions). +--- +--- @type string +vim.o.complete = ".,w,b,u,t" +vim.o.cpt = vim.o.complete +vim.bo.complete = vim.o.complete +vim.bo.cpt = vim.bo.complete + +--- This option specifies a function to be used for Insert mode completion +--- with CTRL-X CTRL-U. `i_CTRL-X_CTRL-U` +--- See `complete-functions` for an explanation of how the function is +--- invoked and what it should return. The value can be the name of a +--- function, a `lambda` or a `Funcref`. See `option-value-function` for +--- more information. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.completefunc = "" +vim.o.cfu = vim.o.completefunc +vim.bo.completefunc = vim.o.completefunc +vim.bo.cfu = vim.bo.completefunc + +--- A comma-separated list of options for Insert mode completion +--- `ins-completion`. The supported values are: +--- +--- menu Use a popup menu to show the possible completions. The +--- menu is only shown when there is more than one match and +--- sufficient colors are available. `ins-completion-menu` +--- +--- menuone Use the popup menu also when there is only one match. +--- Useful when there is additional information about the +--- match, e.g., what file it comes from. +--- +--- longest Only insert the longest common text of the matches. If +--- the menu is displayed you can use CTRL-L to add more +--- characters. Whether case is ignored depends on the kind +--- of completion. For buffer text the 'ignorecase' option is +--- used. +--- +--- preview Show extra information about the currently selected +--- completion in the preview window. Only works in +--- combination with "menu" or "menuone". +--- +--- noinsert Do not insert any text for a match until the user selects +--- a match from the menu. Only works in combination with +--- "menu" or "menuone". No effect if "longest" is present. +--- +--- noselect Do not select a match in the menu, force the user to +--- select one from the menu. Only works in combination with +--- "menu" or "menuone". +--- +--- @type string +vim.o.completeopt = "menu,preview" +vim.o.cot = vim.o.completeopt +vim.go.completeopt = vim.o.completeopt +vim.go.cot = vim.go.completeopt + +--- only for MS-Windows +--- When this option is set it overrules 'shellslash' for completion: +--- - When this option is set to "slash", a forward slash is used for path +--- completion in insert mode. This is useful when editing HTML tag, or +--- Makefile with 'noshellslash' on MS-Windows. +--- - When this option is set to "backslash", backslash is used. This is +--- useful when editing a batch file with 'shellslash' set on MS-Windows. +--- - When this option is empty, same character is used as for +--- 'shellslash'. +--- For Insert mode completion the buffer-local value is used. For +--- command line completion the global value is used. +--- +--- @type string +vim.o.completeslash = "" +vim.o.csl = vim.o.completeslash +vim.bo.completeslash = vim.o.completeslash +vim.bo.csl = vim.bo.completeslash + +--- Sets the modes in which text in the cursor line can also be concealed. +--- When the current mode is listed then concealing happens just like in +--- other lines. +--- n Normal mode +--- v Visual mode +--- i Insert mode +--- c Command line editing, for 'incsearch' +--- +--- 'v' applies to all lines in the Visual area, not only the cursor. +--- A useful value is "nc". This is used in help files. So long as you +--- are moving around text is concealed, but when starting to insert text +--- or selecting a Visual area the concealed text is displayed, so that +--- you can see what you are doing. +--- Keep in mind that the cursor position is not always where it's +--- displayed. E.g., when moving vertically it may change column. +--- +--- @type string +vim.o.concealcursor = "" +vim.o.cocu = vim.o.concealcursor +vim.wo.concealcursor = vim.o.concealcursor +vim.wo.cocu = vim.wo.concealcursor + +--- Determine how text with the "conceal" syntax attribute `:syn-conceal` +--- is shown: +--- +--- Value Effect ~ +--- 0 Text is shown normally +--- 1 Each block of concealed text is replaced with one +--- character. If the syntax item does not have a custom +--- replacement character defined (see `:syn-cchar`) the +--- character defined in 'listchars' is used. +--- It is highlighted with the "Conceal" highlight group. +--- 2 Concealed text is completely hidden unless it has a +--- custom replacement character defined (see +--- `:syn-cchar`). +--- 3 Concealed text is completely hidden. +--- +--- Note: in the cursor line concealed text is not hidden, so that you can +--- edit and copy the text. This can be changed with the 'concealcursor' +--- option. +--- +--- @type integer +vim.o.conceallevel = 0 +vim.o.cole = vim.o.conceallevel +vim.wo.conceallevel = vim.o.conceallevel +vim.wo.cole = vim.wo.conceallevel + +--- When 'confirm' is on, certain operations that would normally +--- fail because of unsaved changes to a buffer, e.g. ":q" and ":e", +--- instead raise a dialog asking if you wish to save the current +--- file(s). You can still use a ! to unconditionally `abandon` a buffer. +--- If 'confirm' is off you can still activate confirmation for one +--- command only (this is most useful in mappings) with the `:confirm` +--- command. +--- Also see the `confirm()` function and the 'v' flag in 'guioptions'. +--- +--- @type boolean +vim.o.confirm = false +vim.o.cf = vim.o.confirm +vim.go.confirm = vim.o.confirm +vim.go.cf = vim.go.confirm + +--- Copy the structure of the existing lines indent when autoindenting a +--- new line. Normally the new indent is reconstructed by a series of +--- tabs followed by spaces as required (unless `'expandtab'` is enabled, +--- in which case only spaces are used). Enabling this option makes the +--- new line copy whatever characters were used for indenting on the +--- existing line. 'expandtab' has no effect on these characters, a Tab +--- remains a Tab. If the new indent is greater than on the existing +--- line, the remaining space is filled in the normal manner. +--- See 'preserveindent'. +--- +--- @type boolean +vim.o.copyindent = false +vim.o.ci = vim.o.copyindent +vim.bo.copyindent = vim.o.copyindent +vim.bo.ci = vim.bo.copyindent + +--- A sequence of single character flags. When a character is present +--- this indicates Vi-compatible behavior. This is used for things where +--- not being Vi-compatible is mostly or sometimes preferred. +--- 'cpoptions' stands for "compatible-options". +--- Commas can be added for readability. +--- To avoid problems with flags that are added in the future, use the +--- "+=" and "-=" feature of ":set" `add-option-flags`. +--- +--- contains behavior ~ +--- *cpo-a* +--- a When included, a ":read" command with a file name +--- argument will set the alternate file name for the +--- current window. +--- *cpo-A* +--- A When included, a ":write" command with a file name +--- argument will set the alternate file name for the +--- current window. +--- *cpo-b* +--- b "\|" in a ":map" command is recognized as the end of +--- the map command. The '\' is included in the mapping, +--- the text after the '|' is interpreted as the next +--- command. Use a CTRL-V instead of a backslash to +--- include the '|' in the mapping. Applies to all +--- mapping, abbreviation, menu and autocmd commands. +--- See also `map_bar`. +--- *cpo-B* +--- B A backslash has no special meaning in mappings, +--- abbreviations, user commands and the "to" part of the +--- menu commands. Remove this flag to be able to use a +--- backslash like a CTRL-V. For example, the command +--- ":map X \\<Esc>" results in X being mapped to: +--- 'B' included: "\^[" (^[ is a real <Esc>) +--- 'B' excluded: "<Esc>" (5 characters) +--- *cpo-c* +--- c Searching continues at the end of any match at the +--- cursor position, but not further than the start of the +--- next line. When not present searching continues +--- one character from the cursor position. With 'c' +--- "abababababab" only gets three matches when repeating +--- "/abab", without 'c' there are five matches. +--- *cpo-C* +--- C Do not concatenate sourced lines that start with a +--- backslash. See `line-continuation`. +--- *cpo-d* +--- d Using "./" in the 'tags' option doesn't mean to use +--- the tags file relative to the current file, but the +--- tags file in the current directory. +--- *cpo-D* +--- D Can't use CTRL-K to enter a digraph after Normal mode +--- commands with a character argument, like `r`, `f` and +--- `t`. +--- *cpo-e* +--- e When executing a register with ":@r", always add a +--- <CR> to the last line, also when the register is not +--- linewise. If this flag is not present, the register +--- is not linewise and the last line does not end in a +--- <CR>, then the last line is put on the command-line +--- and can be edited before hitting <CR>. +--- *cpo-E* +--- E It is an error when using "y", "d", "c", "g~", "gu" or +--- "gU" on an Empty region. The operators only work when +--- at least one character is to be operated on. Example: +--- This makes "y0" fail in the first column. +--- *cpo-f* +--- f When included, a ":read" command with a file name +--- argument will set the file name for the current buffer, +--- if the current buffer doesn't have a file name yet. +--- *cpo-F* +--- F When included, a ":write" command with a file name +--- argument will set the file name for the current +--- buffer, if the current buffer doesn't have a file name +--- yet. Also see `cpo-P`. +--- *cpo-i* +--- i When included, interrupting the reading of a file will +--- leave it modified. +--- *cpo-I* +--- I When moving the cursor up or down just after inserting +--- indent for 'autoindent', do not delete the indent. +--- *cpo-J* +--- J A `sentence` has to be followed by two spaces after +--- the '.', '!' or '?'. A <Tab> is not recognized as +--- white space. +--- *cpo-K* +--- K Don't wait for a key code to complete when it is +--- halfway through a mapping. This breaks mapping +--- <F1><F1> when only part of the second <F1> has been +--- read. It enables cancelling the mapping by typing +--- <F1><Esc>. +--- *cpo-l* +--- l Backslash in a [] range in a search pattern is taken +--- literally, only "\]", "\^", "\-" and "\\" are special. +--- See `/[]` +--- 'l' included: "/[ \t]" finds <Space>, '\' and 't' +--- 'l' excluded: "/[ \t]" finds <Space> and <Tab> +--- *cpo-L* +--- L When the 'list' option is set, 'wrapmargin', +--- 'textwidth', 'softtabstop' and Virtual Replace mode +--- (see `gR`) count a <Tab> as two characters, instead of +--- the normal behavior of a <Tab>. +--- *cpo-m* +--- m When included, a showmatch will always wait half a +--- second. When not included, a showmatch will wait half +--- a second or until a character is typed. `'showmatch'` +--- *cpo-M* +--- M When excluded, "%" matching will take backslashes into +--- account. Thus in "( \( )" and "\( ( \)" the outer +--- parenthesis match. When included "%" ignores +--- backslashes, which is Vi compatible. +--- *cpo-n* +--- n When included, the column used for 'number' and +--- 'relativenumber' will also be used for text of wrapped +--- lines. +--- *cpo-o* +--- o Line offset to search command is not remembered for +--- next search. +--- *cpo-O* +--- O Don't complain if a file is being overwritten, even +--- when it didn't exist when editing it. This is a +--- protection against a file unexpectedly created by +--- someone else. Vi didn't complain about this. +--- *cpo-p* +--- p Vi compatible Lisp indenting. When not present, a +--- slightly better algorithm is used. +--- *cpo-P* +--- P When included, a ":write" command that appends to a +--- file will set the file name for the current buffer, if +--- the current buffer doesn't have a file name yet and +--- the 'F' flag is also included `cpo-F`. +--- *cpo-q* +--- q When joining multiple lines leave the cursor at the +--- position where it would be when joining two lines. +--- *cpo-r* +--- r Redo ("." command) uses "/" to repeat a search +--- command, instead of the actually used search string. +--- *cpo-R* +--- R Remove marks from filtered lines. Without this flag +--- marks are kept like `:keepmarks` was used. +--- *cpo-s* +--- s Set buffer options when entering the buffer for the +--- first time. This is like it is in Vim version 3.0. +--- And it is the default. If not present the options are +--- set when the buffer is created. +--- *cpo-S* +--- S Set buffer options always when entering a buffer +--- (except 'readonly', 'fileformat', 'filetype' and +--- 'syntax'). This is the (most) Vi compatible setting. +--- The options are set to the values in the current +--- buffer. When you change an option and go to another +--- buffer, the value is copied. Effectively makes the +--- buffer options global to all buffers. +--- +--- 's' 'S' copy buffer options +--- no no when buffer created +--- yes no when buffer first entered (default) +--- X yes each time when buffer entered (vi comp.) +--- *cpo-t* +--- t Search pattern for the tag command is remembered for +--- "n" command. Otherwise Vim only puts the pattern in +--- the history for search pattern, but doesn't change the +--- last used search pattern. +--- *cpo-u* +--- u Undo is Vi compatible. See `undo-two-ways`. +--- *cpo-v* +--- v Backspaced characters remain visible on the screen in +--- Insert mode. Without this flag the characters are +--- erased from the screen right away. With this flag the +--- screen newly typed text overwrites backspaced +--- characters. +--- *cpo-W* +--- W Don't overwrite a readonly file. When omitted, ":w!" +--- overwrites a readonly file, if possible. +--- *cpo-x* +--- x <Esc> on the command-line executes the command-line. +--- The default in Vim is to abandon the command-line, +--- because <Esc> normally aborts a command. `c_<Esc>` +--- *cpo-X* +--- X When using a count with "R" the replaced text is +--- deleted only once. Also when repeating "R" with "." +--- and a count. +--- *cpo-y* +--- y A yank command can be redone with ".". Think twice if +--- you really want to use this, it may break some +--- plugins, since most people expect "." to only repeat a +--- change. +--- *cpo-Z* +--- Z When using "w!" while the 'readonly' option is set, +--- don't reset 'readonly'. +--- *cpo-!* +--- ! When redoing a filter command, use the last used +--- external command, whatever it was. Otherwise the last +--- used -filter- command is used. +--- *cpo-$* +--- $ When making a change to one line, don't redisplay the +--- line, but put a '$' at the end of the changed text. +--- The changed text will be overwritten when you type the +--- new text. The line is redisplayed if you type any +--- command that moves the cursor from the insertion +--- point. +--- *cpo-%* +--- % Vi-compatible matching is done for the "%" command. +--- Does not recognize "#if", "#endif", etc. +--- Does not recognize "/*" and "*/". +--- Parens inside single and double quotes are also +--- counted, causing a string that contains a paren to +--- disturb the matching. For example, in a line like +--- "if (strcmp("foo(", s))" the first paren does not +--- match the last one. When this flag is not included, +--- parens inside single and double quotes are treated +--- specially. When matching a paren outside of quotes, +--- everything inside quotes is ignored. When matching a +--- paren inside quotes, it will find the matching one (if +--- there is one). This works very well for C programs. +--- This flag is also used for other features, such as +--- C-indenting. +--- *cpo-+* +--- + When included, a ":write file" command will reset the +--- 'modified' flag of the buffer, even though the buffer +--- itself may still be different from its file. +--- *cpo->* +--- > When appending to a register, put a line break before +--- the appended text. +--- *cpo-;* +--- ; When using `,` or `;` to repeat the last `t` search +--- and the cursor is right in front of the searched +--- character, the cursor won't move. When not included, +--- the cursor would skip over it and jump to the +--- following occurrence. +--- *cpo-_* +--- _ When using `cw` on a word, do not include the +--- whitespace following the word in the motion. +--- +--- @type string +vim.o.cpoptions = "aABceFs_" +vim.o.cpo = vim.o.cpoptions +vim.go.cpoptions = vim.o.cpoptions +vim.go.cpo = vim.go.cpoptions + +--- When this option is set, as the cursor in the current +--- window moves other cursorbound windows (windows that also have +--- this option set) move their cursors to the corresponding line and +--- column. This option is useful for viewing the +--- differences between two versions of a file (see 'diff'); in diff mode, +--- inserted and deleted lines (though not characters within a line) are +--- taken into account. +--- +--- @type boolean +vim.o.cursorbind = false +vim.o.crb = vim.o.cursorbind +vim.wo.cursorbind = vim.o.cursorbind +vim.wo.crb = vim.wo.cursorbind + +--- Highlight the screen column of the cursor with CursorColumn +--- `hl-CursorColumn`. Useful to align text. Will make screen redrawing +--- slower. +--- If you only want the highlighting in the current window you can use +--- these autocommands: +--- ``` +--- au WinLeave * set nocursorline nocursorcolumn +--- au WinEnter * set cursorline cursorcolumn +--- ``` +--- +--- +--- @type boolean +vim.o.cursorcolumn = false +vim.o.cuc = vim.o.cursorcolumn +vim.wo.cursorcolumn = vim.o.cursorcolumn +vim.wo.cuc = vim.wo.cursorcolumn + +--- Highlight the text line of the cursor with CursorLine `hl-CursorLine`. +--- Useful to easily spot the cursor. Will make screen redrawing slower. +--- When Visual mode is active the highlighting isn't used to make it +--- easier to see the selected text. +--- +--- @type boolean +vim.o.cursorline = false +vim.o.cul = vim.o.cursorline +vim.wo.cursorline = vim.o.cursorline +vim.wo.cul = vim.wo.cursorline + +--- Comma-separated list of settings for how 'cursorline' is displayed. +--- Valid values: +--- "line" Highlight the text line of the cursor with +--- CursorLine `hl-CursorLine`. +--- "screenline" Highlight only the screen line of the cursor with +--- CursorLine `hl-CursorLine`. +--- "number" Highlight the line number of the cursor with +--- CursorLineNr `hl-CursorLineNr`. +--- +--- Special value: +--- "both" Alias for the values "line,number". +--- +--- "line" and "screenline" cannot be used together. +--- +--- @type string +vim.o.cursorlineopt = "both" +vim.o.culopt = vim.o.cursorlineopt +vim.wo.cursorlineopt = vim.o.cursorlineopt +vim.wo.culopt = vim.wo.cursorlineopt + +--- These values can be used: +--- msg Error messages that would otherwise be omitted will be given +--- anyway. +--- throw Error messages that would otherwise be omitted will be given +--- anyway and also throw an exception and set `v:errmsg`. +--- beep A message will be given when otherwise only a beep would be +--- produced. +--- The values can be combined, separated by a comma. +--- "msg" and "throw" are useful for debugging 'foldexpr', 'formatexpr' or +--- 'indentexpr'. +--- +--- @type string +vim.o.debug = "" +vim.go.debug = vim.o.debug + +--- Pattern to be used to find a macro definition. It is a search +--- pattern, just like for the "/" command. This option is used for the +--- commands like "[i" and "[d" `include-search`. The 'isident' option is +--- used to recognize the defined name after the match: +--- ``` +--- {match with 'define'}{non-ID chars}{defined name}{non-ID char} +--- ``` +--- See `option-backslash` about inserting backslashes to include a space +--- or backslash. +--- For C++ this value would be useful, to include const type declarations: +--- ``` +--- ^\(#\s*define\|[a-z]*\s*const\s*[a-z]*\) +--- ``` +--- You can also use "\ze" just before the name and continue the pattern +--- to check what is following. E.g. for Javascript, if a function is +--- defined with `func_name = function(args)`: +--- ``` +--- ^\s*\ze\i\+\s*=\s*function( +--- ``` +--- If the function is defined with `func_name : function() {...`: +--- ``` +--- ^\s*\ze\i\+\s*[:]\s*(*function\s*( +--- ``` +--- When using the ":set" command, you need to double the backslashes! +--- To avoid that use `:let` with a single quote string: +--- ``` +--- let &l:define = '^\s*\ze\k\+\s*=\s*function(' +--- ``` +--- +--- +--- @type string +vim.o.define = "" +vim.o.def = vim.o.define +vim.bo.define = vim.o.define +vim.bo.def = vim.bo.define +vim.go.define = vim.o.define +vim.go.def = vim.go.define + +--- If editing Unicode and this option is set, backspace and Normal mode +--- "x" delete each combining character on its own. When it is off (the +--- default) the character along with its combining characters are +--- deleted. +--- Note: When 'delcombine' is set "xx" may work differently from "2x"! +--- +--- This is useful for Arabic, Hebrew and many other languages where one +--- may have combining characters overtop of base characters, and want +--- to remove only the combining ones. +--- +--- @type boolean +vim.o.delcombine = false +vim.o.deco = vim.o.delcombine +vim.go.delcombine = vim.o.delcombine +vim.go.deco = vim.go.delcombine + +--- List of file names, separated by commas, that are used to lookup words +--- for keyword completion commands `i_CTRL-X_CTRL-K`. Each file should +--- contain a list of words. This can be one word per line, or several +--- words per line, separated by non-keyword characters (white space is +--- preferred). Maximum line length is 510 bytes. +--- +--- When this option is empty or an entry "spell" is present, and spell +--- checking is enabled, words in the word lists for the currently active +--- 'spelllang' are used. See `spell`. +--- +--- To include a comma in a file name precede it with a backslash. Spaces +--- after a comma are ignored, otherwise spaces are included in the file +--- name. See `option-backslash` about using backslashes. +--- This has nothing to do with the `Dictionary` variable type. +--- Where to find a list of words? +--- - BSD/macOS include the "/usr/share/dict/words" file. +--- - Try "apt install spell" to get the "/usr/share/dict/words" file on +--- apt-managed systems (Debian/Ubuntu). +--- The use of `:set+=` and `:set-=` is preferred when adding or removing +--- directories from the list. This avoids problems when a future version +--- uses another default. +--- Backticks cannot be used in this option for security reasons. +--- +--- @type string +vim.o.dictionary = "" +vim.o.dict = vim.o.dictionary +vim.bo.dictionary = vim.o.dictionary +vim.bo.dict = vim.bo.dictionary +vim.go.dictionary = vim.o.dictionary +vim.go.dict = vim.go.dictionary + +--- Join the current window in the group of windows that shows differences +--- between files. See `diff-mode`. +--- +--- @type boolean +vim.o.diff = false +vim.wo.diff = vim.o.diff + +--- Expression which is evaluated to obtain a diff file (either ed-style +--- or unified-style) from two versions of a file. See `diff-diffexpr`. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.diffexpr = "" +vim.o.dex = vim.o.diffexpr +vim.go.diffexpr = vim.o.diffexpr +vim.go.dex = vim.go.diffexpr + +--- Option settings for diff mode. It can consist of the following items. +--- All are optional. Items must be separated by a comma. +--- +--- filler Show filler lines, to keep the text +--- synchronized with a window that has inserted +--- lines at the same position. Mostly useful +--- when windows are side-by-side and 'scrollbind' +--- is set. +--- +--- context:{n} Use a context of {n} lines between a change +--- and a fold that contains unchanged lines. +--- When omitted a context of six lines is used. +--- When using zero the context is actually one, +--- since folds require a line in between, also +--- for a deleted line. Set it to a very large +--- value (999999) to disable folding completely. +--- See `fold-diff`. +--- +--- iblank Ignore changes where lines are all blank. Adds +--- the "-B" flag to the "diff" command if +--- 'diffexpr' is empty. Check the documentation +--- of the "diff" command for what this does +--- exactly. +--- NOTE: the diff windows will get out of sync, +--- because no differences between blank lines are +--- taken into account. +--- +--- icase Ignore changes in case of text. "a" and "A" +--- are considered the same. Adds the "-i" flag +--- to the "diff" command if 'diffexpr' is empty. +--- +--- iwhite Ignore changes in amount of white space. Adds +--- the "-b" flag to the "diff" command if +--- 'diffexpr' is empty. Check the documentation +--- of the "diff" command for what this does +--- exactly. It should ignore adding trailing +--- white space, but not leading white space. +--- +--- iwhiteall Ignore all white space changes. Adds +--- the "-w" flag to the "diff" command if +--- 'diffexpr' is empty. Check the documentation +--- of the "diff" command for what this does +--- exactly. +--- +--- iwhiteeol Ignore white space changes at end of line. +--- Adds the "-Z" flag to the "diff" command if +--- 'diffexpr' is empty. Check the documentation +--- of the "diff" command for what this does +--- exactly. +--- +--- horizontal Start diff mode with horizontal splits (unless +--- explicitly specified otherwise). +--- +--- vertical Start diff mode with vertical splits (unless +--- explicitly specified otherwise). +--- +--- closeoff When a window is closed where 'diff' is set +--- and there is only one window remaining in the +--- same tab page with 'diff' set, execute +--- `:diffoff` in that window. This undoes a +--- `:diffsplit` command. +--- +--- hiddenoff Do not use diff mode for a buffer when it +--- becomes hidden. +--- +--- foldcolumn:{n} Set the 'foldcolumn' option to {n} when +--- starting diff mode. Without this 2 is used. +--- +--- followwrap Follow the 'wrap' option and leave as it is. +--- +--- internal Use the internal diff library. This is +--- ignored when 'diffexpr' is set. *E960* +--- When running out of memory when writing a +--- buffer this item will be ignored for diffs +--- involving that buffer. Set the 'verbose' +--- option to see when this happens. +--- +--- indent-heuristic +--- Use the indent heuristic for the internal +--- diff library. +--- +--- linematch:{n} Enable a second stage diff on each generated +--- hunk in order to align lines. When the total +--- number of lines in a hunk exceeds {n}, the +--- second stage diff will not be performed as +--- very large hunks can cause noticeable lag. A +--- recommended setting is "linematch:60", as this +--- will enable alignment for a 2 buffer diff with +--- hunks of up to 30 lines each, or a 3 buffer +--- diff with hunks of up to 20 lines each. +--- +--- algorithm:{text} Use the specified diff algorithm with the +--- internal diff engine. Currently supported +--- algorithms are: +--- myers the default algorithm +--- minimal spend extra time to generate the +--- smallest possible diff +--- patience patience diff algorithm +--- histogram histogram diff algorithm +--- +--- Examples: +--- ``` +--- :set diffopt=internal,filler,context:4 +--- :set diffopt= +--- :set diffopt=internal,filler,foldcolumn:3 +--- :set diffopt-=internal " do NOT use the internal diff parser +--- ``` +--- +--- +--- @type string +vim.o.diffopt = "internal,filler,closeoff" +vim.o.dip = vim.o.diffopt +vim.go.diffopt = vim.o.diffopt +vim.go.dip = vim.go.diffopt + +--- Enable the entering of digraphs in Insert mode with {char1} <BS> +--- {char2}. See `digraphs`. +--- +--- @type boolean +vim.o.digraph = false +vim.o.dg = vim.o.digraph +vim.go.digraph = vim.o.digraph +vim.go.dg = vim.go.digraph + +--- List of directory names for the swap file, separated with commas. +--- +--- Possible items: +--- - The swap file will be created in the first directory where this is +--- possible. If it is not possible in any directory, but last +--- directory listed in the option does not exist, it is created. +--- - Empty means that no swap file will be used (recovery is +--- impossible!) and no `E303` error will be given. +--- - A directory "." means to put the swap file in the same directory as +--- the edited file. On Unix, a dot is prepended to the file name, so +--- it doesn't show in a directory listing. On MS-Windows the "hidden" +--- attribute is set and a dot prepended if possible. +--- - A directory starting with "./" (or ".\" for MS-Windows) means to put +--- the swap file relative to where the edited file is. The leading "." +--- is replaced with the path name of the edited file. +--- - For Unix and Win32, if a directory ends in two path separators "//", +--- the swap file name will be built from the complete path to the file +--- with all path separators replaced by percent '%' signs (including +--- the colon following the drive letter on Win32). This will ensure +--- file name uniqueness in the preserve directory. +--- On Win32, it is also possible to end with "\\". However, When a +--- separating comma is following, you must use "//", since "\\" will +--- include the comma in the file name. Therefore it is recommended to +--- use '//', instead of '\\'. +--- - Spaces after the comma are ignored, other spaces are considered part +--- of the directory name. To have a space at the start of a directory +--- name, precede it with a backslash. +--- - To include a comma in a directory name precede it with a backslash. +--- - A directory name may end in an ':' or '/'. +--- - Environment variables are expanded `:set_env`. +--- - Careful with '\' characters, type one before a space, type two to +--- get one in the option (see `option-backslash`), for example: +--- ``` +--- :set dir=c:\\tmp,\ dir\\,with\\,commas,\\\ dir\ with\ spaces +--- ``` +--- +--- Editing the same file twice will result in a warning. Using "/tmp" on +--- is discouraged: if the system crashes you lose the swap file. And +--- others on the computer may be able to see the files. +--- Use `:set+=` and `:set-=` when adding or removing directories from the +--- list, this avoids problems if the Nvim default is changed. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.directory = "$XDG_STATE_HOME/nvim/swap//" +vim.o.dir = vim.o.directory +vim.go.directory = vim.o.directory +vim.go.dir = vim.go.directory + +--- Change the way text is displayed. This is a comma-separated list of +--- flags: +--- lastline When included, as much as possible of the last line +--- in a window will be displayed. "@@@" is put in the +--- last columns of the last screen line to indicate the +--- rest of the line is not displayed. +--- truncate Like "lastline", but "@@@" is displayed in the first +--- column of the last screen line. Overrules "lastline". +--- uhex Show unprintable characters hexadecimal as <xx> +--- instead of using ^C and ~C. +--- msgsep Obsolete flag. Allowed but takes no effect. `msgsep` +--- +--- When neither "lastline" nor "truncate" is included, a last line that +--- doesn't fit is replaced with "@" lines. +--- +--- The "@" character can be changed by setting the "lastline" item in +--- 'fillchars'. The character is highlighted with `hl-NonText`. +--- +--- @type string +vim.o.display = "lastline" +vim.o.dy = vim.o.display +vim.go.display = vim.o.display +vim.go.dy = vim.go.display + +--- Tells when the 'equalalways' option applies: +--- ver vertically, width of windows is not affected +--- hor horizontally, height of windows is not affected +--- both width and height of windows is affected +--- +--- @type string +vim.o.eadirection = "both" +vim.o.ead = vim.o.eadirection +vim.go.eadirection = vim.o.eadirection +vim.go.ead = vim.go.eadirection + +--- When on all Unicode emoji characters are considered to be full width. +--- This excludes "text emoji" characters, which are normally displayed as +--- single width. Unfortunately there is no good specification for this +--- and it has been determined on trial-and-error basis. Use the +--- `setcellwidths()` function to change the behavior. +--- +--- @type boolean +vim.o.emoji = true +vim.o.emo = vim.o.emoji +vim.go.emoji = vim.o.emoji +vim.go.emo = vim.go.emoji + +--- String-encoding used internally and for `RPC` communication. +--- Always UTF-8. +--- +--- See 'fileencoding' to control file-content encoding. +--- +--- @type string +vim.o.encoding = "utf-8" +vim.o.enc = vim.o.encoding +vim.go.encoding = vim.o.encoding +vim.go.enc = vim.go.encoding + +--- Indicates that a CTRL-Z character was found at the end of the file +--- when reading it. Normally only happens when 'fileformat' is "dos". +--- When writing a file and this option is off and the 'binary' option +--- is on, or 'fixeol' option is off, no CTRL-Z will be written at the +--- end of the file. +--- See `eol-and-eof` for example settings. +--- +--- @type boolean +vim.o.endoffile = false +vim.o.eof = vim.o.endoffile +vim.bo.endoffile = vim.o.endoffile +vim.bo.eof = vim.bo.endoffile + +--- When writing a file and this option is off and the 'binary' option +--- is on, or 'fixeol' option is off, no <EOL> will be written for the +--- last line in the file. This option is automatically set or reset when +--- starting to edit a new file, depending on whether file has an <EOL> +--- for the last line in the file. Normally you don't have to set or +--- reset this option. +--- When 'binary' is off and 'fixeol' is on the value is not used when +--- writing the file. When 'binary' is on or 'fixeol' is off it is used +--- to remember the presence of a <EOL> for the last line in the file, so +--- that when you write the file the situation from the original file can +--- be kept. But you can change it if you want to. +--- See `eol-and-eof` for example settings. +--- +--- @type boolean +vim.o.endofline = true +vim.o.eol = vim.o.endofline +vim.bo.endofline = vim.o.endofline +vim.bo.eol = vim.bo.endofline + +--- When on, all the windows are automatically made the same size after +--- splitting or closing a window. This also happens the moment the +--- option is switched on. When off, splitting a window will reduce the +--- size of the current window and leave the other windows the same. When +--- closing a window the extra lines are given to the window next to it +--- (depending on 'splitbelow' and 'splitright'). +--- When mixing vertically and horizontally split windows, a minimal size +--- is computed and some windows may be larger if there is room. The +--- 'eadirection' option tells in which direction the size is affected. +--- Changing the height and width of a window can be avoided by setting +--- 'winfixheight' and 'winfixwidth', respectively. +--- If a window size is specified when creating a new window sizes are +--- currently not equalized (it's complicated, but may be implemented in +--- the future). +--- +--- @type boolean +vim.o.equalalways = true +vim.o.ea = vim.o.equalalways +vim.go.equalalways = vim.o.equalalways +vim.go.ea = vim.go.equalalways + +--- External program to use for "=" command. When this option is empty +--- the internal formatting functions are used; either 'lisp', 'cindent' +--- or 'indentexpr'. +--- Environment variables are expanded `:set_env`. See `option-backslash` +--- about including spaces and backslashes. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.equalprg = "" +vim.o.ep = vim.o.equalprg +vim.bo.equalprg = vim.o.equalprg +vim.bo.ep = vim.bo.equalprg +vim.go.equalprg = vim.o.equalprg +vim.go.ep = vim.go.equalprg + +--- Ring the bell (beep or screen flash) for error messages. This only +--- makes a difference for error messages, the bell will be used always +--- for a lot of errors without a message (e.g., hitting <Esc> in Normal +--- mode). See 'visualbell' to make the bell behave like a screen flash +--- or do nothing. See 'belloff' to finetune when to ring the bell. +--- +--- @type boolean +vim.o.errorbells = false +vim.o.eb = vim.o.errorbells +vim.go.errorbells = vim.o.errorbells +vim.go.eb = vim.go.errorbells + +--- Name of the errorfile for the QuickFix mode (see `:cf`). +--- When the "-q" command-line argument is used, 'errorfile' is set to the +--- following argument. See `-q`. +--- NOT used for the ":make" command. See 'makeef' for that. +--- Environment variables are expanded `:set_env`. +--- See `option-backslash` about including spaces and backslashes. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.errorfile = "errors.err" +vim.o.ef = vim.o.errorfile +vim.go.errorfile = vim.o.errorfile +vim.go.ef = vim.go.errorfile + +--- Scanf-like description of the format for the lines in the error file +--- (see `errorformat`). +--- +--- @type string +vim.o.errorformat = "%*[^\"]\"%f\"%*\\D%l: %m,\"%f\"%*\\D%l: %m,%-Gg%\\?make[%*\\d]: *** [%f:%l:%m,%-Gg%\\?make: *** [%f:%l:%m,%-G%f:%l: (Each undeclared identifier is reported only once,%-G%f:%l: for each function it appears in.),%-GIn file included from %f:%l:%c:,%-GIn file included from %f:%l:%c\\,,%-GIn file included from %f:%l:%c,%-GIn file included from %f:%l,%-G%*[ ]from %f:%l:%c,%-G%*[ ]from %f:%l:,%-G%*[ ]from %f:%l\\,,%-G%*[ ]from %f:%l,%f:%l:%c:%m,%f(%l):%m,%f:%l:%m,\"%f\"\\, line %l%*\\D%c%*[^ ] %m,%D%*\\a[%*\\d]: Entering directory %*[`']%f',%X%*\\a[%*\\d]: Leaving directory %*[`']%f',%D%*\\a: Entering directory %*[`']%f',%X%*\\a: Leaving directory %*[`']%f',%DMaking %*\\a in %f,%f|%l| %m" +vim.o.efm = vim.o.errorformat +vim.bo.errorformat = vim.o.errorformat +vim.bo.efm = vim.bo.errorformat +vim.go.errorformat = vim.o.errorformat +vim.go.efm = vim.go.errorformat + +--- A list of autocommand event names, which are to be ignored. +--- When set to "all" or when "all" is one of the items, all autocommand +--- events are ignored, autocommands will not be executed. +--- Otherwise this is a comma-separated list of event names. Example: +--- ``` +--- :set ei=WinEnter,WinLeave +--- ``` +--- +--- +--- @type string +vim.o.eventignore = "" +vim.o.ei = vim.o.eventignore +vim.go.eventignore = vim.o.eventignore +vim.go.ei = vim.go.eventignore + +--- In Insert mode: Use the appropriate number of spaces to insert a +--- <Tab>. Spaces are used in indents with the '>' and '<' commands and +--- when 'autoindent' is on. To insert a real tab when 'expandtab' is +--- on, use CTRL-V<Tab>. See also `:retab` and `ins-expandtab`. +--- +--- @type boolean +vim.o.expandtab = false +vim.o.et = vim.o.expandtab +vim.bo.expandtab = vim.o.expandtab +vim.bo.et = vim.bo.expandtab + +--- Automatically execute .nvim.lua, .nvimrc, and .exrc files in the +--- current directory, if the file is in the `trust` list. Use `:trust` to +--- manage trusted files. See also `vim.secure.read()`. +--- +--- Compare 'exrc' to `editorconfig`: +--- - 'exrc' can execute any code; editorconfig only specifies settings. +--- - 'exrc' is Nvim-specific; editorconfig works in other editors. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type boolean +vim.o.exrc = false +vim.o.ex = vim.o.exrc +vim.go.exrc = vim.o.exrc +vim.go.ex = vim.go.exrc + +--- File-content encoding for the current buffer. Conversion is done with +--- iconv() or as specified with 'charconvert'. +--- +--- When 'fileencoding' is not UTF-8, conversion will be done when +--- writing the file. For reading see below. +--- When 'fileencoding' is empty, the file will be saved with UTF-8 +--- encoding (no conversion when reading or writing a file). +--- +--- WARNING: Conversion to a non-Unicode encoding can cause loss of +--- information! +--- +--- See `encoding-names` for the possible values. Additionally, values may be +--- specified that can be handled by the converter, see +--- `mbyte-conversion`. +--- +--- When reading a file 'fileencoding' will be set from 'fileencodings'. +--- To read a file in a certain encoding it won't work by setting +--- 'fileencoding', use the `++enc` argument. One exception: when +--- 'fileencodings' is empty the value of 'fileencoding' is used. +--- For a new file the global value of 'fileencoding' is used. +--- +--- Prepending "8bit-" and "2byte-" has no meaning here, they are ignored. +--- When the option is set, the value is converted to lowercase. Thus +--- you can set it with uppercase values too. '_' characters are +--- replaced with '-'. If a name is recognized from the list at +--- `encoding-names`, it is replaced by the standard name. For example +--- "ISO8859-2" becomes "iso-8859-2". +--- +--- When this option is set, after starting to edit a file, the 'modified' +--- option is set, because the file would be different when written. +--- +--- Keep in mind that changing 'fenc' from a modeline happens +--- AFTER the text has been read, thus it applies to when the file will be +--- written. If you do set 'fenc' in a modeline, you might want to set +--- 'nomodified' to avoid not being able to ":q". +--- +--- This option cannot be changed when 'modifiable' is off. +--- +--- @type string +vim.o.fileencoding = "" +vim.o.fenc = vim.o.fileencoding +vim.bo.fileencoding = vim.o.fileencoding +vim.bo.fenc = vim.bo.fileencoding + +--- This is a list of character encodings considered when starting to edit +--- an existing file. When a file is read, Vim tries to use the first +--- mentioned character encoding. If an error is detected, the next one +--- in the list is tried. When an encoding is found that works, +--- 'fileencoding' is set to it. If all fail, 'fileencoding' is set to +--- an empty string, which means that UTF-8 is used. +--- WARNING: Conversion can cause loss of information! You can use +--- the `++bad` argument to specify what is done with characters +--- that can't be converted. +--- For an empty file or a file with only ASCII characters most encodings +--- will work and the first entry of 'fileencodings' will be used (except +--- "ucs-bom", which requires the BOM to be present). If you prefer +--- another encoding use an BufReadPost autocommand event to test if your +--- preferred encoding is to be used. Example: +--- ``` +--- au BufReadPost * if search('\S', 'w') == 0 | +--- \ set fenc=iso-2022-jp | endif +--- ``` +--- This sets 'fileencoding' to "iso-2022-jp" if the file does not contain +--- non-blank characters. +--- When the `++enc` argument is used then the value of 'fileencodings' is +--- not used. +--- Note that 'fileencodings' is not used for a new file, the global value +--- of 'fileencoding' is used instead. You can set it with: +--- ``` +--- :setglobal fenc=iso-8859-2 +--- ``` +--- This means that a non-existing file may get a different encoding than +--- an empty file. +--- The special value "ucs-bom" can be used to check for a Unicode BOM +--- (Byte Order Mark) at the start of the file. It must not be preceded +--- by "utf-8" or another Unicode encoding for this to work properly. +--- An entry for an 8-bit encoding (e.g., "latin1") should be the last, +--- because Vim cannot detect an error, thus the encoding is always +--- accepted. +--- The special value "default" can be used for the encoding from the +--- environment. It is useful when your environment uses a non-latin1 +--- encoding, such as Russian. +--- When a file contains an illegal UTF-8 byte sequence it won't be +--- recognized as "utf-8". You can use the `8g8` command to find the +--- illegal byte sequence. +--- WRONG VALUES: WHAT'S WRONG: +--- latin1,utf-8 "latin1" will always be used +--- utf-8,ucs-bom,latin1 BOM won't be recognized in an utf-8 +--- file +--- cp1250,latin1 "cp1250" will always be used +--- If 'fileencodings' is empty, 'fileencoding' is not modified. +--- See 'fileencoding' for the possible values. +--- Setting this option does not have an effect until the next time a file +--- is read. +--- +--- @type string +vim.o.fileencodings = "ucs-bom,utf-8,default,latin1" +vim.o.fencs = vim.o.fileencodings +vim.go.fileencodings = vim.o.fileencodings +vim.go.fencs = vim.go.fileencodings + +--- This gives the <EOL> of the current buffer, which is used for +--- reading/writing the buffer from/to a file: +--- dos <CR><NL> +--- unix <NL> +--- mac <CR> +--- When "dos" is used, CTRL-Z at the end of a file is ignored. +--- See `file-formats` and `file-read`. +--- For the character encoding of the file see 'fileencoding'. +--- When 'binary' is set, the value of 'fileformat' is ignored, file I/O +--- works like it was set to "unix". +--- This option is set automatically when starting to edit a file and +--- 'fileformats' is not empty and 'binary' is off. +--- When this option is set, after starting to edit a file, the 'modified' +--- option is set, because the file would be different when written. +--- This option cannot be changed when 'modifiable' is off. +--- +--- @type string +vim.o.fileformat = "unix" +vim.o.ff = vim.o.fileformat +vim.bo.fileformat = vim.o.fileformat +vim.bo.ff = vim.bo.fileformat + +--- This gives the end-of-line (<EOL>) formats that will be tried when +--- starting to edit a new buffer and when reading a file into an existing +--- buffer: +--- - When empty, the format defined with 'fileformat' will be used +--- always. It is not set automatically. +--- - When set to one name, that format will be used whenever a new buffer +--- is opened. 'fileformat' is set accordingly for that buffer. The +--- 'fileformats' name will be used when a file is read into an existing +--- buffer, no matter what 'fileformat' for that buffer is set to. +--- - When more than one name is present, separated by commas, automatic +--- <EOL> detection will be done when reading a file. When starting to +--- edit a file, a check is done for the <EOL>: +--- 1. If all lines end in <CR><NL>, and 'fileformats' includes "dos", +--- 'fileformat' is set to "dos". +--- 2. If a <NL> is found and 'fileformats' includes "unix", 'fileformat' +--- is set to "unix". Note that when a <NL> is found without a +--- preceding <CR>, "unix" is preferred over "dos". +--- 3. If 'fileformat' has not yet been set, and if a <CR> is found, and +--- if 'fileformats' includes "mac", 'fileformat' is set to "mac". +--- This means that "mac" is only chosen when: +--- "unix" is not present or no <NL> is found in the file, and +--- "dos" is not present or no <CR><NL> is found in the file. +--- Except: if "unix" was chosen, but there is a <CR> before +--- the first <NL>, and there appear to be more <CR>s than <NL>s in +--- the first few lines, "mac" is used. +--- 4. If 'fileformat' is still not set, the first name from +--- 'fileformats' is used. +--- When reading a file into an existing buffer, the same is done, but +--- this happens like 'fileformat' has been set appropriately for that +--- file only, the option is not changed. +--- When 'binary' is set, the value of 'fileformats' is not used. +--- +--- When Vim starts up with an empty buffer the first item is used. You +--- can overrule this by setting 'fileformat' in your .vimrc. +--- +--- For systems with a Dos-like <EOL> (<CR><NL>), when reading files that +--- are ":source"ed and for vimrc files, automatic <EOL> detection may be +--- done: +--- - When 'fileformats' is empty, there is no automatic detection. Dos +--- format will be used. +--- - When 'fileformats' is set to one or more names, automatic detection +--- is done. This is based on the first <NL> in the file: If there is a +--- <CR> in front of it, Dos format is used, otherwise Unix format is +--- used. +--- Also see `file-formats`. +--- +--- @type string +vim.o.fileformats = "unix,dos" +vim.o.ffs = vim.o.fileformats +vim.go.fileformats = vim.o.fileformats +vim.go.ffs = vim.go.fileformats + +--- When set case is ignored when using file names and directories. +--- See 'wildignorecase' for only ignoring case when doing completion. +--- +--- @type boolean +vim.o.fileignorecase = false +vim.o.fic = vim.o.fileignorecase +vim.go.fileignorecase = vim.o.fileignorecase +vim.go.fic = vim.go.fileignorecase + +--- When this option is set, the FileType autocommand event is triggered. +--- All autocommands that match with the value of this option will be +--- executed. Thus the value of 'filetype' is used in place of the file +--- name. +--- Otherwise this option does not always reflect the current file type. +--- This option is normally set when the file type is detected. To enable +--- this use the ":filetype on" command. `:filetype` +--- Setting this option to a different value is most useful in a modeline, +--- for a file for which the file type is not automatically recognized. +--- Example, for in an IDL file: +--- ``` +--- /* vim: set filetype=idl : */ +--- ``` +--- `FileType` `filetypes` +--- When a dot appears in the value then this separates two filetype +--- names. Example: +--- ``` +--- /* vim: set filetype=c.doxygen : */ +--- ``` +--- This will use the "c" filetype first, then the "doxygen" filetype. +--- This works both for filetype plugins and for syntax files. More than +--- one dot may appear. +--- This option is not copied to another buffer, independent of the 's' or +--- 'S' flag in 'cpoptions'. +--- Only normal file name characters can be used, `/\*?[|<>` are illegal. +--- +--- @type string +vim.o.filetype = "" +vim.o.ft = vim.o.filetype +vim.bo.filetype = vim.o.filetype +vim.bo.ft = vim.bo.filetype + +--- Characters to fill the statuslines, vertical separators and special +--- lines in the window. +--- It is a comma-separated list of items. Each item has a name, a colon +--- and the value of that item: +--- +--- item default Used for ~ +--- stl ' ' statusline of the current window +--- stlnc ' ' statusline of the non-current windows +--- wbr ' ' window bar +--- horiz '─' or '-' horizontal separators `:split` +--- horizup '┴' or '-' upwards facing horizontal separator +--- horizdown '┬' or '-' downwards facing horizontal separator +--- vert '│' or '|' vertical separators `:vsplit` +--- vertleft '┤' or '|' left facing vertical separator +--- vertright '├' or '|' right facing vertical separator +--- verthoriz '┼' or '+' overlapping vertical and horizontal +--- separator +--- fold '·' or '-' filling 'foldtext' +--- foldopen '-' mark the beginning of a fold +--- foldclose '+' show a closed fold +--- foldsep '│' or '|' open fold middle marker +--- diff '-' deleted lines of the 'diff' option +--- msgsep ' ' message separator 'display' +--- eob '~' empty lines at the end of a buffer +--- lastline '@' 'display' contains lastline/truncate +--- +--- Any one that is omitted will fall back to the default. +--- +--- Note that "horiz", "horizup", "horizdown", "vertleft", "vertright" and +--- "verthoriz" are only used when 'laststatus' is 3, since only vertical +--- window separators are used otherwise. +--- +--- If 'ambiwidth' is "double" then "horiz", "horizup", "horizdown", +--- "vert", "vertleft", "vertright", "verthoriz", "foldsep" and "fold" +--- default to single-byte alternatives. +--- +--- Example: +--- ``` +--- :set fillchars=stl:\ ,stlnc:\ ,vert:│,fold:·,diff:- +--- ``` +--- +--- For the "stl", "stlnc", "foldopen", "foldclose" and "foldsep" items +--- single-byte and multibyte characters are supported. But double-width +--- characters are not supported. +--- +--- The highlighting used for these items: +--- item highlight group ~ +--- stl StatusLine `hl-StatusLine` +--- stlnc StatusLineNC `hl-StatusLineNC` +--- wbr WinBar `hl-WinBar` or `hl-WinBarNC` +--- horiz WinSeparator `hl-WinSeparator` +--- horizup WinSeparator `hl-WinSeparator` +--- horizdown WinSeparator `hl-WinSeparator` +--- vert WinSeparator `hl-WinSeparator` +--- vertleft WinSeparator `hl-WinSeparator` +--- vertright WinSeparator `hl-WinSeparator` +--- verthoriz WinSeparator `hl-WinSeparator` +--- fold Folded `hl-Folded` +--- diff DiffDelete `hl-DiffDelete` +--- eob EndOfBuffer `hl-EndOfBuffer` +--- lastline NonText `hl-NonText` +--- +--- @type string +vim.o.fillchars = "" +vim.o.fcs = vim.o.fillchars +vim.wo.fillchars = vim.o.fillchars +vim.wo.fcs = vim.wo.fillchars +vim.go.fillchars = vim.o.fillchars +vim.go.fcs = vim.go.fillchars + +--- When writing a file and this option is on, <EOL> at the end of file +--- will be restored if missing. Turn this option off if you want to +--- preserve the situation from the original file. +--- When the 'binary' option is set the value of this option doesn't +--- matter. +--- See the 'endofline' option. +--- See `eol-and-eof` for example settings. +--- +--- @type boolean +vim.o.fixendofline = true +vim.o.fixeol = vim.o.fixendofline +vim.bo.fixendofline = vim.o.fixendofline +vim.bo.fixeol = vim.bo.fixendofline + +--- When set to "all", a fold is closed when the cursor isn't in it and +--- its level is higher than 'foldlevel'. Useful if you want folds to +--- automatically close when moving out of them. +--- +--- @type string +vim.o.foldclose = "" +vim.o.fcl = vim.o.foldclose +vim.go.foldclose = vim.o.foldclose +vim.go.fcl = vim.go.foldclose + +--- When and how to draw the foldcolumn. Valid values are: +--- "auto": resize to the minimum amount of folds to display. +--- "auto:[1-9]": resize to accommodate multiple folds up to the +--- selected level +--- "0": to disable foldcolumn +--- "[1-9]": to display a fixed number of columns +--- See `folding`. +--- +--- @type string +vim.o.foldcolumn = "0" +vim.o.fdc = vim.o.foldcolumn +vim.wo.foldcolumn = vim.o.foldcolumn +vim.wo.fdc = vim.wo.foldcolumn + +--- When off, all folds are open. This option can be used to quickly +--- switch between showing all text unfolded and viewing the text with +--- folds (including manually opened or closed folds). It can be toggled +--- with the `zi` command. The 'foldcolumn' will remain blank when +--- 'foldenable' is off. +--- This option is set by commands that create a new fold or close a fold. +--- See `folding`. +--- +--- @type boolean +vim.o.foldenable = true +vim.o.fen = vim.o.foldenable +vim.wo.foldenable = vim.o.foldenable +vim.wo.fen = vim.wo.foldenable + +--- The expression used for when 'foldmethod' is "expr". It is evaluated +--- for each line to obtain its fold level. The context is set to the +--- script where 'foldexpr' was set, script-local items can be accessed. +--- See `fold-expr` for the usage. +--- +--- The expression will be evaluated in the `sandbox` if set from a +--- modeline, see `sandbox-option`. +--- This option can't be set from a `modeline` when the 'diff' option is +--- on or the 'modelineexpr' option is off. +--- +--- It is not allowed to change text or jump to another window while +--- evaluating 'foldexpr' `textlock`. +--- +--- @type string +vim.o.foldexpr = "0" +vim.o.fde = vim.o.foldexpr +vim.wo.foldexpr = vim.o.foldexpr +vim.wo.fde = vim.wo.foldexpr + +--- Used only when 'foldmethod' is "indent". Lines starting with +--- characters in 'foldignore' will get their fold level from surrounding +--- lines. White space is skipped before checking for this character. +--- The default "#" works well for C programs. See `fold-indent`. +--- +--- @type string +vim.o.foldignore = "#" +vim.o.fdi = vim.o.foldignore +vim.wo.foldignore = vim.o.foldignore +vim.wo.fdi = vim.wo.foldignore + +--- Sets the fold level: Folds with a higher level will be closed. +--- Setting this option to zero will close all folds. Higher numbers will +--- close fewer folds. +--- This option is set by commands like `zm`, `zM` and `zR`. +--- See `fold-foldlevel`. +--- +--- @type integer +vim.o.foldlevel = 0 +vim.o.fdl = vim.o.foldlevel +vim.wo.foldlevel = vim.o.foldlevel +vim.wo.fdl = vim.wo.foldlevel + +--- Sets 'foldlevel' when starting to edit another buffer in a window. +--- Useful to always start editing with all folds closed (value zero), +--- some folds closed (one) or no folds closed (99). +--- This is done before reading any modeline, thus a setting in a modeline +--- overrules this option. Starting to edit a file for `diff-mode` also +--- ignores this option and closes all folds. +--- It is also done before BufReadPre autocommands, to allow an autocmd to +--- overrule the 'foldlevel' value for specific files. +--- When the value is negative, it is not used. +--- +--- @type integer +vim.o.foldlevelstart = -1 +vim.o.fdls = vim.o.foldlevelstart +vim.go.foldlevelstart = vim.o.foldlevelstart +vim.go.fdls = vim.go.foldlevelstart + +--- The start and end marker used when 'foldmethod' is "marker". There +--- must be one comma, which separates the start and end marker. The +--- marker is a literal string (a regular expression would be too slow). +--- See `fold-marker`. +--- +--- @type string +vim.o.foldmarker = "{{{,}}}" +vim.o.fmr = vim.o.foldmarker +vim.wo.foldmarker = vim.o.foldmarker +vim.wo.fmr = vim.wo.foldmarker + +--- The kind of folding used for the current window. Possible values: +--- `fold-manual` manual Folds are created manually. +--- `fold-indent` indent Lines with equal indent form a fold. +--- `fold-expr` expr 'foldexpr' gives the fold level of a line. +--- `fold-marker` marker Markers are used to specify folds. +--- `fold-syntax` syntax Syntax highlighting items specify folds. +--- `fold-diff` diff Fold text that is not changed. +--- +--- @type string +vim.o.foldmethod = "manual" +vim.o.fdm = vim.o.foldmethod +vim.wo.foldmethod = vim.o.foldmethod +vim.wo.fdm = vim.wo.foldmethod + +--- Sets the number of screen lines above which a fold can be displayed +--- closed. Also for manually closed folds. With the default value of +--- one a fold can only be closed if it takes up two or more screen lines. +--- Set to zero to be able to close folds of just one screen line. +--- Note that this only has an effect on what is displayed. After using +--- "zc" to close a fold, which is displayed open because it's smaller +--- than 'foldminlines', a following "zc" may close a containing fold. +--- +--- @type integer +vim.o.foldminlines = 1 +vim.o.fml = vim.o.foldminlines +vim.wo.foldminlines = vim.o.foldminlines +vim.wo.fml = vim.wo.foldminlines + +--- Sets the maximum nesting of folds for the "indent" and "syntax" +--- methods. This avoids that too many folds will be created. Using more +--- than 20 doesn't work, because the internal limit is 20. +--- +--- @type integer +vim.o.foldnestmax = 20 +vim.o.fdn = vim.o.foldnestmax +vim.wo.foldnestmax = vim.o.foldnestmax +vim.wo.fdn = vim.wo.foldnestmax + +--- Specifies for which type of commands folds will be opened, if the +--- command moves the cursor into a closed fold. It is a comma-separated +--- list of items. +--- NOTE: When the command is part of a mapping this option is not used. +--- Add the `zv` command to the mapping to get the same effect. +--- (rationale: the mapping may want to control opening folds itself) +--- +--- item commands ~ +--- all any +--- block (, {, [[, [{, etc. +--- hor horizontal movements: "l", "w", "fx", etc. +--- insert any command in Insert mode +--- jump far jumps: "G", "gg", etc. +--- mark jumping to a mark: "'m", CTRL-O, etc. +--- percent "%" +--- quickfix ":cn", ":crew", ":make", etc. +--- search search for a pattern: "/", "n", "*", "gd", etc. +--- (not for a search pattern in a ":" command) +--- Also for `[s` and `]s`. +--- tag jumping to a tag: ":ta", CTRL-T, etc. +--- undo undo or redo: "u" and CTRL-R +--- When a movement command is used for an operator (e.g., "dl" or "y%") +--- this option is not used. This means the operator will include the +--- whole closed fold. +--- Note that vertical movements are not here, because it would make it +--- very difficult to move onto a closed fold. +--- In insert mode the folds containing the cursor will always be open +--- when text is inserted. +--- To close folds you can re-apply 'foldlevel' with the `zx` command or +--- set the 'foldclose' option to "all". +--- +--- @type string +vim.o.foldopen = "block,hor,mark,percent,quickfix,search,tag,undo" +vim.o.fdo = vim.o.foldopen +vim.go.foldopen = vim.o.foldopen +vim.go.fdo = vim.go.foldopen + +--- An expression which is used to specify the text displayed for a closed +--- fold. The context is set to the script where 'foldexpr' was set, +--- script-local items can be accessed. See `fold-foldtext` for the +--- usage. +--- +--- The expression will be evaluated in the `sandbox` if set from a +--- modeline, see `sandbox-option`. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- It is not allowed to change text or jump to another window while +--- evaluating 'foldtext' `textlock`. +--- +--- @type string +vim.o.foldtext = "foldtext()" +vim.o.fdt = vim.o.foldtext +vim.wo.foldtext = vim.o.foldtext +vim.wo.fdt = vim.wo.foldtext + +--- Expression which is evaluated to format a range of lines for the `gq` +--- operator or automatic formatting (see 'formatoptions'). When this +--- option is empty 'formatprg' is used. +--- +--- The `v:lnum` variable holds the first line to be formatted. +--- The `v:count` variable holds the number of lines to be formatted. +--- The `v:char` variable holds the character that is going to be +--- inserted if the expression is being evaluated due to +--- automatic formatting. This can be empty. Don't insert +--- it yet! +--- +--- Example: +--- ``` +--- :set formatexpr=mylang#Format() +--- ``` +--- This will invoke the mylang#Format() function in the +--- autoload/mylang.vim file in 'runtimepath'. `autoload` +--- +--- The expression is also evaluated when 'textwidth' is set and adding +--- text beyond that limit. This happens under the same conditions as +--- when internal formatting is used. Make sure the cursor is kept in the +--- same spot relative to the text then! The `mode()` function will +--- return "i" or "R" in this situation. +--- +--- When the expression evaluates to non-zero Vim will fall back to using +--- the internal format mechanism. +--- +--- If the expression starts with s: or `<SID>`, then it is replaced with +--- the script ID (`local-function`). Example: +--- ``` +--- set formatexpr=s:MyFormatExpr() +--- set formatexpr=<SID>SomeFormatExpr() +--- ``` +--- Otherwise, the expression is evaluated in the context of the script +--- where the option was set, thus script-local items are available. +--- +--- The expression will be evaluated in the `sandbox` when set from a +--- modeline, see `sandbox-option`. That stops the option from working, +--- since changing the buffer text is not allowed. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- NOTE: This option is set to "" when 'compatible' is set. +--- +--- @type string +vim.o.formatexpr = "" +vim.o.fex = vim.o.formatexpr +vim.bo.formatexpr = vim.o.formatexpr +vim.bo.fex = vim.bo.formatexpr + +--- A pattern that is used to recognize a list header. This is used for +--- the "n" flag in 'formatoptions'. +--- The pattern must match exactly the text that will be the indent for +--- the line below it. You can use `/\ze` to mark the end of the match +--- while still checking more characters. There must be a character +--- following the pattern, when it matches the whole line it is handled +--- like there is no match. +--- The default recognizes a number, followed by an optional punctuation +--- character and white space. +--- +--- @type string +vim.o.formatlistpat = "^\\s*\\d\\+[\\]:.)}\\t ]\\s*" +vim.o.flp = vim.o.formatlistpat +vim.bo.formatlistpat = vim.o.formatlistpat +vim.bo.flp = vim.bo.formatlistpat + +--- This is a sequence of letters which describes how automatic +--- formatting is to be done. +--- See `fo-table` for possible values and `gq` for how to format text. +--- Commas can be inserted for readability. +--- To avoid problems with flags that are added in the future, use the +--- "+=" and "-=" feature of ":set" `add-option-flags`. +--- +--- @type string +vim.o.formatoptions = "tcqj" +vim.o.fo = vim.o.formatoptions +vim.bo.formatoptions = vim.o.formatoptions +vim.bo.fo = vim.bo.formatoptions + +--- The name of an external program that will be used to format the lines +--- selected with the `gq` operator. The program must take the input on +--- stdin and produce the output on stdout. The Unix program "fmt" is +--- such a program. +--- If the 'formatexpr' option is not empty it will be used instead. +--- Otherwise, if 'formatprg' option is an empty string, the internal +--- format function will be used `C-indenting`. +--- Environment variables are expanded `:set_env`. See `option-backslash` +--- about including spaces and backslashes. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.formatprg = "" +vim.o.fp = vim.o.formatprg +vim.bo.formatprg = vim.o.formatprg +vim.bo.fp = vim.bo.formatprg +vim.go.formatprg = vim.o.formatprg +vim.go.fp = vim.go.formatprg + +--- When on, the OS function fsync() will be called after saving a file +--- (`:write`, `writefile()`, …), `swap-file`, `undo-persistence` and `shada-file`. +--- This flushes the file to disk, ensuring that it is safely written. +--- Slow on some systems: writing buffers, quitting Nvim, and other +--- operations may sometimes take a few seconds. +--- +--- Files are ALWAYS flushed ('fsync' is ignored) when: +--- - `CursorHold` event is triggered +--- - `:preserve` is called +--- - system signals low battery life +--- - Nvim exits abnormally +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type boolean +vim.o.fsync = true +vim.o.fs = vim.o.fsync +vim.go.fsync = vim.o.fsync +vim.go.fs = vim.go.fsync + +--- When on, the ":substitute" flag 'g' is default on. This means that +--- all matches in a line are substituted instead of one. When a 'g' flag +--- is given to a ":substitute" command, this will toggle the substitution +--- of all or one match. See `complex-change`. +--- +--- command 'gdefault' on 'gdefault' off ~ +--- :s/// subst. all subst. one +--- :s///g subst. one subst. all +--- :s///gg subst. all subst. one +--- +--- DEPRECATED: Setting this option may break plugins that are not aware +--- of this option. Also, many users get confused that adding the /g flag +--- has the opposite effect of that it normally does. +--- +--- @type boolean +vim.o.gdefault = false +vim.o.gd = vim.o.gdefault +vim.go.gdefault = vim.o.gdefault +vim.go.gd = vim.go.gdefault + +--- Format to recognize for the ":grep" command output. +--- This is a scanf-like string that uses the same format as the +--- 'errorformat' option: see `errorformat`. +--- +--- @type string +vim.o.grepformat = "%f:%l:%m,%f:%l%m,%f %l%m" +vim.o.gfm = vim.o.grepformat +vim.go.grepformat = vim.o.grepformat +vim.go.gfm = vim.go.grepformat + +--- Program to use for the `:grep` command. This option may contain '%' +--- and '#' characters, which are expanded like when used in a command- +--- line. The placeholder "$*" is allowed to specify where the arguments +--- will be included. Environment variables are expanded `:set_env`. See +--- `option-backslash` about including spaces and backslashes. +--- When your "grep" accepts the "-H" argument, use this to make ":grep" +--- also work well with a single file: +--- ``` +--- :set grepprg=grep\ -nH +--- ``` +--- Special value: When 'grepprg' is set to "internal" the `:grep` command +--- works like `:vimgrep`, `:lgrep` like `:lvimgrep`, `:grepadd` like +--- `:vimgrepadd` and `:lgrepadd` like `:lvimgrepadd`. +--- See also the section `:make_makeprg`, since most of the comments there +--- apply equally to 'grepprg'. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.grepprg = "grep -n $* /dev/null" +vim.o.gp = vim.o.grepprg +vim.bo.grepprg = vim.o.grepprg +vim.bo.gp = vim.bo.grepprg +vim.go.grepprg = vim.o.grepprg +vim.go.gp = vim.go.grepprg + +--- Configures the cursor style for each mode. Works in the GUI and many +--- terminals. See `tui-cursor-shape`. +--- +--- To disable cursor-styling, reset the option: +--- ``` +--- :set guicursor= +--- ``` +--- To enable mode shapes, "Cursor" highlight, and blinking: +--- ``` +--- :set guicursor=n-v-c:block,i-ci-ve:ver25,r-cr:hor20,o:hor50 +--- \,a:blinkwait700-blinkoff400-blinkon250-Cursor/lCursor +--- \,sm:block-blinkwait175-blinkoff150-blinkon175 +--- ``` +--- The option is a comma-separated list of parts. Each part consists of a +--- mode-list and an argument-list: +--- mode-list:argument-list,mode-list:argument-list,.. +--- The mode-list is a dash separated list of these modes: +--- n Normal mode +--- v Visual mode +--- ve Visual mode with 'selection' "exclusive" (same as 'v', +--- if not specified) +--- o Operator-pending mode +--- i Insert mode +--- r Replace mode +--- c Command-line Normal (append) mode +--- ci Command-line Insert mode +--- cr Command-line Replace mode +--- sm showmatch in Insert mode +--- a all modes +--- The argument-list is a dash separated list of these arguments: +--- hor{N} horizontal bar, {N} percent of the character height +--- ver{N} vertical bar, {N} percent of the character width +--- block block cursor, fills the whole character +--- - Only one of the above three should be present. +--- - Default is "block" for each mode. +--- blinkwait{N} *cursor-blinking* +--- blinkon{N} +--- blinkoff{N} +--- blink times for cursor: blinkwait is the delay before +--- the cursor starts blinking, blinkon is the time that +--- the cursor is shown and blinkoff is the time that the +--- cursor is not shown. Times are in msec. When one of +--- the numbers is zero, there is no blinking. E.g.: +--- ``` +--- :set guicursor=n:blinkon0 +--- ``` +--- - Default is "blinkon0" for each mode. +--- {group-name} +--- Highlight group that decides the color and font of the +--- cursor. +--- In the `TUI`: +--- - `inverse`/reverse and no group-name are interpreted +--- as "host-terminal default cursor colors" which +--- typically means "inverted bg and fg colors". +--- - `ctermfg` and `guifg` are ignored. +--- {group-name}/{group-name} +--- Two highlight group names, the first is used when +--- no language mappings are used, the other when they +--- are. `language-mapping` +--- +--- Examples of parts: +--- n-c-v:block-nCursor In Normal, Command-line and Visual mode, use a +--- block cursor with colors from the "nCursor" +--- highlight group +--- n-v-c-sm:block,i-ci-ve:ver25-Cursor,r-cr-o:hor20 +--- In Normal et al. modes, use a block cursor +--- with the default colors defined by the host +--- terminal. In Insert-like modes, use +--- a vertical bar cursor with colors from +--- "Cursor" highlight group. In Replace-like +--- modes, use an underline cursor with +--- default colors. +--- i-ci:ver30-iCursor-blinkwait300-blinkon200-blinkoff150 +--- In Insert and Command-line Insert mode, use a +--- 30% vertical bar cursor with colors from the +--- "iCursor" highlight group. Blink a bit +--- faster. +--- +--- The 'a' mode is different. It will set the given argument-list for +--- all modes. It does not reset anything to defaults. This can be used +--- to do a common setting for all modes. For example, to switch off +--- blinking: "a:blinkon0" +--- +--- Examples of cursor highlighting: +--- ``` +--- :highlight Cursor gui=reverse guifg=NONE guibg=NONE +--- :highlight Cursor gui=NONE guifg=bg guibg=fg +--- ``` +--- +--- +--- @type string +vim.o.guicursor = "n-v-c-sm:block,i-ci-ve:ver25,r-cr-o:hor20" +vim.o.gcr = vim.o.guicursor +vim.go.guicursor = vim.o.guicursor +vim.go.gcr = vim.go.guicursor + +--- This is a list of fonts which will be used for the GUI version of Vim. +--- In its simplest form the value is just one font name. When +--- the font cannot be found you will get an error message. To try other +--- font names a list can be specified, font names separated with commas. +--- The first valid font is used. +--- +--- Spaces after a comma are ignored. To include a comma in a font name +--- precede it with a backslash. Setting an option requires an extra +--- backslash before a space and a backslash. See also +--- `option-backslash`. For example: +--- ``` +--- :set guifont=Screen15,\ 7x13,font\\,with\\,commas +--- ``` +--- will make Vim try to use the font "Screen15" first, and if it fails it +--- will try to use "7x13" and then "font,with,commas" instead. +--- +--- If none of the fonts can be loaded, Vim will keep the current setting. +--- If an empty font list is given, Vim will try using other resource +--- settings (for X, it will use the Vim.font resource), and finally it +--- will try some builtin default which should always be there ("7x13" in +--- the case of X). The font names given should be "normal" fonts. Vim +--- will try to find the related bold and italic fonts. +--- +--- For Win32 and Mac OS: +--- ``` +--- :set guifont=* +--- ``` +--- will bring up a font requester, where you can pick the font you want. +--- +--- The font name depends on the GUI used. +--- +--- For Mac OSX you can use something like this: +--- ``` +--- :set guifont=Monaco:h10 +--- ``` +--- *E236* +--- Note that the fonts must be mono-spaced (all characters have the same +--- width). +--- +--- To preview a font on X11, you might be able to use the "xfontsel" +--- program. The "xlsfonts" program gives a list of all available fonts. +--- +--- For the Win32 GUI *E244* *E245* +--- - takes these options in the font name: +--- hXX - height is XX (points, can be floating-point) +--- wXX - width is XX (points, can be floating-point) +--- b - bold +--- i - italic +--- u - underline +--- s - strikeout +--- cXX - character set XX. Valid charsets are: ANSI, ARABIC, +--- BALTIC, CHINESEBIG5, DEFAULT, EASTEUROPE, GB2312, GREEK, +--- HANGEUL, HEBREW, JOHAB, MAC, OEM, RUSSIAN, SHIFTJIS, +--- SYMBOL, THAI, TURKISH, VIETNAMESE ANSI and BALTIC. +--- Normally you would use "cDEFAULT". +--- +--- Use a ':' to separate the options. +--- - A '_' can be used in the place of a space, so you don't need to use +--- backslashes to escape the spaces. +--- - Examples: +--- ``` +--- :set guifont=courier_new:h12:w5:b:cRUSSIAN +--- :set guifont=Andale_Mono:h7.5:w4.5 +--- ``` +--- +--- +--- @type string +vim.o.guifont = "" +vim.o.gfn = vim.o.guifont +vim.go.guifont = vim.o.guifont +vim.go.gfn = vim.go.guifont + +--- Comma-separated list of fonts to be used for double-width characters. +--- The first font that can be loaded is used. +--- Note: The size of these fonts must be exactly twice as wide as the one +--- specified with 'guifont' and the same height. +--- +--- When 'guifont' has a valid font and 'guifontwide' is empty Vim will +--- attempt to set 'guifontwide' to a matching double-width font. +--- +--- @type string +vim.o.guifontwide = "" +vim.o.gfw = vim.o.guifontwide +vim.go.guifontwide = vim.o.guifontwide +vim.go.gfw = vim.go.guifontwide + +--- This option only has an effect in the GUI version of Vim. It is a +--- sequence of letters which describes what components and options of the +--- GUI should be used. +--- To avoid problems with flags that are added in the future, use the +--- "+=" and "-=" feature of ":set" `add-option-flags`. +--- +--- Valid letters are as follows: +--- *guioptions_a* *'go-a'* +--- 'a' Autoselect: If present, then whenever VISUAL mode is started, +--- or the Visual area extended, Vim tries to become the owner of +--- the windowing system's global selection. This means that the +--- Visually highlighted text is available for pasting into other +--- applications as well as into Vim itself. When the Visual mode +--- ends, possibly due to an operation on the text, or when an +--- application wants to paste the selection, the highlighted text +--- is automatically yanked into the "* selection register. +--- Thus the selection is still available for pasting into other +--- applications after the VISUAL mode has ended. +--- If not present, then Vim won't become the owner of the +--- windowing system's global selection unless explicitly told to +--- by a yank or delete operation for the "* register. +--- The same applies to the modeless selection. +--- *'go-P'* +--- 'P' Like autoselect but using the "+ register instead of the "* +--- register. +--- *'go-A'* +--- 'A' Autoselect for the modeless selection. Like 'a', but only +--- applies to the modeless selection. +--- +--- 'guioptions' autoselect Visual autoselect modeless ~ +--- "" - - +--- "a" yes yes +--- "A" - yes +--- "aA" yes yes +--- +--- *'go-c'* +--- 'c' Use console dialogs instead of popup dialogs for simple +--- choices. +--- *'go-d'* +--- 'd' Use dark theme variant if available. +--- *'go-e'* +--- 'e' Add tab pages when indicated with 'showtabline'. +--- 'guitablabel' can be used to change the text in the labels. +--- When 'e' is missing a non-GUI tab pages line may be used. +--- The GUI tabs are only supported on some systems, currently +--- Mac OS/X and MS-Windows. +--- *'go-i'* +--- 'i' Use a Vim icon. +--- *'go-m'* +--- 'm' Menu bar is present. +--- *'go-M'* +--- 'M' The system menu "$VIMRUNTIME/menu.vim" is not sourced. Note +--- that this flag must be added in the vimrc file, before +--- switching on syntax or filetype recognition (when the `gvimrc` +--- file is sourced the system menu has already been loaded; the +--- `:syntax on` and `:filetype on` commands load the menu too). +--- *'go-g'* +--- 'g' Grey menu items: Make menu items that are not active grey. If +--- 'g' is not included inactive menu items are not shown at all. +--- *'go-T'* +--- 'T' Include Toolbar. Currently only in Win32 GUI. +--- *'go-r'* +--- 'r' Right-hand scrollbar is always present. +--- *'go-R'* +--- 'R' Right-hand scrollbar is present when there is a vertically +--- split window. +--- *'go-l'* +--- 'l' Left-hand scrollbar is always present. +--- *'go-L'* +--- 'L' Left-hand scrollbar is present when there is a vertically +--- split window. +--- *'go-b'* +--- 'b' Bottom (horizontal) scrollbar is present. Its size depends on +--- the longest visible line, or on the cursor line if the 'h' +--- flag is included. `gui-horiz-scroll` +--- *'go-h'* +--- 'h' Limit horizontal scrollbar size to the length of the cursor +--- line. Reduces computations. `gui-horiz-scroll` +--- +--- And yes, you may even have scrollbars on the left AND the right if +--- you really want to :-). See `gui-scrollbars` for more information. +--- +--- *'go-v'* +--- 'v' Use a vertical button layout for dialogs. When not included, +--- a horizontal layout is preferred, but when it doesn't fit a +--- vertical layout is used anyway. Not supported in GTK 3. +--- *'go-p'* +--- 'p' Use Pointer callbacks for X11 GUI. This is required for some +--- window managers. If the cursor is not blinking or hollow at +--- the right moment, try adding this flag. This must be done +--- before starting the GUI. Set it in your `gvimrc`. Adding or +--- removing it after the GUI has started has no effect. +--- *'go-k'* +--- 'k' Keep the GUI window size when adding/removing a scrollbar, or +--- toolbar, tabline, etc. Instead, the behavior is similar to +--- when the window is maximized and will adjust 'lines' and +--- 'columns' to fit to the window. Without the 'k' flag Vim will +--- try to keep 'lines' and 'columns' the same when adding and +--- removing GUI components. +--- +--- @type string +vim.o.guioptions = "" +vim.o.go = vim.o.guioptions +vim.go.guioptions = vim.o.guioptions +vim.go.go = vim.go.guioptions + +--- When non-empty describes the text to use in a label of the GUI tab +--- pages line. When empty and when the result is empty Vim will use a +--- default label. See `setting-guitablabel` for more info. +--- +--- The format of this option is like that of 'statusline'. +--- 'guitabtooltip' is used for the tooltip, see below. +--- The expression will be evaluated in the `sandbox` when set from a +--- modeline, see `sandbox-option`. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- Only used when the GUI tab pages line is displayed. 'e' must be +--- present in 'guioptions'. For the non-GUI tab pages line 'tabline' is +--- used. +--- +--- @type string +vim.o.guitablabel = "" +vim.o.gtl = vim.o.guitablabel +vim.go.guitablabel = vim.o.guitablabel +vim.go.gtl = vim.go.guitablabel + +--- When non-empty describes the text to use in a tooltip for the GUI tab +--- pages line. When empty Vim will use a default tooltip. +--- This option is otherwise just like 'guitablabel' above. +--- You can include a line break. Simplest method is to use `:let`: +--- ``` +--- :let &guitabtooltip = "line one\nline two" +--- ``` +--- +--- +--- @type string +vim.o.guitabtooltip = "" +vim.o.gtt = vim.o.guitabtooltip +vim.go.guitabtooltip = vim.o.guitabtooltip +vim.go.gtt = vim.go.guitabtooltip + +--- Name of the main help file. All distributed help files should be +--- placed together in one directory. Additionally, all "doc" directories +--- in 'runtimepath' will be used. +--- Environment variables are expanded `:set_env`. For example: +--- "$VIMRUNTIME/doc/help.txt". If $VIMRUNTIME is not set, $VIM is also +--- tried. Also see `$VIMRUNTIME` and `option-backslash` about including +--- spaces and backslashes. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.helpfile = "$VIMRUNTIME/doc/help.txt" +vim.o.hf = vim.o.helpfile +vim.go.helpfile = vim.o.helpfile +vim.go.hf = vim.go.helpfile + +--- Minimal initial height of the help window when it is opened with the +--- ":help" command. The initial height of the help window is half of the +--- current window, or (when the 'ea' option is on) the same as other +--- windows. When the height is less than 'helpheight', the height is +--- set to 'helpheight'. Set to zero to disable. +--- +--- @type integer +vim.o.helpheight = 20 +vim.o.hh = vim.o.helpheight +vim.go.helpheight = vim.o.helpheight +vim.go.hh = vim.go.helpheight + +--- Comma-separated list of languages. Vim will use the first language +--- for which the desired help can be found. The English help will always +--- be used as a last resort. You can add "en" to prefer English over +--- another language, but that will only find tags that exist in that +--- language and not in the English help. +--- Example: +--- ``` +--- :set helplang=de,it +--- ``` +--- This will first search German, then Italian and finally English help +--- files. +--- When using `CTRL-]` and ":help!" in a non-English help file Vim will +--- try to find the tag in the current language before using this option. +--- See `help-translated`. +--- +--- @type string +vim.o.helplang = "" +vim.o.hlg = vim.o.helplang +vim.go.helplang = vim.o.helplang +vim.go.hlg = vim.go.helplang + +--- When off a buffer is unloaded (including loss of undo information) +--- when it is `abandon`ed. When on a buffer becomes hidden when it is +--- `abandon`ed. A buffer displayed in another window does not become +--- hidden, of course. +--- +--- Commands that move through the buffer list sometimes hide a buffer +--- although the 'hidden' option is off when these three are true: +--- - the buffer is modified +--- - 'autowrite' is off or writing is not possible +--- - the '!' flag was used +--- Also see `windows`. +--- +--- To hide a specific buffer use the 'bufhidden' option. +--- 'hidden' is set for one command with ":hide {command}" `:hide`. +--- +--- @type boolean +vim.o.hidden = true +vim.o.hid = vim.o.hidden +vim.go.hidden = vim.o.hidden +vim.go.hid = vim.go.hidden + +--- A history of ":" commands, and a history of previous search patterns +--- is remembered. This option decides how many entries may be stored in +--- each of these histories (see `cmdline-editing`). +--- The maximum value is 10000. +--- +--- @type integer +vim.o.history = 10000 +vim.o.hi = vim.o.history +vim.go.history = vim.o.history +vim.go.hi = vim.go.history + +--- When there is a previous search pattern, highlight all its matches. +--- The `hl-Search` highlight group determines the highlighting for all +--- matches not under the cursor while the `hl-CurSearch` highlight group +--- (if defined) determines the highlighting for the match under the +--- cursor. If `hl-CurSearch` is not defined, then `hl-Search` is used for +--- both. Note that only the matching text is highlighted, any offsets +--- are not applied. +--- See also: 'incsearch' and `:match`. +--- When you get bored looking at the highlighted matches, you can turn it +--- off with `:nohlsearch`. This does not change the option value, as +--- soon as you use a search command, the highlighting comes back. +--- 'redrawtime' specifies the maximum time spent on finding matches. +--- When the search pattern can match an end-of-line, Vim will try to +--- highlight all of the matched text. However, this depends on where the +--- search starts. This will be the first line in the window or the first +--- line below a closed fold. A match in a previous line which is not +--- drawn may not continue in a newly drawn line. +--- You can specify whether the highlight status is restored on startup +--- with the 'h' flag in 'shada' `shada-h`. +--- +--- @type boolean +vim.o.hlsearch = true +vim.o.hls = vim.o.hlsearch +vim.go.hlsearch = vim.o.hlsearch +vim.go.hls = vim.go.hlsearch + +--- When on, the icon text of the window will be set to the value of +--- 'iconstring' (if it is not empty), or to the name of the file +--- currently being edited. Only the last part of the name is used. +--- Overridden by the 'iconstring' option. +--- Only works if the terminal supports setting window icons. +--- +--- @type boolean +vim.o.icon = false +vim.go.icon = vim.o.icon + +--- When this option is not empty, it will be used for the icon text of +--- the window. This happens only when the 'icon' option is on. +--- Only works if the terminal supports setting window icon text +--- When this option contains printf-style '%' items, they will be +--- expanded according to the rules used for 'statusline'. See +--- 'titlestring' for example settings. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- @type string +vim.o.iconstring = "" +vim.go.iconstring = vim.o.iconstring + +--- Ignore case in search patterns, `cmdline-completion`, when +--- searching in the tags file, and `expr-==`. +--- Also see 'smartcase' and 'tagcase'. +--- Can be overruled by using "\c" or "\C" in the pattern, see +--- `/ignorecase`. +--- +--- @type boolean +vim.o.ignorecase = false +vim.o.ic = vim.o.ignorecase +vim.go.ignorecase = vim.o.ignorecase +vim.go.ic = vim.go.ignorecase + +--- When set the Input Method is always on when starting to edit a command +--- line, unless entering a search pattern (see 'imsearch' for that). +--- Setting this option is useful when your input method allows entering +--- English characters directly, e.g., when it's used to type accented +--- characters with dead keys. +--- +--- @type boolean +vim.o.imcmdline = false +vim.o.imc = vim.o.imcmdline +vim.go.imcmdline = vim.o.imcmdline +vim.go.imc = vim.go.imcmdline + +--- When set the Input Method is never used. This is useful to disable +--- the IM when it doesn't work properly. +--- Currently this option is on by default for SGI/IRIX machines. This +--- may change in later releases. +--- +--- @type boolean +vim.o.imdisable = false +vim.o.imd = vim.o.imdisable +vim.go.imdisable = vim.o.imdisable +vim.go.imd = vim.go.imdisable + +--- Specifies whether :lmap or an Input Method (IM) is to be used in +--- Insert mode. Valid values: +--- 0 :lmap is off and IM is off +--- 1 :lmap is ON and IM is off +--- 2 :lmap is off and IM is ON +--- To always reset the option to zero when leaving Insert mode with <Esc> +--- this can be used: +--- ``` +--- :inoremap <ESC> <ESC>:set iminsert=0<CR> +--- ``` +--- This makes :lmap and IM turn off automatically when leaving Insert +--- mode. +--- Note that this option changes when using CTRL-^ in Insert mode +--- `i_CTRL-^`. +--- The value is set to 1 when setting 'keymap' to a valid keymap name. +--- It is also used for the argument of commands like "r" and "f". +--- +--- @type integer +vim.o.iminsert = 0 +vim.o.imi = vim.o.iminsert +vim.bo.iminsert = vim.o.iminsert +vim.bo.imi = vim.bo.iminsert + +--- Specifies whether :lmap or an Input Method (IM) is to be used when +--- entering a search pattern. Valid values: +--- -1 the value of 'iminsert' is used, makes it look like +--- 'iminsert' is also used when typing a search pattern +--- 0 :lmap is off and IM is off +--- 1 :lmap is ON and IM is off +--- 2 :lmap is off and IM is ON +--- Note that this option changes when using CTRL-^ in Command-line mode +--- `c_CTRL-^`. +--- The value is set to 1 when it is not -1 and setting the 'keymap' +--- option to a valid keymap name. +--- +--- @type integer +vim.o.imsearch = -1 +vim.o.ims = vim.o.imsearch +vim.bo.imsearch = vim.o.imsearch +vim.bo.ims = vim.bo.imsearch + +--- When nonempty, shows the effects of `:substitute`, `:smagic|, +--- |:snomagic` and user commands with the `:command-preview` flag as you +--- type. +--- +--- Possible values: +--- nosplit Shows the effects of a command incrementally in the +--- buffer. +--- split Like "nosplit", but also shows partial off-screen +--- results in a preview window. +--- +--- If the preview for built-in commands is too slow (exceeds +--- 'redrawtime') then 'inccommand' is automatically disabled until +--- `Command-line-mode` is done. +--- +--- @type string +vim.o.inccommand = "nosplit" +vim.o.icm = vim.o.inccommand +vim.go.inccommand = vim.o.inccommand +vim.go.icm = vim.go.inccommand + +--- Pattern to be used to find an include command. It is a search +--- pattern, just like for the "/" command (See `pattern`). This option +--- is used for the commands "[i", "]I", "[d", etc. +--- Normally the 'isfname' option is used to recognize the file name that +--- comes after the matched pattern. But if "\zs" appears in the pattern +--- then the text matched from "\zs" to the end, or until "\ze" if it +--- appears, is used as the file name. Use this to include characters +--- that are not in 'isfname', such as a space. You can then use +--- 'includeexpr' to process the matched text. +--- See `option-backslash` about including spaces and backslashes. +--- +--- @type string +vim.o.include = "" +vim.o.inc = vim.o.include +vim.bo.include = vim.o.include +vim.bo.inc = vim.bo.include +vim.go.include = vim.o.include +vim.go.inc = vim.go.include + +--- Expression to be used to transform the string found with the 'include' +--- option to a file name. Mostly useful to change "." to "/" for Java: +--- ``` +--- :setlocal includeexpr=substitute(v:fname,'\\.','/','g') +--- ``` +--- The "v:fname" variable will be set to the file name that was detected. +--- Note the double backslash: the `:set` command first halves them, then +--- one remains in the value, where "\." matches a dot literally. For +--- simple character replacements `tr()` avoids the need for escaping: +--- ``` +--- :setlocal includeexpr=tr(v:fname,'.','/') +--- ``` +--- +--- Also used for the `gf` command if an unmodified file name can't be +--- found. Allows doing "gf" on the name after an 'include' statement. +--- Also used for `<cfile>`. +--- +--- If the expression starts with s: or `<SID>`, then it is replaced with +--- the script ID (`local-function`). Example: +--- ``` +--- setlocal includeexpr=s:MyIncludeExpr(v:fname) +--- setlocal includeexpr=<SID>SomeIncludeExpr(v:fname) +--- ``` +--- Otherwise, the expression is evaluated in the context of the script +--- where the option was set, thus script-local items are available. +--- +--- The expression will be evaluated in the `sandbox` when set from a +--- modeline, see `sandbox-option`. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- It is not allowed to change text or jump to another window while +--- evaluating 'includeexpr' `textlock`. +--- +--- @type string +vim.o.includeexpr = "" +vim.o.inex = vim.o.includeexpr +vim.bo.includeexpr = vim.o.includeexpr +vim.bo.inex = vim.bo.includeexpr + +--- While typing a search command, show where the pattern, as it was typed +--- so far, matches. The matched string is highlighted. If the pattern +--- is invalid or not found, nothing is shown. The screen will be updated +--- often, this is only useful on fast terminals. +--- Note that the match will be shown, but the cursor will return to its +--- original position when no match is found and when pressing <Esc>. You +--- still need to finish the search command with <Enter> to move the +--- cursor to the match. +--- You can use the CTRL-G and CTRL-T keys to move to the next and +--- previous match. `c_CTRL-G` `c_CTRL-T` +--- Vim only searches for about half a second. With a complicated +--- pattern and/or a lot of text the match may not be found. This is to +--- avoid that Vim hangs while you are typing the pattern. +--- The `hl-IncSearch` highlight group determines the highlighting. +--- When 'hlsearch' is on, all matched strings are highlighted too while +--- typing a search command. See also: 'hlsearch'. +--- If you don't want to turn 'hlsearch' on, but want to highlight all +--- matches while searching, you can turn on and off 'hlsearch' with +--- autocmd. Example: +--- ``` +--- augroup vimrc-incsearch-highlight +--- autocmd! +--- autocmd CmdlineEnter /,\? :set hlsearch +--- autocmd CmdlineLeave /,\? :set nohlsearch +--- augroup END +--- ``` +--- +--- CTRL-L can be used to add one character from after the current match +--- to the command line. If 'ignorecase' and 'smartcase' are set and the +--- command line has no uppercase characters, the added character is +--- converted to lowercase. +--- CTRL-R CTRL-W can be used to add the word at the end of the current +--- match, excluding the characters that were already typed. +--- +--- @type boolean +vim.o.incsearch = true +vim.o.is = vim.o.incsearch +vim.go.incsearch = vim.o.incsearch +vim.go.is = vim.go.incsearch + +--- Expression which is evaluated to obtain the proper indent for a line. +--- It is used when a new line is created, for the `=` operator and +--- in Insert mode as specified with the 'indentkeys' option. +--- When this option is not empty, it overrules the 'cindent' and +--- 'smartindent' indenting. When 'lisp' is set, this option is +--- is only used when 'lispoptions' contains "expr:1". +--- The expression is evaluated with `v:lnum` set to the line number for +--- which the indent is to be computed. The cursor is also in this line +--- when the expression is evaluated (but it may be moved around). +--- +--- If the expression starts with s: or `<SID>`, then it is replaced with +--- the script ID (`local-function`). Example: +--- ``` +--- set indentexpr=s:MyIndentExpr() +--- set indentexpr=<SID>SomeIndentExpr() +--- ``` +--- Otherwise, the expression is evaluated in the context of the script +--- where the option was set, thus script-local items are available. +--- +--- The expression must return the number of spaces worth of indent. It +--- can return "-1" to keep the current indent (this means 'autoindent' is +--- used for the indent). +--- Functions useful for computing the indent are `indent()`, `cindent()` +--- and `lispindent()`. +--- The evaluation of the expression must not have side effects! It must +--- not change the text, jump to another window, etc. Afterwards the +--- cursor position is always restored, thus the cursor may be moved. +--- Normally this option would be set to call a function: +--- ``` +--- :set indentexpr=GetMyIndent() +--- ``` +--- Error messages will be suppressed, unless the 'debug' option contains +--- "msg". +--- See `indent-expression`. +--- +--- The expression will be evaluated in the `sandbox` when set from a +--- modeline, see `sandbox-option`. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- It is not allowed to change text or jump to another window while +--- evaluating 'indentexpr' `textlock`. +--- +--- @type string +vim.o.indentexpr = "" +vim.o.inde = vim.o.indentexpr +vim.bo.indentexpr = vim.o.indentexpr +vim.bo.inde = vim.bo.indentexpr + +--- A list of keys that, when typed in Insert mode, cause reindenting of +--- the current line. Only happens if 'indentexpr' isn't empty. +--- The format is identical to 'cinkeys', see `indentkeys-format`. +--- See `C-indenting` and `indent-expression`. +--- +--- @type string +vim.o.indentkeys = "0{,0},0),0],:,0#,!^F,o,O,e" +vim.o.indk = vim.o.indentkeys +vim.bo.indentkeys = vim.o.indentkeys +vim.bo.indk = vim.bo.indentkeys + +--- When doing keyword completion in insert mode `ins-completion`, and +--- 'ignorecase' is also on, the case of the match is adjusted depending +--- on the typed text. If the typed text contains a lowercase letter +--- where the match has an upper case letter, the completed part is made +--- lowercase. If the typed text has no lowercase letters and the match +--- has a lowercase letter where the typed text has an uppercase letter, +--- and there is a letter before it, the completed part is made uppercase. +--- With 'noinfercase' the match is used as-is. +--- +--- @type boolean +vim.o.infercase = false +vim.o.inf = vim.o.infercase +vim.bo.infercase = vim.o.infercase +vim.bo.inf = vim.bo.infercase + +--- The characters specified by this option are included in file names and +--- path names. Filenames are used for commands like "gf", "[i" and in +--- the tags file. It is also used for "\f" in a `pattern`. +--- Multi-byte characters 256 and above are always included, only the +--- characters up to 255 are specified with this option. +--- For UTF-8 the characters 0xa0 to 0xff are included as well. +--- Think twice before adding white space to this option. Although a +--- space may appear inside a file name, the effect will be that Vim +--- doesn't know where a file name starts or ends when doing completion. +--- It most likely works better without a space in 'isfname'. +--- +--- Note that on systems using a backslash as path separator, Vim tries to +--- do its best to make it work as you would expect. That is a bit +--- tricky, since Vi originally used the backslash to escape special +--- characters. Vim will not remove a backslash in front of a normal file +--- name character on these systems, but it will on Unix and alikes. The +--- '&' and '^' are not included by default, because these are special for +--- cmd.exe. +--- +--- The format of this option is a list of parts, separated with commas. +--- Each part can be a single character number or a range. A range is two +--- character numbers with '-' in between. A character number can be a +--- decimal number between 0 and 255 or the ASCII character itself (does +--- not work for digits). Example: +--- "_,-,128-140,#-43" (include '_' and '-' and the range +--- 128 to 140 and '#' to 43) +--- If a part starts with '^', the following character number or range +--- will be excluded from the option. The option is interpreted from left +--- to right. Put the excluded character after the range where it is +--- included. To include '^' itself use it as the last character of the +--- option or the end of a range. Example: +--- "^a-z,#,^" (exclude 'a' to 'z', include '#' and '^') +--- If the character is '@', all characters where isalpha() returns TRUE +--- are included. Normally these are the characters a to z and A to Z, +--- plus accented characters. To include '@' itself use "@-@". Examples: +--- "@,^a-z" All alphabetic characters, excluding lower +--- case ASCII letters. +--- "a-z,A-Z,@-@" All letters plus the '@' character. +--- A comma can be included by using it where a character number is +--- expected. Example: +--- "48-57,,,_" Digits, comma and underscore. +--- A comma can be excluded by prepending a '^'. Example: +--- " -~,^,,9" All characters from space to '~', excluding +--- comma, plus <Tab>. +--- See `option-backslash` about including spaces and backslashes. +--- +--- @type string +vim.o.isfname = "@,48-57,/,.,-,_,+,,,#,$,%,~,=" +vim.o.isf = vim.o.isfname +vim.go.isfname = vim.o.isfname +vim.go.isf = vim.go.isfname + +--- The characters given by this option are included in identifiers. +--- Identifiers are used in recognizing environment variables and after a +--- match of the 'define' option. It is also used for "\i" in a +--- `pattern`. See 'isfname' for a description of the format of this +--- option. For '@' only characters up to 255 are used. +--- Careful: If you change this option, it might break expanding +--- environment variables. E.g., when '/' is included and Vim tries to +--- expand "$HOME/.local/state/nvim/shada/main.shada". Maybe you should +--- change 'iskeyword' instead. +--- +--- @type string +vim.o.isident = "@,48-57,_,192-255" +vim.o.isi = vim.o.isident +vim.go.isident = vim.o.isident +vim.go.isi = vim.go.isident + +--- Keywords are used in searching and recognizing with many commands: +--- "w", "*", "[i", etc. It is also used for "\k" in a `pattern`. See +--- 'isfname' for a description of the format of this option. For '@' +--- characters above 255 check the "word" character class (any character +--- that is not white space or punctuation). +--- For C programs you could use "a-z,A-Z,48-57,_,.,-,>". +--- For a help file it is set to all non-blank printable characters except +--- "*", '"' and '|' (so that CTRL-] on a command finds the help for that +--- command). +--- When the 'lisp' option is on the '-' character is always included. +--- This option also influences syntax highlighting, unless the syntax +--- uses `:syn-iskeyword`. +--- +--- @type string +vim.o.iskeyword = "@,48-57,_,192-255" +vim.o.isk = vim.o.iskeyword +vim.bo.iskeyword = vim.o.iskeyword +vim.bo.isk = vim.bo.iskeyword + +--- The characters given by this option are displayed directly on the +--- screen. It is also used for "\p" in a `pattern`. The characters from +--- space (ASCII 32) to '~' (ASCII 126) are always displayed directly, +--- even when they are not included in 'isprint' or excluded. See +--- 'isfname' for a description of the format of this option. +--- +--- Non-printable characters are displayed with two characters: +--- 0 - 31 "^@" - "^_" +--- 32 - 126 always single characters +--- 127 "^?" +--- 128 - 159 "~@" - "~_" +--- 160 - 254 "| " - "|~" +--- 255 "~?" +--- Illegal bytes from 128 to 255 (invalid UTF-8) are +--- displayed as <xx>, with the hexadecimal value of the byte. +--- When 'display' contains "uhex" all unprintable characters are +--- displayed as <xx>. +--- The SpecialKey highlighting will be used for unprintable characters. +--- `hl-SpecialKey` +--- +--- Multi-byte characters 256 and above are always included, only the +--- characters up to 255 are specified with this option. When a character +--- is printable but it is not available in the current font, a +--- replacement character will be shown. +--- Unprintable and zero-width Unicode characters are displayed as <xxxx>. +--- There is no option to specify these characters. +--- +--- @type string +vim.o.isprint = "@,161-255" +vim.o.isp = vim.o.isprint +vim.go.isprint = vim.o.isprint +vim.go.isp = vim.go.isprint + +--- Insert two spaces after a '.', '?' and '!' with a join command. +--- Otherwise only one space is inserted. +--- +--- @type boolean +vim.o.joinspaces = false +vim.o.js = vim.o.joinspaces +vim.go.joinspaces = vim.o.joinspaces +vim.go.js = vim.go.joinspaces + +--- List of words that change the behavior of the `jumplist`. +--- stack Make the jumplist behave like the tagstack. +--- Relative location of entries in the jumplist is +--- preserved at the cost of discarding subsequent entries +--- when navigating backwards in the jumplist and then +--- jumping to a location. `jumplist-stack` +--- +--- view When moving through the jumplist, `changelist|, +--- |alternate-file` or using `mark-motions` try to +--- restore the `mark-view` in which the action occurred. +--- +--- @type string +vim.o.jumpoptions = "" +vim.o.jop = vim.o.jumpoptions +vim.go.jumpoptions = vim.o.jumpoptions +vim.go.jop = vim.go.jumpoptions + +--- Name of a keyboard mapping. See `mbyte-keymap`. +--- Setting this option to a valid keymap name has the side effect of +--- setting 'iminsert' to one, so that the keymap becomes effective. +--- 'imsearch' is also set to one, unless it was -1 +--- Only normal file name characters can be used, `/\*?[|<>` are illegal. +--- +--- @type string +vim.o.keymap = "" +vim.o.kmp = vim.o.keymap +vim.bo.keymap = vim.o.keymap +vim.bo.kmp = vim.bo.keymap + +--- List of comma-separated words, which enable special things that keys +--- can do. These values can be used: +--- startsel Using a shifted special key starts selection (either +--- Select mode or Visual mode, depending on "key" being +--- present in 'selectmode'). +--- stopsel Using a not-shifted special key stops selection. +--- Special keys in this context are the cursor keys, <End>, <Home>, +--- <PageUp> and <PageDown>. +--- +--- @type string +vim.o.keymodel = "" +vim.o.km = vim.o.keymodel +vim.go.keymodel = vim.o.keymodel +vim.go.km = vim.go.keymodel + +--- Program to use for the `K` command. Environment variables are +--- expanded `:set_env`. ":help" may be used to access the Vim internal +--- help. (Note that previously setting the global option to the empty +--- value did this, which is now deprecated.) +--- When the first character is ":", the command is invoked as a Vim +--- Ex command prefixed with [count]. +--- When "man" or "man -s" is used, Vim will automatically translate +--- a [count] for the "K" command to a section number. +--- See `option-backslash` about including spaces and backslashes. +--- Example: +--- ``` +--- :set keywordprg=man\ -s +--- :set keywordprg=:Man +--- ``` +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.keywordprg = ":Man" +vim.o.kp = vim.o.keywordprg +vim.bo.keywordprg = vim.o.keywordprg +vim.bo.kp = vim.bo.keywordprg +vim.go.keywordprg = vim.o.keywordprg +vim.go.kp = vim.go.keywordprg + +--- This option allows switching your keyboard into a special language +--- mode. When you are typing text in Insert mode the characters are +--- inserted directly. When in Normal mode the 'langmap' option takes +--- care of translating these special characters to the original meaning +--- of the key. This means you don't have to change the keyboard mode to +--- be able to execute Normal mode commands. +--- This is the opposite of the 'keymap' option, where characters are +--- mapped in Insert mode. +--- Also consider setting 'langremap' to off, to prevent 'langmap' from +--- applying to characters resulting from a mapping. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- Example (for Greek, in UTF-8): *greek* +--- ``` +--- :set langmap=ΑA,ΒB,ΨC,ΔD,ΕE,ΦF,ΓG,ΗH,ΙI,ΞJ,ΚK,ΛL,ΜM,ΝN,ΟO,ΠP,QQ,ΡR,ΣS,ΤT,ΘU,ΩV,WW,ΧX,ΥY,ΖZ,αa,βb,ψc,δd,εe,φf,γg,ηh,ιi,ξj,κk,λl,μm,νn,οo,πp,qq,ρr,σs,τt,θu,ωv,ςw,χx,υy,ζz +--- ``` +--- Example (exchanges meaning of z and y for commands): +--- ``` +--- :set langmap=zy,yz,ZY,YZ +--- ``` +--- +--- The 'langmap' option is a list of parts, separated with commas. Each +--- part can be in one of two forms: +--- 1. A list of pairs. Each pair is a "from" character immediately +--- followed by the "to" character. Examples: "aA", "aAbBcC". +--- 2. A list of "from" characters, a semi-colon and a list of "to" +--- characters. Example: "abc;ABC" +--- Example: "aA,fgh;FGH,cCdDeE" +--- Special characters need to be preceded with a backslash. These are +--- ";", ',', '"', '|' and backslash itself. +--- +--- This will allow you to activate vim actions without having to switch +--- back and forth between the languages. Your language characters will +--- be understood as normal vim English characters (according to the +--- langmap mappings) in the following cases: +--- o Normal/Visual mode (commands, buffer/register names, user mappings) +--- o Insert/Replace Mode: Register names after CTRL-R +--- o Insert/Replace Mode: Mappings +--- Characters entered in Command-line mode will NOT be affected by +--- this option. Note that this option can be changed at any time +--- allowing to switch between mappings for different languages/encodings. +--- Use a mapping to avoid having to type it each time! +--- +--- @type string +vim.o.langmap = "" +vim.o.lmap = vim.o.langmap +vim.go.langmap = vim.o.langmap +vim.go.lmap = vim.go.langmap + +--- Language to use for menu translation. Tells which file is loaded +--- from the "lang" directory in 'runtimepath': +--- ``` +--- "lang/menu_" .. &langmenu .. ".vim" +--- ``` +--- (without the spaces). For example, to always use the Dutch menus, no +--- matter what $LANG is set to: +--- ``` +--- :set langmenu=nl_NL.ISO_8859-1 +--- ``` +--- When 'langmenu' is empty, `v:lang` is used. +--- Only normal file name characters can be used, `/\*?[|<>` are illegal. +--- If your $LANG is set to a non-English language but you do want to use +--- the English menus: +--- ``` +--- :set langmenu=none +--- ``` +--- This option must be set before loading menus, switching on filetype +--- detection or syntax highlighting. Once the menus are defined setting +--- this option has no effect. But you could do this: +--- ``` +--- :source $VIMRUNTIME/delmenu.vim +--- :set langmenu=de_DE.ISO_8859-1 +--- :source $VIMRUNTIME/menu.vim +--- ``` +--- Warning: This deletes all menus that you defined yourself! +--- +--- @type string +vim.o.langmenu = "" +vim.o.lm = vim.o.langmenu +vim.go.langmenu = vim.o.langmenu +vim.go.lm = vim.go.langmenu + +--- When off, setting 'langmap' does not apply to characters resulting from +--- a mapping. If setting 'langmap' disables some of your mappings, make +--- sure this option is off. +--- +--- @type boolean +vim.o.langremap = false +vim.o.lrm = vim.o.langremap +vim.go.langremap = vim.o.langremap +vim.go.lrm = vim.go.langremap + +--- The value of this option influences when the last window will have a +--- status line: +--- 0: never +--- 1: only if there are at least two windows +--- 2: always +--- 3: always and ONLY the last window +--- The screen looks nicer with a status line if you have several +--- windows, but it takes another screen line. `status-line` +--- +--- @type integer +vim.o.laststatus = 2 +vim.o.ls = vim.o.laststatus +vim.go.laststatus = vim.o.laststatus +vim.go.ls = vim.go.laststatus + +--- When this option is set, the screen will not be redrawn while +--- executing macros, registers and other commands that have not been +--- typed. Also, updating the window title is postponed. To force an +--- update use `:redraw`. +--- This may occasionally cause display errors. It is only meant to be set +--- temporarily when performing an operation where redrawing may cause +--- flickering or cause a slow down. +--- +--- @type boolean +vim.o.lazyredraw = false +vim.o.lz = vim.o.lazyredraw +vim.go.lazyredraw = vim.o.lazyredraw +vim.go.lz = vim.go.lazyredraw + +--- If on, Vim will wrap long lines at a character in 'breakat' rather +--- than at the last character that fits on the screen. Unlike +--- 'wrapmargin' and 'textwidth', this does not insert <EOL>s in the file, +--- it only affects the way the file is displayed, not its contents. +--- If 'breakindent' is set, line is visually indented. Then, the value +--- of 'showbreak' is used to put in front of wrapped lines. This option +--- is not used when the 'wrap' option is off. +--- Note that <Tab> characters after an <EOL> are mostly not displayed +--- with the right amount of white space. +--- +--- @type boolean +vim.o.linebreak = false +vim.o.lbr = vim.o.linebreak +vim.wo.linebreak = vim.o.linebreak +vim.wo.lbr = vim.wo.linebreak + +--- Number of lines of the Vim window. +--- Normally you don't need to set this. It is done automatically by the +--- terminal initialization code. +--- When Vim is running in the GUI or in a resizable window, setting this +--- option will cause the window size to be changed. When you only want +--- to use the size for the GUI, put the command in your `gvimrc` file. +--- Vim limits the number of lines to what fits on the screen. You can +--- use this command to get the tallest window possible: +--- ``` +--- :set lines=999 +--- ``` +--- Minimum value is 2, maximum value is 1000. +--- +--- @type integer +vim.o.lines = 24 +vim.go.lines = vim.o.lines + +--- only in the GUI +--- Number of pixel lines inserted between characters. Useful if the font +--- uses the full character cell height, making lines touch each other. +--- When non-zero there is room for underlining. +--- With some fonts there can be too much room between lines (to have +--- space for ascents and descents). Then it makes sense to set +--- 'linespace' to a negative value. This may cause display problems +--- though! +--- +--- @type integer +vim.o.linespace = 0 +vim.o.lsp = vim.o.linespace +vim.go.linespace = vim.o.linespace +vim.go.lsp = vim.go.linespace + +--- Lisp mode: When <Enter> is typed in insert mode set the indent for +--- the next line to Lisp standards (well, sort of). Also happens with +--- "cc" or "S". 'autoindent' must also be on for this to work. The 'p' +--- flag in 'cpoptions' changes the method of indenting: Vi compatible or +--- better. Also see 'lispwords'. +--- The '-' character is included in keyword characters. Redefines the +--- "=" operator to use this same indentation algorithm rather than +--- calling an external program if 'equalprg' is empty. +--- +--- @type boolean +vim.o.lisp = false +vim.bo.lisp = vim.o.lisp + +--- Comma-separated list of items that influence the Lisp indenting when +--- enabled with the `'lisp'` option. Currently only one item is +--- supported: +--- expr:1 use 'indentexpr' for Lisp indenting when it is set +--- expr:0 do not use 'indentexpr' for Lisp indenting (default) +--- Note that when using 'indentexpr' the `=` operator indents all the +--- lines, otherwise the first line is not indented (Vi-compatible). +--- +--- @type string +vim.o.lispoptions = "" +vim.o.lop = vim.o.lispoptions +vim.bo.lispoptions = vim.o.lispoptions +vim.bo.lop = vim.bo.lispoptions + +--- Comma-separated list of words that influence the Lisp indenting when +--- enabled with the `'lisp'` option. +--- +--- @type string +vim.o.lispwords = "defun,define,defmacro,set!,lambda,if,case,let,flet,let*,letrec,do,do*,define-syntax,let-syntax,letrec-syntax,destructuring-bind,defpackage,defparameter,defstruct,deftype,defvar,do-all-symbols,do-external-symbols,do-symbols,dolist,dotimes,ecase,etypecase,eval-when,labels,macrolet,multiple-value-bind,multiple-value-call,multiple-value-prog1,multiple-value-setq,prog1,progv,typecase,unless,unwind-protect,when,with-input-from-string,with-open-file,with-open-stream,with-output-to-string,with-package-iterator,define-condition,handler-bind,handler-case,restart-bind,restart-case,with-simple-restart,store-value,use-value,muffle-warning,abort,continue,with-slots,with-slots*,with-accessors,with-accessors*,defclass,defmethod,print-unreadable-object" +vim.o.lw = vim.o.lispwords +vim.bo.lispwords = vim.o.lispwords +vim.bo.lw = vim.bo.lispwords +vim.go.lispwords = vim.o.lispwords +vim.go.lw = vim.go.lispwords + +--- List mode: By default, show tabs as ">", trailing spaces as "-", and +--- non-breakable space characters as "+". Useful to see the difference +--- between tabs and spaces and for trailing blanks. Further changed by +--- the 'listchars' option. +--- +--- The cursor is displayed at the start of the space a Tab character +--- occupies, not at the end as usual in Normal mode. To get this cursor +--- position while displaying Tabs with spaces, use: +--- ``` +--- :set list lcs=tab:\ \ +--- ``` +--- +--- Note that list mode will also affect formatting (set with 'textwidth' +--- or 'wrapmargin') when 'cpoptions' includes 'L'. See 'listchars' for +--- changing the way tabs are displayed. +--- +--- @type boolean +vim.o.list = false +vim.wo.list = vim.o.list + +--- Strings to use in 'list' mode and for the `:list` command. It is a +--- comma-separated list of string settings. +--- +--- *lcs-eol* +--- eol:c Character to show at the end of each line. When +--- omitted, there is no extra character at the end of the +--- line. +--- *lcs-tab* +--- tab:xy[z] Two or three characters to be used to show a tab. +--- The third character is optional. +--- +--- tab:xy The 'x' is always used, then 'y' as many times as will +--- fit. Thus "tab:>-" displays: +--- ``` +--- +--- ``` +--- >- +--- >-- +--- etc. +--- ``` +--- +--- tab:xyz The 'z' is always used, then 'x' is prepended, and +--- then 'y' is used as many times as will fit. Thus +--- "tab:<->" displays: +--- ``` +--- +--- ``` +--- <> +--- <-> +--- <--> +--- etc. +--- ``` +--- +--- When "tab:" is omitted, a tab is shown as ^I. +--- *lcs-space* +--- space:c Character to show for a space. When omitted, spaces +--- are left blank. +--- *lcs-multispace* +--- multispace:c... +--- One or more characters to use cyclically to show for +--- multiple consecutive spaces. Overrides the "space" +--- setting, except for single spaces. When omitted, the +--- "space" setting is used. For example, +--- `:set listchars=multispace:---+` shows ten consecutive +--- spaces as: +--- ``` +--- ---+---+-- +--- ``` +--- +--- *lcs-lead* +--- lead:c Character to show for leading spaces. When omitted, +--- leading spaces are blank. Overrides the "space" and +--- "multispace" settings for leading spaces. You can +--- combine it with "tab:", for example: +--- ``` +--- :set listchars+=tab:>-,lead:. +--- ``` +--- +--- *lcs-leadmultispace* +--- leadmultispace:c... +--- Like the `lcs-multispace` value, but for leading +--- spaces only. Also overrides `lcs-lead` for leading +--- multiple spaces. +--- `:set listchars=leadmultispace:---+` shows ten +--- consecutive leading spaces as: +--- ``` +--- ---+---+--XXX +--- ``` +--- +--- Where "XXX" denotes the first non-blank characters in +--- the line. +--- *lcs-trail* +--- trail:c Character to show for trailing spaces. When omitted, +--- trailing spaces are blank. Overrides the "space" and +--- "multispace" settings for trailing spaces. +--- *lcs-extends* +--- extends:c Character to show in the last column, when 'wrap' is +--- off and the line continues beyond the right of the +--- screen. +--- *lcs-precedes* +--- precedes:c Character to show in the first visible column of the +--- physical line, when there is text preceding the +--- character visible in the first column. +--- *lcs-conceal* +--- conceal:c Character to show in place of concealed text, when +--- 'conceallevel' is set to 1. A space when omitted. +--- *lcs-nbsp* +--- nbsp:c Character to show for a non-breakable space character +--- (0xA0 (160 decimal) and U+202F). Left blank when +--- omitted. +--- +--- The characters ':' and ',' should not be used. UTF-8 characters can +--- be used. All characters must be single width. +--- +--- Each character can be specified as hex: +--- ``` +--- set listchars=eol:\\x24 +--- set listchars=eol:\\u21b5 +--- set listchars=eol:\\U000021b5 +--- ``` +--- Note that a double backslash is used. The number of hex characters +--- must be exactly 2 for \\x, 4 for \\u and 8 for \\U. +--- +--- Examples: +--- ``` +--- :set lcs=tab:>-,trail:- +--- :set lcs=tab:>-,eol:<,nbsp:% +--- :set lcs=extends:>,precedes:< +--- ``` +--- `hl-NonText` highlighting will be used for "eol", "extends" and +--- "precedes". `hl-Whitespace` for "nbsp", "space", "tab", "multispace", +--- "lead" and "trail". +--- +--- @type string +vim.o.listchars = "tab:> ,trail:-,nbsp:+" +vim.o.lcs = vim.o.listchars +vim.wo.listchars = vim.o.listchars +vim.wo.lcs = vim.wo.listchars +vim.go.listchars = vim.o.listchars +vim.go.lcs = vim.go.listchars + +--- When on the plugin scripts are loaded when starting up `load-plugins`. +--- This option can be reset in your `vimrc` file to disable the loading +--- of plugins. +--- Note that using the "-u NONE" and "--noplugin" command line arguments +--- reset this option. `-u` `--noplugin` +--- +--- @type boolean +vim.o.loadplugins = true +vim.o.lpl = vim.o.loadplugins +vim.go.loadplugins = vim.o.loadplugins +vim.go.lpl = vim.go.loadplugins + +--- Changes the special characters that can be used in search patterns. +--- See `pattern`. +--- WARNING: Switching this option off most likely breaks plugins! That +--- is because many patterns assume it's on and will fail when it's off. +--- Only switch it off when working with old Vi scripts. In any other +--- situation write patterns that work when 'magic' is on. Include "\M" +--- when you want to `/\M`. +--- +--- @type boolean +vim.o.magic = true +vim.go.magic = vim.o.magic + +--- Name of the errorfile for the `:make` command (see `:make_makeprg`) +--- and the `:grep` command. +--- When it is empty, an internally generated temp file will be used. +--- When "##" is included, it is replaced by a number to make the name +--- unique. This makes sure that the ":make" command doesn't overwrite an +--- existing file. +--- NOT used for the ":cf" command. See 'errorfile' for that. +--- Environment variables are expanded `:set_env`. +--- See `option-backslash` about including spaces and backslashes. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.makeef = "" +vim.o.mef = vim.o.makeef +vim.go.makeef = vim.o.makeef +vim.go.mef = vim.go.makeef + +--- Encoding used for reading the output of external commands. When empty, +--- encoding is not converted. +--- This is used for `:make`, `:lmake`, `:grep`, `:lgrep`, `:grepadd`, +--- `:lgrepadd`, `:cfile`, `:cgetfile`, `:caddfile`, `:lfile`, `:lgetfile`, +--- and `:laddfile`. +--- +--- This would be mostly useful when you use MS-Windows. If iconv is +--- enabled, setting 'makeencoding' to "char" has the same effect as +--- setting to the system locale encoding. Example: +--- ``` +--- :set makeencoding=char " system locale is used +--- ``` +--- +--- +--- @type string +vim.o.makeencoding = "" +vim.o.menc = vim.o.makeencoding +vim.bo.makeencoding = vim.o.makeencoding +vim.bo.menc = vim.bo.makeencoding +vim.go.makeencoding = vim.o.makeencoding +vim.go.menc = vim.go.makeencoding + +--- Program to use for the ":make" command. See `:make_makeprg`. +--- This option may contain '%' and '#' characters (see `:_%` and `:_#`), +--- which are expanded to the current and alternate file name. Use `::S` +--- to escape file names in case they contain special characters. +--- Environment variables are expanded `:set_env`. See `option-backslash` +--- about including spaces and backslashes. +--- Note that a '|' must be escaped twice: once for ":set" and once for +--- the interpretation of a command. When you use a filter called +--- "myfilter" do it like this: +--- ``` +--- :set makeprg=gmake\ \\\|\ myfilter +--- ``` +--- The placeholder "$*" can be given (even multiple times) to specify +--- where the arguments will be included, for example: +--- ``` +--- :set makeprg=latex\ \\\\nonstopmode\ \\\\input\\{$*} +--- ``` +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.makeprg = "make" +vim.o.mp = vim.o.makeprg +vim.bo.makeprg = vim.o.makeprg +vim.bo.mp = vim.bo.makeprg +vim.go.makeprg = vim.o.makeprg +vim.go.mp = vim.go.makeprg + +--- Characters that form pairs. The `%` command jumps from one to the +--- other. +--- Only character pairs are allowed that are different, thus you cannot +--- jump between two double quotes. +--- The characters must be separated by a colon. +--- The pairs must be separated by a comma. Example for including '<' and +--- '>' (for HTML): +--- ``` +--- :set mps+=<:> +--- ``` +--- A more exotic example, to jump between the '=' and ';' in an +--- assignment, useful for languages like C and Java: +--- ``` +--- :au FileType c,cpp,java set mps+==:; +--- ``` +--- For a more advanced way of using "%", see the matchit.vim plugin in +--- the $VIMRUNTIME/plugin directory. `add-local-help` +--- +--- @type string +vim.o.matchpairs = "(:),{:},[:]" +vim.o.mps = vim.o.matchpairs +vim.bo.matchpairs = vim.o.matchpairs +vim.bo.mps = vim.bo.matchpairs + +--- Tenths of a second to show the matching paren, when 'showmatch' is +--- set. Note that this is not in milliseconds, like other options that +--- set a time. This is to be compatible with Nvi. +--- +--- @type integer +vim.o.matchtime = 5 +vim.o.mat = vim.o.matchtime +vim.go.matchtime = vim.o.matchtime +vim.go.mat = vim.go.matchtime + +--- Maximum depth of function calls for user functions. This normally +--- catches endless recursion. When using a recursive function with +--- more depth, set 'maxfuncdepth' to a bigger number. But this will use +--- more memory, there is the danger of failing when memory is exhausted. +--- Increasing this limit above 200 also changes the maximum for Ex +--- command recursion, see `E169`. +--- See also `:function`. +--- +--- @type integer +vim.o.maxfuncdepth = 100 +vim.o.mfd = vim.o.maxfuncdepth +vim.go.maxfuncdepth = vim.o.maxfuncdepth +vim.go.mfd = vim.go.maxfuncdepth + +--- Maximum number of times a mapping is done without resulting in a +--- character to be used. This normally catches endless mappings, like +--- ":map x y" with ":map y x". It still does not catch ":map g wg", +--- because the 'w' is used before the next mapping is done. See also +--- `key-mapping`. +--- +--- @type integer +vim.o.maxmapdepth = 1000 +vim.o.mmd = vim.o.maxmapdepth +vim.go.maxmapdepth = vim.o.maxmapdepth +vim.go.mmd = vim.go.maxmapdepth + +--- Maximum amount of memory (in Kbyte) to use for pattern matching. +--- The maximum value is about 2000000. Use this to work without a limit. +--- *E363* +--- When Vim runs into the limit it gives an error message and mostly +--- behaves like CTRL-C was typed. +--- Running into the limit often means that the pattern is very +--- inefficient or too complex. This may already happen with the pattern +--- "\(.\)*" on a very long line. ".*" works much better. +--- Might also happen on redraw, when syntax rules try to match a complex +--- text structure. +--- Vim may run out of memory before hitting the 'maxmempattern' limit, in +--- which case you get an "Out of memory" error instead. +--- +--- @type integer +vim.o.maxmempattern = 1000 +vim.o.mmp = vim.o.maxmempattern +vim.go.maxmempattern = vim.o.maxmempattern +vim.go.mmp = vim.go.maxmempattern + +--- Maximum number of items to use in a menu. Used for menus that are +--- generated from a list of items, e.g., the Buffers menu. Changing this +--- option has no direct effect, the menu must be refreshed first. +--- +--- @type integer +vim.o.menuitems = 25 +vim.o.mis = vim.o.menuitems +vim.go.menuitems = vim.o.menuitems +vim.go.mis = vim.go.menuitems + +--- Parameters for `:mkspell`. This tunes when to start compressing the +--- word tree. Compression can be slow when there are many words, but +--- it's needed to avoid running out of memory. The amount of memory used +--- per word depends very much on how similar the words are, that's why +--- this tuning is complicated. +--- +--- There are three numbers, separated by commas: +--- ``` +--- {start},{inc},{added} +--- ``` +--- +--- For most languages the uncompressed word tree fits in memory. {start} +--- gives the amount of memory in Kbyte that can be used before any +--- compression is done. It should be a bit smaller than the amount of +--- memory that is available to Vim. +--- +--- When going over the {start} limit the {inc} number specifies the +--- amount of memory in Kbyte that can be allocated before another +--- compression is done. A low number means compression is done after +--- less words are added, which is slow. A high number means more memory +--- will be allocated. +--- +--- After doing compression, {added} times 1024 words can be added before +--- the {inc} limit is ignored and compression is done when any extra +--- amount of memory is needed. A low number means there is a smaller +--- chance of hitting the {inc} limit, less memory is used but it's +--- slower. +--- +--- The languages for which these numbers are important are Italian and +--- Hungarian. The default works for when you have about 512 Mbyte. If +--- you have 1 Gbyte you could use: +--- ``` +--- :set mkspellmem=900000,3000,800 +--- ``` +--- If you have less than 512 Mbyte `:mkspell` may fail for some +--- languages, no matter what you set 'mkspellmem' to. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.mkspellmem = "460000,2000,500" +vim.o.msm = vim.o.mkspellmem +vim.go.mkspellmem = vim.o.mkspellmem +vim.go.msm = vim.go.mkspellmem + +--- If 'modeline' is on 'modelines' gives the number of lines that is +--- checked for set commands. If 'modeline' is off or 'modelines' is zero +--- no lines are checked. See `modeline`. +--- +--- @type boolean +vim.o.modeline = true +vim.o.ml = vim.o.modeline +vim.bo.modeline = vim.o.modeline +vim.bo.ml = vim.bo.modeline + +--- When on allow some options that are an expression to be set in the +--- modeline. Check the option for whether it is affected by +--- 'modelineexpr'. Also see `modeline`. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type boolean +vim.o.modelineexpr = false +vim.o.mle = vim.o.modelineexpr +vim.go.modelineexpr = vim.o.modelineexpr +vim.go.mle = vim.go.modelineexpr + +--- If 'modeline' is on 'modelines' gives the number of lines that is +--- checked for set commands. If 'modeline' is off or 'modelines' is zero +--- no lines are checked. See `modeline`. +--- +--- +--- @type integer +vim.o.modelines = 5 +vim.o.mls = vim.o.modelines +vim.go.modelines = vim.o.modelines +vim.go.mls = vim.go.modelines + +--- When off the buffer contents cannot be changed. The 'fileformat' and +--- 'fileencoding' options also can't be changed. +--- Can be reset on startup with the `-M` command line argument. +--- +--- @type boolean +vim.o.modifiable = true +vim.o.ma = vim.o.modifiable +vim.bo.modifiable = vim.o.modifiable +vim.bo.ma = vim.bo.modifiable + +--- When on, the buffer is considered to be modified. This option is set +--- when: +--- 1. A change was made to the text since it was last written. Using the +--- `undo` command to go back to the original text will reset the +--- option. But undoing changes that were made before writing the +--- buffer will set the option again, since the text is different from +--- when it was written. +--- 2. 'fileformat' or 'fileencoding' is different from its original +--- value. The original value is set when the buffer is read or +--- written. A ":set nomodified" command also resets the original +--- values to the current values and the 'modified' option will be +--- reset. +--- Similarly for 'eol' and 'bomb'. +--- This option is not set when a change is made to the buffer as the +--- result of a BufNewFile, BufRead/BufReadPost, BufWritePost, +--- FileAppendPost or VimLeave autocommand event. See `gzip-example` for +--- an explanation. +--- When 'buftype' is "nowrite" or "nofile" this option may be set, but +--- will be ignored. +--- Note that the text may actually be the same, e.g. 'modified' is set +--- when using "rA" on an "A". +--- +--- @type boolean +vim.o.modified = false +vim.o.mod = vim.o.modified +vim.bo.modified = vim.o.modified +vim.bo.mod = vim.bo.modified + +--- When on, listings pause when the whole screen is filled. You will get +--- the `more-prompt`. When this option is off there are no pauses, the +--- listing continues until finished. +--- +--- @type boolean +vim.o.more = true +vim.go.more = vim.o.more + +--- Enables mouse support. For example, to enable the mouse in Normal mode +--- and Visual mode: +--- ``` +--- :set mouse=nv +--- ``` +--- +--- To temporarily disable mouse support, hold the shift key while using +--- the mouse. +--- +--- Mouse support can be enabled for different modes: +--- n Normal mode +--- v Visual mode +--- i Insert mode +--- c Command-line mode +--- h all previous modes when editing a help file +--- a all previous modes +--- r for `hit-enter` and `more-prompt` prompt +--- +--- Left-click anywhere in a text buffer to place the cursor there. This +--- works with operators too, e.g. type `d` then left-click to delete text +--- from the current cursor position to the position where you clicked. +--- +--- Drag the `status-line` or vertical separator of a window to resize it. +--- +--- If enabled for "v" (Visual mode) then double-click selects word-wise, +--- triple-click makes it line-wise, and quadruple-click makes it +--- rectangular block-wise. +--- +--- For scrolling with a mouse wheel see `scroll-mouse-wheel`. +--- +--- Note: When enabling the mouse in a terminal, copy/paste will use the +--- "* register if possible. See also 'clipboard'. +--- +--- Related options: +--- 'mousefocus' window focus follows mouse pointer +--- 'mousemodel' what mouse button does which action +--- 'mousehide' hide mouse pointer while typing text +--- 'selectmode' whether to start Select mode or Visual mode +--- +--- @type string +vim.o.mouse = "nvi" +vim.go.mouse = vim.o.mouse + +--- The window that the mouse pointer is on is automatically activated. +--- When changing the window layout or window focus in another way, the +--- mouse pointer is moved to the window with keyboard focus. Off is the +--- default because it makes using the pull down menus a little goofy, as +--- a pointer transit may activate a window unintentionally. +--- +--- @type boolean +vim.o.mousefocus = false +vim.o.mousef = vim.o.mousefocus +vim.go.mousefocus = vim.o.mousefocus +vim.go.mousef = vim.go.mousefocus + +--- only in the GUI +--- When on, the mouse pointer is hidden when characters are typed. +--- The mouse pointer is restored when the mouse is moved. +--- +--- @type boolean +vim.o.mousehide = true +vim.o.mh = vim.o.mousehide +vim.go.mousehide = vim.o.mousehide +vim.go.mh = vim.go.mousehide + +--- Sets the model to use for the mouse. The name mostly specifies what +--- the right mouse button is used for: +--- extend Right mouse button extends a selection. This works +--- like in an xterm. +--- popup Right mouse button pops up a menu. The shifted left +--- mouse button extends a selection. This works like +--- with Microsoft Windows. +--- popup_setpos Like "popup", but the cursor will be moved to the +--- position where the mouse was clicked, and thus the +--- selected operation will act upon the clicked object. +--- If clicking inside a selection, that selection will +--- be acted upon, i.e. no cursor move. This implies of +--- course, that right clicking outside a selection will +--- end Visual mode. +--- Overview of what button does what for each model: +--- mouse extend popup(_setpos) ~ +--- left click place cursor place cursor +--- left drag start selection start selection +--- shift-left search word extend selection +--- right click extend selection popup menu (place cursor) +--- right drag extend selection - +--- middle click paste paste +--- +--- In the "popup" model the right mouse button produces a pop-up menu. +--- Nvim creates a default `popup-menu` but you can redefine it. +--- +--- Note that you can further refine the meaning of buttons with mappings. +--- See `mouse-overview`. But mappings are NOT used for modeless selection. +--- +--- Example: +--- ``` +--- :map <S-LeftMouse> <RightMouse> +--- :map <S-LeftDrag> <RightDrag> +--- :map <S-LeftRelease> <RightRelease> +--- :map <2-S-LeftMouse> <2-RightMouse> +--- :map <2-S-LeftDrag> <2-RightDrag> +--- :map <2-S-LeftRelease> <2-RightRelease> +--- :map <3-S-LeftMouse> <3-RightMouse> +--- :map <3-S-LeftDrag> <3-RightDrag> +--- :map <3-S-LeftRelease> <3-RightRelease> +--- :map <4-S-LeftMouse> <4-RightMouse> +--- :map <4-S-LeftDrag> <4-RightDrag> +--- :map <4-S-LeftRelease> <4-RightRelease> +--- ``` +--- +--- Mouse commands requiring the CTRL modifier can be simulated by typing +--- the "g" key before using the mouse: +--- "g<LeftMouse>" is "<C-LeftMouse> (jump to tag under mouse click) +--- "g<RightMouse>" is "<C-RightMouse> ("CTRL-T") +--- +--- @type string +vim.o.mousemodel = "popup_setpos" +vim.o.mousem = vim.o.mousemodel +vim.go.mousemodel = vim.o.mousemodel +vim.go.mousem = vim.go.mousemodel + +--- When on, mouse move events are delivered to the input queue and are +--- available for mapping. The default, off, avoids the mouse movement +--- overhead except when needed. +--- Warning: Setting this option can make pending mappings to be aborted +--- when the mouse is moved. +--- +--- @type boolean +vim.o.mousemoveevent = false +vim.o.mousemev = vim.o.mousemoveevent +vim.go.mousemoveevent = vim.o.mousemoveevent +vim.go.mousemev = vim.go.mousemoveevent + +--- This option controls the number of lines / columns to scroll by when +--- scrolling with a mouse wheel (`scroll-mouse-wheel`). The option is +--- a comma-separated list. Each part consists of a direction and a count +--- as follows: +--- direction:count,direction:count +--- Direction is one of either "hor" or "ver". "hor" controls horizontal +--- scrolling and "ver" controls vertical scrolling. Count sets the amount +--- to scroll by for the given direction, it should be a non negative +--- integer. Each direction should be set at most once. If a direction +--- is omitted, a default value is used (6 for horizontal scrolling and 3 +--- for vertical scrolling). You can disable mouse scrolling by using +--- a count of 0. +--- +--- Example: +--- ``` +--- :set mousescroll=ver:5,hor:2 +--- ``` +--- Will make Nvim scroll 5 lines at a time when scrolling vertically, and +--- scroll 2 columns at a time when scrolling horizontally. +--- +--- @type string +vim.o.mousescroll = "ver:3,hor:6" +vim.go.mousescroll = vim.o.mousescroll + +--- This option tells Vim what the mouse pointer should look like in +--- different modes. The option is a comma-separated list of parts, much +--- like used for 'guicursor'. Each part consist of a mode/location-list +--- and an argument-list: +--- mode-list:shape,mode-list:shape,.. +--- The mode-list is a dash separated list of these modes/locations: +--- In a normal window: ~ +--- n Normal mode +--- v Visual mode +--- ve Visual mode with 'selection' "exclusive" (same as 'v', +--- if not specified) +--- o Operator-pending mode +--- i Insert mode +--- r Replace mode +--- +--- Others: ~ +--- c appending to the command-line +--- ci inserting in the command-line +--- cr replacing in the command-line +--- m at the 'Hit ENTER' or 'More' prompts +--- ml idem, but cursor in the last line +--- e any mode, pointer below last window +--- s any mode, pointer on a status line +--- sd any mode, while dragging a status line +--- vs any mode, pointer on a vertical separator line +--- vd any mode, while dragging a vertical separator line +--- a everywhere +--- +--- The shape is one of the following: +--- avail name looks like ~ +--- w x arrow Normal mouse pointer +--- w x blank no pointer at all (use with care!) +--- w x beam I-beam +--- w x updown up-down sizing arrows +--- w x leftright left-right sizing arrows +--- w x busy The system's usual busy pointer +--- w x no The system's usual "no input" pointer +--- x udsizing indicates up-down resizing +--- x lrsizing indicates left-right resizing +--- x crosshair like a big thin + +--- x hand1 black hand +--- x hand2 white hand +--- x pencil what you write with +--- x question big ? +--- x rightup-arrow arrow pointing right-up +--- w x up-arrow arrow pointing up +--- x <number> any X11 pointer number (see X11/cursorfont.h) +--- +--- The "avail" column contains a 'w' if the shape is available for Win32, +--- x for X11. +--- Any modes not specified or shapes not available use the normal mouse +--- pointer. +--- +--- Example: +--- ``` +--- :set mouseshape=s:udsizing,m:no +--- ``` +--- will make the mouse turn to a sizing arrow over the status lines and +--- indicate no input when the hit-enter prompt is displayed (since +--- clicking the mouse has no effect in this state.) +--- +--- @type string +vim.o.mouseshape = "" +vim.o.mouses = vim.o.mouseshape +vim.go.mouseshape = vim.o.mouseshape +vim.go.mouses = vim.go.mouseshape + +--- Defines the maximum time in msec between two mouse clicks for the +--- second click to be recognized as a multi click. +--- +--- @type integer +vim.o.mousetime = 500 +vim.o.mouset = vim.o.mousetime +vim.go.mousetime = vim.o.mousetime +vim.go.mouset = vim.go.mousetime + +--- This defines what bases Vim will consider for numbers when using the +--- CTRL-A and CTRL-X commands for adding to and subtracting from a number +--- respectively; see `CTRL-A` for more info on these commands. +--- alpha If included, single alphabetical characters will be +--- incremented or decremented. This is useful for a list with a +--- letter index a), b), etc. *octal-nrformats* +--- octal If included, numbers that start with a zero will be considered +--- to be octal. Example: Using CTRL-A on "007" results in "010". +--- hex If included, numbers starting with "0x" or "0X" will be +--- considered to be hexadecimal. Example: Using CTRL-X on +--- "0x100" results in "0x0ff". +--- bin If included, numbers starting with "0b" or "0B" will be +--- considered to be binary. Example: Using CTRL-X on +--- "0b1000" subtracts one, resulting in "0b0111". +--- unsigned If included, numbers are recognized as unsigned. Thus a +--- leading dash or negative sign won't be considered as part of +--- the number. Examples: +--- Using CTRL-X on "2020" in "9-2020" results in "9-2019" +--- (without "unsigned" it would become "9-2021"). +--- Using CTRL-A on "2020" in "9-2020" results in "9-2021" +--- (without "unsigned" it would become "9-2019"). +--- Using CTRL-X on "0" or CTRL-A on "18446744073709551615" +--- (2^64 - 1) has no effect, overflow is prevented. +--- Numbers which simply begin with a digit in the range 1-9 are always +--- considered decimal. This also happens for numbers that are not +--- recognized as octal or hex. +--- +--- @type string +vim.o.nrformats = "bin,hex" +vim.o.nf = vim.o.nrformats +vim.bo.nrformats = vim.o.nrformats +vim.bo.nf = vim.bo.nrformats + +--- Print the line number in front of each line. When the 'n' option is +--- excluded from 'cpoptions' a wrapped line will not use the column of +--- line numbers. +--- Use the 'numberwidth' option to adjust the room for the line number. +--- When a long, wrapped line doesn't start with the first character, '-' +--- characters are put before the number. +--- For highlighting see `hl-LineNr`, `hl-CursorLineNr`, and the +--- `:sign-define` "numhl" argument. +--- *number_relativenumber* +--- The 'relativenumber' option changes the displayed number to be +--- relative to the cursor. Together with 'number' there are these +--- four combinations (cursor in line 3): +--- +--- 'nonu' 'nu' 'nonu' 'nu' +--- 'nornu' 'nornu' 'rnu' 'rnu' +--- ``` +--- |apple | 1 apple | 2 apple | 2 apple +--- |pear | 2 pear | 1 pear | 1 pear +--- |nobody | 3 nobody | 0 nobody |3 nobody +--- |there | 4 there | 1 there | 1 there +--- ``` +--- +--- +--- @type boolean +vim.o.number = false +vim.o.nu = vim.o.number +vim.wo.number = vim.o.number +vim.wo.nu = vim.wo.number + +--- Minimal number of columns to use for the line number. Only relevant +--- when the 'number' or 'relativenumber' option is set or printing lines +--- with a line number. Since one space is always between the number and +--- the text, there is one less character for the number itself. +--- The value is the minimum width. A bigger width is used when needed to +--- fit the highest line number in the buffer respectively the number of +--- rows in the window, depending on whether 'number' or 'relativenumber' +--- is set. Thus with the Vim default of 4 there is room for a line number +--- up to 999. When the buffer has 1000 lines five columns will be used. +--- The minimum value is 1, the maximum value is 20. +--- +--- @type integer +vim.o.numberwidth = 4 +vim.o.nuw = vim.o.numberwidth +vim.wo.numberwidth = vim.o.numberwidth +vim.wo.nuw = vim.wo.numberwidth + +--- This option specifies a function to be used for Insert mode omni +--- completion with CTRL-X CTRL-O. `i_CTRL-X_CTRL-O` +--- See `complete-functions` for an explanation of how the function is +--- invoked and what it should return. The value can be the name of a +--- function, a `lambda` or a `Funcref`. See `option-value-function` for +--- more information. +--- This option is usually set by a filetype plugin: +--- `:filetype-plugin-on` +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.omnifunc = "" +vim.o.ofu = vim.o.omnifunc +vim.bo.omnifunc = vim.o.omnifunc +vim.bo.ofu = vim.bo.omnifunc + +--- only for Windows +--- Enable reading and writing from devices. This may get Vim stuck on a +--- device that can be opened but doesn't actually do the I/O. Therefore +--- it is off by default. +--- Note that on Windows editing "aux.h", "lpt1.txt" and the like also +--- result in editing a device. +--- +--- @type boolean +vim.o.opendevice = false +vim.o.odev = vim.o.opendevice +vim.go.opendevice = vim.o.opendevice +vim.go.odev = vim.go.opendevice + +--- This option specifies a function to be called by the `g@` operator. +--- See `:map-operator` for more info and an example. The value can be +--- the name of a function, a `lambda` or a `Funcref`. See +--- `option-value-function` for more information. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.operatorfunc = "" +vim.o.opfunc = vim.o.operatorfunc +vim.go.operatorfunc = vim.o.operatorfunc +vim.go.opfunc = vim.go.operatorfunc + +--- Directories used to find packages. +--- See `packages` and `packages-runtimepath`. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.packpath = "..." +vim.o.pp = vim.o.packpath +vim.go.packpath = vim.o.packpath +vim.go.pp = vim.go.packpath + +--- Specifies the nroff macros that separate paragraphs. These are pairs +--- of two letters (see `object-motions`). +--- +--- @type string +vim.o.paragraphs = "IPLPPPQPP TPHPLIPpLpItpplpipbp" +vim.o.para = vim.o.paragraphs +vim.go.paragraphs = vim.o.paragraphs +vim.go.para = vim.go.paragraphs + +--- Expression which is evaluated to apply a patch to a file and generate +--- the resulting new version of the file. See `diff-patchexpr`. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.patchexpr = "" +vim.o.pex = vim.o.patchexpr +vim.go.patchexpr = vim.o.patchexpr +vim.go.pex = vim.go.patchexpr + +--- When non-empty the oldest version of a file is kept. This can be used +--- to keep the original version of a file if you are changing files in a +--- source distribution. Only the first time that a file is written a +--- copy of the original file will be kept. The name of the copy is the +--- name of the original file with the string in the 'patchmode' option +--- appended. This option should start with a dot. Use a string like +--- ".orig" or ".org". 'backupdir' must not be empty for this to work +--- (Detail: The backup file is renamed to the patchmode file after the +--- new file has been successfully written, that's why it must be possible +--- to write a backup file). If there was no file to be backed up, an +--- empty file is created. +--- When the 'backupskip' pattern matches, a patchmode file is not made. +--- Using 'patchmode' for compressed files appends the extension at the +--- end (e.g., "file.gz.orig"), thus the resulting name isn't always +--- recognized as a compressed file. +--- Only normal file name characters can be used, `/\*?[|<>` are illegal. +--- +--- @type string +vim.o.patchmode = "" +vim.o.pm = vim.o.patchmode +vim.go.patchmode = vim.o.patchmode +vim.go.pm = vim.go.patchmode + +--- This is a list of directories which will be searched when using the +--- `gf`, [f, ]f, ^Wf, `:find`, `:sfind`, `:tabfind` and other commands, +--- provided that the file being searched for has a relative path (not +--- starting with "/", "./" or "../"). The directories in the 'path' +--- option may be relative or absolute. +--- - Use commas to separate directory names: +--- ``` +--- :set path=.,/usr/local/include,/usr/include +--- ``` +--- - Spaces can also be used to separate directory names. To have a +--- space in a directory name, precede it with an extra backslash, and +--- escape the space: +--- ``` +--- :set path=.,/dir/with\\\ space +--- ``` +--- - To include a comma in a directory name precede it with an extra +--- backslash: +--- ``` +--- :set path=.,/dir/with\\,comma +--- ``` +--- - To search relative to the directory of the current file, use: +--- ``` +--- :set path=. +--- ``` +--- - To search in the current directory use an empty string between two +--- commas: +--- ``` +--- :set path=,, +--- ``` +--- - A directory name may end in a ':' or '/'. +--- - Environment variables are expanded `:set_env`. +--- - When using `netrw.vim` URLs can be used. For example, adding +--- "https://www.vim.org" will make ":find index.html" work. +--- - Search upwards and downwards in a directory tree using "*", "**" and +--- ";". See `file-searching` for info and syntax. +--- - Careful with '\' characters, type two to get one in the option: +--- ``` +--- :set path=.,c:\\include +--- ``` +--- Or just use '/' instead: +--- ``` +--- :set path=.,c:/include +--- ``` +--- Don't forget "." or files won't even be found in the same directory as +--- the file! +--- The maximum length is limited. How much depends on the system, mostly +--- it is something like 256 or 1024 characters. +--- You can check if all the include files are found, using the value of +--- 'path', see `:checkpath`. +--- The use of `:set+=` and `:set-=` is preferred when adding or removing +--- directories from the list. This avoids problems when a future version +--- uses another default. To remove the current directory use: +--- ``` +--- :set path-= +--- ``` +--- To add the current directory use: +--- ``` +--- :set path+= +--- ``` +--- To use an environment variable, you probably need to replace the +--- separator. Here is an example to append $INCL, in which directory +--- names are separated with a semi-colon: +--- ``` +--- :let &path = &path .. "," .. substitute($INCL, ';', ',', 'g') +--- ``` +--- Replace the ';' with a ':' or whatever separator is used. Note that +--- this doesn't work when $INCL contains a comma or white space. +--- +--- @type string +vim.o.path = ".,," +vim.o.pa = vim.o.path +vim.bo.path = vim.o.path +vim.bo.pa = vim.bo.path +vim.go.path = vim.o.path +vim.go.pa = vim.go.path + +--- When changing the indent of the current line, preserve as much of the +--- indent structure as possible. Normally the indent is replaced by a +--- series of tabs followed by spaces as required (unless `'expandtab'` is +--- enabled, in which case only spaces are used). Enabling this option +--- means the indent will preserve as many existing characters as possible +--- for indenting, and only add additional tabs or spaces as required. +--- 'expandtab' does not apply to the preserved white space, a Tab remains +--- a Tab. +--- NOTE: When using ">>" multiple times the resulting indent is a mix of +--- tabs and spaces. You might not like this. +--- Also see 'copyindent'. +--- Use `:retab` to clean up white space. +--- +--- @type boolean +vim.o.preserveindent = false +vim.o.pi = vim.o.preserveindent +vim.bo.preserveindent = vim.o.preserveindent +vim.bo.pi = vim.bo.preserveindent + +--- Default height for a preview window. Used for `:ptag` and associated +--- commands. Used for `CTRL-W_}` when no count is given. +--- +--- @type integer +vim.o.previewheight = 12 +vim.o.pvh = vim.o.previewheight +vim.go.previewheight = vim.o.previewheight +vim.go.pvh = vim.go.previewheight + +--- Identifies the preview window. Only one window can have this option +--- set. It's normally not set directly, but by using one of the commands +--- `:ptag`, `:pedit`, etc. +--- +--- @type boolean +vim.o.previewwindow = false +vim.o.pvw = vim.o.previewwindow +vim.wo.previewwindow = vim.o.previewwindow +vim.wo.pvw = vim.wo.previewwindow + +--- Enables pseudo-transparency for the `popup-menu`. Valid values are in +--- the range of 0 for fully opaque popupmenu (disabled) to 100 for fully +--- transparent background. Values between 0-30 are typically most useful. +--- +--- It is possible to override the level for individual highlights within +--- the popupmenu using `highlight-blend`. For instance, to enable +--- transparency but force the current selected element to be fully opaque: +--- ``` +--- :set pumblend=15 +--- :hi PmenuSel blend=0 +--- ``` +--- +--- UI-dependent. Works best with RGB colors. 'termguicolors' +--- +--- @type integer +vim.o.pumblend = 0 +vim.o.pb = vim.o.pumblend +vim.go.pumblend = vim.o.pumblend +vim.go.pb = vim.go.pumblend + +--- Maximum number of items to show in the popup menu +--- (`ins-completion-menu`). Zero means "use available screen space". +--- +--- @type integer +vim.o.pumheight = 0 +vim.o.ph = vim.o.pumheight +vim.go.pumheight = vim.o.pumheight +vim.go.ph = vim.go.pumheight + +--- Minimum width for the popup menu (`ins-completion-menu`). If the +--- cursor column + 'pumwidth' exceeds screen width, the popup menu is +--- nudged to fit on the screen. +--- +--- @type integer +vim.o.pumwidth = 15 +vim.o.pw = vim.o.pumwidth +vim.go.pumwidth = vim.o.pumwidth +vim.go.pw = vim.go.pumwidth + +--- Specifies the python version used for pyx* functions and commands +--- `python_x`. As only Python 3 is supported, this always has the value +--- `3`. Setting any other value is an error. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type integer +vim.o.pyxversion = 3 +vim.o.pyx = vim.o.pyxversion +vim.go.pyxversion = vim.o.pyxversion +vim.go.pyx = vim.go.pyxversion + +--- This option specifies a function to be used to get the text to display +--- in the quickfix and location list windows. This can be used to +--- customize the information displayed in the quickfix or location window +--- for each entry in the corresponding quickfix or location list. See +--- `quickfix-window-function` for an explanation of how to write the +--- function and an example. The value can be the name of a function, a +--- `lambda` or a `Funcref`. See `option-value-function` for more +--- information. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.quickfixtextfunc = "" +vim.o.qftf = vim.o.quickfixtextfunc +vim.go.quickfixtextfunc = vim.o.quickfixtextfunc +vim.go.qftf = vim.go.quickfixtextfunc + +--- The characters that are used to escape quotes in a string. Used for +--- objects like a', a" and a` `a'`. +--- When one of the characters in this option is found inside a string, +--- the following character will be skipped. The default value makes the +--- text "foo\"bar\\" considered to be one string. +--- +--- @type string +vim.o.quoteescape = "\\" +vim.o.qe = vim.o.quoteescape +vim.bo.quoteescape = vim.o.quoteescape +vim.bo.qe = vim.bo.quoteescape + +--- If on, writes fail unless you use a '!'. Protects you from +--- accidentally overwriting a file. Default on when Vim is started +--- in read-only mode ("vim -R") or when the executable is called "view". +--- When using ":w!" the 'readonly' option is reset for the current +--- buffer, unless the 'Z' flag is in 'cpoptions'. +--- When using the ":view" command the 'readonly' option is set for the +--- newly edited buffer. +--- See 'modifiable' for disallowing changes to the buffer. +--- +--- @type boolean +vim.o.readonly = false +vim.o.ro = vim.o.readonly +vim.bo.readonly = vim.o.readonly +vim.bo.ro = vim.bo.readonly + +--- Flags to change the way redrawing works, for debugging purposes. +--- Most useful with 'writedelay' set to some reasonable value. +--- Supports the following flags: +--- compositor Indicate each redraw event handled by the compositor +--- by briefly flashing the redrawn regions in colors +--- indicating the redraw type. These are the highlight +--- groups used (and their default colors): +--- RedrawDebugNormal gui=reverse normal redraw passed through +--- RedrawDebugClear guibg=Yellow clear event passed through +--- RedrawDebugComposed guibg=Green redraw event modified by the +--- compositor (due to +--- overlapping grids, etc) +--- RedrawDebugRecompose guibg=Red redraw generated by the +--- compositor itself, due to a +--- grid being moved or deleted. +--- line introduce a delay after each line drawn on the screen. +--- When using the TUI or another single-grid UI, "compositor" +--- gives more information and should be preferred (every +--- line is processed as a separate event by the compositor) +--- flush introduce a delay after each "flush" event. +--- nothrottle Turn off throttling of the message grid. This is an +--- optimization that joins many small scrolls to one +--- larger scroll when drawing the message area (with +--- 'display' msgsep flag active). +--- invalid Enable stricter checking (abort) of inconsistencies +--- of the internal screen state. This is mostly +--- useful when running nvim inside a debugger (and +--- the test suite). +--- nodelta Send all internally redrawn cells to the UI, even if +--- they are unchanged from the already displayed state. +--- +--- @type string +vim.o.redrawdebug = "" +vim.o.rdb = vim.o.redrawdebug +vim.go.redrawdebug = vim.o.redrawdebug +vim.go.rdb = vim.go.redrawdebug + +--- Time in milliseconds for redrawing the display. Applies to +--- 'hlsearch', 'inccommand', `:match` highlighting and syntax +--- highlighting. +--- When redrawing takes more than this many milliseconds no further +--- matches will be highlighted. +--- For syntax highlighting the time applies per window. When over the +--- limit syntax highlighting is disabled until `CTRL-L` is used. +--- This is used to avoid that Vim hangs when using a very complicated +--- pattern. +--- +--- @type integer +vim.o.redrawtime = 2000 +vim.o.rdt = vim.o.redrawtime +vim.go.redrawtime = vim.o.redrawtime +vim.go.rdt = vim.go.redrawtime + +--- This selects the default regexp engine. `two-engines` +--- The possible values are: +--- 0 automatic selection +--- 1 old engine +--- 2 NFA engine +--- Note that when using the NFA engine and the pattern contains something +--- that is not supported the pattern will not match. This is only useful +--- for debugging the regexp engine. +--- Using automatic selection enables Vim to switch the engine, if the +--- default engine becomes too costly. E.g., when the NFA engine uses too +--- many states. This should prevent Vim from hanging on a combination of +--- a complex pattern with long text. +--- +--- @type integer +vim.o.regexpengine = 0 +vim.o.re = vim.o.regexpengine +vim.go.regexpengine = vim.o.regexpengine +vim.go.re = vim.go.regexpengine + +--- Show the line number relative to the line with the cursor in front of +--- each line. Relative line numbers help you use the `count` you can +--- precede some vertical motion commands (e.g. j k + -) with, without +--- having to calculate it yourself. Especially useful in combination with +--- other commands (e.g. y d c < > gq gw =). +--- When the 'n' option is excluded from 'cpoptions' a wrapped +--- line will not use the column of line numbers. +--- The 'numberwidth' option can be used to set the room used for the line +--- number. +--- When a long, wrapped line doesn't start with the first character, '-' +--- characters are put before the number. +--- See `hl-LineNr` and `hl-CursorLineNr` for the highlighting used for +--- the number. +--- +--- The number in front of the cursor line also depends on the value of +--- 'number', see `number_relativenumber` for all combinations of the two +--- options. +--- +--- @type boolean +vim.o.relativenumber = false +vim.o.rnu = vim.o.relativenumber +vim.wo.relativenumber = vim.o.relativenumber +vim.wo.rnu = vim.wo.relativenumber + +--- Threshold for reporting number of lines changed. When the number of +--- changed lines is more than 'report' a message will be given for most +--- ":" commands. If you want it always, set 'report' to 0. +--- For the ":substitute" command the number of substitutions is used +--- instead of the number of lines. +--- +--- @type integer +vim.o.report = 2 +vim.go.report = vim.o.report + +--- Inserting characters in Insert mode will work backwards. See "typing +--- backwards" `ins-reverse`. This option can be toggled with the CTRL-_ +--- command in Insert mode, when 'allowrevins' is set. +--- +--- @type boolean +vim.o.revins = false +vim.o.ri = vim.o.revins +vim.go.revins = vim.o.revins +vim.go.ri = vim.go.revins + +--- When on, display orientation becomes right-to-left, i.e., characters +--- that are stored in the file appear from the right to the left. +--- Using this option, it is possible to edit files for languages that +--- are written from the right to the left such as Hebrew and Arabic. +--- This option is per window, so it is possible to edit mixed files +--- simultaneously, or to view the same file in both ways (this is +--- useful whenever you have a mixed text file with both right-to-left +--- and left-to-right strings so that both sets are displayed properly +--- in different windows). Also see `rileft.txt`. +--- +--- @type boolean +vim.o.rightleft = false +vim.o.rl = vim.o.rightleft +vim.wo.rightleft = vim.o.rightleft +vim.wo.rl = vim.wo.rightleft + +--- Each word in this option enables the command line editing to work in +--- right-to-left mode for a group of commands: +--- +--- search "/" and "?" commands +--- +--- This is useful for languages such as Hebrew, Arabic and Farsi. +--- The 'rightleft' option must be set for 'rightleftcmd' to take effect. +--- +--- @type string +vim.o.rightleftcmd = "search" +vim.o.rlc = vim.o.rightleftcmd +vim.wo.rightleftcmd = vim.o.rightleftcmd +vim.wo.rlc = vim.wo.rightleftcmd + +--- Show the line and column number of the cursor position, separated by a +--- comma. When there is room, the relative position of the displayed +--- text in the file is shown on the far right: +--- Top first line is visible +--- Bot last line is visible +--- All first and last line are visible +--- 45% relative position in the file +--- If 'rulerformat' is set, it will determine the contents of the ruler. +--- Each window has its own ruler. If a window has a status line, the +--- ruler is shown there. If a window doesn't have a status line and +--- 'cmdheight' is zero, the ruler is not shown. Otherwise it is shown in +--- the last line of the screen. If the statusline is given by +--- 'statusline' (i.e. not empty), this option takes precedence over +--- 'ruler' and 'rulerformat'. +--- If the number of characters displayed is different from the number of +--- bytes in the text (e.g., for a TAB or a multibyte character), both +--- the text column (byte number) and the screen column are shown, +--- separated with a dash. +--- For an empty line "0-1" is shown. +--- For an empty buffer the line number will also be zero: "0,0-1". +--- If you don't want to see the ruler all the time but want to know where +--- you are, use "g CTRL-G" `g_CTRL-G`. +--- +--- @type boolean +vim.o.ruler = true +vim.o.ru = vim.o.ruler +vim.go.ruler = vim.o.ruler +vim.go.ru = vim.go.ruler + +--- When this option is not empty, it determines the content of the ruler +--- string, as displayed for the 'ruler' option. +--- The format of this option is like that of 'statusline'. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- The default ruler width is 17 characters. To make the ruler 15 +--- characters wide, put "%15(" at the start and "%)" at the end. +--- Example: +--- ``` +--- :set rulerformat=%15(%c%V\ %p%%%) +--- ``` +--- +--- +--- @type string +vim.o.rulerformat = "" +vim.o.ruf = vim.o.rulerformat +vim.go.rulerformat = vim.o.rulerformat +vim.go.ruf = vim.go.rulerformat + +--- List of directories to be searched for these runtime files: +--- filetype.lua filetypes `new-filetype` +--- autoload/ automatically loaded scripts `autoload-functions` +--- colors/ color scheme files `:colorscheme` +--- compiler/ compiler files `:compiler` +--- doc/ documentation `write-local-help` +--- ftplugin/ filetype plugins `write-filetype-plugin` +--- indent/ indent scripts `indent-expression` +--- keymap/ key mapping files `mbyte-keymap` +--- lang/ menu translations `:menutrans` +--- lua/ `Lua` plugins +--- menu.vim GUI menus `menu.vim` +--- pack/ packages `:packadd` +--- parser/ `treesitter` syntax parsers +--- plugin/ plugin scripts `write-plugin` +--- queries/ `treesitter` queries +--- rplugin/ `remote-plugin` scripts +--- spell/ spell checking files `spell` +--- syntax/ syntax files `mysyntaxfile` +--- tutor/ tutorial files `:Tutor` +--- +--- And any other file searched for with the `:runtime` command. +--- +--- Defaults are setup to search these locations: +--- 1. Your home directory, for personal preferences. +--- Given by `stdpath("config")`. `$XDG_CONFIG_HOME` +--- 2. Directories which must contain configuration files according to +--- `xdg` ($XDG_CONFIG_DIRS, defaults to /etc/xdg). This also contains +--- preferences from system administrator. +--- 3. Data home directory, for plugins installed by user. +--- Given by `stdpath("data")/site`. `$XDG_DATA_HOME` +--- 4. nvim/site subdirectories for each directory in $XDG_DATA_DIRS. +--- This is for plugins which were installed by system administrator, +--- but are not part of the Nvim distribution. XDG_DATA_DIRS defaults +--- to /usr/local/share/:/usr/share/, so system administrators are +--- expected to install site plugins to /usr/share/nvim/site. +--- 5. Session state directory, for state data such as swap, backupdir, +--- viewdir, undodir, etc. +--- Given by `stdpath("state")`. `$XDG_STATE_HOME` +--- 6. $VIMRUNTIME, for files distributed with Nvim. +--- *after-directory* +--- 7, 8, 9, 10. In after/ subdirectories of 1, 2, 3 and 4, with reverse +--- ordering. This is for preferences to overrule or add to the +--- distributed defaults or system-wide settings (rarely needed). +--- +--- *packages-runtimepath* +--- "start" packages will also be searched (`runtime-search-path`) for +--- runtime files after these, though such packages are not explicitly +--- reported in &runtimepath. But "opt" packages are explicitly added to +--- &runtimepath by `:packadd`. +--- +--- Note that, unlike 'path', no wildcards like "**" are allowed. Normal +--- wildcards are allowed, but can significantly slow down searching for +--- runtime files. For speed, use as few items as possible and avoid +--- wildcards. +--- See `:runtime`. +--- Example: +--- ``` +--- :set runtimepath=~/vimruntime,/mygroup/vim,$VIMRUNTIME +--- ``` +--- This will use the directory "~/vimruntime" first (containing your +--- personal Nvim runtime files), then "/mygroup/vim", and finally +--- "$VIMRUNTIME" (the default runtime files). +--- You can put a directory before $VIMRUNTIME to find files which replace +--- distributed runtime files. You can put a directory after $VIMRUNTIME +--- to find files which add to distributed runtime files. +--- +--- With `--clean` the home directory entries are not included. +--- +--- @type string +vim.o.runtimepath = "..." +vim.o.rtp = vim.o.runtimepath +vim.go.runtimepath = vim.o.runtimepath +vim.go.rtp = vim.go.runtimepath + +--- Number of lines to scroll with CTRL-U and CTRL-D commands. Will be +--- set to half the number of lines in the window when the window size +--- changes. This may happen when enabling the `status-line` or +--- 'tabline' option after setting the 'scroll' option. +--- If you give a count to the CTRL-U or CTRL-D command it will +--- be used as the new value for 'scroll'. Reset to half the window +--- height with ":set scroll=0". +--- +--- @type integer +vim.o.scroll = 0 +vim.o.scr = vim.o.scroll +vim.wo.scroll = vim.o.scroll +vim.wo.scr = vim.wo.scroll + +--- Maximum number of lines kept beyond the visible screen. Lines at the +--- top are deleted if new lines exceed this limit. +--- Minimum is 1, maximum is 100000. +--- Only in `terminal` buffers. +--- +--- Note: Lines that are not visible and kept in scrollback are not +--- reflown when the terminal buffer is resized horizontally. +--- +--- @type integer +vim.o.scrollback = -1 +vim.o.scbk = vim.o.scrollback +vim.bo.scrollback = vim.o.scrollback +vim.bo.scbk = vim.bo.scrollback + +--- See also `scroll-binding`. When this option is set, scrolling the +--- current window also scrolls other scrollbind windows (windows that +--- also have this option set). This option is useful for viewing the +--- differences between two versions of a file, see 'diff'. +--- See `'scrollopt'` for options that determine how this option should be +--- interpreted. +--- This option is mostly reset when splitting a window to edit another +--- file. This means that ":split | edit file" results in two windows +--- with scroll-binding, but ":split file" does not. +--- +--- @type boolean +vim.o.scrollbind = false +vim.o.scb = vim.o.scrollbind +vim.wo.scrollbind = vim.o.scrollbind +vim.wo.scb = vim.wo.scrollbind + +--- Minimal number of lines to scroll when the cursor gets off the +--- screen (e.g., with "j"). Not used for scroll commands (e.g., CTRL-E, +--- CTRL-D). Useful if your terminal scrolls very slowly. +--- When set to a negative number from -1 to -100 this is used as the +--- percentage of the window height. Thus -50 scrolls half the window +--- height. +--- +--- @type integer +vim.o.scrolljump = 1 +vim.o.sj = vim.o.scrolljump +vim.go.scrolljump = vim.o.scrolljump +vim.go.sj = vim.go.scrolljump + +--- Minimal number of screen lines to keep above and below the cursor. +--- This will make some context visible around where you are working. If +--- you set it to a very large value (999) the cursor line will always be +--- in the middle of the window (except at the start or end of the file or +--- when long lines wrap). +--- After using the local value, go back the global value with one of +--- these two: +--- ``` +--- setlocal scrolloff< +--- setlocal scrolloff=-1 +--- ``` +--- For scrolling horizontally see 'sidescrolloff'. +--- +--- @type integer +vim.o.scrolloff = 0 +vim.o.so = vim.o.scrolloff +vim.wo.scrolloff = vim.o.scrolloff +vim.wo.so = vim.wo.scrolloff +vim.go.scrolloff = vim.o.scrolloff +vim.go.so = vim.go.scrolloff + +--- This is a comma-separated list of words that specifies how +--- 'scrollbind' windows should behave. 'sbo' stands for ScrollBind +--- Options. +--- The following words are available: +--- ver Bind vertical scrolling for 'scrollbind' windows +--- hor Bind horizontal scrolling for 'scrollbind' windows +--- jump Applies to the offset between two windows for vertical +--- scrolling. This offset is the difference in the first +--- displayed line of the bound windows. When moving +--- around in a window, another 'scrollbind' window may +--- reach a position before the start or after the end of +--- the buffer. The offset is not changed though, when +--- moving back the 'scrollbind' window will try to scroll +--- to the desired position when possible. +--- When now making that window the current one, two +--- things can be done with the relative offset: +--- 1. When "jump" is not included, the relative offset is +--- adjusted for the scroll position in the new current +--- window. When going back to the other window, the +--- new relative offset will be used. +--- 2. When "jump" is included, the other windows are +--- scrolled to keep the same relative offset. When +--- going back to the other window, it still uses the +--- same relative offset. +--- Also see `scroll-binding`. +--- When 'diff' mode is active there always is vertical scroll binding, +--- even when "ver" isn't there. +--- +--- @type string +vim.o.scrollopt = "ver,jump" +vim.o.sbo = vim.o.scrollopt +vim.go.scrollopt = vim.o.scrollopt +vim.go.sbo = vim.go.scrollopt + +--- Specifies the nroff macros that separate sections. These are pairs of +--- two letters (See `object-motions`). The default makes a section start +--- at the nroff macros ".SH", ".NH", ".H", ".HU", ".nh" and ".sh". +--- +--- @type string +vim.o.sections = "SHNHH HUnhsh" +vim.o.sect = vim.o.sections +vim.go.sections = vim.o.sections +vim.go.sect = vim.go.sections + +--- This option defines the behavior of the selection. It is only used +--- in Visual and Select mode. +--- Possible values: +--- value past line inclusive ~ +--- old no yes +--- inclusive yes yes +--- exclusive yes no +--- "past line" means that the cursor is allowed to be positioned one +--- character past the line. +--- "inclusive" means that the last character of the selection is included +--- in an operation. For example, when "x" is used to delete the +--- selection. +--- When "old" is used and 'virtualedit' allows the cursor to move past +--- the end of line the line break still isn't included. +--- Note that when "exclusive" is used and selecting from the end +--- backwards, you cannot include the last character of a line, when +--- starting in Normal mode and 'virtualedit' empty. +--- +--- @type string +vim.o.selection = "inclusive" +vim.o.sel = vim.o.selection +vim.go.selection = vim.o.selection +vim.go.sel = vim.go.selection + +--- This is a comma-separated list of words, which specifies when to start +--- Select mode instead of Visual mode, when a selection is started. +--- Possible values: +--- mouse when using the mouse +--- key when using shifted special keys +--- cmd when using "v", "V" or CTRL-V +--- See `Select-mode`. +--- +--- @type string +vim.o.selectmode = "" +vim.o.slm = vim.o.selectmode +vim.go.selectmode = vim.o.selectmode +vim.go.slm = vim.go.selectmode + +--- Changes the effect of the `:mksession` command. It is a comma- +--- separated list of words. Each word enables saving and restoring +--- something: +--- word save and restore ~ +--- blank empty windows +--- buffers hidden and unloaded buffers, not just those in windows +--- curdir the current directory +--- folds manually created folds, opened/closed folds and local +--- fold options +--- globals global variables that start with an uppercase letter +--- and contain at least one lowercase letter. Only +--- String and Number types are stored. +--- help the help window +--- localoptions options and mappings local to a window or buffer (not +--- global values for local options) +--- options all options and mappings (also global values for local +--- options) +--- skiprtp exclude 'runtimepath' and 'packpath' from the options +--- resize size of the Vim window: 'lines' and 'columns' +--- sesdir the directory in which the session file is located +--- will become the current directory (useful with +--- projects accessed over a network from different +--- systems) +--- tabpages all tab pages; without this only the current tab page +--- is restored, so that you can make a session for each +--- tab page separately +--- terminal include terminal windows where the command can be +--- restored +--- winpos position of the whole Vim window +--- winsize window sizes +--- slash `deprecated` Always enabled. Uses "/" in filenames. +--- unix `deprecated` Always enabled. Uses "\n" line endings. +--- +--- Don't include both "curdir" and "sesdir". When neither is included +--- filenames are stored as absolute paths. +--- If you leave out "options" many things won't work well after restoring +--- the session. +--- +--- @type string +vim.o.sessionoptions = "blank,buffers,curdir,folds,help,tabpages,winsize,terminal" +vim.o.ssop = vim.o.sessionoptions +vim.go.sessionoptions = vim.o.sessionoptions +vim.go.ssop = vim.go.sessionoptions + +--- When non-empty, the shada file is read upon startup and written +--- when exiting Vim (see `shada-file`). The string should be a comma- +--- separated list of parameters, each consisting of a single character +--- identifying the particular parameter, followed by a number or string +--- which specifies the value of that parameter. If a particular +--- character is left out, then the default value is used for that +--- parameter. The following is a list of the identifying characters and +--- the effect of their value. +--- CHAR VALUE ~ +--- *shada-!* +--- ! When included, save and restore global variables that start +--- with an uppercase letter, and don't contain a lowercase +--- letter. Thus "KEEPTHIS and "K_L_M" are stored, but "KeepThis" +--- and "_K_L_M" are not. Nested List and Dict items may not be +--- read back correctly, you end up with an empty item. +--- *shada-quote* +--- " Maximum number of lines saved for each register. Old name of +--- the '<' item, with the disadvantage that you need to put a +--- backslash before the ", otherwise it will be recognized as the +--- start of a comment! +--- *shada-%* +--- % When included, save and restore the buffer list. If Vim is +--- started with a file name argument, the buffer list is not +--- restored. If Vim is started without a file name argument, the +--- buffer list is restored from the shada file. Quickfix +--- ('buftype'), unlisted ('buflisted'), unnamed and buffers on +--- removable media (`shada-r`) are not saved. +--- When followed by a number, the number specifies the maximum +--- number of buffers that are stored. Without a number all +--- buffers are stored. +--- *shada-'* +--- ' Maximum number of previously edited files for which the marks +--- are remembered. This parameter must always be included when +--- 'shada' is non-empty. +--- Including this item also means that the `jumplist` and the +--- `changelist` are stored in the shada file. +--- *shada-/* +--- / Maximum number of items in the search pattern history to be +--- saved. If non-zero, then the previous search and substitute +--- patterns are also saved. When not included, the value of +--- 'history' is used. +--- *shada-:* +--- : Maximum number of items in the command-line history to be +--- saved. When not included, the value of 'history' is used. +--- *shada-<* +--- \< Maximum number of lines saved for each register. If zero then +--- registers are not saved. When not included, all lines are +--- saved. '"' is the old name for this item. +--- Also see the 's' item below: limit specified in KiB. +--- *shada-@* +--- @ Maximum number of items in the input-line history to be +--- saved. When not included, the value of 'history' is used. +--- *shada-c* +--- c Dummy option, kept for compatibility reasons. Has no actual +--- effect: ShaDa always uses UTF-8 and 'encoding' value is fixed +--- to UTF-8 as well. +--- *shada-f* +--- f Whether file marks need to be stored. If zero, file marks ('0 +--- to '9, 'A to 'Z) are not stored. When not present or when +--- non-zero, they are all stored. '0 is used for the current +--- cursor position (when exiting or when doing `:wshada`). +--- *shada-h* +--- h Disable the effect of 'hlsearch' when loading the shada +--- file. When not included, it depends on whether ":nohlsearch" +--- has been used since the last search command. +--- *shada-n* +--- n Name of the shada file. The name must immediately follow +--- the 'n'. Must be at the end of the option! If the +--- 'shadafile' option is set, that file name overrides the one +--- given here with 'shada'. Environment variables are +--- expanded when opening the file, not when setting the option. +--- *shada-r* +--- r Removable media. The argument is a string (up to the next +--- ','). This parameter can be given several times. Each +--- specifies the start of a path for which no marks will be +--- stored. This is to avoid removable media. For Windows you +--- could use "ra:,rb:". You can also use it for temp files, +--- e.g., for Unix: "r/tmp". Case is ignored. +--- *shada-s* +--- s Maximum size of an item contents in KiB. If zero then nothing +--- is saved. Unlike Vim this applies to all items, except for +--- the buffer list and header. Full item size is off by three +--- unsigned integers: with `s10` maximum item size may be 1 byte +--- (type: 7-bit integer) + 9 bytes (timestamp: up to 64-bit +--- integer) + 3 bytes (item size: up to 16-bit integer because +--- 2^8 < 10240 < 2^16) + 10240 bytes (requested maximum item +--- contents size) = 10253 bytes. +--- +--- Example: +--- ``` +--- :set shada='50,<1000,s100,:0,n~/nvim/shada +--- ``` +--- +--- '50 Marks will be remembered for the last 50 files you +--- edited. +--- <1000 Contents of registers (up to 1000 lines each) will be +--- remembered. +--- s100 Items with contents occupying more then 100 KiB are +--- skipped. +--- :0 Command-line history will not be saved. +--- n~/nvim/shada The name of the file to use is "~/nvim/shada". +--- no / Since '/' is not specified, the default will be used, +--- that is, save all of the search history, and also the +--- previous search and substitute patterns. +--- no % The buffer list will not be saved nor read back. +--- no h 'hlsearch' highlighting will be restored. +--- +--- When setting 'shada' from an empty value you can use `:rshada` to +--- load the contents of the file, this is not done automatically. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shada = "!,'100,<50,s10,h" +vim.o.sd = vim.o.shada +vim.go.shada = vim.o.shada +vim.go.sd = vim.go.shada + +--- When non-empty, overrides the file name used for `shada` (viminfo). +--- When equal to "NONE" no shada file will be read or written. +--- This option can be set with the `-i` command line flag. The `--clean` +--- command line flag sets it to "NONE". +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shadafile = "" +vim.o.sdf = vim.o.shadafile +vim.go.shadafile = vim.o.shadafile +vim.go.sdf = vim.go.shadafile + +--- Name of the shell to use for ! and :! commands. When changing the +--- value also check these options: 'shellpipe', 'shellslash' +--- 'shellredir', 'shellquote', 'shellxquote' and 'shellcmdflag'. +--- It is allowed to give an argument to the command, e.g. "csh -f". +--- See `option-backslash` about including spaces and backslashes. +--- Environment variables are expanded `:set_env`. +--- +--- If the name of the shell contains a space, you need to enclose it in +--- quotes. Example with quotes: +--- ``` +--- :set shell=\"c:\program\ files\unix\sh.exe\"\ -f +--- ``` +--- Note the backslash before each quote (to avoid starting a comment) and +--- each space (to avoid ending the option value), so better use `:let-&` +--- like this: +--- ``` +--- :let &shell='"C:\Program Files\unix\sh.exe" -f' +--- ``` +--- Also note that the "-f" is not inside the quotes, because it is not +--- part of the command name. +--- *shell-unquoting* +--- Rules regarding quotes: +--- 1. Option is split on space and tab characters that are not inside +--- quotes: "abc def" runs shell named "abc" with additional argument +--- "def", '"abc def"' runs shell named "abc def" with no additional +--- arguments (here and below: additional means “additional to +--- 'shellcmdflag'”). +--- 2. Quotes in option may be present in any position and any number: +--- '"abc"', '"a"bc', 'a"b"c', 'ab"c"' and '"a"b"c"' are all equivalent +--- to just "abc". +--- 3. Inside quotes backslash preceding backslash means one backslash. +--- Backslash preceding quote means one quote. Backslash preceding +--- anything else means backslash and next character literally: +--- '"a\\b"' is the same as "a\b", '"a\\"b"' runs shell named literally +--- 'a"b', '"a\b"' is the same as "a\b" again. +--- 4. Outside of quotes backslash always means itself, it cannot be used +--- to escape quote: 'a\"b"' is the same as "a\b". +--- Note that such processing is done after `:set` did its own round of +--- unescaping, so to keep yourself sane use `:let-&` like shown above. +--- *shell-powershell* +--- To use PowerShell: +--- ``` +--- let &shell = executable('pwsh') ? 'pwsh' : 'powershell' +--- let &shellcmdflag = '-NoLogo -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();$PSDefaultParameterValues[''Out-File:Encoding'']=''utf8'';Remove-Alias -Force -ErrorAction SilentlyContinue tee;' +--- let &shellredir = '2>&1 | %%{ "$_" } | Out-File %s; exit $LastExitCode' +--- let &shellpipe = '2>&1 | %%{ "$_" } | tee %s; exit $LastExitCode' +--- set shellquote= shellxquote= +--- ``` +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shell = "sh" +vim.o.sh = vim.o.shell +vim.go.shell = vim.o.shell +vim.go.sh = vim.go.shell + +--- Flag passed to the shell to execute "!" and ":!" commands; e.g., +--- `bash.exe -c ls` or `cmd.exe /s /c "dir"`. For MS-Windows, the +--- default is set according to the value of 'shell', to reduce the need +--- to set this option by the user. +--- On Unix it can have more than one flag. Each white space separated +--- part is passed as an argument to the shell command. +--- See `option-backslash` about including spaces and backslashes. +--- See `shell-unquoting` which talks about separating this option into +--- multiple arguments. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shellcmdflag = "-c" +vim.o.shcf = vim.o.shellcmdflag +vim.go.shellcmdflag = vim.o.shellcmdflag +vim.go.shcf = vim.go.shellcmdflag + +--- String to be used to put the output of the ":make" command in the +--- error file. See also `:make_makeprg`. See `option-backslash` about +--- including spaces and backslashes. +--- The name of the temporary file can be represented by "%s" if necessary +--- (the file name is appended automatically if no %s appears in the value +--- of this option). +--- For MS-Windows the default is "2>&1| tee". The stdout and stderr are +--- saved in a file and echoed to the screen. +--- For Unix the default is "| tee". The stdout of the compiler is saved +--- in a file and echoed to the screen. If the 'shell' option is "csh" or +--- "tcsh" after initializations, the default becomes "|& tee". If the +--- 'shell' option is "sh", "ksh", "mksh", "pdksh", "zsh", "zsh-beta", +--- "bash", "fish", "ash" or "dash" the default becomes "2>&1| tee". This +--- means that stderr is also included. Before using the 'shell' option a +--- path is removed, thus "/bin/sh" uses "sh". +--- The initialization of this option is done after reading the vimrc +--- and the other initializations, so that when the 'shell' option is set +--- there, the 'shellpipe' option changes automatically, unless it was +--- explicitly set before. +--- When 'shellpipe' is set to an empty string, no redirection of the +--- ":make" output will be done. This is useful if you use a 'makeprg' +--- that writes to 'makeef' by itself. If you want no piping, but do +--- want to include the 'makeef', set 'shellpipe' to a single space. +--- Don't forget to precede the space with a backslash: ":set sp=\ ". +--- In the future pipes may be used for filtering and this option will +--- become obsolete (at least for Unix). +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shellpipe = "| tee" +vim.o.sp = vim.o.shellpipe +vim.go.shellpipe = vim.o.shellpipe +vim.go.sp = vim.go.shellpipe + +--- Quoting character(s), put around the command passed to the shell, for +--- the "!" and ":!" commands. The redirection is kept outside of the +--- quoting. See 'shellxquote' to include the redirection. It's +--- probably not useful to set both options. +--- This is an empty string by default. Only known to be useful for +--- third-party shells on Windows systems, such as the MKS Korn Shell +--- or bash, where it should be "\"". The default is adjusted according +--- the value of 'shell', to reduce the need to set this option by the +--- user. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shellquote = "" +vim.o.shq = vim.o.shellquote +vim.go.shellquote = vim.o.shellquote +vim.go.shq = vim.go.shellquote + +--- String to be used to put the output of a filter command in a temporary +--- file. See also `:!`. See `option-backslash` about including spaces +--- and backslashes. +--- The name of the temporary file can be represented by "%s" if necessary +--- (the file name is appended automatically if no %s appears in the value +--- of this option). +--- The default is ">". For Unix, if the 'shell' option is "csh" or +--- "tcsh" during initializations, the default becomes ">&". If the +--- 'shell' option is "sh", "ksh", "mksh", "pdksh", "zsh", "zsh-beta", +--- "bash" or "fish", the default becomes ">%s 2>&1". This means that +--- stderr is also included. For Win32, the Unix checks are done and +--- additionally "cmd" is checked for, which makes the default ">%s 2>&1". +--- Also, the same names with ".exe" appended are checked for. +--- The initialization of this option is done after reading the vimrc +--- and the other initializations, so that when the 'shell' option is set +--- there, the 'shellredir' option changes automatically unless it was +--- explicitly set before. +--- In the future pipes may be used for filtering and this option will +--- become obsolete (at least for Unix). +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shellredir = ">" +vim.o.srr = vim.o.shellredir +vim.go.shellredir = vim.o.shellredir +vim.go.srr = vim.go.shellredir + +--- only for MS-Windows +--- When set, a forward slash is used when expanding file names. This is +--- useful when a Unix-like shell is used instead of cmd.exe. Backward +--- slashes can still be typed, but they are changed to forward slashes by +--- Vim. +--- Note that setting or resetting this option has no effect for some +--- existing file names, thus this option needs to be set before opening +--- any file for best results. This might change in the future. +--- 'shellslash' only works when a backslash can be used as a path +--- separator. To test if this is so use: +--- ``` +--- if exists('+shellslash') +--- ``` +--- Also see 'completeslash'. +--- +--- @type boolean +vim.o.shellslash = false +vim.o.ssl = vim.o.shellslash +vim.go.shellslash = vim.o.shellslash +vim.go.ssl = vim.go.shellslash + +--- When on, use temp files for shell commands. When off use a pipe. +--- When using a pipe is not possible temp files are used anyway. +--- The advantage of using a pipe is that nobody can read the temp file +--- and the 'shell' command does not need to support redirection. +--- The advantage of using a temp file is that the file type and encoding +--- can be detected. +--- The `FilterReadPre`, `FilterReadPost` and `FilterWritePre|, +--- |FilterWritePost` autocommands event are not triggered when +--- 'shelltemp' is off. +--- `system()` does not respect this option, it always uses pipes. +--- +--- @type boolean +vim.o.shelltemp = true +vim.o.stmp = vim.o.shelltemp +vim.go.shelltemp = vim.o.shelltemp +vim.go.stmp = vim.go.shelltemp + +--- When 'shellxquote' is set to "(" then the characters listed in this +--- option will be escaped with a '^' character. This makes it possible +--- to execute most external commands with cmd.exe. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shellxescape = "" +vim.o.sxe = vim.o.shellxescape +vim.go.shellxescape = vim.o.shellxescape +vim.go.sxe = vim.go.shellxescape + +--- Quoting character(s), put around the command passed to the shell, for +--- the "!" and ":!" commands. Includes the redirection. See +--- 'shellquote' to exclude the redirection. It's probably not useful +--- to set both options. +--- When the value is '(' then ')' is appended. When the value is '"(' +--- then ')"' is appended. +--- When the value is '(' then also see 'shellxescape'. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.shellxquote = "" +vim.o.sxq = vim.o.shellxquote +vim.go.shellxquote = vim.o.shellxquote +vim.go.sxq = vim.go.shellxquote + +--- Round indent to multiple of 'shiftwidth'. Applies to > and < +--- commands. CTRL-T and CTRL-D in Insert mode always round the indent to +--- a multiple of 'shiftwidth' (this is Vi compatible). +--- +--- @type boolean +vim.o.shiftround = false +vim.o.sr = vim.o.shiftround +vim.go.shiftround = vim.o.shiftround +vim.go.sr = vim.go.shiftround + +--- Number of spaces to use for each step of (auto)indent. Used for +--- `'cindent'`, `>>`, `<<`, etc. +--- When zero the 'tabstop' value will be used. Use the `shiftwidth()` +--- function to get the effective shiftwidth value. +--- +--- @type integer +vim.o.shiftwidth = 8 +vim.o.sw = vim.o.shiftwidth +vim.bo.shiftwidth = vim.o.shiftwidth +vim.bo.sw = vim.bo.shiftwidth + +--- This option helps to avoid all the `hit-enter` prompts caused by file +--- messages, for example with CTRL-G, and to avoid some other messages. +--- It is a list of flags: +--- flag meaning when present ~ +--- l use "999L, 888B" instead of "999 lines, 888 bytes" *shm-l* +--- m use "[+]" instead of "[Modified]" *shm-m* +--- r use "[RO]" instead of "[readonly]" *shm-r* +--- w use "[w]" instead of "written" for file write message *shm-w* +--- and "[a]" instead of "appended" for ':w >> file' command +--- a all of the above abbreviations *shm-a* +--- +--- o overwrite message for writing a file with subsequent *shm-o* +--- message for reading a file (useful for ":wn" or when +--- 'autowrite' on) +--- O message for reading a file overwrites any previous *shm-O* +--- message; also for quickfix message (e.g., ":cn") +--- s don't give "search hit BOTTOM, continuing at TOP" or *shm-s* +--- "search hit TOP, continuing at BOTTOM" messages; when using +--- the search count do not show "W" after the count message (see +--- S below) +--- t truncate file message at the start if it is too long *shm-t* +--- to fit on the command-line, "<" will appear in the left most +--- column; ignored in Ex mode +--- T truncate other messages in the middle if they are too *shm-T* +--- long to fit on the command line; "..." will appear in the +--- middle; ignored in Ex mode +--- W don't give "written" or "[w]" when writing a file *shm-W* +--- A don't give the "ATTENTION" message when an existing *shm-A* +--- swap file is found +--- I don't give the intro message when starting Vim, *shm-I* +--- see `:intro` +--- c don't give `ins-completion-menu` messages; for *shm-c* +--- example, "-- XXX completion (YYY)", "match 1 of 2", "The only +--- match", "Pattern not found", "Back at original", etc. +--- C don't give messages while scanning for ins-completion *shm-C* +--- items, for instance "scanning tags" +--- q use "recording" instead of "recording @a" *shm-q* +--- F don't give the file info when editing a file, like *shm-F* +--- `:silent` was used for the command +--- S do not show search count message when searching, e.g. *shm-S* +--- "[1/5]" +--- +--- This gives you the opportunity to avoid that a change between buffers +--- requires you to hit <Enter>, but still gives as useful a message as +--- possible for the space available. To get the whole message that you +--- would have got with 'shm' empty, use ":file!" +--- Useful values: +--- shm= No abbreviation of message. +--- shm=a Abbreviation, but no loss of information. +--- shm=at Abbreviation, and truncate message when necessary. +--- +--- @type string +vim.o.shortmess = "ltToOCF" +vim.o.shm = vim.o.shortmess +vim.go.shortmess = vim.o.shortmess +vim.go.shm = vim.go.shortmess + +--- String to put at the start of lines that have been wrapped. Useful +--- values are "> " or "+++ ": +--- ``` +--- :let &showbreak = "> " +--- :let &showbreak = '+++ ' +--- ``` +--- Only printable single-cell characters are allowed, excluding <Tab> and +--- comma (in a future version the comma might be used to separate the +--- part that is shown at the end and at the start of a line). +--- The `hl-NonText` highlight group determines the highlighting. +--- Note that tabs after the showbreak will be displayed differently. +--- If you want the 'showbreak' to appear in between line numbers, add the +--- "n" flag to 'cpoptions'. +--- A window-local value overrules a global value. If the global value is +--- set and you want no value in the current window use NONE: +--- ``` +--- :setlocal showbreak=NONE +--- ``` +--- +--- +--- @type string +vim.o.showbreak = "" +vim.o.sbr = vim.o.showbreak +vim.wo.showbreak = vim.o.showbreak +vim.wo.sbr = vim.wo.showbreak +vim.go.showbreak = vim.o.showbreak +vim.go.sbr = vim.go.showbreak + +--- Show (partial) command in the last line of the screen. Set this +--- option off if your terminal is slow. +--- In Visual mode the size of the selected area is shown: +--- - When selecting characters within a line, the number of characters. +--- If the number of bytes is different it is also displayed: "2-6" +--- means two characters and six bytes. +--- - When selecting more than one line, the number of lines. +--- - When selecting a block, the size in screen characters: +--- {lines}x{columns}. +--- This information can be displayed in an alternative location using the +--- 'showcmdloc' option, useful when 'cmdheight' is 0. +--- +--- @type boolean +vim.o.showcmd = true +vim.o.sc = vim.o.showcmd +vim.go.showcmd = vim.o.showcmd +vim.go.sc = vim.go.showcmd + +--- This option can be used to display the (partially) entered command in +--- another location. Possible values are: +--- last Last line of the screen (default). +--- statusline Status line of the current window. +--- tabline First line of the screen if 'showtabline' is enabled. +--- Setting this option to "statusline" or "tabline" means that these will +--- be redrawn whenever the command changes, which can be on every key +--- pressed. +--- The %S 'statusline' item can be used in 'statusline' or 'tabline' to +--- place the text. Without a custom 'statusline' or 'tabline' it will be +--- displayed in a convenient location. +--- +--- @type string +vim.o.showcmdloc = "last" +vim.o.sloc = vim.o.showcmdloc +vim.go.showcmdloc = vim.o.showcmdloc +vim.go.sloc = vim.go.showcmdloc + +--- When completing a word in insert mode (see `ins-completion`) from the +--- tags file, show both the tag name and a tidied-up form of the search +--- pattern (if there is one) as possible matches. Thus, if you have +--- matched a C function, you can see a template for what arguments are +--- required (coding style permitting). +--- Note that this doesn't work well together with having "longest" in +--- 'completeopt', because the completion from the search pattern may not +--- match the typed text. +--- +--- @type boolean +vim.o.showfulltag = false +vim.o.sft = vim.o.showfulltag +vim.go.showfulltag = vim.o.showfulltag +vim.go.sft = vim.go.showfulltag + +--- When a bracket is inserted, briefly jump to the matching one. The +--- jump is only done if the match can be seen on the screen. The time to +--- show the match can be set with 'matchtime'. +--- A Beep is given if there is no match (no matter if the match can be +--- seen or not). +--- When the 'm' flag is not included in 'cpoptions', typing a character +--- will immediately move the cursor back to where it belongs. +--- See the "sm" field in 'guicursor' for setting the cursor shape and +--- blinking when showing the match. +--- The 'matchpairs' option can be used to specify the characters to show +--- matches for. 'rightleft' and 'revins' are used to look for opposite +--- matches. +--- Also see the matchparen plugin for highlighting the match when moving +--- around `pi_paren.txt`. +--- Note: Use of the short form is rated PG. +--- +--- @type boolean +vim.o.showmatch = false +vim.o.sm = vim.o.showmatch +vim.go.showmatch = vim.o.showmatch +vim.go.sm = vim.go.showmatch + +--- If in Insert, Replace or Visual mode put a message on the last line. +--- The `hl-ModeMsg` highlight group determines the highlighting. +--- The option has no effect when 'cmdheight' is zero. +--- +--- @type boolean +vim.o.showmode = true +vim.o.smd = vim.o.showmode +vim.go.showmode = vim.o.showmode +vim.go.smd = vim.go.showmode + +--- The value of this option specifies when the line with tab page labels +--- will be displayed: +--- 0: never +--- 1: only if there are at least two tab pages +--- 2: always +--- This is both for the GUI and non-GUI implementation of the tab pages +--- line. +--- See `tab-page` for more information about tab pages. +--- +--- @type integer +vim.o.showtabline = 1 +vim.o.stal = vim.o.showtabline +vim.go.showtabline = vim.o.showtabline +vim.go.stal = vim.go.showtabline + +--- The minimal number of columns to scroll horizontally. Used only when +--- the 'wrap' option is off and the cursor is moved off of the screen. +--- When it is zero the cursor will be put in the middle of the screen. +--- When using a slow terminal set it to a large number or 0. Not used +--- for "zh" and "zl" commands. +--- +--- @type integer +vim.o.sidescroll = 1 +vim.o.ss = vim.o.sidescroll +vim.go.sidescroll = vim.o.sidescroll +vim.go.ss = vim.go.sidescroll + +--- The minimal number of screen columns to keep to the left and to the +--- right of the cursor if 'nowrap' is set. Setting this option to a +--- value greater than 0 while having `'sidescroll'` also at a non-zero +--- value makes some context visible in the line you are scrolling in +--- horizontally (except at beginning of the line). Setting this option +--- to a large value (like 999) has the effect of keeping the cursor +--- horizontally centered in the window, as long as one does not come too +--- close to the beginning of the line. +--- After using the local value, go back the global value with one of +--- these two: +--- ``` +--- setlocal sidescrolloff< +--- setlocal sidescrolloff=-1 +--- ``` +--- +--- Example: Try this together with 'sidescroll' and 'listchars' as +--- in the following example to never allow the cursor to move +--- onto the "extends" character: +--- ``` +--- :set nowrap sidescroll=1 listchars=extends:>,precedes:< +--- :set sidescrolloff=1 +--- ``` +--- +--- +--- @type integer +vim.o.sidescrolloff = 0 +vim.o.siso = vim.o.sidescrolloff +vim.wo.sidescrolloff = vim.o.sidescrolloff +vim.wo.siso = vim.wo.sidescrolloff +vim.go.sidescrolloff = vim.o.sidescrolloff +vim.go.siso = vim.go.sidescrolloff + +--- When and how to draw the signcolumn. Valid values are: +--- "auto" only when there is a sign to display +--- "auto:[1-9]" resize to accommodate multiple signs up to the +--- given number (maximum 9), e.g. "auto:4" +--- "auto:[1-8]-[2-9]" +--- resize to accommodate multiple signs up to the +--- given maximum number (maximum 9) while keeping +--- at least the given minimum (maximum 8) fixed +--- space. The minimum number should always be less +--- than the maximum number, e.g. "auto:2-5" +--- "no" never +--- "yes" always +--- "yes:[1-9]" always, with fixed space for signs up to the given +--- number (maximum 9), e.g. "yes:3" +--- "number" display signs in the 'number' column. If the number +--- column is not present, then behaves like "auto". +--- +--- @type string +vim.o.signcolumn = "auto" +vim.o.scl = vim.o.signcolumn +vim.wo.signcolumn = vim.o.signcolumn +vim.wo.scl = vim.wo.signcolumn + +--- Override the 'ignorecase' option if the search pattern contains upper +--- case characters. Only used when the search pattern is typed and +--- 'ignorecase' option is on. Used for the commands "/", "?", "n", "N", +--- ":g" and ":s". Not used for "*", "#", "gd", tag search, etc. After +--- "*" and "#" you can make 'smartcase' used by doing a "/" command, +--- recalling the search pattern from history and hitting <Enter>. +--- +--- @type boolean +vim.o.smartcase = false +vim.o.scs = vim.o.smartcase +vim.go.smartcase = vim.o.smartcase +vim.go.scs = vim.go.smartcase + +--- Do smart autoindenting when starting a new line. Works for C-like +--- programs, but can also be used for other languages. 'cindent' does +--- something like this, works better in most cases, but is more strict, +--- see `C-indenting`. When 'cindent' is on or 'indentexpr' is set, +--- setting 'si' has no effect. 'indentexpr' is a more advanced +--- alternative. +--- Normally 'autoindent' should also be on when using 'smartindent'. +--- An indent is automatically inserted: +--- - After a line ending in "{". +--- - After a line starting with a keyword from 'cinwords'. +--- - Before a line starting with "}" (only with the "O" command). +--- When typing '}' as the first character in a new line, that line is +--- given the same indent as the matching "{". +--- When typing '#' as the first character in a new line, the indent for +--- that line is removed, the '#' is put in the first column. The indent +--- is restored for the next line. If you don't want this, use this +--- mapping: ":inoremap # X^H#", where ^H is entered with CTRL-V CTRL-H. +--- When using the ">>" command, lines starting with '#' are not shifted +--- right. +--- +--- @type boolean +vim.o.smartindent = false +vim.o.si = vim.o.smartindent +vim.bo.smartindent = vim.o.smartindent +vim.bo.si = vim.bo.smartindent + +--- When on, a <Tab> in front of a line inserts blanks according to +--- 'shiftwidth'. 'tabstop' or 'softtabstop' is used in other places. A +--- <BS> will delete a 'shiftwidth' worth of space at the start of the +--- line. +--- When off, a <Tab> always inserts blanks according to 'tabstop' or +--- 'softtabstop'. 'shiftwidth' is only used for shifting text left or +--- right `shift-left-right`. +--- What gets inserted (a <Tab> or spaces) depends on the 'expandtab' +--- option. Also see `ins-expandtab`. When 'expandtab' is not set, the +--- number of spaces is minimized by using <Tab>s. +--- +--- @type boolean +vim.o.smarttab = true +vim.o.sta = vim.o.smarttab +vim.go.smarttab = vim.o.smarttab +vim.go.sta = vim.go.smarttab + +--- Scrolling works with screen lines. When 'wrap' is set and the first +--- line in the window wraps part of it may not be visible, as if it is +--- above the window. "<<<" is displayed at the start of the first line, +--- highlighted with `hl-NonText`. +--- You may also want to add "lastline" to the 'display' option to show as +--- much of the last line as possible. +--- NOTE: only partly implemented, currently works with CTRL-E, CTRL-Y +--- and scrolling with the mouse. +--- +--- @type boolean +vim.o.smoothscroll = false +vim.o.sms = vim.o.smoothscroll +vim.wo.smoothscroll = vim.o.smoothscroll +vim.wo.sms = vim.wo.smoothscroll + +--- Number of spaces that a <Tab> counts for while performing editing +--- operations, like inserting a <Tab> or using <BS>. It "feels" like +--- <Tab>s are being inserted, while in fact a mix of spaces and <Tab>s is +--- used. This is useful to keep the 'ts' setting at its standard value +--- of 8, while being able to edit like it is set to 'sts'. However, +--- commands like "x" still work on the actual characters. +--- When 'sts' is zero, this feature is off. +--- When 'sts' is negative, the value of 'shiftwidth' is used. +--- See also `ins-expandtab`. When 'expandtab' is not set, the number of +--- spaces is minimized by using <Tab>s. +--- The 'L' flag in 'cpoptions' changes how tabs are used when 'list' is +--- set. +--- +--- The value of 'softtabstop' will be ignored if `'varsofttabstop'` is set +--- to anything other than an empty string. +--- +--- @type integer +vim.o.softtabstop = 0 +vim.o.sts = vim.o.softtabstop +vim.bo.softtabstop = vim.o.softtabstop +vim.bo.sts = vim.bo.softtabstop + +--- When on spell checking will be done. See `spell`. +--- The languages are specified with 'spelllang'. +--- +--- @type boolean +vim.o.spell = false +vim.wo.spell = vim.o.spell + +--- Pattern to locate the end of a sentence. The following word will be +--- checked to start with a capital letter. If not then it is highlighted +--- with SpellCap `hl-SpellCap` (unless the word is also badly spelled). +--- When this check is not wanted make this option empty. +--- Only used when 'spell' is set. +--- Be careful with special characters, see `option-backslash` about +--- including spaces and backslashes. +--- To set this option automatically depending on the language, see +--- `set-spc-auto`. +--- +--- @type string +vim.o.spellcapcheck = "[.?!]\\_[\\])'\"\\t ]\\+" +vim.o.spc = vim.o.spellcapcheck +vim.bo.spellcapcheck = vim.o.spellcapcheck +vim.bo.spc = vim.bo.spellcapcheck + +--- Name of the word list file where words are added for the `zg` and `zw` +--- commands. It must end in ".{encoding}.add". You need to include the +--- path, otherwise the file is placed in the current directory. +--- The path may include characters from 'isfname', space, comma and '@'. +--- *E765* +--- It may also be a comma-separated list of names. A count before the +--- `zg` and `zw` commands can be used to access each. This allows using +--- a personal word list file and a project word list file. +--- When a word is added while this option is empty Vim will set it for +--- you: Using the first directory in 'runtimepath' that is writable. If +--- there is no "spell" directory yet it will be created. For the file +--- name the first language name that appears in 'spelllang' is used, +--- ignoring the region. +--- The resulting ".spl" file will be used for spell checking, it does not +--- have to appear in 'spelllang'. +--- Normally one file is used for all regions, but you can add the region +--- name if you want to. However, it will then only be used when +--- 'spellfile' is set to it, for entries in 'spelllang' only files +--- without region name will be found. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.spellfile = "" +vim.o.spf = vim.o.spellfile +vim.bo.spellfile = vim.o.spellfile +vim.bo.spf = vim.bo.spellfile + +--- A comma-separated list of word list names. When the 'spell' option is +--- on spellchecking will be done for these languages. Example: +--- ``` +--- set spelllang=en_us,nl,medical +--- ``` +--- This means US English, Dutch and medical words are recognized. Words +--- that are not recognized will be highlighted. +--- The word list name must consist of alphanumeric characters, a dash or +--- an underscore. It should not include a comma or dot. Using a dash is +--- recommended to separate the two letter language name from a +--- specification. Thus "en-rare" is used for rare English words. +--- A region name must come last and have the form "_xx", where "xx" is +--- the two-letter, lower case region name. You can use more than one +--- region by listing them: "en_us,en_ca" supports both US and Canadian +--- English, but not words specific for Australia, New Zealand or Great +--- Britain. (Note: currently en_au and en_nz dictionaries are older than +--- en_ca, en_gb and en_us). +--- If the name "cjk" is included East Asian characters are excluded from +--- spell checking. This is useful when editing text that also has Asian +--- words. +--- Note that the "medical" dictionary does not exist, it is just an +--- example of a longer name. +--- *E757* +--- As a special case the name of a .spl file can be given as-is. The +--- first "_xx" in the name is removed and used as the region name +--- (_xx is an underscore, two letters and followed by a non-letter). +--- This is mainly for testing purposes. You must make sure the correct +--- encoding is used, Vim doesn't check it. +--- How the related spell files are found is explained here: `spell-load`. +--- +--- If the `spellfile.vim` plugin is active and you use a language name +--- for which Vim cannot find the .spl file in 'runtimepath' the plugin +--- will ask you if you want to download the file. +--- +--- After this option has been set successfully, Vim will source the files +--- "spell/LANG.vim" in 'runtimepath'. "LANG" is the value of 'spelllang' +--- up to the first character that is not an ASCII letter or number and +--- not a dash. Also see `set-spc-auto`. +--- +--- @type string +vim.o.spelllang = "en" +vim.o.spl = vim.o.spelllang +vim.bo.spelllang = vim.o.spelllang +vim.bo.spl = vim.bo.spelllang + +--- A comma-separated list of options for spell checking: +--- camel When a word is CamelCased, assume "Cased" is a +--- separate word: every upper-case character in a word +--- that comes after a lower case character indicates the +--- start of a new word. +--- noplainbuffer Only spellcheck a buffer when 'syntax' is enabled, +--- or when extmarks are set within the buffer. Only +--- designated regions of the buffer are spellchecked in +--- this case. +--- +--- @type string +vim.o.spelloptions = "" +vim.o.spo = vim.o.spelloptions +vim.bo.spelloptions = vim.o.spelloptions +vim.bo.spo = vim.bo.spelloptions + +--- Methods used for spelling suggestions. Both for the `z=` command and +--- the `spellsuggest()` function. This is a comma-separated list of +--- items: +--- +--- best Internal method that works best for English. Finds +--- changes like "fast" and uses a bit of sound-a-like +--- scoring to improve the ordering. +--- +--- double Internal method that uses two methods and mixes the +--- results. The first method is "fast", the other method +--- computes how much the suggestion sounds like the bad +--- word. That only works when the language specifies +--- sound folding. Can be slow and doesn't always give +--- better results. +--- +--- fast Internal method that only checks for simple changes: +--- character inserts/deletes/swaps. Works well for +--- simple typing mistakes. +--- +--- {number} The maximum number of suggestions listed for `z=`. +--- Not used for `spellsuggest()`. The number of +--- suggestions is never more than the value of 'lines' +--- minus two. +--- +--- timeout:{millisec} Limit the time searching for suggestions to +--- {millisec} milli seconds. Applies to the following +--- methods. When omitted the limit is 5000. When +--- negative there is no limit. +--- +--- file:{filename} Read file {filename}, which must have two columns, +--- separated by a slash. The first column contains the +--- bad word, the second column the suggested good word. +--- Example: +--- theribal/terrible ~ +--- Use this for common mistakes that do not appear at the +--- top of the suggestion list with the internal methods. +--- Lines without a slash are ignored, use this for +--- comments. +--- The word in the second column must be correct, +--- otherwise it will not be used. Add the word to an +--- ".add" file if it is currently flagged as a spelling +--- mistake. +--- The file is used for all languages. +--- +--- expr:{expr} Evaluate expression {expr}. Use a function to avoid +--- trouble with spaces. `v:val` holds the badly spelled +--- word. The expression must evaluate to a List of +--- Lists, each with a suggestion and a score. +--- Example: +--- [['the', 33], ['that', 44]] ~ +--- Set 'verbose' and use `z=` to see the scores that the +--- internal methods use. A lower score is better. +--- This may invoke `spellsuggest()` if you temporarily +--- set 'spellsuggest' to exclude the "expr:" part. +--- Errors are silently ignored, unless you set the +--- 'verbose' option to a non-zero value. +--- +--- Only one of "best", "double" or "fast" may be used. The others may +--- appear several times in any order. Example: +--- ``` +--- :set sps=file:~/.config/nvim/sugg,best,expr:MySuggest() +--- ``` +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.spellsuggest = "best" +vim.o.sps = vim.o.spellsuggest +vim.go.spellsuggest = vim.o.spellsuggest +vim.go.sps = vim.go.spellsuggest + +--- When on, splitting a window will put the new window below the current +--- one. `:split` +--- +--- @type boolean +vim.o.splitbelow = false +vim.o.sb = vim.o.splitbelow +vim.go.splitbelow = vim.o.splitbelow +vim.go.sb = vim.go.splitbelow + +--- The value of this option determines the scroll behavior when opening, +--- closing or resizing horizontal splits. +--- +--- Possible values are: +--- cursor Keep the same relative cursor position. +--- screen Keep the text on the same screen line. +--- topline Keep the topline the same. +--- +--- For the "screen" and "topline" values, the cursor position will be +--- changed when necessary. In this case, the jumplist will be populated +--- with the previous cursor position. For "screen", the text cannot always +--- be kept on the same screen line when 'wrap' is enabled. +--- +--- @type string +vim.o.splitkeep = "cursor" +vim.o.spk = vim.o.splitkeep +vim.go.splitkeep = vim.o.splitkeep +vim.go.spk = vim.go.splitkeep + +--- When on, splitting a window will put the new window right of the +--- current one. `:vsplit` +--- +--- @type boolean +vim.o.splitright = false +vim.o.spr = vim.o.splitright +vim.go.splitright = vim.o.splitright +vim.go.spr = vim.go.splitright + +--- When "on" the commands listed below move the cursor to the first +--- non-blank of the line. When off the cursor is kept in the same column +--- (if possible). This applies to the commands: +--- - CTRL-D, CTRL-U, CTRL-B, CTRL-F, "G", "H", "M", "L", "gg" +--- - "d", "<<" and ">>" with a linewise operator +--- - "%" with a count +--- - buffer changing commands (CTRL-^, :bnext, :bNext, etc.) +--- - Ex commands that only have a line number, e.g., ":25" or ":+". +--- In case of buffer changing commands the cursor is placed at the column +--- where it was the last time the buffer was edited. +--- +--- @type boolean +vim.o.startofline = false +vim.o.sol = vim.o.startofline +vim.go.startofline = vim.o.startofline +vim.go.sol = vim.go.startofline + +--- EXPERIMENTAL +--- When non-empty, this option determines the content of the area to the +--- side of a window, normally containing the fold, sign and number columns. +--- The format of this option is like that of 'statusline'. +--- +--- Some of the items from the 'statusline' format are different for +--- 'statuscolumn': +--- +--- %l line number of currently drawn line +--- %r relative line number of currently drawn line +--- %s sign column for currently drawn line +--- %C fold column for currently drawn line +--- +--- NOTE: To draw the sign and fold columns, their items must be included in +--- 'statuscolumn'. Even when they are not included, the status column width +--- will adapt to the 'signcolumn' and 'foldcolumn' width. +--- +--- The `v:lnum` variable holds the line number to be drawn. +--- The `v:relnum` variable holds the relative line number to be drawn. +--- The `v:virtnum` variable is negative when drawing virtual lines, zero +--- when drawing the actual buffer line, and positive when +--- drawing the wrapped part of a buffer line. +--- +--- NOTE: The %@ click execute function item is supported as well but the +--- specified function will be the same for each row in the same column. +--- It cannot be switched out through a dynamic 'statuscolumn' format, the +--- handler should be written with this in mind. +--- +--- Examples: +--- +--- ```vim +--- " Relative number with bar separator and click handlers: +--- :set statuscolumn=%@SignCb@%s%=%T%@NumCb@%r│%T +--- +--- " Right aligned relative cursor line number: +--- :let &stc='%=%{v:relnum?v:relnum:v:lnum} ' +--- +--- " Line numbers in hexadecimal for non wrapped part of lines: +--- :let &stc='%=%{v:virtnum>0?"":printf("%x",v:lnum)} ' +--- +--- " Human readable line numbers with thousands separator: +--- :let &stc='%{substitute(v:lnum,"\\d\\zs\\ze\\' +--- . '%(\\d\\d\\d\\)\\+$",",","g")}' +--- +--- " Both relative and absolute line numbers with different +--- " highlighting for odd and even relative numbers: +--- :let &stc='%#NonText#%{&nu?v:lnum:""}' . +--- '%=%{&rnu&&(v:lnum%2)?"\ ".v:relnum:""}' . +--- '%#LineNr#%{&rnu&&!(v:lnum%2)?"\ ".v:relnum:""}' +--- ``` +--- WARNING: this expression is evaluated for each screen line so defining +--- an expensive expression can negatively affect render performance. +--- +--- @type string +vim.o.statuscolumn = "" +vim.o.stc = vim.o.statuscolumn +vim.wo.statuscolumn = vim.o.statuscolumn +vim.wo.stc = vim.wo.statuscolumn + +--- When non-empty, this option determines the content of the status line. +--- Also see `status-line`. +--- +--- The option consists of printf style '%' items interspersed with +--- normal text. Each status line item is of the form: +--- %-0{minwid}.{maxwid}{item} +--- All fields except the {item} are optional. A single percent sign can +--- be given as "%%". +--- +--- When the option starts with "%!" then it is used as an expression, +--- evaluated and the result is used as the option value. Example: +--- ``` +--- :set statusline=%!MyStatusLine() +--- ``` +--- The *g:statusline_winid* variable will be set to the `window-ID` of the +--- window that the status line belongs to. +--- The result can contain %{} items that will be evaluated too. +--- Note that the "%!" expression is evaluated in the context of the +--- current window and buffer, while %{} items are evaluated in the +--- context of the window that the statusline belongs to. +--- +--- When there is error while evaluating the option then it will be made +--- empty to avoid further errors. Otherwise screen updating would loop. +--- When the result contains unprintable characters the result is +--- unpredictable. +--- +--- Note that the only effect of 'ruler' when this option is set (and +--- 'laststatus' is 2 or 3) is controlling the output of `CTRL-G`. +--- +--- field meaning ~ +--- - Left justify the item. The default is right justified +--- when minwid is larger than the length of the item. +--- 0 Leading zeroes in numeric items. Overridden by "-". +--- minwid Minimum width of the item, padding as set by "-" & "0". +--- Value must be 50 or less. +--- maxwid Maximum width of the item. Truncation occurs with a "<" +--- on the left for text items. Numeric items will be +--- shifted down to maxwid-2 digits followed by ">"number +--- where number is the amount of missing digits, much like +--- an exponential notation. +--- item A one letter code as described below. +--- +--- Following is a description of the possible statusline items. The +--- second character in "item" is the type: +--- N for number +--- S for string +--- F for flags as described below +--- - not applicable +--- +--- item meaning ~ +--- f S Path to the file in the buffer, as typed or relative to current +--- directory. +--- F S Full path to the file in the buffer. +--- t S File name (tail) of file in the buffer. +--- m F Modified flag, text is "[+]"; "[-]" if 'modifiable' is off. +--- M F Modified flag, text is ",+" or ",-". +--- r F Readonly flag, text is "[RO]". +--- R F Readonly flag, text is ",RO". +--- h F Help buffer flag, text is "[help]". +--- H F Help buffer flag, text is ",HLP". +--- w F Preview window flag, text is "[Preview]". +--- W F Preview window flag, text is ",PRV". +--- y F Type of file in the buffer, e.g., "[vim]". See 'filetype'. +--- Y F Type of file in the buffer, e.g., ",VIM". See 'filetype'. +--- q S "[Quickfix List]", "[Location List]" or empty. +--- k S Value of "b:keymap_name" or 'keymap' when `:lmap` mappings are +--- being used: "<keymap>" +--- n N Buffer number. +--- b N Value of character under cursor. +--- B N As above, in hexadecimal. +--- o N Byte number in file of byte under cursor, first byte is 1. +--- Mnemonic: Offset from start of file (with one added) +--- O N As above, in hexadecimal. +--- l N Line number. +--- L N Number of lines in buffer. +--- c N Column number (byte index). +--- v N Virtual column number (screen column). +--- V N Virtual column number as -{num}. Not displayed if equal to 'c'. +--- p N Percentage through file in lines as in `CTRL-G`. +--- P S Percentage through file of displayed window. This is like the +--- percentage described for 'ruler'. Always 3 in length, unless +--- translated. +--- S S 'showcmd' content, see 'showcmdloc'. +--- a S Argument list status as in default title. ({current} of {max}) +--- Empty if the argument file count is zero or one. +--- { NF Evaluate expression between "%{" and "}" and substitute result. +--- Note that there is no "%" before the closing "}". The +--- expression cannot contain a "}" character, call a function to +--- work around that. See `stl-%{` below. +--- `{%` - This is almost same as "{" except the result of the expression is +--- re-evaluated as a statusline format string. Thus if the +--- return value of expr contains "%" items they will get expanded. +--- The expression can contain the "}" character, the end of +--- expression is denoted by "%}". +--- For example: +--- ``` +--- func! Stl_filename() abort +--- return "%t" +--- endfunc +--- ``` +--- `stl=%{Stl_filename()}` results in `"%t"` +--- `stl=%{%Stl_filename()%}` results in `"Name of current file"` +--- %} - End of "{%" expression +--- ( - Start of item group. Can be used for setting the width and +--- alignment of a section. Must be followed by %) somewhere. +--- ) - End of item group. No width fields allowed. +--- T N For 'tabline': start of tab page N label. Use %T or %X to end +--- the label. Clicking this label with left mouse button switches +--- to the specified tab page. +--- X N For 'tabline': start of close tab N label. Use %X or %T to end +--- the label, e.g.: %3Xclose%X. Use %999X for a "close current +--- tab" label. Clicking this label with left mouse button closes +--- specified tab page. +--- @ N Start of execute function label. Use %X or %T to +--- end the label, e.g.: %10@SwitchBuffer@foo.c%X. Clicking this +--- label runs specified function: in the example when clicking once +--- using left mouse button on "foo.c" "SwitchBuffer(10, 1, 'l', +--- ' ')" expression will be run. Function receives the +--- following arguments in order: +--- 1. minwid field value or zero if no N was specified +--- 2. number of mouse clicks to detect multiple clicks +--- 3. mouse button used: "l", "r" or "m" for left, right or middle +--- button respectively; one should not rely on third argument +--- being only "l", "r" or "m": any other non-empty string value +--- that contains only ASCII lower case letters may be expected +--- for other mouse buttons +--- 4. modifiers pressed: string which contains "s" if shift +--- modifier was pressed, "c" for control, "a" for alt and "m" +--- for meta; currently if modifier is not pressed string +--- contains space instead, but one should not rely on presence +--- of spaces or specific order of modifiers: use `stridx()` to +--- test whether some modifier is present; string is guaranteed +--- to contain only ASCII letters and spaces, one letter per +--- modifier; "?" modifier may also be present, but its presence +--- is a bug that denotes that new mouse button recognition was +--- added without modifying code that reacts on mouse clicks on +--- this label. +--- Use `getmousepos()`.winid in the specified function to get the +--- corresponding window id of the clicked item. +--- \< - Where to truncate line if too long. Default is at the start. +--- No width fields allowed. +--- = - Separation point between alignment sections. Each section will +--- be separated by an equal number of spaces. With one %= what +--- comes after it will be right-aligned. With two %= there is a +--- middle part, with white space left and right of it. +--- No width fields allowed. +--- # - Set highlight group. The name must follow and then a # again. +--- Thus use %#HLname# for highlight group HLname. The same +--- highlighting is used, also for the statusline of non-current +--- windows. +--- * - Set highlight group to User{N}, where {N} is taken from the +--- minwid field, e.g. %1*. Restore normal highlight with %* or %0*. +--- The difference between User{N} and StatusLine will be applied to +--- StatusLineNC for the statusline of non-current windows. +--- The number N must be between 1 and 9. See `hl-User1..9` +--- +--- When displaying a flag, Vim removes the leading comma, if any, when +--- that flag comes right after plaintext. This will make a nice display +--- when flags are used like in the examples below. +--- +--- When all items in a group becomes an empty string (i.e. flags that are +--- not set) and a minwid is not set for the group, the whole group will +--- become empty. This will make a group like the following disappear +--- completely from the statusline when none of the flags are set. +--- ``` +--- :set statusline=...%(\ [%M%R%H]%)... +--- ``` +--- Beware that an expression is evaluated each and every time the status +--- line is displayed. +--- *stl-%{* *g:actual_curbuf* *g:actual_curwin* +--- While evaluating %{} the current buffer and current window will be set +--- temporarily to that of the window (and buffer) whose statusline is +--- currently being drawn. The expression will evaluate in this context. +--- The variable "g:actual_curbuf" is set to the `bufnr()` number of the +--- real current buffer and "g:actual_curwin" to the `window-ID` of the +--- real current window. These values are strings. +--- +--- The 'statusline' option will be evaluated in the `sandbox` if set from +--- a modeline, see `sandbox-option`. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- It is not allowed to change text or jump to another window while +--- evaluating 'statusline' `textlock`. +--- +--- If the statusline is not updated when you want it (e.g., after setting +--- a variable that's used in an expression), you can force an update by +--- using `:redrawstatus`. +--- +--- A result of all digits is regarded a number for display purposes. +--- Otherwise the result is taken as flag text and applied to the rules +--- described above. +--- +--- Watch out for errors in expressions. They may render Vim unusable! +--- If you are stuck, hold down ':' or 'Q' to get a prompt, then quit and +--- edit your vimrc or whatever with "vim --clean" to get it right. +--- +--- Examples: +--- Emulate standard status line with 'ruler' set +--- ``` +--- :set statusline=%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P +--- ``` +--- Similar, but add ASCII value of char under the cursor (like "ga") +--- ``` +--- :set statusline=%<%f%h%m%r%=%b\ 0x%B\ \ %l,%c%V\ %P +--- ``` +--- Display byte count and byte value, modified flag in red. +--- ``` +--- :set statusline=%<%f%=\ [%1*%M%*%n%R%H]\ %-19(%3l,%02c%03V%)%O'%02b' +--- :hi User1 term=inverse,bold cterm=inverse,bold ctermfg=red +--- ``` +--- Display a ,GZ flag if a compressed file is loaded +--- ``` +--- :set statusline=...%r%{VarExists('b:gzflag','\ [GZ]')}%h... +--- ``` +--- In the `:autocmd`'s: +--- ``` +--- :let b:gzflag = 1 +--- ``` +--- And: +--- ``` +--- :unlet b:gzflag +--- ``` +--- And define this function: +--- ``` +--- :function VarExists(var, val) +--- : if exists(a:var) | return a:val | else | return '' | endif +--- :endfunction +--- ``` +--- +--- +--- @type string +vim.o.statusline = "" +vim.o.stl = vim.o.statusline +vim.wo.statusline = vim.o.statusline +vim.wo.stl = vim.wo.statusline +vim.go.statusline = vim.o.statusline +vim.go.stl = vim.go.statusline + +--- Files with these suffixes get a lower priority when multiple files +--- match a wildcard. See `suffixes`. Commas can be used to separate the +--- suffixes. Spaces after the comma are ignored. A dot is also seen as +--- the start of a suffix. To avoid a dot or comma being recognized as a +--- separator, precede it with a backslash (see `option-backslash` about +--- including spaces and backslashes). +--- See 'wildignore' for completely ignoring files. +--- The use of `:set+=` and `:set-=` is preferred when adding or removing +--- suffixes from the list. This avoids problems when a future version +--- uses another default. +--- +--- @type string +vim.o.suffixes = ".bak,~,.o,.h,.info,.swp,.obj" +vim.o.su = vim.o.suffixes +vim.go.suffixes = vim.o.suffixes +vim.go.su = vim.go.suffixes + +--- Comma-separated list of suffixes, which are used when searching for a +--- file for the "gf", "[I", etc. commands. Example: +--- ``` +--- :set suffixesadd=.java +--- ``` +--- +--- +--- @type string +vim.o.suffixesadd = "" +vim.o.sua = vim.o.suffixesadd +vim.bo.suffixesadd = vim.o.suffixesadd +vim.bo.sua = vim.bo.suffixesadd + +--- Use a swapfile for the buffer. This option can be reset when a +--- swapfile is not wanted for a specific buffer. For example, with +--- confidential information that even root must not be able to access. +--- Careful: All text will be in memory: +--- - Don't use this for big files. +--- - Recovery will be impossible! +--- A swapfile will only be present when `'updatecount'` is non-zero and +--- 'swapfile' is set. +--- When 'swapfile' is reset, the swap file for the current buffer is +--- immediately deleted. When 'swapfile' is set, and 'updatecount' is +--- non-zero, a swap file is immediately created. +--- Also see `swap-file`. +--- If you want to open a new buffer without creating a swap file for it, +--- use the `:noswapfile` modifier. +--- See 'directory' for where the swap file is created. +--- +--- This option is used together with 'bufhidden' and 'buftype' to +--- specify special kinds of buffers. See `special-buffers`. +--- +--- @type boolean +vim.o.swapfile = true +vim.o.swf = vim.o.swapfile +vim.bo.swapfile = vim.o.swapfile +vim.bo.swf = vim.bo.swapfile + +--- This option controls the behavior when switching between buffers. +--- This option is checked, when +--- - jumping to errors with the `quickfix` commands (`:cc`, `:cn`, `:cp`, +--- etc.). +--- - jumping to a tag using the `:stag` command. +--- - opening a file using the `CTRL-W_f` or `CTRL-W_F` command. +--- - jumping to a buffer using a buffer split command (e.g. `:sbuffer`, +--- `:sbnext`, or `:sbrewind`). +--- Possible values (comma-separated list): +--- useopen If included, jump to the first open window in the +--- current tab page that contains the specified buffer +--- (if there is one). Otherwise: Do not examine other +--- windows. +--- usetab Like "useopen", but also consider windows in other tab +--- pages. +--- split If included, split the current window before loading +--- a buffer for a `quickfix` command that display errors. +--- Otherwise: do not split, use current window (when used +--- in the quickfix window: the previously used window or +--- split if there is no other window). +--- vsplit Just like "split" but split vertically. +--- newtab Like "split", but open a new tab page. Overrules +--- "split" when both are present. +--- uselast If included, jump to the previously used window when +--- jumping to errors with `quickfix` commands. +--- +--- @type string +vim.o.switchbuf = "uselast" +vim.o.swb = vim.o.switchbuf +vim.go.switchbuf = vim.o.switchbuf +vim.go.swb = vim.go.switchbuf + +--- Maximum column in which to search for syntax items. In long lines the +--- text after this column is not highlighted and following lines may not +--- be highlighted correctly, because the syntax state is cleared. +--- This helps to avoid very slow redrawing for an XML file that is one +--- long line. +--- Set to zero to remove the limit. +--- +--- @type integer +vim.o.synmaxcol = 3000 +vim.o.smc = vim.o.synmaxcol +vim.bo.synmaxcol = vim.o.synmaxcol +vim.bo.smc = vim.bo.synmaxcol + +--- When this option is set, the syntax with this name is loaded, unless +--- syntax highlighting has been switched off with ":syntax off". +--- Otherwise this option does not always reflect the current syntax (the +--- b:current_syntax variable does). +--- This option is most useful in a modeline, for a file which syntax is +--- not automatically recognized. Example, in an IDL file: +--- ``` +--- /* vim: set syntax=idl : */ +--- ``` +--- When a dot appears in the value then this separates two filetype +--- names. Example: +--- ``` +--- /* vim: set syntax=c.doxygen : */ +--- ``` +--- This will use the "c" syntax first, then the "doxygen" syntax. +--- Note that the second one must be prepared to be loaded as an addition, +--- otherwise it will be skipped. More than one dot may appear. +--- To switch off syntax highlighting for the current file, use: +--- ``` +--- :set syntax=OFF +--- ``` +--- To switch syntax highlighting on according to the current value of the +--- 'filetype' option: +--- ``` +--- :set syntax=ON +--- ``` +--- What actually happens when setting the 'syntax' option is that the +--- Syntax autocommand event is triggered with the value as argument. +--- This option is not copied to another buffer, independent of the 's' or +--- 'S' flag in 'cpoptions'. +--- Only normal file name characters can be used, `/\*?[|<>` are illegal. +--- +--- @type string +vim.o.syntax = "" +vim.o.syn = vim.o.syntax +vim.bo.syntax = vim.o.syntax +vim.bo.syn = vim.bo.syntax + +--- When non-empty, this option determines the content of the tab pages +--- line at the top of the Vim window. When empty Vim will use a default +--- tab pages line. See `setting-tabline` for more info. +--- +--- The tab pages line only appears as specified with the 'showtabline' +--- option and only when there is no GUI tab line. When 'e' is in +--- 'guioptions' and the GUI supports a tab line 'guitablabel' is used +--- instead. Note that the two tab pages lines are very different. +--- +--- The value is evaluated like with 'statusline'. You can use +--- `tabpagenr()`, `tabpagewinnr()` and `tabpagebuflist()` to figure out +--- the text to be displayed. Use "%1T" for the first label, "%2T" for +--- the second one, etc. Use "%X" items for closing labels. +--- +--- When changing something that is used in 'tabline' that does not +--- trigger it to be updated, use `:redrawtabline`. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- Keep in mind that only one of the tab pages is the current one, others +--- are invisible and you can't jump to their windows. +--- +--- @type string +vim.o.tabline = "" +vim.o.tal = vim.o.tabline +vim.go.tabline = vim.o.tabline +vim.go.tal = vim.go.tabline + +--- Maximum number of tab pages to be opened by the `-p` command line +--- argument or the ":tab all" command. `tabpage` +--- +--- @type integer +vim.o.tabpagemax = 50 +vim.o.tpm = vim.o.tabpagemax +vim.go.tabpagemax = vim.o.tabpagemax +vim.go.tpm = vim.go.tabpagemax + +--- Number of spaces that a <Tab> in the file counts for. Also see +--- the `:retab` command, and the 'softtabstop' option. +--- +--- Note: Setting 'tabstop' to any other value than 8 can make your file +--- appear wrong in many places. +--- The value must be more than 0 and less than 10000. +--- +--- There are four main ways to use tabs in Vim: +--- 1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 +--- (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim +--- will use a mix of tabs and spaces, but typing <Tab> and <BS> will +--- behave like a tab appears every 4 (or 3) characters. +--- This is the recommended way, the file will look the same with other +--- tools and when listing it in a terminal. +--- 2. Set 'softtabstop' and 'shiftwidth' to whatever you prefer and use +--- 'expandtab'. This way you will always insert spaces. The +--- formatting will never be messed up when 'tabstop' is changed (leave +--- it at 8 just in case). The file will be a bit larger. +--- You do need to check if no Tabs exist in the file. You can get rid +--- of them by first setting 'expandtab' and using `%retab!`, making +--- sure the value of 'tabstop' is set correctly. +--- 3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use +--- 'expandtab'. This way you will always insert spaces. The +--- formatting will never be messed up when 'tabstop' is changed. +--- You do need to check if no Tabs exist in the file, just like in the +--- item just above. +--- 4. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a +--- `modeline` to set these values when editing the file again. Only +--- works when using Vim to edit the file, other tools assume a tabstop +--- is worth 8 spaces. +--- 5. Always set 'tabstop' and 'shiftwidth' to the same value, and +--- 'noexpandtab'. This should then work (for initial indents only) +--- for any tabstop setting that people use. It might be nice to have +--- tabs after the first non-blank inserted as spaces if you do this +--- though. Otherwise aligned comments will be wrong when 'tabstop' is +--- changed. +--- +--- The value of 'tabstop' will be ignored if `'vartabstop'` is set to +--- anything other than an empty string. +--- +--- @type integer +vim.o.tabstop = 8 +vim.o.ts = vim.o.tabstop +vim.bo.tabstop = vim.o.tabstop +vim.bo.ts = vim.bo.tabstop + +--- When searching for a tag (e.g., for the `:ta` command), Vim can either +--- use a binary search or a linear search in a tags file. Binary +--- searching makes searching for a tag a LOT faster, but a linear search +--- will find more tags if the tags file wasn't properly sorted. +--- Vim normally assumes that your tags files are sorted, or indicate that +--- they are not sorted. Only when this is not the case does the +--- 'tagbsearch' option need to be switched off. +--- +--- When 'tagbsearch' is on, binary searching is first used in the tags +--- files. In certain situations, Vim will do a linear search instead for +--- certain files, or retry all files with a linear search. When +--- 'tagbsearch' is off, only a linear search is done. +--- +--- Linear searching is done anyway, for one file, when Vim finds a line +--- at the start of the file indicating that it's not sorted: +--- ``` +--- !_TAG_FILE_SORTED 0 /some comment/ +--- ``` +--- [The whitespace before and after the '0' must be a single <Tab>] +--- +--- When a binary search was done and no match was found in any of the +--- files listed in 'tags', and case is ignored or a pattern is used +--- instead of a normal tag name, a retry is done with a linear search. +--- Tags in unsorted tags files, and matches with different case will only +--- be found in the retry. +--- +--- If a tag file indicates that it is case-fold sorted, the second, +--- linear search can be avoided when case is ignored. Use a value of '2' +--- in the "!_TAG_FILE_SORTED" line for this. A tag file can be case-fold +--- sorted with the -f switch to "sort" in most unices, as in the command: +--- "sort -f -o tags tags". For Universal ctags and Exuberant ctags +--- version 5.x or higher (at least 5.5) the --sort=foldcase switch can be +--- used for this as well. Note that case must be folded to uppercase for +--- this to work. +--- +--- By default, tag searches are case-sensitive. Case is ignored when +--- 'ignorecase' is set and 'tagcase' is "followic", or when 'tagcase' is +--- "ignore". +--- Also when 'tagcase' is "followscs" and 'smartcase' is set, or +--- 'tagcase' is "smart", and the pattern contains only lowercase +--- characters. +--- +--- When 'tagbsearch' is off, tags searching is slower when a full match +--- exists, but faster when no full match exists. Tags in unsorted tags +--- files may only be found with 'tagbsearch' off. +--- When the tags file is not sorted, or sorted in a wrong way (not on +--- ASCII byte value), 'tagbsearch' should be off, or the line given above +--- must be included in the tags file. +--- This option doesn't affect commands that find all matching tags (e.g., +--- command-line completion and ":help"). +--- +--- @type boolean +vim.o.tagbsearch = true +vim.o.tbs = vim.o.tagbsearch +vim.go.tagbsearch = vim.o.tagbsearch +vim.go.tbs = vim.go.tagbsearch + +--- This option specifies how case is handled when searching the tags +--- file: +--- followic Follow the 'ignorecase' option +--- followscs Follow the 'smartcase' and 'ignorecase' options +--- ignore Ignore case +--- match Match case +--- smart Ignore case unless an upper case letter is used +--- +--- @type string +vim.o.tagcase = "followic" +vim.o.tc = vim.o.tagcase +vim.bo.tagcase = vim.o.tagcase +vim.bo.tc = vim.bo.tagcase +vim.go.tagcase = vim.o.tagcase +vim.go.tc = vim.go.tagcase + +--- This option specifies a function to be used to perform tag searches. +--- The function gets the tag pattern and should return a List of matching +--- tags. See `tag-function` for an explanation of how to write the +--- function and an example. The value can be the name of a function, a +--- `lambda` or a `Funcref`. See `option-value-function` for more +--- information. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.tagfunc = "" +vim.o.tfu = vim.o.tagfunc +vim.bo.tagfunc = vim.o.tagfunc +vim.bo.tfu = vim.bo.tagfunc + +--- If non-zero, tags are significant up to this number of characters. +--- +--- @type integer +vim.o.taglength = 0 +vim.o.tl = vim.o.taglength +vim.go.taglength = vim.o.taglength +vim.go.tl = vim.go.taglength + +--- If on and using a tags file in another directory, file names in that +--- tags file are relative to the directory where the tags file is. +--- +--- @type boolean +vim.o.tagrelative = true +vim.o.tr = vim.o.tagrelative +vim.go.tagrelative = vim.o.tagrelative +vim.go.tr = vim.go.tagrelative + +--- Filenames for the tag command, separated by spaces or commas. To +--- include a space or comma in a file name, precede it with backslashes +--- (see `option-backslash` about including spaces/commas and backslashes). +--- When a file name starts with "./", the '.' is replaced with the path +--- of the current file. But only when the 'd' flag is not included in +--- 'cpoptions'. Environment variables are expanded `:set_env`. Also see +--- `tags-option`. +--- "*", "**" and other wildcards can be used to search for tags files in +--- a directory tree. See `file-searching`. E.g., "/lib/**/tags" will +--- find all files named "tags" below "/lib". The filename itself cannot +--- contain wildcards, it is used as-is. E.g., "/lib/**/tags?" will find +--- files called "tags?". +--- The `tagfiles()` function can be used to get a list of the file names +--- actually used. +--- The use of `:set+=` and `:set-=` is preferred when adding or removing +--- file names from the list. This avoids problems when a future version +--- uses another default. +--- +--- @type string +vim.o.tags = "./tags;,tags" +vim.o.tag = vim.o.tags +vim.bo.tags = vim.o.tags +vim.bo.tag = vim.bo.tags +vim.go.tags = vim.o.tags +vim.go.tag = vim.go.tags + +--- When on, the `tagstack` is used normally. When off, a ":tag" or +--- ":tselect" command with an argument will not push the tag onto the +--- tagstack. A following ":tag" without an argument, a ":pop" command or +--- any other command that uses the tagstack will use the unmodified +--- tagstack, but does change the pointer to the active entry. +--- Resetting this option is useful when using a ":tag" command in a +--- mapping which should not change the tagstack. +--- +--- @type boolean +vim.o.tagstack = true +vim.o.tgst = vim.o.tagstack +vim.go.tagstack = vim.o.tagstack +vim.go.tgst = vim.go.tagstack + +--- The terminal is in charge of Bi-directionality of text (as specified +--- by Unicode). The terminal is also expected to do the required shaping +--- that some languages (such as Arabic) require. +--- Setting this option implies that 'rightleft' will not be set when +--- 'arabic' is set and the value of 'arabicshape' will be ignored. +--- Note that setting 'termbidi' has the immediate effect that +--- 'arabicshape' is ignored, but 'rightleft' isn't changed automatically. +--- For further details see `arabic.txt`. +--- +--- @type boolean +vim.o.termbidi = false +vim.o.tbidi = vim.o.termbidi +vim.go.termbidi = vim.o.termbidi +vim.go.tbidi = vim.go.termbidi + +--- Enables 24-bit RGB color in the `TUI`. Uses "gui" `:highlight` +--- attributes instead of "cterm" attributes. `guifg` +--- Requires an ISO-8613-3 compatible terminal. +--- +--- @type boolean +vim.o.termguicolors = false +vim.o.tgc = vim.o.termguicolors +vim.go.termguicolors = vim.o.termguicolors +vim.go.tgc = vim.go.termguicolors + +--- A comma-separated list of options for specifying control characters +--- to be removed from the text pasted into the terminal window. The +--- supported values are: +--- +--- BS Backspace +--- +--- HT TAB +--- +--- FF Form feed +--- +--- ESC Escape +--- +--- DEL DEL +--- +--- C0 Other control characters, excluding Line feed and +--- Carriage return < ' ' +--- +--- C1 Control characters 0x80...0x9F +--- +--- @type string +vim.o.termpastefilter = "BS,HT,ESC,DEL" +vim.o.tpf = vim.o.termpastefilter +vim.go.termpastefilter = vim.o.termpastefilter +vim.go.tpf = vim.go.termpastefilter + +--- If the host terminal supports it, buffer all screen updates +--- made during a redraw cycle so that each screen is displayed in +--- the terminal all at once. This can prevent tearing or flickering +--- when the terminal updates faster than Nvim can redraw. +--- +--- @type boolean +vim.o.termsync = true +vim.go.termsync = vim.o.termsync + +--- Maximum width of text that is being inserted. A longer line will be +--- broken after white space to get this width. A zero value disables +--- this. +--- When 'textwidth' is zero, 'wrapmargin' may be used. See also +--- 'formatoptions' and `ins-textwidth`. +--- When 'formatexpr' is set it will be used to break the line. +--- +--- @type integer +vim.o.textwidth = 0 +vim.o.tw = vim.o.textwidth +vim.bo.textwidth = vim.o.textwidth +vim.bo.tw = vim.bo.textwidth + +--- List of file names, separated by commas, that are used to lookup words +--- for thesaurus completion commands `i_CTRL-X_CTRL-T`. See +--- `compl-thesaurus`. +--- +--- This option is not used if 'thesaurusfunc' is set, either for the +--- buffer or globally. +--- +--- To include a comma in a file name precede it with a backslash. Spaces +--- after a comma are ignored, otherwise spaces are included in the file +--- name. See `option-backslash` about using backslashes. The use of +--- `:set+=` and `:set-=` is preferred when adding or removing directories +--- from the list. This avoids problems when a future version uses +--- another default. Backticks cannot be used in this option for security +--- reasons. +--- +--- @type string +vim.o.thesaurus = "" +vim.o.tsr = vim.o.thesaurus +vim.bo.thesaurus = vim.o.thesaurus +vim.bo.tsr = vim.bo.thesaurus +vim.go.thesaurus = vim.o.thesaurus +vim.go.tsr = vim.go.thesaurus + +--- This option specifies a function to be used for thesaurus completion +--- with CTRL-X CTRL-T. `i_CTRL-X_CTRL-T` See `compl-thesaurusfunc`. +--- The value can be the name of a function, a `lambda` or a `Funcref`. +--- See `option-value-function` for more information. +--- +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.thesaurusfunc = "" +vim.o.tsrfu = vim.o.thesaurusfunc +vim.bo.thesaurusfunc = vim.o.thesaurusfunc +vim.bo.tsrfu = vim.bo.thesaurusfunc +vim.go.thesaurusfunc = vim.o.thesaurusfunc +vim.go.tsrfu = vim.go.thesaurusfunc + +--- When on: The tilde command "~" behaves like an operator. +--- +--- @type boolean +vim.o.tildeop = false +vim.o.top = vim.o.tildeop +vim.go.tildeop = vim.o.tildeop +vim.go.top = vim.go.tildeop + +--- This option and 'timeoutlen' determine the behavior when part of a +--- mapped key sequence has been received. For example, if <c-f> is +--- pressed and 'timeout' is set, Nvim will wait 'timeoutlen' milliseconds +--- for any key that can follow <c-f> in a mapping. +--- +--- @type boolean +vim.o.timeout = true +vim.o.to = vim.o.timeout +vim.go.timeout = vim.o.timeout +vim.go.to = vim.go.timeout + +--- Time in milliseconds to wait for a mapped sequence to complete. +--- +--- @type integer +vim.o.timeoutlen = 1000 +vim.o.tm = vim.o.timeoutlen +vim.go.timeoutlen = vim.o.timeoutlen +vim.go.tm = vim.go.timeoutlen + +--- When on, the title of the window will be set to the value of +--- 'titlestring' (if it is not empty), or to: +--- filename [+=-] (path) - NVIM +--- Where: +--- filename the name of the file being edited +--- - indicates the file cannot be modified, 'ma' off +--- + indicates the file was modified +--- = indicates the file is read-only +--- =+ indicates the file is read-only and modified +--- (path) is the path of the file being edited +--- - NVIM the server name `v:servername` or "NVIM" +--- +--- @type boolean +vim.o.title = false +vim.go.title = vim.o.title + +--- Gives the percentage of 'columns' to use for the length of the window +--- title. When the title is longer, only the end of the path name is +--- shown. A '<' character before the path name is used to indicate this. +--- Using a percentage makes this adapt to the width of the window. But +--- it won't work perfectly, because the actual number of characters +--- available also depends on the font used and other things in the title +--- bar. When 'titlelen' is zero the full path is used. Otherwise, +--- values from 1 to 30000 percent can be used. +--- 'titlelen' is also used for the 'titlestring' option. +--- +--- @type integer +vim.o.titlelen = 85 +vim.go.titlelen = vim.o.titlelen + +--- If not empty, this option will be used to set the window title when +--- exiting. Only if 'title' is enabled. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.titleold = "" +vim.go.titleold = vim.o.titleold + +--- When this option is not empty, it will be used for the title of the +--- window. This happens only when the 'title' option is on. +--- +--- When this option contains printf-style '%' items, they will be +--- expanded according to the rules used for 'statusline'. +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- Example: +--- ``` +--- :auto BufEnter * let &titlestring = hostname() .. "/" .. expand("%:p") +--- :set title titlestring=%<%F%=%l/%L-%P titlelen=70 +--- ``` +--- The value of 'titlelen' is used to align items in the middle or right +--- of the available space. +--- Some people prefer to have the file name first: +--- ``` +--- :set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:~:.:h\")})%)%(\ %a%) +--- ``` +--- Note the use of "%{ }" and an expression to get the path of the file, +--- without the file name. The "%( %)" constructs are used to add a +--- separating space only when needed. +--- NOTE: Use of special characters in 'titlestring' may cause the display +--- to be garbled (e.g., when it contains a CR or NL character). +--- +--- @type string +vim.o.titlestring = "" +vim.go.titlestring = vim.o.titlestring + +--- This option and 'ttimeoutlen' determine the behavior when part of a +--- key code sequence has been received by the `TUI`. +--- +--- For example if <Esc> (the \x1b byte) is received and 'ttimeout' is +--- set, Nvim waits 'ttimeoutlen' milliseconds for the terminal to +--- complete a key code sequence. If no input arrives before the timeout, +--- a single <Esc> is assumed. Many TUI cursor key codes start with <Esc>. +--- +--- On very slow systems this may fail, causing cursor keys not to work +--- sometimes. If you discover this problem you can ":set ttimeoutlen=9999". +--- Nvim will wait for the next character to arrive after an <Esc>. +--- +--- @type boolean +vim.o.ttimeout = true +vim.go.ttimeout = vim.o.ttimeout + +--- Time in milliseconds to wait for a key code sequence to complete. Also +--- used for CTRL-\ CTRL-N and CTRL-\ CTRL-G when part of a command has +--- been typed. +--- +--- @type integer +vim.o.ttimeoutlen = 50 +vim.o.ttm = vim.o.ttimeoutlen +vim.go.ttimeoutlen = vim.o.ttimeoutlen +vim.go.ttm = vim.go.ttimeoutlen + +--- List of directory names for undo files, separated with commas. +--- See 'backupdir' for details of the format. +--- "." means using the directory of the file. The undo file name for +--- "file.txt" is ".file.txt.un~". +--- For other directories the file name is the full path of the edited +--- file, with path separators replaced with "%". +--- When writing: The first directory that exists is used. "." always +--- works, no directories after "." will be used for writing. If none of +--- the directories exist Nvim will attempt to create the last directory in +--- the list. +--- When reading all entries are tried to find an undo file. The first +--- undo file that exists is used. When it cannot be read an error is +--- given, no further entry is used. +--- See `undo-persistence`. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- Note that unlike 'directory' and 'backupdir', 'undodir' always acts as +--- though the trailing slashes are present (see 'backupdir' for what this +--- means). +--- +--- @type string +vim.o.undodir = "$XDG_STATE_HOME/nvim/undo//" +vim.o.udir = vim.o.undodir +vim.go.undodir = vim.o.undodir +vim.go.udir = vim.go.undodir + +--- When on, Vim automatically saves undo history to an undo file when +--- writing a buffer to a file, and restores undo history from the same +--- file on buffer read. +--- The directory where the undo file is stored is specified by 'undodir'. +--- For more information about this feature see `undo-persistence`. +--- The undo file is not read when 'undoreload' causes the buffer from +--- before a reload to be saved for undo. +--- When 'undofile' is turned off the undo file is NOT deleted. +--- +--- @type boolean +vim.o.undofile = false +vim.o.udf = vim.o.undofile +vim.bo.undofile = vim.o.undofile +vim.bo.udf = vim.bo.undofile + +--- Maximum number of changes that can be undone. Since undo information +--- is kept in memory, higher numbers will cause more memory to be used. +--- Nevertheless, a single change can already use a large amount of memory. +--- Set to 0 for Vi compatibility: One level of undo and "u" undoes +--- itself: +--- ``` +--- set ul=0 +--- ``` +--- But you can also get Vi compatibility by including the 'u' flag in +--- 'cpoptions', and still be able to use CTRL-R to repeat undo. +--- Also see `undo-two-ways`. +--- Set to -1 for no undo at all. You might want to do this only for the +--- current buffer: +--- ``` +--- setlocal ul=-1 +--- ``` +--- This helps when you run out of memory for a single change. +--- +--- The local value is set to -123456 when the global value is to be used. +--- +--- Also see `clear-undo`. +--- +--- @type integer +vim.o.undolevels = 1000 +vim.o.ul = vim.o.undolevels +vim.bo.undolevels = vim.o.undolevels +vim.bo.ul = vim.bo.undolevels +vim.go.undolevels = vim.o.undolevels +vim.go.ul = vim.go.undolevels + +--- Save the whole buffer for undo when reloading it. This applies to the +--- ":e!" command and reloading for when the buffer changed outside of +--- Vim. `FileChangedShell` +--- The save only happens when this option is negative or when the number +--- of lines is smaller than the value of this option. +--- Set this option to zero to disable undo for a reload. +--- +--- When saving undo for a reload, any undo file is not read. +--- +--- Note that this causes the whole buffer to be stored in memory. Set +--- this option to a lower value if you run out of memory. +--- +--- @type integer +vim.o.undoreload = 10000 +vim.o.ur = vim.o.undoreload +vim.go.undoreload = vim.o.undoreload +vim.go.ur = vim.go.undoreload + +--- After typing this many characters the swap file will be written to +--- disk. When zero, no swap file will be created at all (see chapter on +--- recovery `crash-recovery`). 'updatecount' is set to zero by starting +--- Vim with the "-n" option, see `startup`. When editing in readonly +--- mode this option will be initialized to 10000. +--- The swapfile can be disabled per buffer with `'swapfile'`. +--- When 'updatecount' is set from zero to non-zero, swap files are +--- created for all buffers that have 'swapfile' set. When 'updatecount' +--- is set to zero, existing swap files are not deleted. +--- This option has no meaning in buffers where `'buftype'` is "nofile" +--- or "nowrite". +--- +--- @type integer +vim.o.updatecount = 200 +vim.o.uc = vim.o.updatecount +vim.go.updatecount = vim.o.updatecount +vim.go.uc = vim.go.updatecount + +--- If this many milliseconds nothing is typed the swap file will be +--- written to disk (see `crash-recovery`). Also used for the +--- `CursorHold` autocommand event. +--- +--- @type integer +vim.o.updatetime = 4000 +vim.o.ut = vim.o.updatetime +vim.go.updatetime = vim.o.updatetime +vim.go.ut = vim.go.updatetime + +--- A list of the number of spaces that a <Tab> counts for while editing, +--- such as inserting a <Tab> or using <BS>. It "feels" like variable- +--- width <Tab>s are being inserted, while in fact a mixture of spaces +--- and <Tab>s is used. Tab widths are separated with commas, with the +--- final value applying to all subsequent tabs. +--- +--- For example, when editing assembly language files where statements +--- start in the 9th column and comments in the 41st, it may be useful +--- to use the following: +--- ``` +--- :set varsofttabstop=8,32,8 +--- ``` +--- This will set soft tabstops with 8 and 8 + 32 spaces, and 8 more +--- for every column thereafter. +--- +--- Note that the value of `'softtabstop'` will be ignored while +--- 'varsofttabstop' is set. +--- +--- @type string +vim.o.varsofttabstop = "" +vim.o.vsts = vim.o.varsofttabstop +vim.bo.varsofttabstop = vim.o.varsofttabstop +vim.bo.vsts = vim.bo.varsofttabstop + +--- A list of the number of spaces that a <Tab> in the file counts for, +--- separated by commas. Each value corresponds to one tab, with the +--- final value applying to all subsequent tabs. For example: +--- ``` +--- :set vartabstop=4,20,10,8 +--- ``` +--- This will make the first tab 4 spaces wide, the second 20 spaces, +--- the third 10 spaces, and all following tabs 8 spaces. +--- +--- Note that the value of `'tabstop'` will be ignored while 'vartabstop' +--- is set. +--- +--- @type string +vim.o.vartabstop = "" +vim.o.vts = vim.o.vartabstop +vim.bo.vartabstop = vim.o.vartabstop +vim.bo.vts = vim.bo.vartabstop + +--- Sets the verbosity level. Also set by `-V` and `:verbose`. +--- +--- Tracing of options in Lua scripts is activated at level 1; Lua scripts +--- are not traced with verbose=0, for performance. +--- +--- If greater than or equal to a given level, Nvim produces the following +--- messages: +--- +--- Level Messages ~ +--- ---------------------------------------------------------------------- +--- 1 Lua assignments to options, mappings, etc. +--- 2 When a file is ":source"'ed, or `shada` file is read or written. +--- 3 UI info, terminal capabilities. +--- 4 Shell commands. +--- 5 Every searched tags file and include file. +--- 8 Files for which a group of autocommands is executed. +--- 9 Executed autocommands. +--- 11 Finding items in a path. +--- 12 Vimscript function calls. +--- 13 When an exception is thrown, caught, finished, or discarded. +--- 14 Anything pending in a ":finally" clause. +--- 15 Ex commands from a script (truncated at 200 characters). +--- 16 Ex commands. +--- +--- If 'verbosefile' is set then the verbose messages are not displayed. +--- +--- @type integer +vim.o.verbose = 0 +vim.o.vbs = vim.o.verbose +vim.go.verbose = vim.o.verbose +vim.go.vbs = vim.go.verbose + +--- When not empty all messages are written in a file with this name. +--- When the file exists messages are appended. +--- Writing to the file ends when Vim exits or when 'verbosefile' is made +--- empty. Writes are buffered, thus may not show up for some time. +--- Setting 'verbosefile' to a new value is like making it empty first. +--- The difference with `:redir` is that verbose messages are not +--- displayed when 'verbosefile' is set. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.verbosefile = "" +vim.o.vfile = vim.o.verbosefile +vim.go.verbosefile = vim.o.verbosefile +vim.go.vfile = vim.go.verbosefile + +--- Name of the directory where to store files for `:mkview`. +--- This option cannot be set from a `modeline` or in the `sandbox`, for +--- security reasons. +--- +--- @type string +vim.o.viewdir = "$XDG_STATE_HOME/nvim/view//" +vim.o.vdir = vim.o.viewdir +vim.go.viewdir = vim.o.viewdir +vim.go.vdir = vim.go.viewdir + +--- Changes the effect of the `:mkview` command. It is a comma-separated +--- list of words. Each word enables saving and restoring something: +--- word save and restore ~ +--- cursor cursor position in file and in window +--- curdir local current directory, if set with `:lcd` +--- folds manually created folds, opened/closed folds and local +--- fold options +--- options options and mappings local to a window or buffer (not +--- global values for local options) +--- localoptions same as "options" +--- slash `deprecated` Always enabled. Uses "/" in filenames. +--- unix `deprecated` Always enabled. Uses "\n" line endings. +--- +--- @type string +vim.o.viewoptions = "folds,cursor,curdir" +vim.o.vop = vim.o.viewoptions +vim.go.viewoptions = vim.o.viewoptions +vim.go.vop = vim.go.viewoptions + +--- A comma-separated list of these words: +--- block Allow virtual editing in Visual block mode. +--- insert Allow virtual editing in Insert mode. +--- all Allow virtual editing in all modes. +--- onemore Allow the cursor to move just past the end of the line +--- none When used as the local value, do not allow virtual +--- editing even when the global value is set. When used +--- as the global value, "none" is the same as "". +--- NONE Alternative spelling of "none". +--- +--- Virtual editing means that the cursor can be positioned where there is +--- no actual character. This can be halfway into a tab or beyond the end +--- of the line. Useful for selecting a rectangle in Visual mode and +--- editing a table. +--- "onemore" is not the same, it will only allow moving the cursor just +--- after the last character of the line. This makes some commands more +--- consistent. Previously the cursor was always past the end of the line +--- if the line was empty. But it is far from Vi compatible. It may also +--- break some plugins or Vim scripts. For example because `l` can move +--- the cursor after the last character. Use with care! +--- Using the `$` command will move to the last character in the line, not +--- past it. This may actually move the cursor to the left! +--- The `g$` command will move to the end of the screen line. +--- It doesn't make sense to combine "all" with "onemore", but you will +--- not get a warning for it. +--- When combined with other words, "none" is ignored. +--- +--- @type string +vim.o.virtualedit = "" +vim.o.ve = vim.o.virtualedit +vim.wo.virtualedit = vim.o.virtualedit +vim.wo.ve = vim.wo.virtualedit +vim.go.virtualedit = vim.o.virtualedit +vim.go.ve = vim.go.virtualedit + +--- Use visual bell instead of beeping. Also see 'errorbells'. +--- +--- @type boolean +vim.o.visualbell = false +vim.o.vb = vim.o.visualbell +vim.go.visualbell = vim.o.visualbell +vim.go.vb = vim.go.visualbell + +--- Give a warning message when a shell command is used while the buffer +--- has been changed. +--- +--- @type boolean +vim.o.warn = true +vim.go.warn = vim.o.warn + +--- Allow specified keys that move the cursor left/right to move to the +--- previous/next line when the cursor is on the first/last character in +--- the line. Concatenate characters to allow this for these keys: +--- char key mode ~ +--- b <BS> Normal and Visual +--- s <Space> Normal and Visual +--- h "h" Normal and Visual (not recommended) +--- l "l" Normal and Visual (not recommended) +--- < <Left> Normal and Visual +--- > <Right> Normal and Visual +--- ~ "~" Normal +--- [ <Left> Insert and Replace +--- ] <Right> Insert and Replace +--- For example: +--- ``` +--- :set ww=<,>,[,] +--- ``` +--- allows wrap only when cursor keys are used. +--- When the movement keys are used in combination with a delete or change +--- operator, the <EOL> also counts for a character. This makes "3h" +--- different from "3dh" when the cursor crosses the end of a line. This +--- is also true for "x" and "X", because they do the same as "dl" and +--- "dh". If you use this, you may also want to use the mapping +--- ":map <BS> X" to make backspace delete the character in front of the +--- cursor. +--- When 'l' is included and it is used after an operator at the end of a +--- line (not an empty line) then it will not move to the next line. This +--- makes "dl", "cl", "yl" etc. work normally. +--- +--- @type string +vim.o.whichwrap = "b,s" +vim.o.ww = vim.o.whichwrap +vim.go.whichwrap = vim.o.whichwrap +vim.go.ww = vim.go.whichwrap + +--- Character you have to type to start wildcard expansion in the +--- command-line, as specified with 'wildmode'. +--- More info here: `cmdline-completion`. +--- The character is not recognized when used inside a macro. See +--- 'wildcharm' for that. +--- Some keys will not work, such as CTRL-C, <CR> and Enter. +--- <Esc> can be used, but hitting it twice in a row will still exit +--- command-line as a failsafe measure. +--- Although 'wc' is a number option, you can set it to a special key: +--- ``` +--- :set wc=<Tab> +--- ``` +--- +--- +--- @type integer +vim.o.wildchar = 9 +vim.o.wc = vim.o.wildchar +vim.go.wildchar = vim.o.wildchar +vim.go.wc = vim.go.wildchar + +--- 'wildcharm' works exactly like 'wildchar', except that it is +--- recognized when used inside a macro. You can find "spare" command-line +--- keys suitable for this option by looking at `ex-edit-index`. Normally +--- you'll never actually type 'wildcharm', just use it in mappings that +--- automatically invoke completion mode, e.g.: +--- ``` +--- :set wcm=<C-Z> +--- :cnoremap ss so $vim/sessions/*.vim<C-Z> +--- ``` +--- Then after typing :ss you can use CTRL-P & CTRL-N. +--- +--- @type integer +vim.o.wildcharm = 0 +vim.o.wcm = vim.o.wildcharm +vim.go.wildcharm = vim.o.wildcharm +vim.go.wcm = vim.go.wildcharm + +--- A list of file patterns. A file that matches with one of these +--- patterns is ignored when expanding `wildcards`, completing file or +--- directory names, and influences the result of `expand()`, `glob()` and +--- `globpath()` unless a flag is passed to disable this. +--- The pattern is used like with `:autocmd`, see `autocmd-pattern`. +--- Also see 'suffixes'. +--- Example: +--- ``` +--- :set wildignore=*.o,*.obj +--- ``` +--- The use of `:set+=` and `:set-=` is preferred when adding or removing +--- a pattern from the list. This avoids problems when a future version +--- uses another default. +--- +--- @type string +vim.o.wildignore = "" +vim.o.wig = vim.o.wildignore +vim.go.wildignore = vim.o.wildignore +vim.go.wig = vim.go.wildignore + +--- When set case is ignored when completing file names and directories. +--- Has no effect when 'fileignorecase' is set. +--- Does not apply when the shell is used to expand wildcards, which +--- happens when there are special characters. +--- +--- @type boolean +vim.o.wildignorecase = false +vim.o.wic = vim.o.wildignorecase +vim.go.wildignorecase = vim.o.wildignorecase +vim.go.wic = vim.go.wildignorecase + +--- When 'wildmenu' is on, command-line completion operates in an enhanced +--- mode. On pressing 'wildchar' (usually <Tab>) to invoke completion, +--- the possible matches are shown. +--- When 'wildoptions' contains "pum", then the completion matches are +--- shown in a popup menu. Otherwise they are displayed just above the +--- command line, with the first match highlighted (overwriting the status +--- line, if there is one). +--- Keys that show the previous/next match, such as <Tab> or +--- CTRL-P/CTRL-N, cause the highlight to move to the appropriate match. +--- 'wildmode' must specify "full": "longest" and "list" do not start +--- 'wildmenu' mode. You can check the current mode with `wildmenumode()`. +--- The menu is cancelled when a key is hit that is not used for selecting +--- a completion. +--- +--- While the menu is active these keys have special meanings: +--- CTRL-P - go to the previous entry +--- CTRL-N - go to the next entry +--- <Left> <Right> - select previous/next match (like CTRL-P/CTRL-N) +--- <PageUp> - select a match several entries back +--- <PageDown> - select a match several entries further +--- <Up> - in filename/menu name completion: move up into +--- parent directory or parent menu. +--- <Down> - in filename/menu name completion: move into a +--- subdirectory or submenu. +--- <CR> - in menu completion, when the cursor is just after a +--- dot: move into a submenu. +--- CTRL-E - end completion, go back to what was there before +--- selecting a match. +--- CTRL-Y - accept the currently selected match and stop +--- completion. +--- +--- If you want <Left> and <Right> to move the cursor instead of selecting +--- a different match, use this: +--- ``` +--- :cnoremap <Left> <Space><BS><Left> +--- :cnoremap <Right> <Space><BS><Right> +--- ``` +--- +--- `hl-WildMenu` highlights the current match. +--- +--- @type boolean +vim.o.wildmenu = true +vim.o.wmnu = vim.o.wildmenu +vim.go.wildmenu = vim.o.wildmenu +vim.go.wmnu = vim.go.wildmenu + +--- Completion mode that is used for the character specified with +--- 'wildchar'. It is a comma-separated list of up to four parts. Each +--- part specifies what to do for each consecutive use of 'wildchar'. The +--- first part specifies the behavior for the first use of 'wildchar', +--- The second part for the second use, etc. +--- +--- Each part consists of a colon separated list consisting of the +--- following possible values: +--- "" Complete only the first match. +--- "full" Complete the next full match. After the last match, +--- the original string is used and then the first match +--- again. Will also start 'wildmenu' if it is enabled. +--- "longest" Complete till longest common string. If this doesn't +--- result in a longer string, use the next part. +--- "list" When more than one match, list all matches. +--- "lastused" When completing buffer names and more than one buffer +--- matches, sort buffers by time last used (other than +--- the current buffer). +--- When there is only a single match, it is fully completed in all cases. +--- +--- Examples of useful colon-separated values: +--- "longest:full" Like "longest", but also start 'wildmenu' if it is +--- enabled. Will not complete to the next full match. +--- "list:full" When more than one match, list all matches and +--- complete first match. +--- "list:longest" When more than one match, list all matches and +--- complete till longest common string. +--- "list:lastused" When more than one buffer matches, list all matches +--- and sort buffers by time last used (other than the +--- current buffer). +--- +--- Examples: +--- ``` +--- :set wildmode=full +--- ``` +--- Complete first full match, next match, etc. (the default) +--- ``` +--- :set wildmode=longest,full +--- ``` +--- Complete longest common string, then each full match +--- ``` +--- :set wildmode=list:full +--- ``` +--- List all matches and complete each full match +--- ``` +--- :set wildmode=list,full +--- ``` +--- List all matches without completing, then each full match +--- ``` +--- :set wildmode=longest,list +--- ``` +--- Complete longest common string, then list alternatives. +--- More info here: `cmdline-completion`. +--- +--- @type string +vim.o.wildmode = "full" +vim.o.wim = vim.o.wildmode +vim.go.wildmode = vim.o.wildmode +vim.go.wim = vim.go.wildmode + +--- A list of words that change how `cmdline-completion` is done. +--- The following values are supported: +--- fuzzy Use `fuzzy-matching` to find completion matches. When +--- this value is specified, wildcard expansion will not +--- be used for completion. The matches will be sorted by +--- the "best match" rather than alphabetically sorted. +--- This will find more matches than the wildcard +--- expansion. Currently fuzzy matching based completion +--- is not supported for file and directory names and +--- instead wildcard expansion is used. +--- pum Display the completion matches using the popup menu +--- in the same style as the `ins-completion-menu`. +--- tagfile When using CTRL-D to list matching tags, the kind of +--- tag and the file of the tag is listed. Only one match +--- is displayed per line. Often used tag kinds are: +--- d #define +--- f function +--- +--- @type string +vim.o.wildoptions = "pum,tagfile" +vim.o.wop = vim.o.wildoptions +vim.go.wildoptions = vim.o.wildoptions +vim.go.wop = vim.go.wildoptions + +--- only used in Win32 +--- Some GUI versions allow the access to menu entries by using the ALT +--- key in combination with a character that appears underlined in the +--- menu. This conflicts with the use of the ALT key for mappings and +--- entering special characters. This option tells what to do: +--- no Don't use ALT keys for menus. ALT key combinations can be +--- mapped, but there is no automatic handling. +--- yes ALT key handling is done by the windowing system. ALT key +--- combinations cannot be mapped. +--- menu Using ALT in combination with a character that is a menu +--- shortcut key, will be handled by the windowing system. Other +--- keys can be mapped. +--- If the menu is disabled by excluding 'm' from 'guioptions', the ALT +--- key is never used for the menu. +--- This option is not used for <F10>; on Win32. +--- +--- @type string +vim.o.winaltkeys = "menu" +vim.o.wak = vim.o.winaltkeys +vim.go.winaltkeys = vim.o.winaltkeys +vim.go.wak = vim.go.winaltkeys + +--- When non-empty, this option enables the window bar and determines its +--- contents. The window bar is a bar that's shown at the top of every +--- window with it enabled. The value of 'winbar' is evaluated like with +--- 'statusline'. +--- +--- When changing something that is used in 'winbar' that does not trigger +--- it to be updated, use `:redrawstatus`. +--- +--- Floating windows do not use the global value of 'winbar'. The +--- window-local value of 'winbar' must be set for a floating window to +--- have a window bar. +--- +--- This option cannot be set in a modeline when 'modelineexpr' is off. +--- +--- @type string +vim.o.winbar = "" +vim.o.wbr = vim.o.winbar +vim.wo.winbar = vim.o.winbar +vim.wo.wbr = vim.wo.winbar +vim.go.winbar = vim.o.winbar +vim.go.wbr = vim.go.winbar + +--- Enables pseudo-transparency for a floating window. Valid values are in +--- the range of 0 for fully opaque window (disabled) to 100 for fully +--- transparent background. Values between 0-30 are typically most useful. +--- +--- UI-dependent. Works best with RGB colors. 'termguicolors' +--- +--- @type integer +vim.o.winblend = 0 +vim.o.winbl = vim.o.winblend +vim.wo.winblend = vim.o.winblend +vim.wo.winbl = vim.wo.winblend + +--- Window height used for `CTRL-F` and `CTRL-B` when there is only one +--- window and the value is smaller than 'lines' minus one. The screen +--- will scroll 'window' minus two lines, with a minimum of one. +--- When 'window' is equal to 'lines' minus one CTRL-F and CTRL-B scroll +--- in a much smarter way, taking care of wrapping lines. +--- When resizing the Vim window, the value is smaller than 1 or more than +--- or equal to 'lines' it will be set to 'lines' minus 1. +--- Note: Do not confuse this with the height of the Vim window, use +--- 'lines' for that. +--- +--- @type integer +vim.o.window = 0 +vim.o.wi = vim.o.window +vim.go.window = vim.o.window +vim.go.wi = vim.go.window + +--- Keep the window height when windows are opened or closed and +--- 'equalalways' is set. Also for `CTRL-W_=`. Set by default for the +--- `preview-window` and `quickfix-window`. +--- The height may be changed anyway when running out of room. +--- +--- @type boolean +vim.o.winfixheight = false +vim.o.wfh = vim.o.winfixheight +vim.wo.winfixheight = vim.o.winfixheight +vim.wo.wfh = vim.wo.winfixheight + +--- Keep the window width when windows are opened or closed and +--- 'equalalways' is set. Also for `CTRL-W_=`. +--- The width may be changed anyway when running out of room. +--- +--- @type boolean +vim.o.winfixwidth = false +vim.o.wfw = vim.o.winfixwidth +vim.wo.winfixwidth = vim.o.winfixwidth +vim.wo.wfw = vim.wo.winfixwidth + +--- Minimal number of lines for the current window. This is not a hard +--- minimum, Vim will use fewer lines if there is not enough room. If the +--- focus goes to a window that is smaller, its size is increased, at the +--- cost of the height of other windows. +--- Set 'winheight' to a small number for normal editing. +--- Set it to 999 to make the current window fill most of the screen. +--- Other windows will be only 'winminheight' high. This has the drawback +--- that ":all" will create only two windows. To avoid "vim -o 1 2 3 4" +--- to create only two windows, set the option after startup is done, +--- using the `VimEnter` event: +--- ``` +--- au VimEnter * set winheight=999 +--- ``` +--- Minimum value is 1. +--- The height is not adjusted after one of the commands that change the +--- height of the current window. +--- 'winheight' applies to the current window. Use 'winminheight' to set +--- the minimal height for other windows. +--- +--- @type integer +vim.o.winheight = 1 +vim.o.wh = vim.o.winheight +vim.go.winheight = vim.o.winheight +vim.go.wh = vim.go.winheight + +--- Window-local highlights. Comma-delimited list of highlight +--- `group-name` pairs "{hl-from}:{hl-to},..." where each {hl-from} is +--- a `highlight-groups` item to be overridden by {hl-to} group in +--- the window. +--- +--- Note: highlight namespaces take precedence over 'winhighlight'. +--- See `nvim_win_set_hl_ns()` and `nvim_set_hl()`. +--- +--- Highlights of vertical separators are determined by the window to the +--- left of the separator. The 'tabline' highlight of a tabpage is +--- decided by the last-focused window of the tabpage. Highlights of +--- the popupmenu are determined by the current window. Highlights in the +--- message area cannot be overridden. +--- +--- Example: show a different color for non-current windows: +--- ``` +--- set winhighlight=Normal:MyNormal,NormalNC:MyNormalNC +--- ``` +--- +--- +--- @type string +vim.o.winhighlight = "" +vim.o.winhl = vim.o.winhighlight +vim.wo.winhighlight = vim.o.winhighlight +vim.wo.winhl = vim.wo.winhighlight + +--- The minimal height of a window, when it's not the current window. +--- This is a hard minimum, windows will never become smaller. +--- When set to zero, windows may be "squashed" to zero lines (i.e. just a +--- status bar) if necessary. They will return to at least one line when +--- they become active (since the cursor has to have somewhere to go.) +--- Use 'winheight' to set the minimal height of the current window. +--- This option is only checked when making a window smaller. Don't use a +--- large number, it will cause errors when opening more than a few +--- windows. A value of 0 to 3 is reasonable. +--- +--- @type integer +vim.o.winminheight = 1 +vim.o.wmh = vim.o.winminheight +vim.go.winminheight = vim.o.winminheight +vim.go.wmh = vim.go.winminheight + +--- The minimal width of a window, when it's not the current window. +--- This is a hard minimum, windows will never become smaller. +--- When set to zero, windows may be "squashed" to zero columns (i.e. just +--- a vertical separator) if necessary. They will return to at least one +--- line when they become active (since the cursor has to have somewhere +--- to go.) +--- Use 'winwidth' to set the minimal width of the current window. +--- This option is only checked when making a window smaller. Don't use a +--- large number, it will cause errors when opening more than a few +--- windows. A value of 0 to 12 is reasonable. +--- +--- @type integer +vim.o.winminwidth = 1 +vim.o.wmw = vim.o.winminwidth +vim.go.winminwidth = vim.o.winminwidth +vim.go.wmw = vim.go.winminwidth + +--- Minimal number of columns for the current window. This is not a hard +--- minimum, Vim will use fewer columns if there is not enough room. If +--- the current window is smaller, its size is increased, at the cost of +--- the width of other windows. Set it to 999 to make the current window +--- always fill the screen. Set it to a small number for normal editing. +--- The width is not adjusted after one of the commands to change the +--- width of the current window. +--- 'winwidth' applies to the current window. Use 'winminwidth' to set +--- the minimal width for other windows. +--- +--- @type integer +vim.o.winwidth = 20 +vim.o.wiw = vim.o.winwidth +vim.go.winwidth = vim.o.winwidth +vim.go.wiw = vim.go.winwidth + +--- This option changes how text is displayed. It doesn't change the text +--- in the buffer, see 'textwidth' for that. +--- When on, lines longer than the width of the window will wrap and +--- displaying continues on the next line. When off lines will not wrap +--- and only part of long lines will be displayed. When the cursor is +--- moved to a part that is not shown, the screen will scroll +--- horizontally. +--- The line will be broken in the middle of a word if necessary. See +--- 'linebreak' to get the break at a word boundary. +--- To make scrolling horizontally a bit more useful, try this: +--- ``` +--- :set sidescroll=5 +--- :set listchars+=precedes:<,extends:> +--- ``` +--- See 'sidescroll', 'listchars' and `wrap-off`. +--- This option can't be set from a `modeline` when the 'diff' option is +--- on. +--- +--- @type boolean +vim.o.wrap = true +vim.wo.wrap = vim.o.wrap + +--- Number of characters from the right window border where wrapping +--- starts. When typing text beyond this limit, an <EOL> will be inserted +--- and inserting continues on the next line. +--- Options that add a margin, such as 'number' and 'foldcolumn', cause +--- the text width to be further reduced. +--- When 'textwidth' is non-zero, this option is not used. +--- See also 'formatoptions' and `ins-textwidth`. +--- +--- @type integer +vim.o.wrapmargin = 0 +vim.o.wm = vim.o.wrapmargin +vim.bo.wrapmargin = vim.o.wrapmargin +vim.bo.wm = vim.bo.wrapmargin + +--- Searches wrap around the end of the file. Also applies to `]s` and +--- `[s`, searching for spelling mistakes. +--- +--- @type boolean +vim.o.wrapscan = true +vim.o.ws = vim.o.wrapscan +vim.go.wrapscan = vim.o.wrapscan +vim.go.ws = vim.go.wrapscan + +--- Allows writing files. When not set, writing a file is not allowed. +--- Can be used for a view-only mode, where modifications to the text are +--- still allowed. Can be reset with the `-m` or `-M` command line +--- argument. Filtering text is still possible, even though this requires +--- writing a temporary file. +--- +--- @type boolean +vim.o.write = true +vim.go.write = vim.o.write + +--- Allows writing to any file with no need for "!" override. +--- +--- @type boolean +vim.o.writeany = false +vim.o.wa = vim.o.writeany +vim.go.writeany = vim.o.writeany +vim.go.wa = vim.go.writeany + +--- Make a backup before overwriting a file. The backup is removed after +--- the file was successfully written, unless the 'backup' option is +--- also on. +--- WARNING: Switching this option off means that when Vim fails to write +--- your buffer correctly and then, for whatever reason, Vim exits, you +--- lose both the original file and what you were writing. Only reset +--- this option if your file system is almost full and it makes the write +--- fail (and make sure not to exit Vim until the write was successful). +--- See `backup-table` for another explanation. +--- When the 'backupskip' pattern matches, a backup is not made anyway. +--- Depending on 'backupcopy' the backup is a new file or the original +--- file renamed (and a new file is written). +--- +--- @type boolean +vim.o.writebackup = true +vim.o.wb = vim.o.writebackup +vim.go.writebackup = vim.o.writebackup +vim.go.wb = vim.go.writebackup + +--- Only takes effect together with 'redrawdebug'. +--- The number of milliseconds to wait after each line or each flush +--- +--- @type integer +vim.o.writedelay = 0 +vim.o.wd = vim.o.writedelay +vim.go.writedelay = vim.o.writedelay +vim.go.wd = vim.go.writedelay diff --git a/runtime/lua/vim/_meta/regex.lua b/runtime/lua/vim/_meta/regex.lua new file mode 100644 index 0000000000..58aa2be8c2 --- /dev/null +++ b/runtime/lua/vim/_meta/regex.lua @@ -0,0 +1,36 @@ +--- @meta + +-- luacheck: no unused args + +--- @defgroup vim.regex +--- +--- @brief Vim regexes can be used directly from Lua. Currently they only allow +--- matching within a single line. + +--- Parse the Vim regex {re} and return a regex object. Regexes are "magic" +--- and case-sensitive by default, regardless of 'magic' and 'ignorecase'. +--- They can be controlled with flags, see |/magic| and |/ignorecase|. +--- @param re string +--- @return vim.regex +function vim.regex(re) end + +--- @class vim.regex +local regex = {} -- luacheck: no unused + +--- Match the string against the regex. If the string should match the regex +--- precisely, surround the regex with `^` and `$`. If there was a match, the +--- byte indices for the beginning and end of the match are returned. When +--- there is no match, `nil` is returned. Because any integer is "truthy", +--- `regex:match_str()` can be directly used as a condition in an if-statement. +--- @param str string +function regex:match_str(str) end + +--- Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end} +--- are supplied, match only this byte index range. Otherwise see +--- |regex:match_str()|. If {start} is used, then the returned byte indices +--- will be relative {start}. +--- @param bufnr integer +--- @param line_idx integer +--- @param start? integer +--- @param end_? integer +function regex:match_line(bufnr, line_idx, start, end_) end diff --git a/runtime/lua/vim/_meta/spell.lua b/runtime/lua/vim/_meta/spell.lua new file mode 100644 index 0000000000..57f2180895 --- /dev/null +++ b/runtime/lua/vim/_meta/spell.lua @@ -0,0 +1,32 @@ +--- @meta + +-- luacheck: no unused args + +--- Check {str} for spelling errors. Similar to the Vimscript function +--- |spellbadword()|. +--- +--- Note: The behaviour of this function is dependent on: 'spelllang', +--- 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to +--- the buffer. Consider calling this with |nvim_buf_call()|. +--- +--- Example: +--- +--- ```lua +--- vim.spell.check("the quik brown fox") +--- -- => +--- -- { +--- -- {'quik', 'bad', 5} +--- -- } +--- ``` +--- +--- @param str string +--- @return {[1]: string, [2]: string, [3]: string}[] +--- List of tuples with three items: +--- - The badly spelled word. +--- - The type of the spelling error: +--- "bad" spelling mistake +--- "rare" rare word +--- "local" word only valid in another region +--- "caps" word should start with Capital +--- - The position in {str} where the word begins. +function vim.spell.check(str) end diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua new file mode 100644 index 0000000000..05e5b2b871 --- /dev/null +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -0,0 +1,10689 @@ +--- @meta _ +-- THIS FILE IS GENERATED +-- DO NOT EDIT +error('Cannot require a meta file') + +--- Return the absolute value of {expr}. When {expr} evaluates to +--- a |Float| abs() returns a |Float|. When {expr} can be +--- converted to a |Number| abs() returns a |Number|. Otherwise +--- abs() gives an error message and returns -1. +--- Examples: >vim +--- echo abs(1.456) +--- < 1.456 >vim +--- echo abs(-5.456) +--- < 5.456 >vim +--- echo abs(-4) +--- < 4 +--- +--- @param expr any +--- @return number +function vim.fn.abs(expr) end + +--- Return the arc cosine of {expr} measured in radians, as a +--- |Float| in the range of [0, pi]. +--- {expr} must evaluate to a |Float| or a |Number| in the range +--- [-1, 1]. +--- Returns NaN if {expr} is outside the range [-1, 1]. Returns +--- 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo acos(0) +--- < 1.570796 >vim +--- echo acos(-0.5) +--- < 2.094395 +--- +--- @param expr any +--- @return number +function vim.fn.acos(expr) end + +--- Append the item {expr} to |List| or |Blob| {object}. Returns +--- the resulting |List| or |Blob|. Examples: >vim +--- let alist = add([1, 2, 3], item) +--- call add(mylist, "woodstock") +--- <Note that when {expr} is a |List| it is appended as a single +--- item. Use |extend()| to concatenate |Lists|. +--- When {object} is a |Blob| then {expr} must be a number. +--- Use |insert()| to add an item at another position. +--- Returns 1 if {object} is not a |List| or a |Blob|. +--- +--- @param object any +--- @param expr any +--- @return any +function vim.fn.add(object, expr) end + +--- Bitwise AND on the two arguments. The arguments are converted +--- to a number. A List, Dict or Float argument causes an error. +--- Also see `or()` and `xor()`. +--- Example: >vim +--- let flag = and(bits, 0x80) +--- < +--- +--- @param expr any +--- @param expr1 any +--- @return integer +vim.fn['and'] = function(expr, expr1) end + +--- Returns Dictionary of |api-metadata|. +--- +--- View it in a nice human-readable format: >vim +--- lua vim.print(vim.fn.api_info()) +--- < +--- +--- @return table +function vim.fn.api_info() end + +--- When {text} is a |List|: Append each item of the |List| as a +--- text line below line {lnum} in the current buffer. +--- Otherwise append {text} as one text line below line {lnum} in +--- the current buffer. +--- Any type of item is accepted and converted to a String. +--- {lnum} can be zero to insert a line before the first one. +--- {lnum} is used like with |getline()|. +--- Returns 1 for failure ({lnum} out of range or out of memory), +--- 0 for success. When {text} is an empty list zero is returned, +--- no matter the value of {lnum}. Example: >vim +--- let failed = append(line('$'), "# THE END") +--- let failed = append(0, ["Chapter 1", "the beginning"]) +--- < +--- +--- @param lnum integer +--- @param text any +--- @return 0|1 +function vim.fn.append(lnum, text) end + +--- Like |append()| but append the text in buffer {expr}. +--- +--- This function works only for loaded buffers. First call +--- |bufload()| if needed. +--- +--- For the use of {buf}, see |bufname()|. +--- +--- {lnum} is the line number to append below. Note that using +--- |line()| would use the current buffer, not the one appending +--- to. Use "$" to append at the end of the buffer. Other string +--- values are not supported. +--- +--- On success 0 is returned, on failure 1 is returned. +--- +--- If {buf} is not a valid buffer or {lnum} is not valid, an +--- error message is given. Example: >vim +--- let failed = appendbufline(13, 0, "# THE START") +--- <However, when {text} is an empty list then no error is given +--- for an invalid {lnum}, since {lnum} isn't actually used. +--- +--- @param buf any +--- @param lnum integer +--- @param text string +--- @return 0|1 +function vim.fn.appendbufline(buf, lnum, text) end + +--- The result is the number of files in the argument list. See +--- |arglist|. +--- If {winid} is not supplied, the argument list of the current +--- window is used. +--- If {winid} is -1, the global argument list is used. +--- Otherwise {winid} specifies the window of which the argument +--- list is used: either the window number or the window ID. +--- Returns -1 if the {winid} argument is invalid. +--- +--- @param winid? integer +--- @return integer +function vim.fn.argc(winid) end + +--- The result is the current index in the argument list. 0 is +--- the first file. argc() - 1 is the last one. See |arglist|. +--- +--- @return integer +function vim.fn.argidx() end + +--- Return the argument list ID. This is a number which +--- identifies the argument list being used. Zero is used for the +--- global argument list. See |arglist|. +--- Returns -1 if the arguments are invalid. +--- +--- Without arguments use the current window. +--- With {winnr} only use this window in the current tab page. +--- With {winnr} and {tabnr} use the window in the specified tab +--- page. +--- {winnr} can be the window number or the |window-ID|. +--- +--- @param winnr? integer +--- @param tabnr? integer +--- @return integer +function vim.fn.arglistid(winnr, tabnr) end + +--- The result is the {nr}th file in the argument list. See +--- |arglist|. "argv(0)" is the first one. Example: >vim +--- let i = 0 +--- while i < argc() +--- let f = escape(fnameescape(argv(i)), '.') +--- exe 'amenu Arg.' .. f .. ' :e ' .. f .. '<CR>' +--- let i = i + 1 +--- endwhile +--- <Without the {nr} argument, or when {nr} is -1, a |List| with +--- the whole |arglist| is returned. +--- +--- The {winid} argument specifies the window ID, see |argc()|. +--- For the Vim command line arguments see |v:argv|. +--- +--- Returns an empty string if {nr}th argument is not present in +--- the argument list. Returns an empty List if the {winid} +--- argument is invalid. +--- +--- @param nr? integer +--- @param winid? integer +--- @return string|string[] +function vim.fn.argv(nr, winid) end + +--- Return the arc sine of {expr} measured in radians, as a |Float| +--- in the range of [-pi/2, pi/2]. +--- {expr} must evaluate to a |Float| or a |Number| in the range +--- [-1, 1]. +--- Returns NaN if {expr} is outside the range [-1, 1]. Returns +--- 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo asin(0.8) +--- < 0.927295 >vim +--- echo asin(-0.5) +--- < -0.523599 +--- +--- @param expr any +--- @return number +function vim.fn.asin(expr) end + +--- Run {cmd} and add an error message to |v:errors| if it does +--- NOT produce a beep or visual bell. +--- Also see |assert_fails()|, |assert_nobeep()| and +--- |assert-return|. +--- +--- @param cmd any +--- @return 0|1 +function vim.fn.assert_beeps(cmd) end + +--- When {expected} and {actual} are not equal an error message is +--- added to |v:errors| and 1 is returned. Otherwise zero is +--- returned. |assert-return| +--- The error is in the form "Expected {expected} but got +--- {actual}". When {msg} is present it is prefixed to that. +--- +--- There is no automatic conversion, the String "4" is different +--- from the Number 4. And the number 4 is different from the +--- Float 4.0. The value of 'ignorecase' is not used here, case +--- always matters. +--- Example: >vim +--- assert_equal('foo', 'bar') +--- <Will result in a string to be added to |v:errors|: +--- test.vim line 12: Expected 'foo' but got 'bar' ~ +--- +--- @param expected any +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_equal(expected, actual, msg) end + +--- When the files {fname-one} and {fname-two} do not contain +--- exactly the same text an error message is added to |v:errors|. +--- Also see |assert-return|. +--- When {fname-one} or {fname-two} does not exist the error will +--- mention that. +--- +--- @return 0|1 +function vim.fn.assert_equalfile() end + +--- When v:exception does not contain the string {error} an error +--- message is added to |v:errors|. Also see |assert-return|. +--- This can be used to assert that a command throws an exception. +--- Using the error number, followed by a colon, avoids problems +--- with translations: >vim +--- try +--- commandthatfails +--- call assert_false(1, 'command should have failed') +--- catch +--- call assert_exception('E492:') +--- endtry +--- < +--- +--- @param error any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_exception(error, msg) end + +--- Run {cmd} and add an error message to |v:errors| if it does +--- NOT produce an error or when {error} is not found in the +--- error message. Also see |assert-return|. +--- +--- When {error} is a string it must be found literally in the +--- first reported error. Most often this will be the error code, +--- including the colon, e.g. "E123:". >vim +--- assert_fails('bad cmd', 'E987:') +--- < +--- When {error} is a |List| with one or two strings, these are +--- used as patterns. The first pattern is matched against the +--- first reported error: >vim +--- assert_fails('cmd', ['E987:.*expected bool']) +--- <The second pattern, if present, is matched against the last +--- reported error. To only match the last error use an empty +--- string for the first error: >vim +--- assert_fails('cmd', ['', 'E987:']) +--- < +--- If {msg} is empty then it is not used. Do this to get the +--- default message when passing the {lnum} argument. +--- +--- When {lnum} is present and not negative, and the {error} +--- argument is present and matches, then this is compared with +--- the line number at which the error was reported. That can be +--- the line number in a function or in a script. +--- +--- When {context} is present it is used as a pattern and matched +--- against the context (script name or function name) where +--- {lnum} is located in. +--- +--- Note that beeping is not considered an error, and some failing +--- commands only beep. Use |assert_beeps()| for those. +--- +--- @param cmd any +--- @param error? any +--- @param msg? any +--- @param lnum? integer +--- @param context? any +--- @return 0|1 +function vim.fn.assert_fails(cmd, error, msg, lnum, context) end + +--- When {actual} is not false an error message is added to +--- |v:errors|, like with |assert_equal()|. +--- The error is in the form "Expected False but got {actual}". +--- When {msg} is present it is prepended to that. +--- Also see |assert-return|. +--- +--- A value is false when it is zero. When {actual} is not a +--- number the assert fails. +--- +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_false(actual, msg) end + +--- This asserts number and |Float| values. When {actual} is lower +--- than {lower} or higher than {upper} an error message is added +--- to |v:errors|. Also see |assert-return|. +--- The error is in the form "Expected range {lower} - {upper}, +--- but got {actual}". When {msg} is present it is prefixed to +--- that. +--- +--- @param lower any +--- @param upper any +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_inrange(lower, upper, actual, msg) end + +--- When {pattern} does not match {actual} an error message is +--- added to |v:errors|. Also see |assert-return|. +--- The error is in the form "Pattern {pattern} does not match +--- {actual}". When {msg} is present it is prefixed to that. +--- +--- {pattern} is used as with |expr-=~|: The matching is always done +--- like 'magic' was set and 'cpoptions' is empty, no matter what +--- the actual value of 'magic' or 'cpoptions' is. +--- +--- {actual} is used as a string, automatic conversion applies. +--- Use "^" and "$" to match with the start and end of the text. +--- Use both to match the whole text. +--- +--- Example: >vim +--- assert_match('^f.*o$', 'foobar') +--- <Will result in a string to be added to |v:errors|: +--- test.vim line 12: Pattern '^f.*o$' does not match 'foobar' ~ +--- +--- @param pattern any +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_match(pattern, actual, msg) end + +--- Run {cmd} and add an error message to |v:errors| if it +--- produces a beep or visual bell. +--- Also see |assert_beeps()|. +--- +--- @param cmd any +--- @return 0|1 +function vim.fn.assert_nobeep(cmd) end + +--- The opposite of `assert_equal()`: add an error message to +--- |v:errors| when {expected} and {actual} are equal. +--- Also see |assert-return|. +--- +--- @param expected any +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_notequal(expected, actual, msg) end + +--- The opposite of `assert_match()`: add an error message to +--- |v:errors| when {pattern} matches {actual}. +--- Also see |assert-return|. +--- +--- @param pattern any +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_notmatch(pattern, actual, msg) end + +--- Report a test failure directly, using String {msg}. +--- Always returns one. +--- +--- @param msg any +--- @return 0|1 +function vim.fn.assert_report(msg) end + +--- When {actual} is not true an error message is added to +--- |v:errors|, like with |assert_equal()|. +--- Also see |assert-return|. +--- A value is |TRUE| when it is a non-zero number or |v:true|. +--- When {actual} is not a number or |v:true| the assert fails. +--- When {msg} is given it precedes the default message. +--- +--- @param actual any +--- @param msg? any +--- @return 0|1 +function vim.fn.assert_true(actual, msg) end + +--- Return the principal value of the arc tangent of {expr}, in +--- the range [-pi/2, +pi/2] radians, as a |Float|. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo atan(100) +--- < 1.560797 >vim +--- echo atan(-4.01) +--- < -1.326405 +--- +--- @param expr any +--- @return number +function vim.fn.atan(expr) end + +--- Return the arc tangent of {expr1} / {expr2}, measured in +--- radians, as a |Float| in the range [-pi, pi]. +--- {expr1} and {expr2} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr1} or {expr2} is not a |Float| or a +--- |Number|. +--- Examples: >vim +--- echo atan2(-1, 1) +--- < -0.785398 >vim +--- echo atan2(1, -1) +--- < 2.356194 +--- +--- @param expr1 any +--- @param expr2 any +--- @return number +function vim.fn.atan2(expr1, expr2) end + +--- Return a List containing the number value of each byte in Blob +--- {blob}. Examples: >vim +--- blob2list(0z0102.0304) " returns [1, 2, 3, 4] +--- blob2list(0z) " returns [] +--- <Returns an empty List on error. |list2blob()| does the +--- opposite. +--- +--- @param blob any +--- @return any[] +function vim.fn.blob2list(blob) end + +--- Put up a file requester. This only works when "has("browse")" +--- returns |TRUE| (only in some GUI versions). +--- The input fields are: +--- {save} when |TRUE|, select file to write +--- {title} title for the requester +--- {initdir} directory to start browsing in +--- {default} default file name +--- An empty string is returned when the "Cancel" button is hit, +--- something went wrong, or browsing is not possible. +--- +--- @param save any +--- @param title any +--- @param initdir any +--- @param default any +--- @return 0|1 +function vim.fn.browse(save, title, initdir, default) end + +--- Put up a directory requester. This only works when +--- "has("browse")" returns |TRUE| (only in some GUI versions). +--- On systems where a directory browser is not supported a file +--- browser is used. In that case: select a file in the directory +--- to be used. +--- The input fields are: +--- {title} title for the requester +--- {initdir} directory to start browsing in +--- When the "Cancel" button is hit, something went wrong, or +--- browsing is not possible, an empty string is returned. +--- +--- @param title any +--- @param initdir any +--- @return 0|1 +function vim.fn.browsedir(title, initdir) end + +--- Add a buffer to the buffer list with name {name} (must be a +--- String). +--- If a buffer for file {name} already exists, return that buffer +--- number. Otherwise return the buffer number of the newly +--- created buffer. When {name} is an empty string then a new +--- buffer is always created. +--- The buffer will not have 'buflisted' set and not be loaded +--- yet. To add some text to the buffer use this: >vim +--- let bufnr = bufadd('someName') +--- call bufload(bufnr) +--- call setbufline(bufnr, 1, ['some', 'text']) +--- <Returns 0 on error. +--- +--- @param name string +--- @return integer +function vim.fn.bufadd(name) end + +--- The result is a Number, which is |TRUE| if a buffer called +--- {buf} exists. +--- If the {buf} argument is a number, buffer numbers are used. +--- Number zero is the alternate buffer for the current window. +--- +--- If the {buf} argument is a string it must match a buffer name +--- exactly. The name can be: +--- - Relative to the current directory. +--- - A full path. +--- - The name of a buffer with 'buftype' set to "nofile". +--- - A URL name. +--- Unlisted buffers will be found. +--- Note that help files are listed by their short name in the +--- output of |:buffers|, but bufexists() requires using their +--- long name to be able to find them. +--- bufexists() may report a buffer exists, but to use the name +--- with a |:buffer| command you may need to use |expand()|. Esp +--- for MS-Windows 8.3 names in the form "c:\DOCUME~1" +--- Use "bufexists(0)" to test for the existence of an alternate +--- file name. +--- +--- @param buf any +--- @return 0|1 +function vim.fn.bufexists(buf) end + +--- @deprecated +--- Obsolete name for |bufexists()|. +--- +--- @param ... any +--- @return 0|1 +function vim.fn.buffer_exists(...) end + +--- @deprecated +--- Obsolete name for |bufname()|. +--- +--- @param ... any +--- @return string +function vim.fn.buffer_name(...) end + +--- @deprecated +--- Obsolete name for |bufnr()|. +--- +--- @param ... any +--- @return integer +function vim.fn.buffer_number(...) end + +--- The result is a Number, which is |TRUE| if a buffer called +--- {buf} exists and is listed (has the 'buflisted' option set). +--- The {buf} argument is used like with |bufexists()|. +--- +--- @param buf any +--- @return 0|1 +function vim.fn.buflisted(buf) end + +--- Ensure the buffer {buf} is loaded. When the buffer name +--- refers to an existing file then the file is read. Otherwise +--- the buffer will be empty. If the buffer was already loaded +--- then there is no change. If the buffer is not related to a +--- file then no file is read (e.g., when 'buftype' is "nofile"). +--- If there is an existing swap file for the file of the buffer, +--- there will be no dialog, the buffer will be loaded anyway. +--- The {buf} argument is used like with |bufexists()|. +--- +--- @param buf any +function vim.fn.bufload(buf) end + +--- The result is a Number, which is |TRUE| if a buffer called +--- {buf} exists and is loaded (shown in a window or hidden). +--- The {buf} argument is used like with |bufexists()|. +--- +--- @param buf any +--- @return 0|1 +function vim.fn.bufloaded(buf) end + +--- The result is the name of a buffer. Mostly as it is displayed +--- by the `:ls` command, but not using special names such as +--- "[No Name]". +--- If {buf} is omitted the current buffer is used. +--- If {buf} is a Number, that buffer number's name is given. +--- Number zero is the alternate buffer for the current window. +--- If {buf} is a String, it is used as a |file-pattern| to match +--- with the buffer names. This is always done like 'magic' is +--- set and 'cpoptions' is empty. When there is more than one +--- match an empty string is returned. +--- "" or "%" can be used for the current buffer, "#" for the +--- alternate buffer. +--- A full match is preferred, otherwise a match at the start, end +--- or middle of the buffer name is accepted. If you only want a +--- full match then put "^" at the start and "$" at the end of the +--- pattern. +--- Listed buffers are found first. If there is a single match +--- with a listed buffer, that one is returned. Next unlisted +--- buffers are searched for. +--- If the {buf} is a String, but you want to use it as a buffer +--- number, force it to be a Number by adding zero to it: >vim +--- echo bufname("3" + 0) +--- <If the buffer doesn't exist, or doesn't have a name, an empty +--- string is returned. >vim +--- echo bufname("#") " alternate buffer name +--- echo bufname(3) " name of buffer 3 +--- echo bufname("%") " name of current buffer +--- echo bufname("file2") " name of buffer where "file2" matches. +--- < +--- +--- @param buf? any +--- @return string +function vim.fn.bufname(buf) end + +--- The result is the number of a buffer, as it is displayed by +--- the `:ls` command. For the use of {buf}, see |bufname()| +--- above. +--- If the buffer doesn't exist, -1 is returned. Or, if the +--- {create} argument is present and TRUE, a new, unlisted, +--- buffer is created and its number is returned. +--- bufnr("$") is the last buffer: >vim +--- let last_buffer = bufnr("$") +--- <The result is a Number, which is the highest buffer number +--- of existing buffers. Note that not all buffers with a smaller +--- number necessarily exist, because ":bwipeout" may have removed +--- them. Use bufexists() to test for the existence of a buffer. +--- +--- @param buf? any +--- @param create? any +--- @return integer +function vim.fn.bufnr(buf, create) end + +--- The result is a Number, which is the |window-ID| of the first +--- window associated with buffer {buf}. For the use of {buf}, +--- see |bufname()| above. If buffer {buf} doesn't exist or +--- there is no such window, -1 is returned. Example: >vim +--- +--- echo "A window containing buffer 1 is " .. (bufwinid(1)) +--- < +--- Only deals with the current tab page. See |win_findbuf()| for +--- finding more. +--- +--- @param buf any +--- @return integer +function vim.fn.bufwinid(buf) end + +--- Like |bufwinid()| but return the window number instead of the +--- |window-ID|. +--- If buffer {buf} doesn't exist or there is no such window, -1 +--- is returned. Example: >vim +--- +--- echo "A window containing buffer 1 is " .. (bufwinnr(1)) +--- +--- <The number can be used with |CTRL-W_w| and ":wincmd w" +--- |:wincmd|. +--- +--- @param buf any +--- @return integer +function vim.fn.bufwinnr(buf) end + +--- Return the line number that contains the character at byte +--- count {byte} in the current buffer. This includes the +--- end-of-line character, depending on the 'fileformat' option +--- for the current buffer. The first character has byte count +--- one. +--- Also see |line2byte()|, |go| and |:goto|. +--- +--- Returns -1 if the {byte} value is invalid. +--- +--- @param byte any +--- @return integer +function vim.fn.byte2line(byte) end + +--- Return byte index of the {nr}th character in the String +--- {expr}. Use zero for the first character, it then returns +--- zero. +--- If there are no multibyte characters the returned value is +--- equal to {nr}. +--- Composing characters are not counted separately, their byte +--- length is added to the preceding base character. See +--- |byteidxcomp()| below for counting composing characters +--- separately. +--- When {utf16} is present and TRUE, {nr} is used as the UTF-16 +--- index in the String {expr} instead of as the character index. +--- The UTF-16 index is the index in the string when it is encoded +--- with 16-bit words. If the specified UTF-16 index is in the +--- middle of a character (e.g. in a 4-byte character), then the +--- byte index of the first byte in the character is returned. +--- Refer to |string-offset-encoding| for more information. +--- Example : >vim +--- echo matchstr(str, ".", byteidx(str, 3)) +--- <will display the fourth character. Another way to do the +--- same: >vim +--- let s = strpart(str, byteidx(str, 3)) +--- echo strpart(s, 0, byteidx(s, 1)) +--- <Also see |strgetchar()| and |strcharpart()|. +--- +--- If there are less than {nr} characters -1 is returned. +--- If there are exactly {nr} characters the length of the string +--- in bytes is returned. +--- See |charidx()| and |utf16idx()| for getting the character and +--- UTF-16 index respectively from the byte index. +--- Examples: >vim +--- echo byteidx('a😊😊', 2) " returns 5 +--- echo byteidx('a😊😊', 2, 1) " returns 1 +--- echo byteidx('a😊😊', 3, 1) " returns 5 +--- < +--- +--- @param expr any +--- @param nr integer +--- @param utf16? any +--- @return integer +function vim.fn.byteidx(expr, nr, utf16) end + +--- Like byteidx(), except that a composing character is counted +--- as a separate character. Example: >vim +--- let s = 'e' .. nr2char(0x301) +--- echo byteidx(s, 1) +--- echo byteidxcomp(s, 1) +--- echo byteidxcomp(s, 2) +--- <The first and third echo result in 3 ('e' plus composing +--- character is 3 bytes), the second echo results in 1 ('e' is +--- one byte). +--- +--- @param expr any +--- @param nr integer +--- @param utf16? any +--- @return integer +function vim.fn.byteidxcomp(expr, nr, utf16) end + +--- Call function {func} with the items in |List| {arglist} as +--- arguments. +--- {func} can either be a |Funcref| or the name of a function. +--- a:firstline and a:lastline are set to the cursor line. +--- Returns the return value of the called function. +--- {dict} is for functions with the "dict" attribute. It will be +--- used to set the local variable "self". |Dictionary-function| +--- +--- @param func any +--- @param arglist any +--- @param dict? any +--- @return any +function vim.fn.call(func, arglist, dict) end + +--- Return the smallest integral value greater than or equal to +--- {expr} as a |Float| (round up). +--- {expr} must evaluate to a |Float| or a |Number|. +--- Examples: >vim +--- echo ceil(1.456) +--- < 2.0 >vim +--- echo ceil(-5.456) +--- < -5.0 >vim +--- echo ceil(4.0) +--- < 4.0 +--- +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- +--- @param expr any +--- @return number +function vim.fn.ceil(expr) end + +--- Close a channel or a specific stream associated with it. +--- For a job, {stream} can be one of "stdin", "stdout", +--- "stderr" or "rpc" (closes stdin/stdout for a job started +--- with `"rpc":v:true`) If {stream} is omitted, all streams +--- are closed. If the channel is a pty, this will then close the +--- pty master, sending SIGHUP to the job process. +--- For a socket, there is only one stream, and {stream} should be +--- omitted. +--- +--- @param id any +--- @param stream? any +--- @return 0|1 +function vim.fn.chanclose(id, stream) end + +--- Return the number of the most recent change. This is the same +--- number as what is displayed with |:undolist| and can be used +--- with the |:undo| command. +--- When a change was made it is the number of that change. After +--- redo it is the number of the redone change. After undo it is +--- one less than the number of the undone change. +--- Returns 0 if the undo list is empty. +--- +--- @return integer +function vim.fn.changenr() end + +--- Send data to channel {id}. For a job, it writes it to the +--- stdin of the process. For the stdio channel |channel-stdio|, +--- it writes to Nvim's stdout. Returns the number of bytes +--- written if the write succeeded, 0 otherwise. +--- See |channel-bytes| for more information. +--- +--- {data} may be a string, string convertible, |Blob|, or a list. +--- If {data} is a list, the items will be joined by newlines; any +--- newlines in an item will be sent as NUL. To send a final +--- newline, include a final empty string. Example: >vim +--- call chansend(id, ["abc", "123\n456", ""]) +--- <will send "abc<NL>123<NUL>456<NL>". +--- +--- chansend() writes raw data, not RPC messages. If the channel +--- was created with `"rpc":v:true` then the channel expects RPC +--- messages, use |rpcnotify()| and |rpcrequest()| instead. +--- +--- @param id any +--- @param data any +--- @return 0|1 +function vim.fn.chansend(id, data) end + +--- Return Number value of the first char in {string}. +--- Examples: >vim +--- echo char2nr(" ") " returns 32 +--- echo char2nr("ABC") " returns 65 +--- echo char2nr("á") " returns 225 +--- echo char2nr("á"[0]) " returns 195 +--- echo char2nr("\<M-x>") " returns 128 +--- <Non-ASCII characters are always treated as UTF-8 characters. +--- {utf8} is ignored, it exists only for backwards-compatibility. +--- A combining character is a separate character. +--- |nr2char()| does the opposite. +--- +--- Returns 0 if {string} is not a |String|. +--- +--- @param string string +--- @param utf8? any +--- @return 0|1 +function vim.fn.char2nr(string, utf8) end + +--- Return the character class of the first character in {string}. +--- The character class is one of: +--- 0 blank +--- 1 punctuation +--- 2 word character +--- 3 emoji +--- other specific Unicode class +--- The class is used in patterns and word motions. +--- Returns 0 if {string} is not a |String|. +--- +--- @param string string +--- @return 0|1|2|3|'other' +function vim.fn.charclass(string) end + +--- Same as |col()| but returns the character index of the column +--- position given with {expr} instead of the byte position. +--- +--- Example: +--- With the cursor on '세' in line 5 with text "여보세요": >vim +--- echo charcol('.') " returns 3 +--- echo col('.') " returns 7 +--- +--- @param expr any +--- @param winid? integer +--- @return integer +function vim.fn.charcol(expr, winid) end + +--- Return the character index of the byte at {idx} in {string}. +--- The index of the first character is zero. +--- If there are no multibyte characters the returned value is +--- equal to {idx}. +--- +--- When {countcc} is omitted or |FALSE|, then composing characters +--- are not counted separately, their byte length is added to the +--- preceding base character. +--- When {countcc} is |TRUE|, then composing characters are +--- counted as separate characters. +--- +--- When {utf16} is present and TRUE, {idx} is used as the UTF-16 +--- index in the String {expr} instead of as the byte index. +--- +--- Returns -1 if the arguments are invalid or if there are less +--- than {idx} bytes. If there are exactly {idx} bytes the length +--- of the string in characters is returned. +--- +--- An error is given and -1 is returned if the first argument is +--- not a string, the second argument is not a number or when the +--- third argument is present and is not zero or one. +--- +--- See |byteidx()| and |byteidxcomp()| for getting the byte index +--- from the character index and |utf16idx()| for getting the +--- UTF-16 index from the character index. +--- Refer to |string-offset-encoding| for more information. +--- Examples: >vim +--- echo charidx('áb́ć', 3) " returns 1 +--- echo charidx('áb́ć', 6, 1) " returns 4 +--- echo charidx('áb́ć', 16) " returns -1 +--- echo charidx('a😊😊', 4, 0, 1) " returns 2 +--- < +--- +--- @param string string +--- @param idx integer +--- @param countcc? any +--- @param utf16? any +--- @return integer +function vim.fn.charidx(string, idx, countcc, utf16) end + +--- Change the current working directory to {dir}. The scope of +--- the directory change depends on the directory of the current +--- window: +--- - If the current window has a window-local directory +--- (|:lcd|), then changes the window local directory. +--- - Otherwise, if the current tabpage has a local +--- directory (|:tcd|) then changes the tabpage local +--- directory. +--- - Otherwise, changes the global directory. +--- {dir} must be a String. +--- If successful, returns the previous working directory. Pass +--- this to another chdir() to restore the directory. +--- On failure, returns an empty string. +--- +--- Example: >vim +--- let save_dir = chdir(newdir) +--- if save_dir != "" +--- " ... do some work +--- call chdir(save_dir) +--- endif +--- +--- @param dir string +--- @return string +function vim.fn.chdir(dir) end + +--- Get the amount of indent for line {lnum} according the C +--- indenting rules, as with 'cindent'. +--- The indent is counted in spaces, the value of 'tabstop' is +--- relevant. {lnum} is used just like in |getline()|. +--- When {lnum} is invalid -1 is returned. +--- See |C-indenting|. +--- +--- @param lnum integer +--- @return integer +function vim.fn.cindent(lnum) end + +--- Clears all matches previously defined for the current window +--- by |matchadd()| and the |:match| commands. +--- If {win} is specified, use the window with this number or +--- window ID instead of the current window. +--- +--- @param win? any +function vim.fn.clearmatches(win) end + +--- The result is a Number, which is the byte index of the column +--- position given with {expr}. The accepted positions are: +--- . the cursor position +--- $ the end of the cursor line (the result is the +--- number of bytes in the cursor line plus one) +--- 'x position of mark x (if the mark is not set, 0 is +--- returned) +--- v In Visual mode: the start of the Visual area (the +--- cursor is the end). When not in Visual mode +--- returns the cursor position. Differs from |'<| in +--- that it's updated right away. +--- Additionally {expr} can be [lnum, col]: a |List| with the line +--- and column number. Most useful when the column is "$", to get +--- the last column of a specific line. When "lnum" or "col" is +--- out of range then col() returns zero. +--- With the optional {winid} argument the values are obtained for +--- that window instead of the current window. +--- To get the line number use |line()|. To get both use +--- |getpos()|. +--- For the screen column position use |virtcol()|. For the +--- character position use |charcol()|. +--- Note that only marks in the current file can be used. +--- Examples: >vim +--- echo col(".") " column of cursor +--- echo col("$") " length of cursor line plus one +--- echo col("'t") " column of mark t +--- echo col("'" .. markname) " column of mark markname +--- <The first column is 1. Returns 0 if {expr} is invalid or when +--- the window with ID {winid} is not found. +--- For an uppercase mark the column may actually be in another +--- buffer. +--- For the cursor position, when 'virtualedit' is active, the +--- column is one higher if the cursor is after the end of the +--- line. Also, when using a <Cmd> mapping the cursor isn't +--- moved, this can be used to obtain the column in Insert mode: >vim +--- imap <F2> <Cmd>echo col(".").."\n"<CR> +--- +--- @param expr any +--- @param winid? integer +--- @return integer +function vim.fn.col(expr, winid) end + +--- Set the matches for Insert mode completion. +--- Can only be used in Insert mode. You need to use a mapping +--- with CTRL-R = (see |i_CTRL-R|). It does not work after CTRL-O +--- or with an expression mapping. +--- {startcol} is the byte offset in the line where the completed +--- text start. The text up to the cursor is the original text +--- that will be replaced by the matches. Use col('.') for an +--- empty string. "col('.') - 1" will replace one character by a +--- match. +--- {matches} must be a |List|. Each |List| item is one match. +--- See |complete-items| for the kind of items that are possible. +--- "longest" in 'completeopt' is ignored. +--- Note that the after calling this function you need to avoid +--- inserting anything that would cause completion to stop. +--- The match can be selected with CTRL-N and CTRL-P as usual with +--- Insert mode completion. The popup menu will appear if +--- specified, see |ins-completion-menu|. +--- Example: >vim +--- inoremap <F5> <C-R>=ListMonths()<CR> +--- +--- func ListMonths() +--- call complete(col('.'), ['January', 'February', 'March', +--- \ 'April', 'May', 'June', 'July', 'August', 'September', +--- \ 'October', 'November', 'December']) +--- return '' +--- endfunc +--- <This isn't very useful, but it shows how it works. Note that +--- an empty string is returned to avoid a zero being inserted. +--- +--- @param startcol any +--- @param matches any +function vim.fn.complete(startcol, matches) end + +--- Add {expr} to the list of matches. Only to be used by the +--- function specified with the 'completefunc' option. +--- Returns 0 for failure (empty string or out of memory), +--- 1 when the match was added, 2 when the match was already in +--- the list. +--- See |complete-functions| for an explanation of {expr}. It is +--- the same as one item in the list that 'omnifunc' would return. +--- +--- @param expr any +--- @return 0|1|2 +function vim.fn.complete_add(expr) end + +--- Check for a key typed while looking for completion matches. +--- This is to be used when looking for matches takes some time. +--- Returns |TRUE| when searching for matches is to be aborted, +--- zero otherwise. +--- Only to be used by the function specified with the +--- 'completefunc' option. +--- +--- @return 0|1 +function vim.fn.complete_check() end + +--- Returns a |Dictionary| with information about Insert mode +--- completion. See |ins-completion|. +--- The items are: +--- mode Current completion mode name string. +--- See |complete_info_mode| for the values. +--- pum_visible |TRUE| if popup menu is visible. +--- See |pumvisible()|. +--- items List of completion matches. Each item is a +--- dictionary containing the entries "word", +--- "abbr", "menu", "kind", "info" and "user_data". +--- See |complete-items|. +--- selected Selected item index. First index is zero. +--- Index is -1 if no item is selected (showing +--- typed text only, or the last completion after +--- no item is selected when using the <Up> or +--- <Down> keys) +--- inserted Inserted string. [NOT IMPLEMENTED YET] +--- +--- *complete_info_mode* +--- mode values are: +--- "" Not in completion mode +--- "keyword" Keyword completion |i_CTRL-X_CTRL-N| +--- "ctrl_x" Just pressed CTRL-X |i_CTRL-X| +--- "scroll" Scrolling with |i_CTRL-X_CTRL-E| or +--- |i_CTRL-X_CTRL-Y| +--- "whole_line" Whole lines |i_CTRL-X_CTRL-L| +--- "files" File names |i_CTRL-X_CTRL-F| +--- "tags" Tags |i_CTRL-X_CTRL-]| +--- "path_defines" Definition completion |i_CTRL-X_CTRL-D| +--- "path_patterns" Include completion |i_CTRL-X_CTRL-I| +--- "dictionary" Dictionary |i_CTRL-X_CTRL-K| +--- "thesaurus" Thesaurus |i_CTRL-X_CTRL-T| +--- "cmdline" Vim Command line |i_CTRL-X_CTRL-V| +--- "function" User defined completion |i_CTRL-X_CTRL-U| +--- "omni" Omni completion |i_CTRL-X_CTRL-O| +--- "spell" Spelling suggestions |i_CTRL-X_s| +--- "eval" |complete()| completion +--- "unknown" Other internal modes +--- +--- If the optional {what} list argument is supplied, then only +--- the items listed in {what} are returned. Unsupported items in +--- {what} are silently ignored. +--- +--- To get the position and size of the popup menu, see +--- |pum_getpos()|. It's also available in |v:event| during the +--- |CompleteChanged| event. +--- +--- Returns an empty |Dictionary| on error. +--- +--- Examples: >vim +--- " Get all items +--- call complete_info() +--- " Get only 'mode' +--- call complete_info(['mode']) +--- " Get only 'mode' and 'pum_visible' +--- call complete_info(['mode', 'pum_visible']) +--- +--- @param what? any +--- @return table +function vim.fn.complete_info(what) end + +--- confirm() offers the user a dialog, from which a choice can be +--- made. It returns the number of the choice. For the first +--- choice this is 1. +--- +--- {msg} is displayed in a dialog with {choices} as the +--- alternatives. When {choices} is missing or empty, "&OK" is +--- used (and translated). +--- {msg} is a String, use '\n' to include a newline. Only on +--- some systems the string is wrapped when it doesn't fit. +--- +--- {choices} is a String, with the individual choices separated +--- by '\n', e.g. >vim +--- confirm("Save changes?", "&Yes\n&No\n&Cancel") +--- <The letter after the '&' is the shortcut key for that choice. +--- Thus you can type 'c' to select "Cancel". The shortcut does +--- not need to be the first letter: >vim +--- confirm("file has been modified", "&Save\nSave &All") +--- <For the console, the first letter of each choice is used as +--- the default shortcut key. Case is ignored. +--- +--- The optional {type} String argument gives the type of dialog. +--- It can be one of these values: "Error", "Question", "Info", +--- "Warning" or "Generic". Only the first character is relevant. +--- When {type} is omitted, "Generic" is used. +--- +--- The optional {type} argument gives the type of dialog. This +--- is only used for the icon of the Win32 GUI. It can be one of +--- these values: "Error", "Question", "Info", "Warning" or +--- "Generic". Only the first character is relevant. +--- When {type} is omitted, "Generic" is used. +--- +--- If the user aborts the dialog by pressing <Esc>, CTRL-C, +--- or another valid interrupt key, confirm() returns 0. +--- +--- An example: >vim +--- let choice = confirm("What do you want?", +--- \ "&Apples\n&Oranges\n&Bananas", 2) +--- if choice == 0 +--- echo "make up your mind!" +--- elseif choice == 3 +--- echo "tasteful" +--- else +--- echo "I prefer bananas myself." +--- endif +--- <In a GUI dialog, buttons are used. The layout of the buttons +--- depends on the 'v' flag in 'guioptions'. If it is included, +--- the buttons are always put vertically. Otherwise, confirm() +--- tries to put the buttons in one horizontal line. If they +--- don't fit, a vertical layout is used anyway. For some systems +--- the horizontal layout is always used. +--- +--- @param msg any +--- @param choices? any +--- @param default? any +--- @param type? any +--- @return integer +function vim.fn.confirm(msg, choices, default, type) end + +--- Make a copy of {expr}. For Numbers and Strings this isn't +--- different from using {expr} directly. +--- When {expr} is a |List| a shallow copy is created. This means +--- that the original |List| can be changed without changing the +--- copy, and vice versa. But the items are identical, thus +--- changing an item changes the contents of both |Lists|. +--- A |Dictionary| is copied in a similar way as a |List|. +--- Also see |deepcopy()|. +--- +--- @param expr any +--- @return any +function vim.fn.copy(expr) end + +--- Return the cosine of {expr}, measured in radians, as a |Float|. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo cos(100) +--- < 0.862319 >vim +--- echo cos(-4.01) +--- < -0.646043 +--- +--- @param expr any +--- @return number +function vim.fn.cos(expr) end + +--- Return the hyperbolic cosine of {expr} as a |Float| in the range +--- [1, inf]. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo cosh(0.5) +--- < 1.127626 >vim +--- echo cosh(-0.5) +--- < -1.127626 +--- +--- @param expr any +--- @return number +function vim.fn.cosh(expr) end + +--- Return the number of times an item with value {expr} appears +--- in |String|, |List| or |Dictionary| {comp}. +--- +--- If {start} is given then start with the item with this index. +--- {start} can only be used with a |List|. +--- +--- When {ic} is given and it's |TRUE| then case is ignored. +--- +--- When {comp} is a string then the number of not overlapping +--- occurrences of {expr} is returned. Zero is returned when +--- {expr} is an empty string. +--- +--- @param comp any +--- @param expr any +--- @param ic? any +--- @param start? any +--- @return integer +function vim.fn.count(comp, expr, ic, start) end + +--- Returns a |Dictionary| representing the |context| at {index} +--- from the top of the |context-stack| (see |context-dict|). +--- If {index} is not given, it is assumed to be 0 (i.e.: top). +--- +--- @param index? any +--- @return table +function vim.fn.ctxget(index) end + +--- Pops and restores the |context| at the top of the +--- |context-stack|. +--- +--- @return any +function vim.fn.ctxpop() end + +--- Pushes the current editor state (|context|) on the +--- |context-stack|. +--- If {types} is given and is a |List| of |String|s, it specifies +--- which |context-types| to include in the pushed context. +--- Otherwise, all context types are included. +--- +--- @param types? any +--- @return any +function vim.fn.ctxpush(types) end + +--- Sets the |context| at {index} from the top of the +--- |context-stack| to that represented by {context}. +--- {context} is a Dictionary with context data (|context-dict|). +--- If {index} is not given, it is assumed to be 0 (i.e.: top). +--- +--- @param context any +--- @param index? any +--- @return any +function vim.fn.ctxset(context, index) end + +--- Returns the size of the |context-stack|. +--- +--- @return any +function vim.fn.ctxsize() end + +--- @param lnum integer +--- @param col? integer +--- @param off? any +--- @return any +function vim.fn.cursor(lnum, col, off) end + +--- Positions the cursor at the column (byte count) {col} in the +--- line {lnum}. The first column is one. +--- +--- When there is one argument {list} this is used as a |List| +--- with two, three or four item: +--- [{lnum}, {col}] +--- [{lnum}, {col}, {off}] +--- [{lnum}, {col}, {off}, {curswant}] +--- This is like the return value of |getpos()| or |getcurpos()|, +--- but without the first item. +--- +--- To position the cursor using {col} as the character count, use +--- |setcursorcharpos()|. +--- +--- Does not change the jumplist. +--- {lnum} is used like with |getline()|, except that if {lnum} is +--- zero, the cursor will stay in the current line. +--- If {lnum} is greater than the number of lines in the buffer, +--- the cursor will be positioned at the last line in the buffer. +--- If {col} is greater than the number of bytes in the line, +--- the cursor will be positioned at the last character in the +--- line. +--- If {col} is zero, the cursor will stay in the current column. +--- If {curswant} is given it is used to set the preferred column +--- for vertical movement. Otherwise {col} is used. +--- +--- When 'virtualedit' is used {off} specifies the offset in +--- screen columns from the start of the character. E.g., a +--- position within a <Tab> or after the last character. +--- Returns 0 when the position could be set, -1 otherwise. +--- +--- @param list any +--- @return any +function vim.fn.cursor(list) end + +--- Specifically used to interrupt a program being debugged. It +--- will cause process {pid} to get a SIGTRAP. Behavior for other +--- processes is undefined. See |terminal-debug|. +--- (Sends a SIGINT to a process {pid} other than MS-Windows) +--- +--- Returns |TRUE| if successfully interrupted the program. +--- Otherwise returns |FALSE|. +--- +--- @param pid any +--- @return any +function vim.fn.debugbreak(pid) end + +--- Make a copy of {expr}. For Numbers and Strings this isn't +--- different from using {expr} directly. +--- When {expr} is a |List| a full copy is created. This means +--- that the original |List| can be changed without changing the +--- copy, and vice versa. When an item is a |List|, a copy for it +--- is made, recursively. Thus changing an item in the copy does +--- not change the contents of the original |List|. +--- +--- When {noref} is omitted or zero a contained |List| or +--- |Dictionary| is only copied once. All references point to +--- this single copy. With {noref} set to 1 every occurrence of a +--- |List| or |Dictionary| results in a new copy. This also means +--- that a cyclic reference causes deepcopy() to fail. +--- *E724* +--- Nesting is possible up to 100 levels. When there is an item +--- that refers back to a higher level making a deep copy with +--- {noref} set to 1 will fail. +--- Also see |copy()|. +--- +--- @param expr any +--- @param noref? any +--- @return any +function vim.fn.deepcopy(expr, noref) end + +--- Without {flags} or with {flags} empty: Deletes the file by the +--- name {fname}. +--- +--- This also works when {fname} is a symbolic link. The symbolic +--- link itself is deleted, not what it points to. +--- +--- When {flags} is "d": Deletes the directory by the name +--- {fname}. This fails when directory {fname} is not empty. +--- +--- When {flags} is "rf": Deletes the directory by the name +--- {fname} and everything in it, recursively. BE CAREFUL! +--- Note: on MS-Windows it is not possible to delete a directory +--- that is being used. +--- +--- The result is a Number, which is 0/false if the delete +--- operation was successful and -1/true when the deletion failed +--- or partly failed. +--- +--- @param fname string +--- @param flags? string +--- @return integer +function vim.fn.delete(fname, flags) end + +--- Delete lines {first} to {last} (inclusive) from buffer {buf}. +--- If {last} is omitted then delete line {first} only. +--- On success 0 is returned, on failure 1 is returned. +--- +--- This function works only for loaded buffers. First call +--- |bufload()| if needed. +--- +--- For the use of {buf}, see |bufname()| above. +--- +--- {first} and {last} are used like with |getline()|. Note that +--- when using |line()| this refers to the current buffer. Use "$" +--- to refer to the last line in buffer {buf}. +--- +--- @param buf any +--- @param first any +--- @param last? any +--- @return any +function vim.fn.deletebufline(buf, first, last) end + +--- Adds a watcher to a dictionary. A dictionary watcher is +--- identified by three components: +--- +--- - A dictionary({dict}); +--- - A key pattern({pattern}). +--- - A function({callback}). +--- +--- After this is called, every change on {dict} and on keys +--- matching {pattern} will result in {callback} being invoked. +--- +--- For example, to watch all global variables: >vim +--- silent! call dictwatcherdel(g:, '*', 'OnDictChanged') +--- function! OnDictChanged(d,k,z) +--- echomsg string(a:k) string(a:z) +--- endfunction +--- call dictwatcheradd(g:, '*', 'OnDictChanged') +--- < +--- For now {pattern} only accepts very simple patterns that can +--- contain a "*" at the end of the string, in which case it will +--- match every key that begins with the substring before the "*". +--- That means if "*" is not the last character of {pattern}, only +--- keys that are exactly equal as {pattern} will be matched. +--- +--- The {callback} receives three arguments: +--- +--- - The dictionary being watched. +--- - The key which changed. +--- - A dictionary containing the new and old values for the key. +--- +--- The type of change can be determined by examining the keys +--- present on the third argument: +--- +--- - If contains both `old` and `new`, the key was updated. +--- - If it contains only `new`, the key was added. +--- - If it contains only `old`, the key was deleted. +--- +--- This function can be used by plugins to implement options with +--- validation and parsing logic. +--- +--- @param dict any +--- @param pattern any +--- @param callback any +--- @return any +function vim.fn.dictwatcheradd(dict, pattern, callback) end + +--- Removes a watcher added with |dictwatcheradd()|. All three +--- arguments must match the ones passed to |dictwatcheradd()| in +--- order for the watcher to be successfully deleted. +--- +--- @param dict any +--- @param pattern any +--- @param callback any +--- @return any +function vim.fn.dictwatcherdel(dict, pattern, callback) end + +--- Returns |TRUE| when autocommands are being executed and the +--- FileType event has been triggered at least once. Can be used +--- to avoid triggering the FileType event again in the scripts +--- that detect the file type. |FileType| +--- Returns |FALSE| when `:setf FALLBACK` was used. +--- When editing another file, the counter is reset, thus this +--- really checks if the FileType event has been triggered for the +--- current buffer. This allows an autocommand that starts +--- editing another buffer to set 'filetype' and load a syntax +--- file. +--- +--- @return any +function vim.fn.did_filetype() end + +--- Returns the number of filler lines above line {lnum}. +--- These are the lines that were inserted at this point in +--- another diff'ed window. These filler lines are shown in the +--- display but don't exist in the buffer. +--- {lnum} is used like with |getline()|. Thus "." is the current +--- line, "'m" mark m, etc. +--- Returns 0 if the current window is not in diff mode. +--- +--- @param lnum integer +--- @return any +function vim.fn.diff_filler(lnum) end + +--- Returns the highlight ID for diff mode at line {lnum} column +--- {col} (byte index). When the current line does not have a +--- diff change zero is returned. +--- {lnum} is used like with |getline()|. Thus "." is the current +--- line, "'m" mark m, etc. +--- {col} is 1 for the leftmost column, {lnum} is 1 for the first +--- line. +--- The highlight ID can be used with |synIDattr()| to obtain +--- syntax information about the highlighting. +--- +--- @param lnum integer +--- @param col integer +--- @return any +function vim.fn.diff_hlID(lnum, col) end + +--- Return the digraph of {chars}. This should be a string with +--- exactly two characters. If {chars} are not just two +--- characters, or the digraph of {chars} does not exist, an error +--- is given and an empty string is returned. +--- +--- Also see |digraph_getlist()|. +--- +--- Examples: >vim +--- " Get a built-in digraph +--- echo digraph_get('00') " Returns '∞' +--- +--- " Get a user-defined digraph +--- call digraph_set('aa', 'あ') +--- echo digraph_get('aa') " Returns 'あ' +--- < +--- +--- @param chars any +--- @return any +function vim.fn.digraph_get(chars) end + +--- Return a list of digraphs. If the {listall} argument is given +--- and it is TRUE, return all digraphs, including the default +--- digraphs. Otherwise, return only user-defined digraphs. +--- +--- Also see |digraph_get()|. +--- +--- Examples: >vim +--- " Get user-defined digraphs +--- echo digraph_getlist() +--- +--- " Get all the digraphs, including default digraphs +--- echo digraph_getlist(1) +--- < +--- +--- @param listall? any +--- @return any +function vim.fn.digraph_getlist(listall) end + +--- Add digraph {chars} to the list. {chars} must be a string +--- with two characters. {digraph} is a string with one UTF-8 +--- encoded character. *E1215* +--- Be careful, composing characters are NOT ignored. This +--- function is similar to |:digraphs| command, but useful to add +--- digraphs start with a white space. +--- +--- The function result is v:true if |digraph| is registered. If +--- this fails an error message is given and v:false is returned. +--- +--- If you want to define multiple digraphs at once, you can use +--- |digraph_setlist()|. +--- +--- Example: >vim +--- call digraph_set(' ', 'あ') +--- < +--- Can be used as a |method|: >vim +--- GetString()->digraph_set('あ') +--- < +--- +--- @param chars any +--- @param digraph any +--- @return any +function vim.fn.digraph_set(chars, digraph) end + +--- Similar to |digraph_set()| but this function can add multiple +--- digraphs at once. {digraphlist} is a list composed of lists, +--- where each list contains two strings with {chars} and +--- {digraph} as in |digraph_set()|. *E1216* +--- Example: >vim +--- call digraph_setlist([['aa', 'あ'], ['ii', 'い']]) +--- < +--- It is similar to the following: >vim +--- for [chars, digraph] in [['aa', 'あ'], ['ii', 'い']] +--- call digraph_set(chars, digraph) +--- endfor +--- <Except that the function returns after the first error, +--- following digraphs will not be added. +--- +--- Can be used as a |method|: >vim +--- GetList()->digraph_setlist() +--- < +--- +--- @param digraphlist any +--- @return any +function vim.fn.digraph_setlist(digraphlist) end + +--- Return the Number 1 if {expr} is empty, zero otherwise. +--- - A |List| or |Dictionary| is empty when it does not have any +--- items. +--- - A |String| is empty when its length is zero. +--- - A |Number| and |Float| are empty when their value is zero. +--- - |v:false| and |v:null| are empty, |v:true| is not. +--- - A |Blob| is empty when its length is zero. +--- +--- @param expr any +--- @return any +function vim.fn.empty(expr) end + +--- Return all of environment variables as dictionary. You can +--- check if an environment variable exists like this: >vim +--- echo has_key(environ(), 'HOME') +--- <Note that the variable name may be CamelCase; to ignore case +--- use this: >vim +--- echo index(keys(environ()), 'HOME', 0, 1) != -1 +--- < +--- +--- @return any +function vim.fn.environ() end + +--- Escape the characters in {chars} that occur in {string} with a +--- backslash. Example: >vim +--- echo escape('c:\program files\vim', ' \') +--- <results in: > +--- c:\\program\ files\\vim +--- <Also see |shellescape()| and |fnameescape()|. +--- +--- @param string string +--- @param chars any +--- @return any +function vim.fn.escape(string, chars) end + +--- Evaluate {string} and return the result. Especially useful to +--- turn the result of |string()| back into the original value. +--- This works for Numbers, Floats, Strings, Blobs and composites +--- of them. Also works for |Funcref|s that refer to existing +--- functions. +--- +--- @param string string +--- @return any +function vim.fn.eval(string) end + +--- Returns 1 when inside an event handler. That is that Vim got +--- interrupted while waiting for the user to type a character, +--- e.g., when dropping a file on Vim. This means interactive +--- commands cannot be used. Otherwise zero is returned. +--- +--- @return any +function vim.fn.eventhandler() end + +--- This function checks if an executable with the name {expr} +--- exists. {expr} must be the name of the program without any +--- arguments. +--- executable() uses the value of $PATH and/or the normal +--- searchpath for programs. *PATHEXT* +--- On MS-Windows the ".exe", ".bat", etc. can optionally be +--- included. Then the extensions in $PATHEXT are tried. Thus if +--- "foo.exe" does not exist, "foo.exe.bat" can be found. If +--- $PATHEXT is not set then ".exe;.com;.bat;.cmd" is used. A dot +--- by itself can be used in $PATHEXT to try using the name +--- without an extension. When 'shell' looks like a Unix shell, +--- then the name is also tried without adding an extension. +--- On MS-Windows it only checks if the file exists and is not a +--- directory, not if it's really executable. +--- On Windows an executable in the same directory as Vim is +--- always found (it is added to $PATH at |startup|). +--- The result is a Number: +--- 1 exists +--- 0 does not exist +--- -1 not implemented on this system +--- |exepath()| can be used to get the full path of an executable. +--- +--- @param expr any +--- @return 0|1|-1 +function vim.fn.executable(expr) end + +--- Execute {command} and capture its output. +--- If {command} is a |String|, returns {command} output. +--- If {command} is a |List|, returns concatenated outputs. +--- Line continuations in {command} are not recognized. +--- Examples: >vim +--- echo execute('echon "foo"') +--- < foo >vim +--- echo execute(['echon "foo"', 'echon "bar"']) +--- < foobar +--- +--- The optional {silent} argument can have these values: +--- "" no `:silent` used +--- "silent" `:silent` used +--- "silent!" `:silent!` used +--- The default is "silent". Note that with "silent!", unlike +--- `:redir`, error messages are dropped. +--- +--- To get a list of lines use `split()` on the result: >vim +--- execute('args')->split("\n") +--- +--- <This function is not available in the |sandbox|. +--- Note: If nested, an outer execute() will not observe output of +--- the inner calls. +--- Note: Text attributes (highlights) are not captured. +--- To execute a command in another window than the current one +--- use `win_execute()`. +--- +--- @param command string|string[] +--- @param silent? ''|'silent'|'silent!' +--- @return string +function vim.fn.execute(command, silent) end + +--- Returns the full path of {expr} if it is an executable and +--- given as a (partial or full) path or is found in $PATH. +--- Returns empty string otherwise. +--- If {expr} starts with "./" the |current-directory| is used. +--- +--- @param expr any +--- @return any +function vim.fn.exepath(expr) end + +--- The result is a Number, which is |TRUE| if {expr} is +--- defined, zero otherwise. +--- +--- For checking for a supported feature use |has()|. +--- For checking if a file exists use |filereadable()|. +--- +--- The {expr} argument is a string, which contains one of these: +--- varname internal variable (see +--- dict.key |internal-variables|). Also works +--- list[i] for |curly-braces-names|, |Dictionary| +--- entries, |List| items, etc. +--- Beware that evaluating an index may +--- cause an error message for an invalid +--- expression. E.g.: >vim +--- let l = [1, 2, 3] +--- echo exists("l[5]") +--- < 0 >vim +--- echo exists("l[xx]") +--- < E121: Undefined variable: xx +--- 0 +--- &option-name Vim option (only checks if it exists, +--- not if it really works) +--- +option-name Vim option that works. +--- $ENVNAME environment variable (could also be +--- done by comparing with an empty +--- string) +--- `*funcname` built-in function (see |functions|) +--- or user defined function (see +--- |user-function|). Also works for a +--- variable that is a Funcref. +--- :cmdname Ex command: built-in command, user +--- command or command modifier |:command|. +--- Returns: +--- 1 for match with start of a command +--- 2 full match with a command +--- 3 matches several user commands +--- To check for a supported command +--- always check the return value to be 2. +--- :2match The |:2match| command. +--- :3match The |:3match| command (but you +--- probably should not use it, it is +--- reserved for internal usage) +--- #event autocommand defined for this event +--- #event#pattern autocommand defined for this event and +--- pattern (the pattern is taken +--- literally and compared to the +--- autocommand patterns character by +--- character) +--- #group autocommand group exists +--- #group#event autocommand defined for this group and +--- event. +--- #group#event#pattern +--- autocommand defined for this group, +--- event and pattern. +--- ##event autocommand for this event is +--- supported. +--- +--- Examples: >vim +--- echo exists("&mouse") +--- echo exists("$HOSTNAME") +--- echo exists("*strftime") +--- echo exists("*s:MyFunc") +--- echo exists("*MyFunc") +--- echo exists("bufcount") +--- echo exists(":Make") +--- echo exists("#CursorHold") +--- echo exists("#BufReadPre#*.gz") +--- echo exists("#filetypeindent") +--- echo exists("#filetypeindent#FileType") +--- echo exists("#filetypeindent#FileType#*") +--- echo exists("##ColorScheme") +--- <There must be no space between the symbol (&/$/*/#) and the +--- name. +--- There must be no extra characters after the name, although in +--- a few cases this is ignored. That may become stricter in the +--- future, thus don't count on it! +--- Working example: >vim +--- echo exists(":make") +--- <NOT working example: >vim +--- echo exists(":make install") +--- +--- <Note that the argument must be a string, not the name of the +--- variable itself. For example: >vim +--- echo exists(bufcount) +--- <This doesn't check for existence of the "bufcount" variable, +--- but gets the value of "bufcount", and checks if that exists. +--- +--- @param expr any +--- @return 0|1 +function vim.fn.exists(expr) end + +--- Return the exponential of {expr} as a |Float| in the range +--- [0, inf]. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo exp(2) +--- < 7.389056 >vim +--- echo exp(-1) +--- < 0.367879 +--- +--- @param expr any +--- @return any +function vim.fn.exp(expr) end + +--- Expand wildcards and the following special keywords in +--- {string}. 'wildignorecase' applies. +--- +--- If {list} is given and it is |TRUE|, a List will be returned. +--- Otherwise the result is a String and when there are several +--- matches, they are separated by <NL> characters. +--- +--- If the expansion fails, the result is an empty string. A name +--- for a non-existing file is not included, unless {string} does +--- not start with '%', '#' or '<', see below. +--- +--- When {string} starts with '%', '#' or '<', the expansion is +--- done like for the |cmdline-special| variables with their +--- associated modifiers. Here is a short overview: +--- +--- % current file name +--- # alternate file name +--- #n alternate file name n +--- <cfile> file name under the cursor +--- <afile> autocmd file name +--- <abuf> autocmd buffer number (as a String!) +--- <amatch> autocmd matched name +--- <cexpr> C expression under the cursor +--- <sfile> sourced script file or function name +--- <slnum> sourced script line number or function +--- line number +--- <sflnum> script file line number, also when in +--- a function +--- <SID> "<SNR>123_" where "123" is the +--- current script ID |<SID>| +--- <script> sourced script file, or script file +--- where the current function was defined +--- <stack> call stack +--- <cword> word under the cursor +--- <cWORD> WORD under the cursor +--- <client> the {clientid} of the last received +--- message +--- Modifiers: +--- :p expand to full path +--- :h head (last path component removed) +--- :t tail (last path component only) +--- :r root (one extension removed) +--- :e extension only +--- +--- Example: >vim +--- let &tags = expand("%:p:h") .. "/tags" +--- <Note that when expanding a string that starts with '%', '#' or +--- '<', any following text is ignored. This does NOT work: >vim +--- let doesntwork = expand("%:h.bak") +--- <Use this: >vim +--- let doeswork = expand("%:h") .. ".bak" +--- <Also note that expanding "<cfile>" and others only returns the +--- referenced file name without further expansion. If "<cfile>" +--- is "~/.cshrc", you need to do another expand() to have the +--- "~/" expanded into the path of the home directory: >vim +--- echo expand(expand("<cfile>")) +--- < +--- There cannot be white space between the variables and the +--- following modifier. The |fnamemodify()| function can be used +--- to modify normal file names. +--- +--- When using '%' or '#', and the current or alternate file name +--- is not defined, an empty string is used. Using "%:p" in a +--- buffer with no name, results in the current directory, with a +--- '/' added. +--- When 'verbose' is set then expanding '%', '#' and <> items +--- will result in an error message if the argument cannot be +--- expanded. +--- +--- When {string} does not start with '%', '#' or '<', it is +--- expanded like a file name is expanded on the command line. +--- 'suffixes' and 'wildignore' are used, unless the optional +--- {nosuf} argument is given and it is |TRUE|. +--- Names for non-existing files are included. The "**" item can +--- be used to search in a directory tree. For example, to find +--- all "README" files in the current directory and below: >vim +--- echo expand("**/README") +--- < +--- expand() can also be used to expand variables and environment +--- variables that are only known in a shell. But this can be +--- slow, because a shell may be used to do the expansion. See +--- |expr-env-expand|. +--- The expanded variable is still handled like a list of file +--- names. When an environment variable cannot be expanded, it is +--- left unchanged. Thus ":echo expand('$FOOBAR')" results in +--- "$FOOBAR". +--- +--- See |glob()| for finding existing files. See |system()| for +--- getting the raw output of an external command. +--- +--- @param string string +--- @param nosuf? boolean +--- @param list? any +--- @return string|string[] +function vim.fn.expand(string, nosuf, list) end + +--- Expand special items in String {string} like what is done for +--- an Ex command such as `:edit`. This expands special keywords, +--- like with |expand()|, and environment variables, anywhere in +--- {string}. "~user" and "~/path" are only expanded at the +--- start. +--- +--- The following items are supported in the {options} Dict +--- argument: +--- errmsg If set to TRUE, error messages are displayed +--- if an error is encountered during expansion. +--- By default, error messages are not displayed. +--- +--- Returns the expanded string. If an error is encountered +--- during expansion, the unmodified {string} is returned. +--- +--- Example: >vim +--- echo expandcmd('make %<.o') +--- < > +--- make /path/runtime/doc/builtin.o +--- < >vim +--- echo expandcmd('make %<.o', {'errmsg': v:true}) +--- < +--- +--- @param string string +--- @param options? table +--- @return any +function vim.fn.expandcmd(string, options) end + +--- {expr1} and {expr2} must be both |Lists| or both +--- |Dictionaries|. +--- +--- If they are |Lists|: Append {expr2} to {expr1}. +--- If {expr3} is given insert the items of {expr2} before the +--- item with index {expr3} in {expr1}. When {expr3} is zero +--- insert before the first item. When {expr3} is equal to +--- len({expr1}) then {expr2} is appended. +--- Examples: >vim +--- echo sort(extend(mylist, [7, 5])) +--- call extend(mylist, [2, 3], 1) +--- <When {expr1} is the same List as {expr2} then the number of +--- items copied is equal to the original length of the List. +--- E.g., when {expr3} is 1 you get N new copies of the first item +--- (where N is the original length of the List). +--- Use |add()| to concatenate one item to a list. To concatenate +--- two lists into a new list use the + operator: >vim +--- let newlist = [1, 2, 3] + [4, 5] +--- < +--- If they are |Dictionaries|: +--- Add all entries from {expr2} to {expr1}. +--- If a key exists in both {expr1} and {expr2} then {expr3} is +--- used to decide what to do: +--- {expr3} = "keep": keep the value of {expr1} +--- {expr3} = "force": use the value of {expr2} +--- {expr3} = "error": give an error message *E737* +--- When {expr3} is omitted then "force" is assumed. +--- +--- {expr1} is changed when {expr2} is not empty. If necessary +--- make a copy of {expr1} first. +--- {expr2} remains unchanged. +--- When {expr1} is locked and {expr2} is not empty the operation +--- fails. +--- Returns {expr1}. Returns 0 on error. +--- +--- @param expr1 any +--- @param expr2 any +--- @param expr3? any +--- @return any +function vim.fn.extend(expr1, expr2, expr3) end + +--- Like |extend()| but instead of adding items to {expr1} a new +--- List or Dictionary is created and returned. {expr1} remains +--- unchanged. +--- +--- @param expr1 any +--- @param expr2 any +--- @param expr3? any +--- @return any +function vim.fn.extendnew(expr1, expr2, expr3) end + +--- Characters in {string} are queued for processing as if they +--- come from a mapping or were typed by the user. +--- +--- By default the string is added to the end of the typeahead +--- buffer, thus if a mapping is still being executed the +--- characters come after them. Use the 'i' flag to insert before +--- other characters, they will be executed next, before any +--- characters from a mapping. +--- +--- The function does not wait for processing of keys contained in +--- {string}. +--- +--- To include special keys into {string}, use double-quotes +--- and "\..." notation |expr-quote|. For example, +--- feedkeys("\<CR>") simulates pressing of the <Enter> key. But +--- feedkeys('\<CR>') pushes 5 characters. +--- The |<Ignore>| keycode may be used to exit the +--- wait-for-character without doing anything. +--- +--- {mode} is a String, which can contain these character flags: +--- 'm' Remap keys. This is default. If {mode} is absent, +--- keys are remapped. +--- 'n' Do not remap keys. +--- 't' Handle keys as if typed; otherwise they are handled as +--- if coming from a mapping. This matters for undo, +--- opening folds, etc. +--- 'i' Insert the string instead of appending (see above). +--- 'x' Execute commands until typeahead is empty. This is +--- similar to using ":normal!". You can call feedkeys() +--- several times without 'x' and then one time with 'x' +--- (possibly with an empty {string}) to execute all the +--- typeahead. Note that when Vim ends in Insert mode it +--- will behave as if <Esc> is typed, to avoid getting +--- stuck, waiting for a character to be typed before the +--- script continues. +--- Note that if you manage to call feedkeys() while +--- executing commands, thus calling it recursively, then +--- all typeahead will be consumed by the last call. +--- '!' When used with 'x' will not end Insert mode. Can be +--- used in a test when a timer is set to exit Insert mode +--- a little later. Useful for testing CursorHoldI. +--- +--- Return value is always 0. +--- +--- @param string string +--- @param mode? string +--- @return any +function vim.fn.feedkeys(string, mode) end + +--- @deprecated +--- Obsolete name for |filereadable()|. +--- +--- @param file string +--- @return any +function vim.fn.file_readable(file) end + +--- The result is a Number, which is |TRUE| when a file with the +--- name {file} exists, and can be read. If {file} doesn't exist, +--- or is a directory, the result is |FALSE|. {file} is any +--- expression, which is used as a String. +--- If you don't care about the file being readable you can use +--- |glob()|. +--- {file} is used as-is, you may want to expand wildcards first: >vim +--- echo filereadable('~/.vimrc') +--- < > +--- 0 +--- < >vim +--- echo filereadable(expand('~/.vimrc')) +--- < > +--- 1 +--- < +--- +--- @param file string +--- @return 0|1 +function vim.fn.filereadable(file) end + +--- The result is a Number, which is 1 when a file with the +--- name {file} exists, and can be written. If {file} doesn't +--- exist, or is not writable, the result is 0. If {file} is a +--- directory, and we can write to it, the result is 2. +--- +--- @param file string +--- @return 0|1 +function vim.fn.filewritable(file) end + +--- {expr1} must be a |List|, |String|, |Blob| or |Dictionary|. +--- For each item in {expr1} evaluate {expr2} and when the result +--- is zero or false remove the item from the |List| or +--- |Dictionary|. Similarly for each byte in a |Blob| and each +--- character in a |String|. +--- +--- {expr2} must be a |string| or |Funcref|. +--- +--- If {expr2} is a |string|, inside {expr2} |v:val| has the value +--- of the current item. For a |Dictionary| |v:key| has the key +--- of the current item and for a |List| |v:key| has the index of +--- the current item. For a |Blob| |v:key| has the index of the +--- current byte. For a |String| |v:key| has the index of the +--- current character. +--- Examples: >vim +--- call filter(mylist, 'v:val !~ "OLD"') +--- <Removes the items where "OLD" appears. >vim +--- call filter(mydict, 'v:key >= 8') +--- <Removes the items with a key below 8. >vim +--- call filter(var, 0) +--- <Removes all the items, thus clears the |List| or |Dictionary|. +--- +--- Note that {expr2} is the result of expression and is then +--- used as an expression again. Often it is good to use a +--- |literal-string| to avoid having to double backslashes. +--- +--- If {expr2} is a |Funcref| it must take two arguments: +--- 1. the key or the index of the current item. +--- 2. the value of the current item. +--- The function must return |TRUE| if the item should be kept. +--- Example that keeps the odd items of a list: >vim +--- func Odd(idx, val) +--- return a:idx % 2 == 1 +--- endfunc +--- call filter(mylist, function('Odd')) +--- <It is shorter when using a |lambda|: >vim +--- call filter(myList, {idx, val -> idx * val <= 42}) +--- <If you do not use "val" you can leave it out: >vim +--- call filter(myList, {idx -> idx % 2 == 1}) +--- < +--- For a |List| and a |Dictionary| the operation is done +--- in-place. If you want it to remain unmodified make a copy +--- first: >vim +--- let l = filter(copy(mylist), 'v:val =~ "KEEP"') +--- +--- <Returns {expr1}, the |List| or |Dictionary| that was filtered, +--- or a new |Blob| or |String|. +--- When an error is encountered while evaluating {expr2} no +--- further items in {expr1} are processed. +--- When {expr2} is a Funcref errors inside a function are ignored, +--- unless it was defined with the "abort" flag. +--- +--- @param expr1 any +--- @param expr2 any +--- @return any +function vim.fn.filter(expr1, expr2) end + +--- Find directory {name} in {path}. Supports both downwards and +--- upwards recursive directory searches. See |file-searching| +--- for the syntax of {path}. +--- +--- Returns the path of the first found match. When the found +--- directory is below the current directory a relative path is +--- returned. Otherwise a full path is returned. +--- If {path} is omitted or empty then 'path' is used. +--- +--- If the optional {count} is given, find {count}'s occurrence of +--- {name} in {path} instead of the first one. +--- When {count} is negative return all the matches in a |List|. +--- +--- Returns an empty string if the directory is not found. +--- +--- This is quite similar to the ex-command `:find`. +--- +--- @param name string +--- @param path? string +--- @param count? any +--- @return any +function vim.fn.finddir(name, path, count) end + +--- Just like |finddir()|, but find a file instead of a directory. +--- Uses 'suffixesadd'. +--- Example: >vim +--- echo findfile("tags.vim", ".;") +--- <Searches from the directory of the current file upwards until +--- it finds the file "tags.vim". +--- +--- @param name string +--- @param path? string +--- @param count? any +--- @return any +function vim.fn.findfile(name, path, count) end + +--- Flatten {list} up to {maxdepth} levels. Without {maxdepth} +--- the result is a |List| without nesting, as if {maxdepth} is +--- a very large number. +--- The {list} is changed in place, use |flattennew()| if you do +--- not want that. +--- *E900* +--- {maxdepth} means how deep in nested lists changes are made. +--- {list} is not modified when {maxdepth} is 0. +--- {maxdepth} must be positive number. +--- +--- If there is an error the number zero is returned. +--- +--- Example: >vim +--- echo flatten([1, [2, [3, 4]], 5]) +--- < [1, 2, 3, 4, 5] >vim +--- echo flatten([1, [2, [3, 4]], 5], 1) +--- < [1, 2, [3, 4], 5] +--- +--- @param list any +--- @param maxdepth? any +--- @return any[]|0 +function vim.fn.flatten(list, maxdepth) end + +--- Like |flatten()| but first make a copy of {list}. +--- +--- @param list any +--- @param maxdepth? any +--- @return any[]|0 +function vim.fn.flattennew(list, maxdepth) end + +--- Convert {expr} to a Number by omitting the part after the +--- decimal point. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0 if {expr} is not a |Float| or a |Number|. +--- When the value of {expr} is out of range for a |Number| the +--- result is truncated to 0x7fffffff or -0x7fffffff (or when +--- 64-bit Number support is enabled, 0x7fffffffffffffff or +--- -0x7fffffffffffffff). NaN results in -0x80000000 (or when +--- 64-bit Number support is enabled, -0x8000000000000000). +--- Examples: >vim +--- echo float2nr(3.95) +--- < 3 >vim +--- echo float2nr(-23.45) +--- < -23 >vim +--- echo float2nr(1.0e100) +--- < 2147483647 (or 9223372036854775807) >vim +--- echo float2nr(-1.0e150) +--- < -2147483647 (or -9223372036854775807) >vim +--- echo float2nr(1.0e-100) +--- < 0 +--- +--- @param expr any +--- @return any +function vim.fn.float2nr(expr) end + +--- Return the largest integral value less than or equal to +--- {expr} as a |Float| (round down). +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo floor(1.856) +--- < 1.0 >vim +--- echo floor(-5.456) +--- < -6.0 >vim +--- echo floor(4.0) +--- < 4.0 +--- +--- @param expr any +--- @return any +function vim.fn.floor(expr) end + +--- Return the remainder of {expr1} / {expr2}, even if the +--- division is not representable. Returns {expr1} - i * {expr2} +--- for some integer i such that if {expr2} is non-zero, the +--- result has the same sign as {expr1} and magnitude less than +--- the magnitude of {expr2}. If {expr2} is zero, the value +--- returned is zero. The value returned is a |Float|. +--- {expr1} and {expr2} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr1} or {expr2} is not a |Float| or a +--- |Number|. +--- Examples: >vim +--- echo fmod(12.33, 1.22) +--- < 0.13 >vim +--- echo fmod(-12.33, 1.22) +--- < -0.13 +--- +--- @param expr1 any +--- @param expr2 any +--- @return any +function vim.fn.fmod(expr1, expr2) end + +--- Escape {string} for use as file name command argument. All +--- characters that have a special meaning, such as `'%'` and `'|'` +--- are escaped with a backslash. +--- For most systems the characters escaped are +--- " \t\n*?[{`$\\%#'\"|!<". For systems where a backslash +--- appears in a filename, it depends on the value of 'isfname'. +--- A leading '+' and '>' is also escaped (special after |:edit| +--- and |:write|). And a "-" by itself (special after |:cd|). +--- Returns an empty string on error. +--- Example: >vim +--- let fname = '+some str%nge|name' +--- exe "edit " .. fnameescape(fname) +--- <results in executing: >vim +--- edit \+some\ str\%nge\|name +--- < +--- +--- @param string string +--- @return string +function vim.fn.fnameescape(string) end + +--- Modify file name {fname} according to {mods}. {mods} is a +--- string of characters like it is used for file names on the +--- command line. See |filename-modifiers|. +--- Example: >vim +--- echo fnamemodify("main.c", ":p:h") +--- <results in: > +--- /home/user/vim/vim/src +--- <If {mods} is empty or an unsupported modifier is used then +--- {fname} is returned. +--- When {fname} is empty then with {mods} ":h" returns ".", so +--- that `:cd` can be used with it. This is different from +--- expand('%:h') without a buffer name, which returns an empty +--- string. +--- Note: Environment variables don't work in {fname}, use +--- |expand()| first then. +--- +--- @param fname string +--- @param mods string +--- @return string +function vim.fn.fnamemodify(fname, mods) end + +--- The result is a Number. If the line {lnum} is in a closed +--- fold, the result is the number of the first line in that fold. +--- If the line {lnum} is not in a closed fold, -1 is returned. +--- {lnum} is used like with |getline()|. Thus "." is the current +--- line, "'m" mark m, etc. +--- +--- @param lnum integer +--- @return integer +function vim.fn.foldclosed(lnum) end + +--- The result is a Number. If the line {lnum} is in a closed +--- fold, the result is the number of the last line in that fold. +--- If the line {lnum} is not in a closed fold, -1 is returned. +--- {lnum} is used like with |getline()|. Thus "." is the current +--- line, "'m" mark m, etc. +--- +--- @param lnum integer +--- @return integer +function vim.fn.foldclosedend(lnum) end + +--- The result is a Number, which is the foldlevel of line {lnum} +--- in the current buffer. For nested folds the deepest level is +--- returned. If there is no fold at line {lnum}, zero is +--- returned. It doesn't matter if the folds are open or closed. +--- When used while updating folds (from 'foldexpr') -1 is +--- returned for lines where folds are still to be updated and the +--- foldlevel is unknown. As a special case the level of the +--- previous line is usually available. +--- {lnum} is used like with |getline()|. Thus "." is the current +--- line, "'m" mark m, etc. +--- +--- @param lnum integer +--- @return integer +function vim.fn.foldlevel(lnum) end + +--- Returns a String, to be displayed for a closed fold. This is +--- the default function used for the 'foldtext' option and should +--- only be called from evaluating 'foldtext'. It uses the +--- |v:foldstart|, |v:foldend| and |v:folddashes| variables. +--- The returned string looks like this: > +--- +-- 45 lines: abcdef +--- <The number of leading dashes depends on the foldlevel. The +--- "45" is the number of lines in the fold. "abcdef" is the text +--- in the first non-blank line of the fold. Leading white space, +--- "//" or "/*" and the text from the 'foldmarker' and +--- 'commentstring' options is removed. +--- When used to draw the actual foldtext, the rest of the line +--- will be filled with the fold char from the 'fillchars' +--- setting. +--- Returns an empty string when there is no fold. +--- +--- @return string +function vim.fn.foldtext() end + +--- Returns the text that is displayed for the closed fold at line +--- {lnum}. Evaluates 'foldtext' in the appropriate context. +--- When there is no closed fold at {lnum} an empty string is +--- returned. +--- {lnum} is used like with |getline()|. Thus "." is the current +--- line, "'m" mark m, etc. +--- Useful when exporting folded text, e.g., to HTML. +--- +--- @param lnum integer +--- @return string +function vim.fn.foldtextresult(lnum) end + +--- Get the full command name from a short abbreviated command +--- name; see |20.2| for details on command abbreviations. +--- +--- The string argument {name} may start with a `:` and can +--- include a [range], these are skipped and not returned. +--- Returns an empty string if a command doesn't exist or if it's +--- ambiguous (for user-defined commands). +--- +--- For example `fullcommand('s')`, `fullcommand('sub')`, +--- `fullcommand(':%substitute')` all return "substitute". +--- +--- @param name string +--- @return string +function vim.fn.fullcommand(name) end + +--- Just like |function()|, but the returned Funcref will lookup +--- the function by reference, not by name. This matters when the +--- function {name} is redefined later. +--- +--- Unlike |function()|, {name} must be an existing user function. +--- It only works for an autoloaded function if it has already +--- been loaded (to avoid mistakenly loading the autoload script +--- when only intending to use the function name, use |function()| +--- instead). {name} cannot be a builtin function. +--- Returns 0 on error. +--- +--- @param name string +--- @param arglist? any +--- @param dict? any +--- @return any +function vim.fn.funcref(name, arglist, dict) end + +--- Return a |Funcref| variable that refers to function {name}. +--- {name} can be the name of a user defined function or an +--- internal function. +--- +--- {name} can also be a Funcref or a partial. When it is a +--- partial the dict stored in it will be used and the {dict} +--- argument is not allowed. E.g.: >vim +--- let FuncWithArg = function(dict.Func, [arg]) +--- let Broken = function(dict.Func, [arg], dict) +--- < +--- When using the Funcref the function will be found by {name}, +--- also when it was redefined later. Use |funcref()| to keep the +--- same function. +--- +--- When {arglist} or {dict} is present this creates a partial. +--- That means the argument list and/or the dictionary is stored in +--- the Funcref and will be used when the Funcref is called. +--- +--- The arguments are passed to the function in front of other +--- arguments, but after any argument from |method|. Example: >vim +--- func Callback(arg1, arg2, name) +--- "... +--- endfunc +--- let Partial = function('Callback', ['one', 'two']) +--- "... +--- call Partial('name') +--- <Invokes the function as with: >vim +--- call Callback('one', 'two', 'name') +--- +--- <With a |method|: >vim +--- func Callback(one, two, three) +--- "... +--- endfunc +--- let Partial = function('Callback', ['two']) +--- "... +--- eval 'one'->Partial('three') +--- <Invokes the function as with: >vim +--- call Callback('one', 'two', 'three') +--- +--- <The function() call can be nested to add more arguments to the +--- Funcref. The extra arguments are appended to the list of +--- arguments. Example: >vim +--- func Callback(arg1, arg2, name) +--- "... +--- endfunc +--- let Func = function('Callback', ['one']) +--- let Func2 = function(Func, ['two']) +--- "... +--- call Func2('name') +--- <Invokes the function as with: >vim +--- call Callback('one', 'two', 'name') +--- +--- <The Dictionary is only useful when calling a "dict" function. +--- In that case the {dict} is passed in as "self". Example: >vim +--- function Callback() dict +--- echo "called for " .. self.name +--- endfunction +--- "... +--- let context = {"name": "example"} +--- let Func = function('Callback', context) +--- "... +--- call Func() " will echo: called for example +--- <The use of function() is not needed when there are no extra +--- arguments, these two are equivalent, if Callback() is defined +--- as context.Callback(): >vim +--- let Func = function('Callback', context) +--- let Func = context.Callback +--- +--- <The argument list and the Dictionary can be combined: >vim +--- function Callback(arg1, count) dict +--- "... +--- endfunction +--- let context = {"name": "example"} +--- let Func = function('Callback', ['one'], context) +--- "... +--- call Func(500) +--- <Invokes the function as with: >vim +--- call context.Callback('one', 500) +--- < +--- Returns 0 on error. +--- +--- @param name string +--- @param arglist? any +--- @param dict? any +--- @return any +vim.fn['function'] = function(name, arglist, dict) end + +--- Cleanup unused |Lists| and |Dictionaries| that have circular +--- references. +--- +--- There is hardly ever a need to invoke this function, as it is +--- automatically done when Vim runs out of memory or is waiting +--- for the user to press a key after 'updatetime'. Items without +--- circular references are always freed when they become unused. +--- This is useful if you have deleted a very big |List| and/or +--- |Dictionary| with circular references in a script that runs +--- for a long time. +--- +--- When the optional {atexit} argument is one, garbage +--- collection will also be done when exiting Vim, if it wasn't +--- done before. This is useful when checking for memory leaks. +--- +--- The garbage collection is not done immediately but only when +--- it's safe to perform. This is when waiting for the user to +--- type a character. +--- +--- @param atexit? any +--- @return any +function vim.fn.garbagecollect(atexit) end + +--- Get item {idx} from |List| {list}. When this item is not +--- available return {default}. Return zero when {default} is +--- omitted. +--- +--- @param list any[] +--- @param idx integer +--- @param default? any +--- @return any +function vim.fn.get(list, idx, default) end + +--- Get byte {idx} from |Blob| {blob}. When this byte is not +--- available return {default}. Return -1 when {default} is +--- omitted. +--- +--- @param blob string +--- @param idx integer +--- @param default? any +--- @return any +function vim.fn.get(blob, idx, default) end + +--- Get item with key {key} from |Dictionary| {dict}. When this +--- item is not available return {default}. Return zero when +--- {default} is omitted. Useful example: >vim +--- let val = get(g:, 'var_name', 'default') +--- <This gets the value of g:var_name if it exists, and uses +--- "default" when it does not exist. +--- +--- @param dict table<string,any> +--- @param key string +--- @param default? any +--- @return any +function vim.fn.get(dict, key, default) end + +--- Get item {what} from Funcref {func}. Possible values for +--- {what} are: +--- "name" The function name +--- "func" The function +--- "dict" The dictionary +--- "args" The list with arguments +--- Returns zero on error. +--- +--- @param func function +--- @param what string +--- @return any +function vim.fn.get(func, what) end + +--- @param buf? integer|string +--- @return vim.fn.getbufinfo.ret.item[] +function vim.fn.getbufinfo(buf) end + +--- Get information about buffers as a List of Dictionaries. +--- +--- Without an argument information about all the buffers is +--- returned. +--- +--- When the argument is a |Dictionary| only the buffers matching +--- the specified criteria are returned. The following keys can +--- be specified in {dict}: +--- buflisted include only listed buffers. +--- bufloaded include only loaded buffers. +--- bufmodified include only modified buffers. +--- +--- Otherwise, {buf} specifies a particular buffer to return +--- information for. For the use of {buf}, see |bufname()| +--- above. If the buffer is found the returned List has one item. +--- Otherwise the result is an empty list. +--- +--- Each returned List item is a dictionary with the following +--- entries: +--- bufnr Buffer number. +--- changed TRUE if the buffer is modified. +--- changedtick Number of changes made to the buffer. +--- hidden TRUE if the buffer is hidden. +--- lastused Timestamp in seconds, like +--- |localtime()|, when the buffer was +--- last used. +--- listed TRUE if the buffer is listed. +--- lnum Line number used for the buffer when +--- opened in the current window. +--- Only valid if the buffer has been +--- displayed in the window in the past. +--- If you want the line number of the +--- last known cursor position in a given +--- window, use |line()|: >vim +--- echo line('.', {winid}) +--- < +--- linecount Number of lines in the buffer (only +--- valid when loaded) +--- loaded TRUE if the buffer is loaded. +--- name Full path to the file in the buffer. +--- signs List of signs placed in the buffer. +--- Each list item is a dictionary with +--- the following fields: +--- id sign identifier +--- lnum line number +--- name sign name +--- variables A reference to the dictionary with +--- buffer-local variables. +--- windows List of |window-ID|s that display this +--- buffer +--- +--- Examples: >vim +--- for buf in getbufinfo() +--- echo buf.name +--- endfor +--- for buf in getbufinfo({'buflisted':1}) +--- if buf.changed +--- " .... +--- endif +--- endfor +--- < +--- To get buffer-local options use: >vim +--- getbufvar({bufnr}, '&option_name') +--- < +--- +--- @param dict? vim.fn.getbufinfo.dict +--- @return vim.fn.getbufinfo.ret.item[] +function vim.fn.getbufinfo(dict) end + +--- Return a |List| with the lines starting from {lnum} to {end} +--- (inclusive) in the buffer {buf}. If {end} is omitted, a +--- |List| with only the line {lnum} is returned. See +--- `getbufoneline()` for only getting the line. +--- +--- For the use of {buf}, see |bufname()| above. +--- +--- For {lnum} and {end} "$" can be used for the last line of the +--- buffer. Otherwise a number must be used. +--- +--- When {lnum} is smaller than 1 or bigger than the number of +--- lines in the buffer, an empty |List| is returned. +--- +--- When {end} is greater than the number of lines in the buffer, +--- it is treated as {end} is set to the number of lines in the +--- buffer. When {end} is before {lnum} an empty |List| is +--- returned. +--- +--- This function works only for loaded buffers. For unloaded and +--- non-existing buffers, an empty |List| is returned. +--- +--- Example: >vim +--- let lines = getbufline(bufnr("myfile"), 1, "$") +--- +--- @param buf any +--- @param lnum integer +--- @param end_? integer +--- @return any +function vim.fn.getbufline(buf, lnum, end_) end + +--- Just like `getbufline()` but only get one line and return it +--- as a string. +--- +--- @param buf integer|string +--- @param lnum integer +--- @return string +function vim.fn.getbufoneline(buf, lnum) end + +--- The result is the value of option or local buffer variable +--- {varname} in buffer {buf}. Note that the name without "b:" +--- must be used. +--- The {varname} argument is a string. +--- When {varname} is empty returns a |Dictionary| with all the +--- buffer-local variables. +--- When {varname} is equal to "&" returns a |Dictionary| with all +--- the buffer-local options. +--- Otherwise, when {varname} starts with "&" returns the value of +--- a buffer-local option. +--- This also works for a global or buffer-local option, but it +--- doesn't work for a global variable, window-local variable or +--- window-local option. +--- For the use of {buf}, see |bufname()| above. +--- When the buffer or variable doesn't exist {def} or an empty +--- string is returned, there is no error message. +--- Examples: >vim +--- let bufmodified = getbufvar(1, "&mod") +--- echo "todo myvar = " .. getbufvar("todo", "myvar") +--- +--- @param buf any +--- @param varname string +--- @param def? any +--- @return any +function vim.fn.getbufvar(buf, varname, def) end + +--- Returns a |List| of cell widths of character ranges overridden +--- by |setcellwidths()|. The format is equal to the argument of +--- |setcellwidths()|. If no character ranges have their cell +--- widths overridden, an empty List is returned. +--- +--- @return any +function vim.fn.getcellwidths() end + +--- Returns the |changelist| for the buffer {buf}. For the use +--- of {buf}, see |bufname()| above. If buffer {buf} doesn't +--- exist, an empty list is returned. +--- +--- The returned list contains two entries: a list with the change +--- locations and the current position in the list. Each +--- entry in the change list is a dictionary with the following +--- entries: +--- col column number +--- coladd column offset for 'virtualedit' +--- lnum line number +--- If buffer {buf} is the current buffer, then the current +--- position refers to the position in the list. For other +--- buffers, it is set to the length of the list. +--- +--- @param buf? integer|string +--- @return table[] +function vim.fn.getchangelist(buf) end + +--- Get a single character from the user or input stream. +--- If [expr] is omitted, wait until a character is available. +--- If [expr] is 0, only get a character when one is available. +--- Return zero otherwise. +--- If [expr] is 1, only check if a character is available, it is +--- not consumed. Return zero if no character available. +--- If you prefer always getting a string use |getcharstr()|. +--- +--- Without [expr] and when [expr] is 0 a whole character or +--- special key is returned. If it is a single character, the +--- result is a Number. Use |nr2char()| to convert it to a String. +--- Otherwise a String is returned with the encoded character. +--- For a special key it's a String with a sequence of bytes +--- starting with 0x80 (decimal: 128). This is the same value as +--- the String "\<Key>", e.g., "\<Left>". The returned value is +--- also a String when a modifier (shift, control, alt) was used +--- that is not included in the character. +--- +--- When [expr] is 0 and Esc is typed, there will be a short delay +--- while Vim waits to see if this is the start of an escape +--- sequence. +--- +--- When [expr] is 1 only the first byte is returned. For a +--- one-byte character it is the character itself as a number. +--- Use nr2char() to convert it to a String. +--- +--- Use getcharmod() to obtain any additional modifiers. +--- +--- When the user clicks a mouse button, the mouse event will be +--- returned. The position can then be found in |v:mouse_col|, +--- |v:mouse_lnum|, |v:mouse_winid| and |v:mouse_win|. +--- |getmousepos()| can also be used. Mouse move events will be +--- ignored. +--- This example positions the mouse as it would normally happen: >vim +--- let c = getchar() +--- if c == "\<LeftMouse>" && v:mouse_win > 0 +--- exe v:mouse_win .. "wincmd w" +--- exe v:mouse_lnum +--- exe "normal " .. v:mouse_col .. "|" +--- endif +--- < +--- There is no prompt, you will somehow have to make clear to the +--- user that a character has to be typed. The screen is not +--- redrawn, e.g. when resizing the window. +--- +--- There is no mapping for the character. +--- Key codes are replaced, thus when the user presses the <Del> +--- key you get the code for the <Del> key, not the raw character +--- sequence. Examples: >vim +--- getchar() == "\<Del>" +--- getchar() == "\<S-Left>" +--- <This example redefines "f" to ignore case: >vim +--- nmap f :call FindChar()<CR> +--- function FindChar() +--- let c = nr2char(getchar()) +--- while col('.') < col('$') - 1 +--- normal l +--- if getline('.')[col('.') - 1] ==? c +--- break +--- endif +--- endwhile +--- endfunction +--- < +--- +--- @return integer +function vim.fn.getchar() end + +--- The result is a Number which is the state of the modifiers for +--- the last obtained character with getchar() or in another way. +--- These values are added together: +--- 2 shift +--- 4 control +--- 8 alt (meta) +--- 16 meta (when it's different from ALT) +--- 32 mouse double click +--- 64 mouse triple click +--- 96 mouse quadruple click (== 32 + 64) +--- 128 command (Macintosh only) +--- Only the modifiers that have not been included in the +--- character itself are obtained. Thus Shift-a results in "A" +--- without a modifier. Returns 0 if no modifiers are used. +--- +--- @return integer +function vim.fn.getcharmod() end + +--- Get the position for String {expr}. Same as |getpos()| but the +--- column number in the returned List is a character index +--- instead of a byte index. +--- If |getpos()| returns a very large column number, equal to +--- |v:maxcol|, then getcharpos() will return the character index +--- of the last character. +--- +--- Example: +--- With the cursor on '세' in line 5 with text "여보세요": >vim +--- getcharpos('.') returns [0, 5, 3, 0] +--- getpos('.') returns [0, 5, 7, 0] +--- < +--- +--- @param expr any +--- @return integer[] +function vim.fn.getcharpos(expr) end + +--- Return the current character search information as a {dict} +--- with the following entries: +--- +--- char character previously used for a character +--- search (|t|, |f|, |T|, or |F|); empty string +--- if no character search has been performed +--- forward direction of character search; 1 for forward, +--- 0 for backward +--- until type of character search; 1 for a |t| or |T| +--- character search, 0 for an |f| or |F| +--- character search +--- +--- This can be useful to always have |;| and |,| search +--- forward/backward regardless of the direction of the previous +--- character search: >vim +--- nnoremap <expr> ; getcharsearch().forward ? ';' : ',' +--- nnoremap <expr> , getcharsearch().forward ? ',' : ';' +--- <Also see |setcharsearch()|. +--- +--- @return table[] +function vim.fn.getcharsearch() end + +--- Get a single character from the user or input stream as a +--- string. +--- If [expr] is omitted, wait until a character is available. +--- If [expr] is 0 or false, only get a character when one is +--- available. Return an empty string otherwise. +--- If [expr] is 1 or true, only check if a character is +--- available, it is not consumed. Return an empty string +--- if no character is available. +--- Otherwise this works like |getchar()|, except that a number +--- result is converted to a string. +--- +--- @return string +function vim.fn.getcharstr() end + +--- Return the type of the current command-line completion. +--- Only works when the command line is being edited, thus +--- requires use of |c_CTRL-\_e| or |c_CTRL-R_=|. +--- See |:command-completion| for the return string. +--- Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and +--- |setcmdline()|. +--- Returns an empty string when completion is not defined. +--- +--- @return string +function vim.fn.getcmdcompltype() end + +--- Return the current command-line. Only works when the command +--- line is being edited, thus requires use of |c_CTRL-\_e| or +--- |c_CTRL-R_=|. +--- Example: >vim +--- cmap <F7> <C-\>eescape(getcmdline(), ' \')<CR> +--- <Also see |getcmdtype()|, |getcmdpos()|, |setcmdpos()| and +--- |setcmdline()|. +--- Returns an empty string when entering a password or using +--- |inputsecret()|. +--- +--- @return string +function vim.fn.getcmdline() end + +--- Return the position of the cursor in the command line as a +--- byte count. The first column is 1. +--- Only works when editing the command line, thus requires use of +--- |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. +--- Returns 0 otherwise. +--- Also see |getcmdtype()|, |setcmdpos()|, |getcmdline()| and +--- |setcmdline()|. +--- +--- @return integer +function vim.fn.getcmdpos() end + +--- Return the screen position of the cursor in the command line +--- as a byte count. The first column is 1. +--- Instead of |getcmdpos()|, it adds the prompt position. +--- Only works when editing the command line, thus requires use of +--- |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. +--- Returns 0 otherwise. +--- Also see |getcmdpos()|, |setcmdpos()|, |getcmdline()| and +--- |setcmdline()|. +--- +--- @return any +function vim.fn.getcmdscreenpos() end + +--- Return the current command-line type. Possible return values +--- are: +--- : normal Ex command +--- > debug mode command |debug-mode| +--- / forward search command +--- ? backward search command +--- \@ |input()| command +--- `-` |:insert| or |:append| command +--- = |i_CTRL-R_=| +--- Only works when editing the command line, thus requires use of +--- |c_CTRL-\_e| or |c_CTRL-R_=| or an expression mapping. +--- Returns an empty string otherwise. +--- Also see |getcmdpos()|, |setcmdpos()| and |getcmdline()|. +--- +--- @return ':'|'>'|'/'|'?'|'@'|'-'|'=' +function vim.fn.getcmdtype() end + +--- Return the current |command-line-window| type. Possible return +--- values are the same as |getcmdtype()|. Returns an empty string +--- when not in the command-line window. +--- +--- @return ':'|'>'|'/'|'?'|'@'|'-'|'=' +function vim.fn.getcmdwintype() end + +--- Return a list of command-line completion matches. The String +--- {type} argument specifies what for. The following completion +--- types are supported: +--- +--- arglist file names in argument list +--- augroup autocmd groups +--- buffer buffer names +--- breakpoint |:breakadd| and |:breakdel| suboptions +--- cmdline |cmdline-completion| result +--- color color schemes +--- command Ex command +--- compiler compilers +--- custom,{func} custom completion, defined via {func} +--- customlist,{func} custom completion, defined via {func} +--- diff_buffer |:diffget| and |:diffput| completion +--- dir directory names +--- environment environment variable names +--- event autocommand events +--- expression Vim expression +--- file file and directory names +--- file_in_path file and directory names in |'path'| +--- filetype filetype names |'filetype'| +--- function function name +--- help help subjects +--- highlight highlight groups +--- history |:history| suboptions +--- locale locale names (as output of locale -a) +--- mapclear buffer argument +--- mapping mapping name +--- menu menus +--- messages |:messages| suboptions +--- option options +--- packadd optional package |pack-add| names +--- runtime |:runtime| completion +--- scriptnames sourced script names |:scriptnames| +--- shellcmd Shell command +--- sign |:sign| suboptions +--- syntax syntax file names |'syntax'| +--- syntime |:syntime| suboptions +--- tag tags +--- tag_listfiles tags, file names +--- user user names +--- var user variables +--- +--- If {pat} is an empty string, then all the matches are +--- returned. Otherwise only items matching {pat} are returned. +--- See |wildcards| for the use of special characters in {pat}. +--- +--- If the optional {filtered} flag is set to 1, then 'wildignore' +--- is applied to filter the results. Otherwise all the matches +--- are returned. The 'wildignorecase' option always applies. +--- +--- If the 'wildoptions' option contains "fuzzy", then fuzzy +--- matching is used to get the completion matches. Otherwise +--- regular expression matching is used. Thus this function +--- follows the user preference, what happens on the command line. +--- If you do not want this you can make 'wildoptions' empty +--- before calling getcompletion() and restore it afterwards. +--- +--- If {type} is "cmdline", then the |cmdline-completion| result is +--- returned. For example, to complete the possible values after +--- a ":call" command: >vim +--- echo getcompletion('call ', 'cmdline') +--- < +--- If there are no matches, an empty list is returned. An +--- invalid value for {type} produces an error. +--- +--- @param pat any +--- @param type any +--- @param filtered? any +--- @return string[] +function vim.fn.getcompletion(pat, type, filtered) end + +--- Get the position of the cursor. This is like getpos('.'), but +--- includes an extra "curswant" item in the list: +--- [0, lnum, col, off, curswant] ~ +--- The "curswant" number is the preferred column when moving the +--- cursor vertically. After |$| command it will be a very large +--- number equal to |v:maxcol|. Also see |getcursorcharpos()| and +--- |getpos()|. +--- The first "bufnum" item is always zero. The byte position of +--- the cursor is returned in "col". To get the character +--- position, use |getcursorcharpos()|. +--- +--- The optional {winid} argument can specify the window. It can +--- be the window number or the |window-ID|. The last known +--- cursor position is returned, this may be invalid for the +--- current value of the buffer if it is not the current window. +--- If {winid} is invalid a list with zeroes is returned. +--- +--- This can be used to save and restore the cursor position: >vim +--- let save_cursor = getcurpos() +--- MoveTheCursorAround +--- call setpos('.', save_cursor) +--- <Note that this only works within the window. See +--- |winrestview()| for restoring more state. +--- +--- @param winid? integer +--- @return any +function vim.fn.getcurpos(winid) end + +--- Same as |getcurpos()| but the column number in the returned +--- List is a character index instead of a byte index. +--- +--- Example: +--- With the cursor on '보' in line 3 with text "여보세요": >vim +--- getcursorcharpos() " returns [0, 3, 2, 0, 3] +--- getcurpos() " returns [0, 3, 4, 0, 3] +--- < +--- +--- @param winid? integer +--- @return any +function vim.fn.getcursorcharpos(winid) end + +--- With no arguments, returns the name of the effective +--- |current-directory|. With {winnr} or {tabnr} the working +--- directory of that scope is returned, and 'autochdir' is +--- ignored. +--- Tabs and windows are identified by their respective numbers, +--- 0 means current tab or window. Missing tab number implies 0. +--- Thus the following are equivalent: >vim +--- getcwd(0) +--- getcwd(0, 0) +--- <If {winnr} is -1 it is ignored, only the tab is resolved. +--- {winnr} can be the window number or the |window-ID|. +--- If both {winnr} and {tabnr} are -1 the global working +--- directory is returned. +--- Throw error if the arguments are invalid. |E5000| |E5001| |E5002| +--- +--- @param winnr? integer +--- @param tabnr? integer +--- @return string +function vim.fn.getcwd(winnr, tabnr) end + +--- Return the value of environment variable {name}. The {name} +--- argument is a string, without a leading '$'. Example: >vim +--- myHome = getenv('HOME') +--- +--- <When the variable does not exist |v:null| is returned. That +--- is different from a variable set to an empty string. +--- See also |expr-env|. +--- +--- @param name string +--- @return string +function vim.fn.getenv(name) end + +--- Without an argument returns the name of the normal font being +--- used. Like what is used for the Normal highlight group +--- |hl-Normal|. +--- With an argument a check is done whether String {name} is a +--- valid font name. If not then an empty string is returned. +--- Otherwise the actual font name is returned, or {name} if the +--- GUI does not support obtaining the real name. +--- Only works when the GUI is running, thus not in your vimrc or +--- gvimrc file. Use the |GUIEnter| autocommand to use this +--- function just after the GUI has started. +--- +--- @param name? string +--- @return string +function vim.fn.getfontname(name) end + +--- The result is a String, which is the read, write, and execute +--- permissions of the given file {fname}. +--- If {fname} does not exist or its directory cannot be read, an +--- empty string is returned. +--- The result is of the form "rwxrwxrwx", where each group of +--- "rwx" flags represent, in turn, the permissions of the owner +--- of the file, the group the file belongs to, and other users. +--- If a user does not have a given permission the flag for this +--- is replaced with the string "-". Examples: >vim +--- echo getfperm("/etc/passwd") +--- echo getfperm(expand("~/.config/nvim/init.vim")) +--- <This will hopefully (from a security point of view) display +--- the string "rw-r--r--" or even "rw-------". +--- +--- For setting permissions use |setfperm()|. +--- +--- @param fname string +--- @return string +function vim.fn.getfperm(fname) end + +--- The result is a Number, which is the size in bytes of the +--- given file {fname}. +--- If {fname} is a directory, 0 is returned. +--- If the file {fname} can't be found, -1 is returned. +--- If the size of {fname} is too big to fit in a Number then -2 +--- is returned. +--- +--- @param fname string +--- @return integer +function vim.fn.getfsize(fname) end + +--- The result is a Number, which is the last modification time of +--- the given file {fname}. The value is measured as seconds +--- since 1st Jan 1970, and may be passed to strftime(). See also +--- |localtime()| and |strftime()|. +--- If the file {fname} can't be found -1 is returned. +--- +--- @param fname string +--- @return integer +function vim.fn.getftime(fname) end + +--- The result is a String, which is a description of the kind of +--- file of the given file {fname}. +--- If {fname} does not exist an empty string is returned. +--- Here is a table over different kinds of files and their +--- results: +--- Normal file "file" +--- Directory "dir" +--- Symbolic link "link" +--- Block device "bdev" +--- Character device "cdev" +--- Socket "socket" +--- FIFO "fifo" +--- All other "other" +--- Example: >vim +--- getftype("/home") +--- <Note that a type such as "link" will only be returned on +--- systems that support it. On some systems only "dir" and +--- "file" are returned. +--- +--- @param fname string +--- @return 'file'|'dir'|'link'|'bdev'|'cdev'|'socket'|'fifo'|'other' +function vim.fn.getftype(fname) end + +--- Returns the |jumplist| for the specified window. +--- +--- Without arguments use the current window. +--- With {winnr} only use this window in the current tab page. +--- {winnr} can also be a |window-ID|. +--- With {winnr} and {tabnr} use the window in the specified tab +--- page. If {winnr} or {tabnr} is invalid, an empty list is +--- returned. +--- +--- The returned list contains two entries: a list with the jump +--- locations and the last used jump position number in the list. +--- Each entry in the jump location list is a dictionary with +--- the following entries: +--- bufnr buffer number +--- col column number +--- coladd column offset for 'virtualedit' +--- filename filename if available +--- lnum line number +--- +--- @param winnr? integer +--- @param tabnr? integer +--- @return vim.fn.getjumplist.ret +function vim.fn.getjumplist(winnr, tabnr) end + +--- Without {end} the result is a String, which is line {lnum} +--- from the current buffer. Example: >vim +--- getline(1) +--- <When {lnum} is a String that doesn't start with a +--- digit, |line()| is called to translate the String into a Number. +--- To get the line under the cursor: >vim +--- getline(".") +--- <When {lnum} is a number smaller than 1 or bigger than the +--- number of lines in the buffer, an empty string is returned. +--- +--- When {end} is given the result is a |List| where each item is +--- a line from the current buffer in the range {lnum} to {end}, +--- including line {end}. +--- {end} is used in the same way as {lnum}. +--- Non-existing lines are silently omitted. +--- When {end} is before {lnum} an empty |List| is returned. +--- Example: >vim +--- let start = line('.') +--- let end = search("^$") - 1 +--- let lines = getline(start, end) +--- +--- <To get lines from another buffer see |getbufline()| and +--- |getbufoneline()| +--- +--- @param lnum integer +--- @param end_? any +--- @return string|string[] +function vim.fn.getline(lnum, end_) end + +--- Returns a |List| with all the entries in the location list for +--- window {nr}. {nr} can be the window number or the |window-ID|. +--- When {nr} is zero the current window is used. +--- +--- For a location list window, the displayed location list is +--- returned. For an invalid window number {nr}, an empty list is +--- returned. Otherwise, same as |getqflist()|. +--- +--- If the optional {what} dictionary argument is supplied, then +--- returns the items listed in {what} as a dictionary. Refer to +--- |getqflist()| for the supported items in {what}. +--- +--- In addition to the items supported by |getqflist()| in {what}, +--- the following item is supported by |getloclist()|: +--- +--- filewinid id of the window used to display files +--- from the location list. This field is +--- applicable only when called from a +--- location list window. See +--- |location-list-file-window| for more +--- details. +--- +--- Returns a |Dictionary| with default values if there is no +--- location list for the window {nr}. +--- Returns an empty Dictionary if window {nr} does not exist. +--- +--- Examples (See also |getqflist-examples|): >vim +--- echo getloclist(3, {'all': 0}) +--- echo getloclist(5, {'filewinid': 0}) +--- < +--- +--- @param nr integer +--- @param what? any +--- @return any +function vim.fn.getloclist(nr, what) end + +--- Without the {buf} argument returns a |List| with information +--- about all the global marks. |mark| +--- +--- If the optional {buf} argument is specified, returns the +--- local marks defined in buffer {buf}. For the use of {buf}, +--- see |bufname()|. If {buf} is invalid, an empty list is +--- returned. +--- +--- Each item in the returned List is a |Dict| with the following: +--- mark name of the mark prefixed by "'" +--- pos a |List| with the position of the mark: +--- [bufnum, lnum, col, off] +--- Refer to |getpos()| for more information. +--- file file name +--- +--- Refer to |getpos()| for getting information about a specific +--- mark. +--- +--- @param buf? any +--- @return any +function vim.fn.getmarklist(buf) end + +--- Returns a |List| with all matches previously defined for the +--- current window by |matchadd()| and the |:match| commands. +--- |getmatches()| is useful in combination with |setmatches()|, +--- as |setmatches()| can restore a list of matches saved by +--- |getmatches()|. +--- If {win} is specified, use the window with this number or +--- window ID instead of the current window. If {win} is invalid, +--- an empty list is returned. +--- Example: >vim +--- echo getmatches() +--- < > +--- [{"group": "MyGroup1", "pattern": "TODO", +--- "priority": 10, "id": 1}, {"group": "MyGroup2", +--- "pattern": "FIXME", "priority": 10, "id": 2}] +--- < >vim +--- let m = getmatches() +--- call clearmatches() +--- echo getmatches() +--- < > +--- [] +--- < >vim +--- call setmatches(m) +--- echo getmatches() +--- < > +--- [{"group": "MyGroup1", "pattern": "TODO", +--- "priority": 10, "id": 1}, {"group": "MyGroup2", +--- "pattern": "FIXME", "priority": 10, "id": 2}] +--- < >vim +--- unlet m +--- < +--- +--- @param win? any +--- @return any +function vim.fn.getmatches(win) end + +--- Returns a |Dictionary| with the last known position of the +--- mouse. This can be used in a mapping for a mouse click. The +--- items are: +--- screenrow screen row +--- screencol screen column +--- winid Window ID of the click +--- winrow row inside "winid" +--- wincol column inside "winid" +--- line text line inside "winid" +--- column text column inside "winid" +--- coladd offset (in screen columns) from the +--- start of the clicked char +--- All numbers are 1-based. +--- +--- If not over a window, e.g. when in the command line, then only +--- "screenrow" and "screencol" are valid, the others are zero. +--- +--- When on the status line below a window or the vertical +--- separator right of a window, the "line" and "column" values +--- are zero. +--- +--- When the position is after the text then "column" is the +--- length of the text in bytes plus one. +--- +--- If the mouse is over a focusable floating window then that +--- window is used. +--- +--- When using |getchar()| the Vim variables |v:mouse_lnum|, +--- |v:mouse_col| and |v:mouse_winid| also provide these values. +--- +--- @return vim.fn.getmousepos.ret +function vim.fn.getmousepos() end + +--- Return a Number which is the process ID of the Vim process. +--- This is a unique number, until Vim exits. +--- +--- @return integer +function vim.fn.getpid() end + +--- Get the position for String {expr}. For possible values of +--- {expr} see |line()|. For getting the cursor position see +--- |getcurpos()|. +--- The result is a |List| with four numbers: +--- [bufnum, lnum, col, off] +--- "bufnum" is zero, unless a mark like '0 or 'A is used, then it +--- is the buffer number of the mark. +--- "lnum" and "col" are the position in the buffer. The first +--- column is 1. +--- The "off" number is zero, unless 'virtualedit' is used. Then +--- it is the offset in screen columns from the start of the +--- character. E.g., a position within a <Tab> or after the last +--- character. +--- Note that for '< and '> Visual mode matters: when it is "V" +--- (visual line mode) the column of '< is zero and the column of +--- '> is a large number equal to |v:maxcol|. +--- The column number in the returned List is the byte position +--- within the line. To get the character position in the line, +--- use |getcharpos()|. +--- A very large column number equal to |v:maxcol| can be returned, +--- in which case it means "after the end of the line". +--- If {expr} is invalid, returns a list with all zeros. +--- This can be used to save and restore the position of a mark: >vim +--- let save_a_mark = getpos("'a") +--- " ... +--- call setpos("'a", save_a_mark) +--- <Also see |getcharpos()|, |getcurpos()| and |setpos()|. +--- +--- @param expr string +--- @return integer[] +function vim.fn.getpos(expr) end + +--- Returns a |List| with all the current quickfix errors. Each +--- list item is a dictionary with these entries: +--- bufnr number of buffer that has the file name, use +--- bufname() to get the name +--- module module name +--- lnum line number in the buffer (first line is 1) +--- end_lnum +--- end of line number if the item is multiline +--- col column number (first column is 1) +--- end_col end of column number if the item has range +--- vcol |TRUE|: "col" is visual column +--- |FALSE|: "col" is byte index +--- nr error number +--- pattern search pattern used to locate the error +--- text description of the error +--- type type of the error, 'E', '1', etc. +--- valid |TRUE|: recognized error message +--- user_data +--- custom data associated with the item, can be +--- any type. +--- +--- When there is no error list or it's empty, an empty list is +--- returned. Quickfix list entries with a non-existing buffer +--- number are returned with "bufnr" set to zero (Note: some +--- functions accept buffer number zero for the alternate buffer, +--- you may need to explicitly check for zero). +--- +--- Useful application: Find pattern matches in multiple files and +--- do something with them: >vim +--- vimgrep /theword/jg *.c +--- for d in getqflist() +--- echo bufname(d.bufnr) ':' d.lnum '=' d.text +--- endfor +--- < +--- If the optional {what} dictionary argument is supplied, then +--- returns only the items listed in {what} as a dictionary. The +--- following string items are supported in {what}: +--- changedtick get the total number of changes made +--- to the list |quickfix-changedtick| +--- context get the |quickfix-context| +--- efm errorformat to use when parsing "lines". If +--- not present, then the 'errorformat' option +--- value is used. +--- id get information for the quickfix list with +--- |quickfix-ID|; zero means the id for the +--- current list or the list specified by "nr" +--- idx get information for the quickfix entry at this +--- index in the list specified by "id" or "nr". +--- If set to zero, then uses the current entry. +--- See |quickfix-index| +--- items quickfix list entries +--- lines parse a list of lines using 'efm' and return +--- the resulting entries. Only a |List| type is +--- accepted. The current quickfix list is not +--- modified. See |quickfix-parse|. +--- nr get information for this quickfix list; zero +--- means the current quickfix list and "$" means +--- the last quickfix list +--- qfbufnr number of the buffer displayed in the quickfix +--- window. Returns 0 if the quickfix buffer is +--- not present. See |quickfix-buffer|. +--- size number of entries in the quickfix list +--- title get the list title |quickfix-title| +--- winid get the quickfix |window-ID| +--- all all of the above quickfix properties +--- Non-string items in {what} are ignored. To get the value of a +--- particular item, set it to zero. +--- If "nr" is not present then the current quickfix list is used. +--- If both "nr" and a non-zero "id" are specified, then the list +--- specified by "id" is used. +--- To get the number of lists in the quickfix stack, set "nr" to +--- "$" in {what}. The "nr" value in the returned dictionary +--- contains the quickfix stack size. +--- When "lines" is specified, all the other items except "efm" +--- are ignored. The returned dictionary contains the entry +--- "items" with the list of entries. +--- +--- The returned dictionary contains the following entries: +--- changedtick total number of changes made to the +--- list |quickfix-changedtick| +--- context quickfix list context. See |quickfix-context| +--- If not present, set to "". +--- id quickfix list ID |quickfix-ID|. If not +--- present, set to 0. +--- idx index of the quickfix entry in the list. If not +--- present, set to 0. +--- items quickfix list entries. If not present, set to +--- an empty list. +--- nr quickfix list number. If not present, set to 0 +--- qfbufnr number of the buffer displayed in the quickfix +--- window. If not present, set to 0. +--- size number of entries in the quickfix list. If not +--- present, set to 0. +--- title quickfix list title text. If not present, set +--- to "". +--- winid quickfix |window-ID|. If not present, set to 0 +--- +--- Examples (See also |getqflist-examples|): >vim +--- echo getqflist({'all': 1}) +--- echo getqflist({'nr': 2, 'title': 1}) +--- echo getqflist({'lines' : ["F1:10:L10"]}) +--- < +--- +--- @param what? any +--- @return any +function vim.fn.getqflist(what) end + +--- The result is a String, which is the contents of register +--- {regname}. Example: >vim +--- let cliptext = getreg('*') +--- <When register {regname} was not set the result is an empty +--- string. +--- The {regname} argument must be a string. +--- +--- getreg('=') returns the last evaluated value of the expression +--- register. (For use in maps.) +--- getreg('=', 1) returns the expression itself, so that it can +--- be restored with |setreg()|. For other registers the extra +--- argument is ignored, thus you can always give it. +--- +--- If {list} is present and |TRUE|, the result type is changed +--- to |List|. Each list item is one text line. Use it if you care +--- about zero bytes possibly present inside register: without +--- third argument both NLs and zero bytes are represented as NLs +--- (see |NL-used-for-Nul|). +--- When the register was not set an empty list is returned. +--- +--- If {regname} is not specified, |v:register| is used. +--- +--- @param regname? string +--- @param list? any +--- @return string|string[] +function vim.fn.getreg(regname, list) end + +--- Returns detailed information about register {regname} as a +--- Dictionary with the following entries: +--- regcontents List of lines contained in register +--- {regname}, like +--- getreg({regname}, 1, 1). +--- regtype the type of register {regname}, as in +--- |getregtype()|. +--- isunnamed Boolean flag, v:true if this register +--- is currently pointed to by the unnamed +--- register. +--- points_to for the unnamed register, gives the +--- single letter name of the register +--- currently pointed to (see |quotequote|). +--- For example, after deleting a line +--- with `dd`, this field will be "1", +--- which is the register that got the +--- deleted text. +--- +--- The {regname} argument is a string. If {regname} is invalid +--- or not set, an empty Dictionary will be returned. +--- If {regname} is not specified, |v:register| is used. +--- The returned Dictionary can be passed to |setreg()|. +--- +--- @param regname? string +--- @return table +function vim.fn.getreginfo(regname) end + +--- The result is a String, which is type of register {regname}. +--- The value will be one of: +--- "v" for |charwise| text +--- "V" for |linewise| text +--- "<CTRL-V>{width}" for |blockwise-visual| text +--- "" for an empty or unknown register +--- <CTRL-V> is one character with value 0x16. +--- The {regname} argument is a string. If {regname} is not +--- specified, |v:register| is used. +--- +--- @param regname? string +--- @return string +function vim.fn.getregtype(regname) end + +--- Returns a |List| with information about all the sourced Vim +--- scripts in the order they were sourced, like what +--- `:scriptnames` shows. +--- +--- The optional Dict argument {opts} supports the following +--- optional items: +--- name Script name match pattern. If specified, +--- and "sid" is not specified, information about +--- scripts with a name that match the pattern +--- "name" are returned. +--- sid Script ID |<SID>|. If specified, only +--- information about the script with ID "sid" is +--- returned and "name" is ignored. +--- +--- Each item in the returned List is a |Dict| with the following +--- items: +--- autoload Always set to FALSE. +--- functions List of script-local function names defined in +--- the script. Present only when a particular +--- script is specified using the "sid" item in +--- {opts}. +--- name Vim script file name. +--- sid Script ID |<SID>|. +--- variables A dictionary with the script-local variables. +--- Present only when a particular script is +--- specified using the "sid" item in {opts}. +--- Note that this is a copy, the value of +--- script-local variables cannot be changed using +--- this dictionary. +--- version Vim script version, always 1 +--- +--- Examples: >vim +--- echo getscriptinfo({'name': 'myscript'}) +--- echo getscriptinfo({'sid': 15}).variables +--- < +--- +--- @param opts? table +--- @return any +function vim.fn.getscriptinfo(opts) end + +--- If {tabnr} is not specified, then information about all the +--- tab pages is returned as a |List|. Each List item is a +--- |Dictionary|. Otherwise, {tabnr} specifies the tab page +--- number and information about that one is returned. If the tab +--- page does not exist an empty List is returned. +--- +--- Each List item is a |Dictionary| with the following entries: +--- tabnr tab page number. +--- variables a reference to the dictionary with +--- tabpage-local variables +--- windows List of |window-ID|s in the tab page. +--- +--- @param tabnr? integer +--- @return any +function vim.fn.gettabinfo(tabnr) end + +--- Get the value of a tab-local variable {varname} in tab page +--- {tabnr}. |t:var| +--- Tabs are numbered starting with one. +--- The {varname} argument is a string. When {varname} is empty a +--- dictionary with all tab-local variables is returned. +--- Note that the name without "t:" must be used. +--- When the tab or variable doesn't exist {def} or an empty +--- string is returned, there is no error message. +--- +--- @param tabnr integer +--- @param varname string +--- @param def? any +--- @return any +function vim.fn.gettabvar(tabnr, varname, def) end + +--- Get the value of window-local variable {varname} in window +--- {winnr} in tab page {tabnr}. +--- The {varname} argument is a string. When {varname} is empty a +--- dictionary with all window-local variables is returned. +--- When {varname} is equal to "&" get the values of all +--- window-local options in a |Dictionary|. +--- Otherwise, when {varname} starts with "&" get the value of a +--- window-local option. +--- Note that {varname} must be the name without "w:". +--- Tabs are numbered starting with one. For the current tabpage +--- use |getwinvar()|. +--- {winnr} can be the window number or the |window-ID|. +--- When {winnr} is zero the current window is used. +--- This also works for a global option, buffer-local option and +--- window-local option, but it doesn't work for a global variable +--- or buffer-local variable. +--- When the tab, window or variable doesn't exist {def} or an +--- empty string is returned, there is no error message. +--- Examples: >vim +--- let list_is_on = gettabwinvar(1, 2, '&list') +--- echo "myvar = " .. gettabwinvar(3, 1, 'myvar') +--- < +--- To obtain all window-local variables use: >vim +--- gettabwinvar({tabnr}, {winnr}, '&') +--- < +--- +--- @param tabnr integer +--- @param winnr integer +--- @param varname string +--- @param def? any +--- @return any +function vim.fn.gettabwinvar(tabnr, winnr, varname, def) end + +--- The result is a Dict, which is the tag stack of window {winnr}. +--- {winnr} can be the window number or the |window-ID|. +--- When {winnr} is not specified, the current window is used. +--- When window {winnr} doesn't exist, an empty Dict is returned. +--- +--- The returned dictionary contains the following entries: +--- curidx Current index in the stack. When at +--- top of the stack, set to (length + 1). +--- Index of bottom of the stack is 1. +--- items List of items in the stack. Each item +--- is a dictionary containing the +--- entries described below. +--- length Number of entries in the stack. +--- +--- Each item in the stack is a dictionary with the following +--- entries: +--- bufnr buffer number of the current jump +--- from cursor position before the tag jump. +--- See |getpos()| for the format of the +--- returned list. +--- matchnr current matching tag number. Used when +--- multiple matching tags are found for a +--- name. +--- tagname name of the tag +--- +--- See |tagstack| for more information about the tag stack. +--- +--- @param winnr? integer +--- @return any +function vim.fn.gettagstack(winnr) end + +--- Translate String {text} if possible. +--- This is mainly for use in the distributed Vim scripts. When +--- generating message translations the {text} is extracted by +--- xgettext, the translator can add the translated message in the +--- .po file and Vim will lookup the translation when gettext() is +--- called. +--- For {text} double quoted strings are preferred, because +--- xgettext does not understand escaping in single quoted +--- strings. +--- +--- @param text any +--- @return any +function vim.fn.gettext(text) end + +--- Returns information about windows as a |List| with Dictionaries. +--- +--- If {winid} is given Information about the window with that ID +--- is returned, as a |List| with one item. If the window does not +--- exist the result is an empty list. +--- +--- Without {winid} information about all the windows in all the +--- tab pages is returned. +--- +--- Each List item is a |Dictionary| with the following entries: +--- botline last complete displayed buffer line +--- bufnr number of buffer in the window +--- height window height (excluding winbar) +--- loclist 1 if showing a location list +--- quickfix 1 if quickfix or location list window +--- terminal 1 if a terminal window +--- tabnr tab page number +--- topline first displayed buffer line +--- variables a reference to the dictionary with +--- window-local variables +--- width window width +--- winbar 1 if the window has a toolbar, 0 +--- otherwise +--- wincol leftmost screen column of the window; +--- "col" from |win_screenpos()| +--- textoff number of columns occupied by any +--- 'foldcolumn', 'signcolumn' and line +--- number in front of the text +--- winid |window-ID| +--- winnr window number +--- winrow topmost screen line of the window; +--- "row" from |win_screenpos()| +--- +--- @param winid? integer +--- @return vim.fn.getwininfo.ret.item[] +function vim.fn.getwininfo(winid) end + +--- The result is a |List| with two numbers, the result of +--- |getwinposx()| and |getwinposy()| combined: +--- [x-pos, y-pos] +--- {timeout} can be used to specify how long to wait in msec for +--- a response from the terminal. When omitted 100 msec is used. +--- +--- Use a longer time for a remote terminal. +--- When using a value less than 10 and no response is received +--- within that time, a previously reported position is returned, +--- if available. This can be used to poll for the position and +--- do some work in the meantime: >vim +--- while 1 +--- let res = getwinpos(1) +--- if res[0] >= 0 +--- break +--- endif +--- " Do some work here +--- endwhile +--- < +--- +--- @param timeout? integer +--- @return any +function vim.fn.getwinpos(timeout) end + +--- The result is a Number, which is the X coordinate in pixels of +--- the left hand side of the GUI Vim window. The result will be +--- -1 if the information is not available. +--- The value can be used with `:winpos`. +--- +--- @return integer +function vim.fn.getwinposx() end + +--- The result is a Number, which is the Y coordinate in pixels of +--- the top of the GUI Vim window. The result will be -1 if the +--- information is not available. +--- The value can be used with `:winpos`. +--- +--- @return integer +function vim.fn.getwinposy() end + +--- Like |gettabwinvar()| for the current tabpage. +--- Examples: >vim +--- let list_is_on = getwinvar(2, '&list') +--- echo "myvar = " .. getwinvar(1, 'myvar') +--- +--- @param winnr integer +--- @param varname string +--- @param def? any +--- @return any +function vim.fn.getwinvar(winnr, varname, def) end + +--- Expand the file wildcards in {expr}. See |wildcards| for the +--- use of special characters. +--- +--- Unless the optional {nosuf} argument is given and is |TRUE|, +--- the 'suffixes' and 'wildignore' options apply: Names matching +--- one of the patterns in 'wildignore' will be skipped and +--- 'suffixes' affect the ordering of matches. +--- 'wildignorecase' always applies. +--- +--- When {list} is present and it is |TRUE| the result is a |List| +--- with all matching files. The advantage of using a List is, +--- you also get filenames containing newlines correctly. +--- Otherwise the result is a String and when there are several +--- matches, they are separated by <NL> characters. +--- +--- If the expansion fails, the result is an empty String or List. +--- +--- You can also use |readdir()| if you need to do complicated +--- things, such as limiting the number of matches. +--- +--- A name for a non-existing file is not included. A symbolic +--- link is only included if it points to an existing file. +--- However, when the {alllinks} argument is present and it is +--- |TRUE| then all symbolic links are included. +--- +--- For most systems backticks can be used to get files names from +--- any external command. Example: >vim +--- let tagfiles = glob("`find . -name tags -print`") +--- let &tags = substitute(tagfiles, "\n", ",", "g") +--- <The result of the program inside the backticks should be one +--- item per line. Spaces inside an item are allowed. +--- +--- See |expand()| for expanding special Vim variables. See +--- |system()| for getting the raw output of an external command. +--- +--- @param expr any +--- @param nosuf? boolean +--- @param list? any +--- @param alllinks? any +--- @return any +function vim.fn.glob(expr, nosuf, list, alllinks) end + +--- Convert a file pattern, as used by glob(), into a search +--- pattern. The result can be used to match with a string that +--- is a file name. E.g. >vim +--- if filename =~ glob2regpat('Make*.mak') +--- " ... +--- endif +--- <This is equivalent to: >vim +--- if filename =~ '^Make.*\.mak$' +--- " ... +--- endif +--- <When {string} is an empty string the result is "^$", match an +--- empty string. +--- Note that the result depends on the system. On MS-Windows +--- a backslash usually means a path separator. +--- +--- @param string string +--- @return any +function vim.fn.glob2regpat(string) end + +--- Perform glob() for String {expr} on all directories in {path} +--- and concatenate the results. Example: >vim +--- echo globpath(&rtp, "syntax/c.vim") +--- < +--- {path} is a comma-separated list of directory names. Each +--- directory name is prepended to {expr} and expanded like with +--- |glob()|. A path separator is inserted when needed. +--- To add a comma inside a directory name escape it with a +--- backslash. Note that on MS-Windows a directory may have a +--- trailing backslash, remove it if you put a comma after it. +--- If the expansion fails for one of the directories, there is no +--- error message. +--- +--- Unless the optional {nosuf} argument is given and is |TRUE|, +--- the 'suffixes' and 'wildignore' options apply: Names matching +--- one of the patterns in 'wildignore' will be skipped and +--- 'suffixes' affect the ordering of matches. +--- +--- When {list} is present and it is |TRUE| the result is a |List| +--- with all matching files. The advantage of using a List is, you +--- also get filenames containing newlines correctly. Otherwise +--- the result is a String and when there are several matches, +--- they are separated by <NL> characters. Example: >vim +--- echo globpath(&rtp, "syntax/c.vim", 0, 1) +--- < +--- {allinks} is used as with |glob()|. +--- +--- The "**" item can be used to search in a directory tree. +--- For example, to find all "README.txt" files in the directories +--- in 'runtimepath' and below: >vim +--- echo globpath(&rtp, "**/README.txt") +--- <Upwards search and limiting the depth of "**" is not +--- supported, thus using 'path' will not always work properly. +--- +--- @param path string +--- @param expr any +--- @param nosuf? boolean +--- @param list? any +--- @param allinks? any +--- @return any +function vim.fn.globpath(path, expr, nosuf, list, allinks) end + +--- Returns 1 if {feature} is supported, 0 otherwise. The +--- {feature} argument is a feature name like "nvim-0.2.1" or +--- "win32", see below. See also |exists()|. +--- +--- To get the system name use |vim.uv|.os_uname() in Lua: >lua +--- print(vim.uv.os_uname().sysname) +--- +--- <If the code has a syntax error then Vimscript may skip the +--- rest of the line. Put |:if| and |:endif| on separate lines to +--- avoid the syntax error: >vim +--- if has('feature') +--- let x = this_breaks_without_the_feature() +--- endif +--- < +--- Vim's compile-time feature-names (prefixed with "+") are not +--- recognized because Nvim is always compiled with all possible +--- features. |feature-compile| +--- +--- Feature names can be: +--- 1. Nvim version. For example the "nvim-0.2.1" feature means +--- that Nvim is version 0.2.1 or later: >vim +--- if has("nvim-0.2.1") +--- " ... +--- endif +--- +--- <2. Runtime condition or other pseudo-feature. For example the +--- "win32" feature checks if the current system is Windows: >vim +--- if has("win32") +--- " ... +--- endif +--- < *feature-list* +--- List of supported pseudo-feature names: +--- acl |ACL| support. +--- bsd BSD system (not macOS, use "mac" for that). +--- clipboard |clipboard| provider is available. +--- fname_case Case in file names matters (for Darwin and MS-Windows +--- this is not present). +--- gui_running Nvim has a GUI. +--- iconv Can use |iconv()| for conversion. +--- linux Linux system. +--- mac MacOS system. +--- nvim This is Nvim. +--- python3 Legacy Vim |python3| interface. |has-python| +--- pythonx Legacy Vim |python_x| interface. |has-pythonx| +--- sun SunOS system. +--- ttyin input is a terminal (tty). +--- ttyout output is a terminal (tty). +--- unix Unix system. +--- *vim_starting* True during |startup|. +--- win32 Windows system (32 or 64 bit). +--- win64 Windows system (64 bit). +--- wsl WSL (Windows Subsystem for Linux) system. +--- +--- *has-patch* +--- 3. Vim patch. For example the "patch123" feature means that +--- Vim patch 123 at the current |v:version| was included: >vim +--- if v:version > 602 || v:version == 602 && has("patch148") +--- " ... +--- endif +--- +--- <4. Vim version. For example the "patch-7.4.237" feature means +--- that Nvim is Vim-compatible to version 7.4.237 or later. >vim +--- if has("patch-7.4.237") +--- " ... +--- endif +--- < +--- +--- @param feature any +--- @return 0|1 +function vim.fn.has(feature) end + +--- The result is a Number, which is TRUE if |Dictionary| {dict} +--- has an entry with key {key}. FALSE otherwise. The {key} +--- argument is a string. +--- +--- @param dict any +--- @param key any +--- @return 0|1 +function vim.fn.has_key(dict, key) end + +--- The result is a Number, which is 1 when the window has set a +--- local path via |:lcd| or when {winnr} is -1 and the tabpage +--- has set a local path via |:tcd|, otherwise 0. +--- +--- Tabs and windows are identified by their respective numbers, +--- 0 means current tab or window. Missing argument implies 0. +--- Thus the following are equivalent: >vim +--- echo haslocaldir() +--- echo haslocaldir(0) +--- echo haslocaldir(0, 0) +--- <With {winnr} use that window in the current tabpage. +--- With {winnr} and {tabnr} use the window in that tabpage. +--- {winnr} can be the window number or the |window-ID|. +--- If {winnr} is -1 it is ignored, only the tab is resolved. +--- Throw error if the arguments are invalid. |E5000| |E5001| |E5002| +--- +--- @param winnr? integer +--- @param tabnr? integer +--- @return 0|1 +function vim.fn.haslocaldir(winnr, tabnr) end + +--- The result is a Number, which is TRUE if there is a mapping +--- that contains {what} in somewhere in the rhs (what it is +--- mapped to) and this mapping exists in one of the modes +--- indicated by {mode}. +--- The arguments {what} and {mode} are strings. +--- When {abbr} is there and it is |TRUE| use abbreviations +--- instead of mappings. Don't forget to specify Insert and/or +--- Command-line mode. +--- Both the global mappings and the mappings local to the current +--- buffer are checked for a match. +--- If no matching mapping is found FALSE is returned. +--- The following characters are recognized in {mode}: +--- n Normal mode +--- v Visual and Select mode +--- x Visual mode +--- s Select mode +--- o Operator-pending mode +--- i Insert mode +--- l Language-Argument ("r", "f", "t", etc.) +--- c Command-line mode +--- When {mode} is omitted, "nvo" is used. +--- +--- This function is useful to check if a mapping already exists +--- to a function in a Vim script. Example: >vim +--- if !hasmapto('\ABCdoit') +--- map <Leader>d \ABCdoit +--- endif +--- <This installs the mapping to "\ABCdoit" only if there isn't +--- already a mapping to "\ABCdoit". +--- +--- @param what any +--- @param mode? string +--- @param abbr? any +--- @return 0|1 +function vim.fn.hasmapto(what, mode, abbr) end + +--- @deprecated +--- Obsolete name for |hlID()|. +--- +--- @param name string +--- @return any +function vim.fn.highlightID(name) end + +--- @deprecated +--- Obsolete name for |hlexists()|. +--- +--- @param name string +--- @return any +function vim.fn.highlight_exists(name) end + +--- Add the String {item} to the history {history} which can be +--- one of: *hist-names* +--- "cmd" or ":" command line history +--- "search" or "/" search pattern history +--- "expr" or "=" typed expression history +--- "input" or "\@" input line history +--- "debug" or ">" debug command history +--- empty the current or last used history +--- The {history} string does not need to be the whole name, one +--- character is sufficient. +--- If {item} does already exist in the history, it will be +--- shifted to become the newest entry. +--- The result is a Number: TRUE if the operation was successful, +--- otherwise FALSE is returned. +--- +--- Example: >vim +--- call histadd("input", strftime("%Y %b %d")) +--- let date=input("Enter date: ") +--- <This function is not available in the |sandbox|. +--- +--- @param history any +--- @param item any +--- @return 0|1 +function vim.fn.histadd(history, item) end + +--- Clear {history}, i.e. delete all its entries. See |hist-names| +--- for the possible values of {history}. +--- +--- If the parameter {item} evaluates to a String, it is used as a +--- regular expression. All entries matching that expression will +--- be removed from the history (if there are any). +--- Upper/lowercase must match, unless "\c" is used |/\c|. +--- If {item} evaluates to a Number, it will be interpreted as +--- an index, see |:history-indexing|. The respective entry will +--- be removed if it exists. +--- +--- The result is TRUE for a successful operation, otherwise FALSE +--- is returned. +--- +--- Examples: +--- Clear expression register history: >vim +--- call histdel("expr") +--- < +--- Remove all entries starting with "*" from the search history: >vim +--- call histdel("/", '^\*') +--- < +--- The following three are equivalent: >vim +--- call histdel("search", histnr("search")) +--- call histdel("search", -1) +--- call histdel("search", '^' .. histget("search", -1) .. '$') +--- < +--- To delete the last search pattern and use the last-but-one for +--- the "n" command and 'hlsearch': >vim +--- call histdel("search", -1) +--- let \@/ = histget("search", -1) +--- < +--- +--- @param history any +--- @param item? any +--- @return 0|1 +function vim.fn.histdel(history, item) end + +--- The result is a String, the entry with Number {index} from +--- {history}. See |hist-names| for the possible values of +--- {history}, and |:history-indexing| for {index}. If there is +--- no such entry, an empty String is returned. When {index} is +--- omitted, the most recent item from the history is used. +--- +--- Examples: +--- Redo the second last search from history. >vim +--- execute '/' .. histget("search", -2) +--- +--- <Define an Ex command ":H {num}" that supports re-execution of +--- the {num}th entry from the output of |:history|. >vim +--- command -nargs=1 H execute histget("cmd", 0+<args>) +--- < +--- +--- @param history any +--- @param index? any +--- @return string +function vim.fn.histget(history, index) end + +--- The result is the Number of the current entry in {history}. +--- See |hist-names| for the possible values of {history}. +--- If an error occurred, -1 is returned. +--- +--- Example: >vim +--- let inp_index = histnr("expr") +--- +--- @param history any +--- @return integer +function vim.fn.histnr(history) end + +--- The result is a Number, which is the ID of the highlight group +--- with name {name}. When the highlight group doesn't exist, +--- zero is returned. +--- This can be used to retrieve information about the highlight +--- group. For example, to get the background color of the +--- "Comment" group: >vim +--- echo synIDattr(synIDtrans(hlID("Comment")), "bg") +--- < +--- +--- @param name string +--- @return integer +function vim.fn.hlID(name) end + +--- The result is a Number, which is TRUE if a highlight group +--- called {name} exists. This is when the group has been +--- defined in some way. Not necessarily when highlighting has +--- been defined for it, it may also have been used for a syntax +--- item. +--- +--- @param name string +--- @return 0|1 +function vim.fn.hlexists(name) end + +--- The result is a String, which is the name of the machine on +--- which Vim is currently running. Machine names greater than +--- 256 characters long are truncated. +--- +--- @return string +function vim.fn.hostname() end + +--- The result is a String, which is the text {string} converted +--- from encoding {from} to encoding {to}. +--- When the conversion completely fails an empty string is +--- returned. When some characters could not be converted they +--- are replaced with "?". +--- The encoding names are whatever the iconv() library function +--- can accept, see ":!man 3 iconv". +--- Note that Vim uses UTF-8 for all Unicode encodings, conversion +--- from/to UCS-2 is automatically changed to use UTF-8. You +--- cannot use UCS-2 in a string anyway, because of the NUL bytes. +--- +--- @param string string +--- @param from any +--- @param to any +--- @return any +function vim.fn.iconv(string, from, to) end + +--- Returns a |String| which is a unique identifier of the +--- container type (|List|, |Dict|, |Blob| and |Partial|). It is +--- guaranteed that for the mentioned types `id(v1) ==# id(v2)` +--- returns true iff `type(v1) == type(v2) && v1 is v2`. +--- Note that `v:_null_string`, `v:_null_list`, `v:_null_dict` and +--- `v:_null_blob` have the same `id()` with different types +--- because they are internally represented as NULL pointers. +--- `id()` returns a hexadecimal representanion of the pointers to +--- the containers (i.e. like `0x994a40`), same as `printf("%p", +--- {expr})`, but it is advised against counting on the exact +--- format of the return value. +--- +--- It is not guaranteed that `id(no_longer_existing_container)` +--- will not be equal to some other `id()`: new containers may +--- reuse identifiers of the garbage-collected ones. +--- +--- @param expr any +--- @return any +function vim.fn.id(expr) end + +--- The result is a Number, which is indent of line {lnum} in the +--- current buffer. The indent is counted in spaces, the value +--- of 'tabstop' is relevant. {lnum} is used just like in +--- |getline()|. +--- When {lnum} is invalid -1 is returned. +--- +--- @param lnum integer +--- @return integer +function vim.fn.indent(lnum) end + +--- Find {expr} in {object} and return its index. See +--- |indexof()| for using a lambda to select the item. +--- +--- If {object} is a |List| return the lowest index where the item +--- has a value equal to {expr}. There is no automatic +--- conversion, so the String "4" is different from the Number 4. +--- And the Number 4 is different from the Float 4.0. The value +--- of 'ignorecase' is not used here, case matters as indicated by +--- the {ic} argument. +--- +--- If {object} is a |Blob| return the lowest index where the byte +--- value is equal to {expr}. +--- +--- If {start} is given then start looking at the item with index +--- {start} (may be negative for an item relative to the end). +--- +--- When {ic} is given and it is |TRUE|, ignore case. Otherwise +--- case must match. +--- +--- -1 is returned when {expr} is not found in {object}. +--- Example: >vim +--- let idx = index(words, "the") +--- if index(numbers, 123) >= 0 +--- " ... +--- endif +--- +--- @param object any +--- @param expr any +--- @param start? any +--- @param ic? any +--- @return any +function vim.fn.index(object, expr, start, ic) end + +--- Returns the index of an item in {object} where {expr} is +--- v:true. {object} must be a |List| or a |Blob|. +--- +--- If {object} is a |List|, evaluate {expr} for each item in the +--- List until the expression is v:true and return the index of +--- this item. +--- +--- If {object} is a |Blob| evaluate {expr} for each byte in the +--- Blob until the expression is v:true and return the index of +--- this byte. +--- +--- {expr} must be a |string| or |Funcref|. +--- +--- If {expr} is a |string|: If {object} is a |List|, inside +--- {expr} |v:key| has the index of the current List item and +--- |v:val| has the value of the item. If {object} is a |Blob|, +--- inside {expr} |v:key| has the index of the current byte and +--- |v:val| has the byte value. +--- +--- If {expr} is a |Funcref| it must take two arguments: +--- 1. the key or the index of the current item. +--- 2. the value of the current item. +--- The function must return |TRUE| if the item is found and the +--- search should stop. +--- +--- The optional argument {opts} is a Dict and supports the +--- following items: +--- startidx start evaluating {expr} at the item with this +--- index; may be negative for an item relative to +--- the end +--- Returns -1 when {expr} evaluates to v:false for all the items. +--- Example: >vim +--- let l = [#{n: 10}, #{n: 20}, #{n: 30}] +--- echo indexof(l, "v:val.n == 20") +--- echo indexof(l, {i, v -> v.n == 30}) +--- echo indexof(l, "v:val.n == 20", #{startidx: 1}) +--- +--- @param object any +--- @param expr any +--- @param opts? table +--- @return any +function vim.fn.indexof(object, expr, opts) end + +--- +--- @param prompt any +--- @param text? any +--- @param completion? any +--- @return any +function vim.fn.input(prompt, text, completion) end + +--- The result is a String, which is whatever the user typed on +--- the command-line. The {prompt} argument is either a prompt +--- string, or a blank string (for no prompt). A '\n' can be used +--- in the prompt to start a new line. +--- +--- In the second form it accepts a single dictionary with the +--- following keys, any of which may be omitted: +--- +--- Key Default Description ~ +--- prompt "" Same as {prompt} in the first form. +--- default "" Same as {text} in the first form. +--- completion nothing Same as {completion} in the first form. +--- cancelreturn "" The value returned when the dialog is +--- cancelled. +--- highlight nothing Highlight handler: |Funcref|. +--- +--- The highlighting set with |:echohl| is used for the prompt. +--- The input is entered just like a command-line, with the same +--- editing commands and mappings. There is a separate history +--- for lines typed for input(). +--- Example: >vim +--- if input("Coffee or beer? ") == "beer" +--- echo "Cheers!" +--- endif +--- < +--- If the optional {text} argument is present and not empty, this +--- is used for the default reply, as if the user typed this. +--- Example: >vim +--- let color = input("Color? ", "white") +--- +--- <The optional {completion} argument specifies the type of +--- completion supported for the input. Without it completion is +--- not performed. The supported completion types are the same as +--- that can be supplied to a user-defined command using the +--- "-complete=" argument. Refer to |:command-completion| for +--- more information. Example: >vim +--- let fname = input("File: ", "", "file") +--- +--- < *input()-highlight* *E5400* *E5402* +--- The optional `highlight` key allows specifying function which +--- will be used for highlighting user input. This function +--- receives user input as its only argument and must return +--- a list of 3-tuples [hl_start_col, hl_end_col + 1, hl_group] +--- where +--- hl_start_col is the first highlighted column, +--- hl_end_col is the last highlighted column (+ 1!), +--- hl_group is |:hi| group used for highlighting. +--- *E5403* *E5404* *E5405* *E5406* +--- Both hl_start_col and hl_end_col + 1 must point to the start +--- of the multibyte character (highlighting must not break +--- multibyte characters), hl_end_col + 1 may be equal to the +--- input length. Start column must be in range [0, len(input)), +--- end column must be in range (hl_start_col, len(input)], +--- sections must be ordered so that next hl_start_col is greater +--- then or equal to previous hl_end_col. +--- +--- Example (try some input with parentheses): >vim +--- highlight RBP1 guibg=Red ctermbg=red +--- highlight RBP2 guibg=Yellow ctermbg=yellow +--- highlight RBP3 guibg=Green ctermbg=green +--- highlight RBP4 guibg=Blue ctermbg=blue +--- let g:rainbow_levels = 4 +--- function! RainbowParens(cmdline) +--- let ret = [] +--- let i = 0 +--- let lvl = 0 +--- while i < len(a:cmdline) +--- if a:cmdline[i] is# '(' +--- call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)]) +--- let lvl += 1 +--- elseif a:cmdline[i] is# ')' +--- let lvl -= 1 +--- call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)]) +--- endif +--- let i += 1 +--- endwhile +--- return ret +--- endfunction +--- call input({'prompt':'>','highlight':'RainbowParens'}) +--- < +--- Highlight function is called at least once for each new +--- displayed input string, before command-line is redrawn. It is +--- expected that function is pure for the duration of one input() +--- call, i.e. it produces the same output for the same input, so +--- output may be memoized. Function is run like under |:silent| +--- modifier. If the function causes any errors, it will be +--- skipped for the duration of the current input() call. +--- +--- Highlighting is disabled if command-line contains arabic +--- characters. +--- +--- NOTE: This function must not be used in a startup file, for +--- the versions that only run in GUI mode (e.g., the Win32 GUI). +--- Note: When input() is called from within a mapping it will +--- consume remaining characters from that mapping, because a +--- mapping is handled like the characters were typed. +--- Use |inputsave()| before input() and |inputrestore()| +--- after input() to avoid that. Another solution is to avoid +--- that further characters follow in the mapping, e.g., by using +--- |:execute| or |:normal|. +--- +--- Example with a mapping: >vim +--- nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR> +--- function GetFoo() +--- call inputsave() +--- let g:Foo = input("enter search pattern: ") +--- call inputrestore() +--- endfunction +--- +--- @param opts table +--- @return any +function vim.fn.input(opts) end + +--- @deprecated +--- Use |input()| instead. +--- +--- @param ... any +--- @return any +function vim.fn.inputdialog(...) end + +--- {textlist} must be a |List| of strings. This |List| is +--- displayed, one string per line. The user will be prompted to +--- enter a number, which is returned. +--- The user can also select an item by clicking on it with the +--- mouse, if the mouse is enabled in the command line ('mouse' is +--- "a" or includes "c"). For the first string 0 is returned. +--- When clicking above the first item a negative number is +--- returned. When clicking on the prompt one more than the +--- length of {textlist} is returned. +--- Make sure {textlist} has less than 'lines' entries, otherwise +--- it won't work. It's a good idea to put the entry number at +--- the start of the string. And put a prompt in the first item. +--- Example: >vim +--- let color = inputlist(['Select color:', '1. red', +--- \ '2. green', '3. blue']) +--- +--- @param textlist any +--- @return any +function vim.fn.inputlist(textlist) end + +--- Restore typeahead that was saved with a previous |inputsave()|. +--- Should be called the same number of times inputsave() is +--- called. Calling it more often is harmless though. +--- Returns TRUE when there is nothing to restore, FALSE otherwise. +--- +--- @return any +function vim.fn.inputrestore() end + +--- Preserve typeahead (also from mappings) and clear it, so that +--- a following prompt gets input from the user. Should be +--- followed by a matching inputrestore() after the prompt. Can +--- be used several times, in which case there must be just as +--- many inputrestore() calls. +--- Returns TRUE when out of memory, FALSE otherwise. +--- +--- @return any +function vim.fn.inputsave() end + +--- This function acts much like the |input()| function with but +--- two exceptions: +--- a) the user's response will be displayed as a sequence of +--- asterisks ("*") thereby keeping the entry secret, and +--- b) the user's response will not be recorded on the input +--- |history| stack. +--- The result is a String, which is whatever the user actually +--- typed on the command-line in response to the issued prompt. +--- NOTE: Command-line completion is not supported. +--- +--- @param prompt any +--- @param text? any +--- @return any +function vim.fn.inputsecret(prompt, text) end + +--- When {object} is a |List| or a |Blob| insert {item} at the start +--- of it. +--- +--- If {idx} is specified insert {item} before the item with index +--- {idx}. If {idx} is zero it goes before the first item, just +--- like omitting {idx}. A negative {idx} is also possible, see +--- |list-index|. -1 inserts just before the last item. +--- +--- Returns the resulting |List| or |Blob|. Examples: >vim +--- let mylist = insert([2, 3, 5], 1) +--- call insert(mylist, 4, -1) +--- call insert(mylist, 6, len(mylist)) +--- <The last example can be done simpler with |add()|. +--- Note that when {item} is a |List| it is inserted as a single +--- item. Use |extend()| to concatenate |Lists|. +--- +--- @param object any +--- @param item any +--- @param idx? integer +--- @return any +function vim.fn.insert(object, item, idx) end + +--- Interrupt script execution. It works more or less like the +--- user typing CTRL-C, most commands won't execute and control +--- returns to the user. This is useful to abort execution +--- from lower down, e.g. in an autocommand. Example: >vim +--- function s:check_typoname(file) +--- if fnamemodify(a:file, ':t') == '[' +--- echomsg 'Maybe typo' +--- call interrupt() +--- endif +--- endfunction +--- au BufWritePre * call s:check_typoname(expand('<amatch>')) +--- < +--- +--- @return any +function vim.fn.interrupt() end + +--- Bitwise invert. The argument is converted to a number. A +--- List, Dict or Float argument causes an error. Example: >vim +--- let bits = invert(bits) +--- < +--- +--- @param expr any +--- @return any +function vim.fn.invert(expr) end + +--- The result is a Number, which is |TRUE| when a directory +--- with the name {directory} exists. If {directory} doesn't +--- exist, or isn't a directory, the result is |FALSE|. {directory} +--- is any expression, which is used as a String. +--- +--- @param directory any +--- @return 0|1 +function vim.fn.isdirectory(directory) end + +--- Return 1 if {expr} is a positive infinity, or -1 a negative +--- infinity, otherwise 0. >vim +--- echo isinf(1.0 / 0.0) +--- < 1 >vim +--- echo isinf(-1.0 / 0.0) +--- < -1 +--- +--- @param expr any +--- @return 1|0|-1 +function vim.fn.isinf(expr) end + +--- The result is a Number, which is |TRUE| when {expr} is the +--- name of a locked variable. +--- The string argument {expr} must be the name of a variable, +--- |List| item or |Dictionary| entry, not the variable itself! +--- Example: >vim +--- let alist = [0, ['a', 'b'], 2, 3] +--- lockvar 1 alist +--- echo islocked('alist') " 1 +--- echo islocked('alist[1]') " 0 +--- +--- <When {expr} is a variable that does not exist you get an error +--- message. Use |exists()| to check for existence. +--- +--- @param expr any +--- @return 0|1 +function vim.fn.islocked(expr) end + +--- Return |TRUE| if {expr} is a float with value NaN. >vim +--- echo isnan(0.0 / 0.0) +--- < 1 +--- +--- @param expr any +--- @return 0|1 +function vim.fn.isnan(expr) end + +--- Return a |List| with all the key-value pairs of {dict}. Each +--- |List| item is a list with two items: the key of a {dict} +--- entry and the value of this entry. The |List| is in arbitrary +--- order. Also see |keys()| and |values()|. +--- Example: >vim +--- for [key, value] in items(mydict) +--- echo key .. ': ' .. value +--- endfor +--- +--- @param dict any +--- @return any +function vim.fn.items(dict) end + +--- @deprecated +--- Obsolete name for |chanclose()| +--- +--- @param ... any +--- @return any +function vim.fn.jobclose(...) end + +--- Return the PID (process id) of |job-id| {job}. +--- +--- @param job any +--- @return integer +function vim.fn.jobpid(job) end + +--- Resize the pseudo terminal window of |job-id| {job} to {width} +--- columns and {height} rows. +--- Fails if the job was not started with `"pty":v:true`. +--- +--- @param job any +--- @param width integer +--- @param height integer +--- @return any +function vim.fn.jobresize(job, width, height) end + +--- @deprecated +--- Obsolete name for |chansend()| +--- +--- @param ... any +--- @return any +function vim.fn.jobsend(...) end + +--- Note: Prefer |vim.system()| in Lua (unless using the `pty` option). +--- +--- Spawns {cmd} as a job. +--- If {cmd} is a List it runs directly (no 'shell'). +--- If {cmd} is a String it runs in the 'shell', like this: >vim +--- call jobstart(split(&shell) + split(&shellcmdflag) + ['{cmd}']) +--- <(See |shell-unquoting| for details.) +--- +--- Example: >vim +--- call jobstart('nvim -h', {'on_stdout':{j,d,e->append(line('.'),d)}}) +--- < +--- Returns |job-id| on success, 0 on invalid arguments (or job +--- table is full), -1 if {cmd}[0] or 'shell' is not executable. +--- The returned job-id is a valid |channel-id| representing the +--- job's stdio streams. Use |chansend()| (or |rpcnotify()| and +--- |rpcrequest()| if "rpc" was enabled) to send data to stdin and +--- |chanclose()| to close the streams without stopping the job. +--- +--- See |job-control| and |RPC|. +--- +--- NOTE: on Windows if {cmd} is a List: +--- - cmd[0] must be an executable (not a "built-in"). If it is +--- in $PATH it can be called by name, without an extension: >vim +--- call jobstart(['ping', 'neovim.io']) +--- < If it is a full or partial path, extension is required: >vim +--- call jobstart(['System32\ping.exe', 'neovim.io']) +--- < - {cmd} is collapsed to a string of quoted args as expected +--- by CommandLineToArgvW https://msdn.microsoft.com/bb776391 +--- unless cmd[0] is some form of "cmd.exe". +--- +--- *jobstart-env* +--- The job environment is initialized as follows: +--- $NVIM is set to |v:servername| of the parent Nvim +--- $NVIM_LISTEN_ADDRESS is unset +--- $NVIM_LOG_FILE is unset +--- $VIM is unset +--- $VIMRUNTIME is unset +--- You can set these with the `env` option. +--- +--- *jobstart-options* +--- {opts} is a dictionary with these keys: +--- clear_env: (boolean) `env` defines the job environment +--- exactly, instead of merging current environment. +--- cwd: (string, default=|current-directory|) Working +--- directory of the job. +--- detach: (boolean) Detach the job process: it will not be +--- killed when Nvim exits. If the process exits +--- before Nvim, `on_exit` will be invoked. +--- env: (dict) Map of environment variable name:value +--- pairs extending (or replace with "clear_env") +--- the current environment. |jobstart-env| +--- height: (number) Height of the `pty` terminal. +--- |on_exit|: (function) Callback invoked when the job exits. +--- |on_stdout|: (function) Callback invoked when the job emits +--- stdout data. +--- |on_stderr|: (function) Callback invoked when the job emits +--- stderr data. +--- overlapped: (boolean) Sets FILE_FLAG_OVERLAPPED for the +--- stdio passed to the child process. Only on +--- MS-Windows; ignored on other platforms. +--- pty: (boolean) Connect the job to a new pseudo +--- terminal, and its streams to the master file +--- descriptor. `on_stdout` receives all output, +--- `on_stderr` is ignored. |terminal-start| +--- rpc: (boolean) Use |msgpack-rpc| to communicate with +--- the job over stdio. Then `on_stdout` is ignored, +--- but `on_stderr` can still be used. +--- stderr_buffered: (boolean) Collect data until EOF (stream closed) +--- before invoking `on_stderr`. |channel-buffered| +--- stdout_buffered: (boolean) Collect data until EOF (stream +--- closed) before invoking `on_stdout`. |channel-buffered| +--- stdin: (string) Either "pipe" (default) to connect the +--- job's stdin to a channel or "null" to disconnect +--- stdin. +--- width: (number) Width of the `pty` terminal. +--- +--- {opts} is passed as |self| dictionary to the callback; the +--- caller may set other keys to pass application-specific data. +--- +--- Returns: +--- - |channel-id| on success +--- - 0 on invalid arguments +--- - -1 if {cmd}[0] is not executable. +--- See also |job-control|, |channel|, |msgpack-rpc|. +--- +--- @param cmd any +--- @param opts? table +--- @return any +function vim.fn.jobstart(cmd, opts) end + +--- Stop |job-id| {id} by sending SIGTERM to the job process. If +--- the process does not terminate after a timeout then SIGKILL +--- will be sent. When the job terminates its |on_exit| handler +--- (if any) will be invoked. +--- See |job-control|. +--- +--- Returns 1 for valid job id, 0 for invalid id, including jobs have +--- exited or stopped. +--- +--- @param id any +--- @return any +function vim.fn.jobstop(id) end + +--- Waits for jobs and their |on_exit| handlers to complete. +--- +--- {jobs} is a List of |job-id|s to wait for. +--- {timeout} is the maximum waiting time in milliseconds. If +--- omitted or -1, wait forever. +--- +--- Timeout of 0 can be used to check the status of a job: >vim +--- let running = jobwait([{job-id}], 0)[0] == -1 +--- < +--- During jobwait() callbacks for jobs not in the {jobs} list may +--- be invoked. The screen will not redraw unless |:redraw| is +--- invoked by a callback. +--- +--- Returns a list of len({jobs}) integers, where each integer is +--- the status of the corresponding job: +--- Exit-code, if the job exited +--- -1 if the timeout was exceeded +--- -2 if the job was interrupted (by |CTRL-C|) +--- -3 if the job-id is invalid +--- +--- @param jobs any +--- @param timeout? integer +--- @return any +function vim.fn.jobwait(jobs, timeout) end + +--- Join the items in {list} together into one String. +--- When {sep} is specified it is put in between the items. If +--- {sep} is omitted a single space is used. +--- Note that {sep} is not added at the end. You might want to +--- add it there too: >vim +--- let lines = join(mylist, "\n") .. "\n" +--- <String items are used as-is. |Lists| and |Dictionaries| are +--- converted into a string like with |string()|. +--- The opposite function is |split()|. +--- +--- @param list any +--- @param sep? any +--- @return any +function vim.fn.join(list, sep) end + +--- Convert {expr} from JSON object. Accepts |readfile()|-style +--- list as the input, as well as regular string. May output any +--- Vim value. In the following cases it will output +--- |msgpack-special-dict|: +--- 1. Dictionary contains duplicate key. +--- 2. Dictionary contains empty key. +--- 3. String contains NUL byte. Two special dictionaries: for +--- dictionary and for string will be emitted in case string +--- with NUL byte was a dictionary key. +--- +--- Note: function treats its input as UTF-8 always. The JSON +--- standard allows only a few encodings, of which UTF-8 is +--- recommended and the only one required to be supported. +--- Non-UTF-8 characters are an error. +--- +--- @param expr any +--- @return any +function vim.fn.json_decode(expr) end + +--- Convert {expr} into a JSON string. Accepts +--- |msgpack-special-dict| as the input. Will not convert +--- |Funcref|s, mappings with non-string keys (can be created as +--- |msgpack-special-dict|), values with self-referencing +--- containers, strings which contain non-UTF-8 characters, +--- pseudo-UTF-8 strings which contain codepoints reserved for +--- surrogate pairs (such strings are not valid UTF-8 strings). +--- Non-printable characters are converted into "\u1234" escapes +--- or special escapes like "\t", other are dumped as-is. +--- |Blob|s are converted to arrays of the individual bytes. +--- +--- @param expr any +--- @return any +function vim.fn.json_encode(expr) end + +--- Return a |List| with all the keys of {dict}. The |List| is in +--- arbitrary order. Also see |items()| and |values()|. +--- +--- @param dict any +--- @return any +function vim.fn.keys(dict) end + +--- Turn the internal byte representation of keys into a form that +--- can be used for |:map|. E.g. >vim +--- let xx = "\<C-Home>" +--- echo keytrans(xx) +--- < <C-Home> +--- +--- @param string string +--- @return any +function vim.fn.keytrans(string) end + +--- @deprecated +--- Obsolete name for bufnr("$"). +--- +--- @return any +function vim.fn.last_buffer_nr() end + +--- The result is a Number, which is the length of the argument. +--- When {expr} is a String or a Number the length in bytes is +--- used, as with |strlen()|. +--- When {expr} is a |List| the number of items in the |List| is +--- returned. +--- When {expr} is a |Blob| the number of bytes is returned. +--- When {expr} is a |Dictionary| the number of entries in the +--- |Dictionary| is returned. +--- Otherwise an error is given and returns zero. +--- +--- @param expr any +--- @return any +function vim.fn.len(expr) end + +--- Call function {funcname} in the run-time library {libname} +--- with single argument {argument}. +--- This is useful to call functions in a library that you +--- especially made to be used with Vim. Since only one argument +--- is possible, calling standard library functions is rather +--- limited. +--- The result is the String returned by the function. If the +--- function returns NULL, this will appear as an empty string "" +--- to Vim. +--- If the function returns a number, use libcallnr()! +--- If {argument} is a number, it is passed to the function as an +--- int; if {argument} is a string, it is passed as a +--- null-terminated string. +--- +--- libcall() allows you to write your own 'plug-in' extensions to +--- Vim without having to recompile the program. It is NOT a +--- means to call system functions! If you try to do so Vim will +--- very probably crash. +--- +--- For Win32, the functions you write must be placed in a DLL +--- and use the normal C calling convention (NOT Pascal which is +--- used in Windows System DLLs). The function must take exactly +--- one parameter, either a character pointer or a long integer, +--- and must return a character pointer or NULL. The character +--- pointer returned must point to memory that will remain valid +--- after the function has returned (e.g. in static data in the +--- DLL). If it points to allocated memory, that memory will +--- leak away. Using a static buffer in the function should work, +--- it's then freed when the DLL is unloaded. +--- +--- WARNING: If the function returns a non-valid pointer, Vim may +--- crash! This also happens if the function returns a number, +--- because Vim thinks it's a pointer. +--- For Win32 systems, {libname} should be the filename of the DLL +--- without the ".DLL" suffix. A full path is only required if +--- the DLL is not in the usual places. +--- For Unix: When compiling your own plugins, remember that the +--- object code must be compiled as position-independent ('PIC'). +--- Examples: >vim +--- echo libcall("libc.so", "getenv", "HOME") +--- +--- @param libname string +--- @param funcname string +--- @param argument any +--- @return any +function vim.fn.libcall(libname, funcname, argument) end + +--- Just like |libcall()|, but used for a function that returns an +--- int instead of a string. +--- Examples: >vim +--- echo libcallnr("/usr/lib/libc.so", "getpid", "") +--- call libcallnr("libc.so", "printf", "Hello World!\n") +--- call libcallnr("libc.so", "sleep", 10) +--- < +--- +--- @param libname string +--- @param funcname string +--- @param argument any +--- @return any +function vim.fn.libcallnr(libname, funcname, argument) end + +--- The result is a Number, which is the line number of the file +--- position given with {expr}. The {expr} argument is a string. +--- The accepted positions are: +--- . the cursor position +--- $ the last line in the current buffer +--- 'x position of mark x (if the mark is not set, 0 is +--- returned) +--- w0 first line visible in current window (one if the +--- display isn't updated, e.g. in silent Ex mode) +--- w$ last line visible in current window (this is one +--- less than "w0" if no lines are visible) +--- v In Visual mode: the start of the Visual area (the +--- cursor is the end). When not in Visual mode +--- returns the cursor position. Differs from |'<| in +--- that it's updated right away. +--- Note that a mark in another file can be used. The line number +--- then applies to another buffer. +--- To get the column number use |col()|. To get both use +--- |getpos()|. +--- With the optional {winid} argument the values are obtained for +--- that window instead of the current window. +--- Returns 0 for invalid values of {expr} and {winid}. +--- Examples: >vim +--- echo line(".") " line number of the cursor +--- echo line(".", winid) " idem, in window "winid" +--- echo line("'t") " line number of mark t +--- echo line("'" .. marker) " line number of mark marker +--- < +--- To jump to the last known position when opening a file see +--- |last-position-jump|. +--- +--- @param expr any +--- @param winid? integer +--- @return integer +function vim.fn.line(expr, winid) end + +--- Return the byte count from the start of the buffer for line +--- {lnum}. This includes the end-of-line character, depending on +--- the 'fileformat' option for the current buffer. The first +--- line returns 1. UTF-8 encoding is used, 'fileencoding' is +--- ignored. This can also be used to get the byte count for the +--- line just below the last line: >vim +--- echo line2byte(line("$") + 1) +--- <This is the buffer size plus one. If 'fileencoding' is empty +--- it is the file size plus one. {lnum} is used like with +--- |getline()|. When {lnum} is invalid -1 is returned. +--- Also see |byte2line()|, |go| and |:goto|. +--- +--- @param lnum integer +--- @return integer +function vim.fn.line2byte(lnum) end + +--- Get the amount of indent for line {lnum} according the lisp +--- indenting rules, as with 'lisp'. +--- The indent is counted in spaces, the value of 'tabstop' is +--- relevant. {lnum} is used just like in |getline()|. +--- When {lnum} is invalid, -1 is returned. +--- +--- @param lnum integer +--- @return any +function vim.fn.lispindent(lnum) end + +--- Return a Blob concatenating all the number values in {list}. +--- Examples: >vim +--- echo list2blob([1, 2, 3, 4]) " returns 0z01020304 +--- echo list2blob([]) " returns 0z +--- <Returns an empty Blob on error. If one of the numbers is +--- negative or more than 255 error *E1239* is given. +--- +--- |blob2list()| does the opposite. +--- +--- @param list any +--- @return any +function vim.fn.list2blob(list) end + +--- Convert each number in {list} to a character string can +--- concatenate them all. Examples: >vim +--- echo list2str([32]) " returns " " +--- echo list2str([65, 66, 67]) " returns "ABC" +--- <The same can be done (slowly) with: >vim +--- echo join(map(list, {nr, val -> nr2char(val)}), '') +--- <|str2list()| does the opposite. +--- +--- UTF-8 encoding is always used, {utf8} option has no effect, +--- and exists only for backwards-compatibility. +--- With UTF-8 composing characters work as expected: >vim +--- echo list2str([97, 769]) " returns "á" +--- < +--- Returns an empty string on error. +--- +--- @param list any +--- @param utf8? any +--- @return any +function vim.fn.list2str(list, utf8) end + +--- Return the current time, measured as seconds since 1st Jan +--- 1970. See also |strftime()|, |strptime()| and |getftime()|. +--- +--- @return any +function vim.fn.localtime() end + +--- Return the natural logarithm (base e) of {expr} as a |Float|. +--- {expr} must evaluate to a |Float| or a |Number| in the range +--- (0, inf]. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo log(10) +--- < 2.302585 >vim +--- echo log(exp(5)) +--- < 5.0 +--- +--- @param expr any +--- @return any +function vim.fn.log(expr) end + +--- Return the logarithm of Float {expr} to base 10 as a |Float|. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo log10(1000) +--- < 3.0 >vim +--- echo log10(0.01) +--- < -2.0 +--- +--- @param expr any +--- @return any +function vim.fn.log10(expr) end + +--- {expr1} must be a |List|, |String|, |Blob| or |Dictionary|. +--- When {expr1} is a |List|| or |Dictionary|, replace each +--- item in {expr1} with the result of evaluating {expr2}. +--- For a |Blob| each byte is replaced. +--- For a |String|, each character, including composing +--- characters, is replaced. +--- If the item type changes you may want to use |mapnew()| to +--- create a new List or Dictionary. +--- +--- {expr2} must be a |String| or |Funcref|. +--- +--- If {expr2} is a |String|, inside {expr2} |v:val| has the value +--- of the current item. For a |Dictionary| |v:key| has the key +--- of the current item and for a |List| |v:key| has the index of +--- the current item. For a |Blob| |v:key| has the index of the +--- current byte. For a |String| |v:key| has the index of the +--- current character. +--- Example: >vim +--- call map(mylist, '"> " .. v:val .. " <"') +--- <This puts "> " before and " <" after each item in "mylist". +--- +--- Note that {expr2} is the result of an expression and is then +--- used as an expression again. Often it is good to use a +--- |literal-string| to avoid having to double backslashes. You +--- still have to double ' quotes +--- +--- If {expr2} is a |Funcref| it is called with two arguments: +--- 1. The key or the index of the current item. +--- 2. the value of the current item. +--- The function must return the new value of the item. Example +--- that changes each value by "key-value": >vim +--- func KeyValue(key, val) +--- return a:key .. '-' .. a:val +--- endfunc +--- call map(myDict, function('KeyValue')) +--- <It is shorter when using a |lambda|: >vim +--- call map(myDict, {key, val -> key .. '-' .. val}) +--- <If you do not use "val" you can leave it out: >vim +--- call map(myDict, {key -> 'item: ' .. key}) +--- <If you do not use "key" you can use a short name: >vim +--- call map(myDict, {_, val -> 'item: ' .. val}) +--- < +--- The operation is done in-place for a |List| and |Dictionary|. +--- If you want it to remain unmodified make a copy first: >vim +--- let tlist = map(copy(mylist), ' v:val .. "\t"') +--- +--- <Returns {expr1}, the |List| or |Dictionary| that was filtered, +--- or a new |Blob| or |String|. +--- When an error is encountered while evaluating {expr2} no +--- further items in {expr1} are processed. +--- When {expr2} is a Funcref errors inside a function are ignored, +--- unless it was defined with the "abort" flag. +--- +--- @param expr1 any +--- @param expr2 any +--- @return any +function vim.fn.map(expr1, expr2) end + +--- When {dict} is omitted or zero: Return the rhs of mapping +--- {name} in mode {mode}. The returned String has special +--- characters translated like in the output of the ":map" command +--- listing. When {dict} is TRUE a dictionary is returned, see +--- below. To get a list of all mappings see |maplist()|. +--- +--- When there is no mapping for {name}, an empty String is +--- returned if {dict} is FALSE, otherwise returns an empty Dict. +--- When the mapping for {name} is empty, then "<Nop>" is +--- returned. +--- +--- The {name} can have special key names, like in the ":map" +--- command. +--- +--- {mode} can be one of these strings: +--- "n" Normal +--- "v" Visual (including Select) +--- "o" Operator-pending +--- "i" Insert +--- "c" Cmd-line +--- "s" Select +--- "x" Visual +--- "l" langmap |language-mapping| +--- "t" Terminal +--- "" Normal, Visual and Operator-pending +--- When {mode} is omitted, the modes for "" are used. +--- +--- When {abbr} is there and it is |TRUE| use abbreviations +--- instead of mappings. +--- +--- When {dict} is there and it is |TRUE| return a dictionary +--- containing all the information of the mapping with the +--- following items: *mapping-dict* +--- "lhs" The {lhs} of the mapping as it would be typed +--- "lhsraw" The {lhs} of the mapping as raw bytes +--- "lhsrawalt" The {lhs} of the mapping as raw bytes, alternate +--- form, only present when it differs from "lhsraw" +--- "rhs" The {rhs} of the mapping as typed. +--- "silent" 1 for a |:map-silent| mapping, else 0. +--- "noremap" 1 if the {rhs} of the mapping is not remappable. +--- "script" 1 if mapping was defined with <script>. +--- "expr" 1 for an expression mapping (|:map-<expr>|). +--- "buffer" 1 for a buffer local mapping (|:map-local|). +--- "mode" Modes for which the mapping is defined. In +--- addition to the modes mentioned above, these +--- characters will be used: +--- " " Normal, Visual and Operator-pending +--- "!" Insert and Commandline mode +--- (|mapmode-ic|) +--- "sid" The script local ID, used for <sid> mappings +--- (|<SID>|). Negative for special contexts. +--- "scriptversion" The version of the script, always 1. +--- "lnum" The line number in "sid", zero if unknown. +--- "nowait" Do not wait for other, longer mappings. +--- (|:map-<nowait>|). +--- "abbr" True if this is an |abbreviation|. +--- "mode_bits" Nvim's internal binary representation of "mode". +--- |mapset()| ignores this; only "mode" is used. +--- See |maplist()| for usage examples. The values +--- are from src/nvim/state_defs.h and may change in +--- the future. +--- +--- The dictionary can be used to restore a mapping with +--- |mapset()|. +--- +--- The mappings local to the current buffer are checked first, +--- then the global mappings. +--- This function can be used to map a key even when it's already +--- mapped, and have it do the original mapping too. Sketch: >vim +--- exe 'nnoremap <Tab> ==' .. maparg('<Tab>', 'n') +--- +--- @param name string +--- @param mode? string +--- @param abbr? boolean +--- @param dict? boolean +--- @return string|table<string,any> +function vim.fn.maparg(name, mode, abbr, dict) end + +--- Check if there is a mapping that matches with {name} in mode +--- {mode}. See |maparg()| for {mode} and special names in +--- {name}. +--- When {abbr} is there and it is non-zero use abbreviations +--- instead of mappings. +--- A match happens with a mapping that starts with {name} and +--- with a mapping which is equal to the start of {name}. +--- +--- matches mapping "a" "ab" "abc" ~ +--- mapcheck("a") yes yes yes +--- mapcheck("abc") yes yes yes +--- mapcheck("ax") yes no no +--- mapcheck("b") no no no +--- +--- The difference with maparg() is that mapcheck() finds a +--- mapping that matches with {name}, while maparg() only finds a +--- mapping for {name} exactly. +--- When there is no mapping that starts with {name}, an empty +--- String is returned. If there is one, the RHS of that mapping +--- is returned. If there are several mappings that start with +--- {name}, the RHS of one of them is returned. This will be +--- "<Nop>" if the RHS is empty. +--- The mappings local to the current buffer are checked first, +--- then the global mappings. +--- This function can be used to check if a mapping can be added +--- without being ambiguous. Example: >vim +--- if mapcheck("_vv") == "" +--- map _vv :set guifont=7x13<CR> +--- endif +--- <This avoids adding the "_vv" mapping when there already is a +--- mapping for "_v" or for "_vvv". +--- +--- @param name string +--- @param mode? string +--- @param abbr? any +--- @return any +function vim.fn.mapcheck(name, mode, abbr) end + +--- Returns a |List| of all mappings. Each List item is a |Dict|, +--- the same as what is returned by |maparg()|, see +--- |mapping-dict|. When {abbr} is there and it is |TRUE| use +--- abbreviations instead of mappings. +--- +--- Example to show all mappings with "MultiMatch" in rhs: >vim +--- echo maplist()->filter({_, m -> +--- \ match(get(m, 'rhs', ''), 'MultiMatch') >= 0 +--- \ }) +--- <It can be tricky to find mappings for particular |:map-modes|. +--- |mapping-dict|'s "mode_bits" can simplify this. For example, +--- the mode_bits for Normal, Insert or Command-line modes are +--- 0x19. To find all the mappings available in those modes you +--- can do: >vim +--- let saved_maps = [] +--- for m in maplist() +--- if and(m.mode_bits, 0x19) != 0 +--- eval saved_maps->add(m) +--- endif +--- endfor +--- echo saved_maps->mapnew({_, m -> m.lhs}) +--- <The values of the mode_bits are defined in Nvim's +--- src/nvim/state_defs.h file and they can be discovered at +--- runtime using |:map-commands| and "maplist()". Example: >vim +--- omap xyzzy <Nop> +--- let op_bit = maplist()->filter( +--- \ {_, m -> m.lhs == 'xyzzy'})[0].mode_bits +--- ounmap xyzzy +--- echo printf("Operator-pending mode bit: 0x%x", op_bit) +--- +--- @return any +function vim.fn.maplist() end + +--- Like |map()| but instead of replacing items in {expr1} a new +--- List or Dictionary is created and returned. {expr1} remains +--- unchanged. Items can still be changed by {expr2}, if you +--- don't want that use |deepcopy()| first. +--- +--- @param expr1 any +--- @param expr2 any +--- @return any +function vim.fn.mapnew(expr1, expr2) end + +--- Restore a mapping from a dictionary, possibly returned by +--- |maparg()| or |maplist()|. A buffer mapping, when dict.buffer +--- is true, is set on the current buffer; it is up to the caller +--- to ensure that the intended buffer is the current buffer. This +--- feature allows copying mappings from one buffer to another. +--- The dict.mode value may restore a single mapping that covers +--- more than one mode, like with mode values of '!', ' ', "nox", +--- or 'v'. *E1276* +--- +--- In the first form, {mode} and {abbr} should be the same as +--- for the call to |maparg()|. *E460* +--- {mode} is used to define the mode in which the mapping is set, +--- not the "mode" entry in {dict}. +--- Example for saving and restoring a mapping: >vim +--- let save_map = maparg('K', 'n', 0, 1) +--- nnoremap K somethingelse +--- " ... +--- call mapset('n', 0, save_map) +--- <Note that if you are going to replace a map in several modes, +--- e.g. with `:map!`, you need to save/restore the mapping for +--- all of them, when they might differ. +--- +--- In the second form, with {dict} as the only argument, mode +--- and abbr are taken from the dict. +--- Example: >vim +--- let save_maps = maplist()->filter( +--- \ {_, m -> m.lhs == 'K'}) +--- nnoremap K somethingelse +--- cnoremap K somethingelse2 +--- " ... +--- unmap K +--- for d in save_maps +--- call mapset(d) +--- endfor +--- +--- @param mode string +--- @param abbr? any +--- @param dict? any +--- @return any +function vim.fn.mapset(mode, abbr, dict) end + +--- When {expr} is a |List| then this returns the index of the +--- first item where {pat} matches. Each item is used as a +--- String, |Lists| and |Dictionaries| are used as echoed. +--- +--- Otherwise, {expr} is used as a String. The result is a +--- Number, which gives the index (byte offset) in {expr} where +--- {pat} matches. +--- +--- A match at the first character or |List| item returns zero. +--- If there is no match -1 is returned. +--- +--- For getting submatches see |matchlist()|. +--- Example: >vim +--- echo match("testing", "ing") " results in 4 +--- echo match([1, 'x'], '\a') " results in 1 +--- <See |string-match| for how {pat} is used. +--- *strpbrk()* +--- Vim doesn't have a strpbrk() function. But you can do: >vim +--- let sepidx = match(line, '[.,;: \t]') +--- < *strcasestr()* +--- Vim doesn't have a strcasestr() function. But you can add +--- "\c" to the pattern to ignore case: >vim +--- let idx = match(haystack, '\cneedle') +--- < +--- If {start} is given, the search starts from byte index +--- {start} in a String or item {start} in a |List|. +--- The result, however, is still the index counted from the +--- first character/item. Example: >vim +--- echo match("testing", "ing", 2) +--- <result is again "4". >vim +--- echo match("testing", "ing", 4) +--- <result is again "4". >vim +--- echo match("testing", "t", 2) +--- <result is "3". +--- For a String, if {start} > 0 then it is like the string starts +--- {start} bytes later, thus "^" will match at {start}. Except +--- when {count} is given, then it's like matches before the +--- {start} byte are ignored (this is a bit complicated to keep it +--- backwards compatible). +--- For a String, if {start} < 0, it will be set to 0. For a list +--- the index is counted from the end. +--- If {start} is out of range ({start} > strlen({expr}) for a +--- String or {start} > len({expr}) for a |List|) -1 is returned. +--- +--- When {count} is given use the {count}th match. When a match +--- is found in a String the search for the next one starts one +--- character further. Thus this example results in 1: >vim +--- echo match("testing", "..", 0, 2) +--- <In a |List| the search continues in the next item. +--- Note that when {count} is added the way {start} works changes, +--- see above. +--- +--- See |pattern| for the patterns that are accepted. +--- The 'ignorecase' option is used to set the ignore-caseness of +--- the pattern. 'smartcase' is NOT used. The matching is always +--- done like 'magic' is set and 'cpoptions' is empty. +--- Note that a match at the start is preferred, thus when the +--- pattern is using "*" (any number of matches) it tends to find +--- zero matches at the start instead of a number of matches +--- further down in the text. +--- +--- @param expr any +--- @param pat any +--- @param start? any +--- @param count? any +--- @return any +function vim.fn.match(expr, pat, start, count) end + +--- Defines a pattern to be highlighted in the current window (a +--- "match"). It will be highlighted with {group}. Returns an +--- identification number (ID), which can be used to delete the +--- match using |matchdelete()|. The ID is bound to the window. +--- Matching is case sensitive and magic, unless case sensitivity +--- or magicness are explicitly overridden in {pattern}. The +--- 'magic', 'smartcase' and 'ignorecase' options are not used. +--- The "Conceal" value is special, it causes the match to be +--- concealed. +--- +--- The optional {priority} argument assigns a priority to the +--- match. A match with a high priority will have its +--- highlighting overrule that of a match with a lower priority. +--- A priority is specified as an integer (negative numbers are no +--- exception). If the {priority} argument is not specified, the +--- default priority is 10. The priority of 'hlsearch' is zero, +--- hence all matches with a priority greater than zero will +--- overrule it. Syntax highlighting (see 'syntax') is a separate +--- mechanism, and regardless of the chosen priority a match will +--- always overrule syntax highlighting. +--- +--- The optional {id} argument allows the request for a specific +--- match ID. If a specified ID is already taken, an error +--- message will appear and the match will not be added. An ID +--- is specified as a positive integer (zero excluded). IDs 1, 2 +--- and 3 are reserved for |:match|, |:2match| and |:3match|, +--- respectively. 3 is reserved for use by the |matchparen| +--- plugin. +--- If the {id} argument is not specified or -1, |matchadd()| +--- automatically chooses a free ID, which is at least 1000. +--- +--- The optional {dict} argument allows for further custom +--- values. Currently this is used to specify a match specific +--- conceal character that will be shown for |hl-Conceal| +--- highlighted matches. The dict can have the following members: +--- +--- conceal Special character to show instead of the +--- match (only for |hl-Conceal| highlighted +--- matches, see |:syn-cchar|) +--- window Instead of the current window use the +--- window with this number or window ID. +--- +--- The number of matches is not limited, as it is the case with +--- the |:match| commands. +--- +--- Returns -1 on error. +--- +--- Example: >vim +--- highlight MyGroup ctermbg=green guibg=green +--- let m = matchadd("MyGroup", "TODO") +--- <Deletion of the pattern: >vim +--- call matchdelete(m) +--- +--- <A list of matches defined by |matchadd()| and |:match| are +--- available from |getmatches()|. All matches can be deleted in +--- one operation by |clearmatches()|. +--- +--- @param group any +--- @param pattern any +--- @param priority? any +--- @param id? any +--- @param dict? any +--- @return any +function vim.fn.matchadd(group, pattern, priority, id, dict) end + +--- Same as |matchadd()|, but requires a list of positions {pos} +--- instead of a pattern. This command is faster than |matchadd()| +--- because it does not require to handle regular expressions and +--- sets buffer line boundaries to redraw screen. It is supposed +--- to be used when fast match additions and deletions are +--- required, for example to highlight matching parentheses. +--- *E5030* *E5031* +--- {pos} is a list of positions. Each position can be one of +--- these: +--- - A number. This whole line will be highlighted. The first +--- line has number 1. +--- - A list with one number, e.g., [23]. The whole line with this +--- number will be highlighted. +--- - A list with two numbers, e.g., [23, 11]. The first number is +--- the line number, the second one is the column number (first +--- column is 1, the value must correspond to the byte index as +--- |col()| would return). The character at this position will +--- be highlighted. +--- - A list with three numbers, e.g., [23, 11, 3]. As above, but +--- the third number gives the length of the highlight in bytes. +--- +--- Entries with zero and negative line numbers are silently +--- ignored, as well as entries with negative column numbers and +--- lengths. +--- +--- Returns -1 on error. +--- +--- Example: >vim +--- highlight MyGroup ctermbg=green guibg=green +--- let m = matchaddpos("MyGroup", [[23, 24], 34]) +--- <Deletion of the pattern: >vim +--- call matchdelete(m) +--- +--- <Matches added by |matchaddpos()| are returned by +--- |getmatches()|. +--- +--- @param group any +--- @param pos any +--- @param priority? any +--- @param id? any +--- @param dict? any +--- @return any +function vim.fn.matchaddpos(group, pos, priority, id, dict) end + +--- Selects the {nr} match item, as set with a |:match|, +--- |:2match| or |:3match| command. +--- Return a |List| with two elements: +--- The name of the highlight group used +--- The pattern used. +--- When {nr} is not 1, 2 or 3 returns an empty |List|. +--- When there is no match item set returns ['', '']. +--- This is useful to save and restore a |:match|. +--- Highlighting matches using the |:match| commands are limited +--- to three matches. |matchadd()| does not have this limitation. +--- +--- @param nr integer +--- @return any +function vim.fn.matcharg(nr) end + +--- Deletes a match with ID {id} previously defined by |matchadd()| +--- or one of the |:match| commands. Returns 0 if successful, +--- otherwise -1. See example for |matchadd()|. All matches can +--- be deleted in one operation by |clearmatches()|. +--- If {win} is specified, use the window with this number or +--- window ID instead of the current window. +--- +--- @param id any +--- @param win? any +--- @return any +function vim.fn.matchdelete(id, win) end + +--- Same as |match()|, but return the index of first character +--- after the match. Example: >vim +--- echo matchend("testing", "ing") +--- <results in "7". +--- *strspn()* *strcspn()* +--- Vim doesn't have a strspn() or strcspn() function, but you can +--- do it with matchend(): >vim +--- let span = matchend(line, '[a-zA-Z]') +--- let span = matchend(line, '[^a-zA-Z]') +--- <Except that -1 is returned when there are no matches. +--- +--- The {start}, if given, has the same meaning as for |match()|. >vim +--- echo matchend("testing", "ing", 2) +--- <results in "7". >vim +--- echo matchend("testing", "ing", 5) +--- <result is "-1". +--- When {expr} is a |List| the result is equal to |match()|. +--- +--- @param expr any +--- @param pat any +--- @param start? any +--- @param count? any +--- @return any +function vim.fn.matchend(expr, pat, start, count) end + +--- If {list} is a list of strings, then returns a |List| with all +--- the strings in {list} that fuzzy match {str}. The strings in +--- the returned list are sorted based on the matching score. +--- +--- The optional {dict} argument always supports the following +--- items: +--- matchseq When this item is present return only matches +--- that contain the characters in {str} in the +--- given sequence. +--- limit Maximum number of matches in {list} to be +--- returned. Zero means no limit. +--- +--- If {list} is a list of dictionaries, then the optional {dict} +--- argument supports the following additional items: +--- key Key of the item which is fuzzy matched against +--- {str}. The value of this item should be a +--- string. +--- text_cb |Funcref| that will be called for every item +--- in {list} to get the text for fuzzy matching. +--- This should accept a dictionary item as the +--- argument and return the text for that item to +--- use for fuzzy matching. +--- +--- {str} is treated as a literal string and regular expression +--- matching is NOT supported. The maximum supported {str} length +--- is 256. +--- +--- When {str} has multiple words each separated by white space, +--- then the list of strings that have all the words is returned. +--- +--- If there are no matching strings or there is an error, then an +--- empty list is returned. If length of {str} is greater than +--- 256, then returns an empty list. +--- +--- When {limit} is given, matchfuzzy() will find up to this +--- number of matches in {list} and return them in sorted order. +--- +--- Refer to |fuzzy-matching| for more information about fuzzy +--- matching strings. +--- +--- Example: >vim +--- echo matchfuzzy(["clay", "crow"], "cay") +--- <results in ["clay"]. >vim +--- echo getbufinfo()->map({_, v -> v.name})->matchfuzzy("ndl") +--- <results in a list of buffer names fuzzy matching "ndl". >vim +--- echo getbufinfo()->matchfuzzy("ndl", {'key' : 'name'}) +--- <results in a list of buffer information dicts with buffer +--- names fuzzy matching "ndl". >vim +--- echo getbufinfo()->matchfuzzy("spl", +--- \ {'text_cb' : {v -> v.name}}) +--- <results in a list of buffer information dicts with buffer +--- names fuzzy matching "spl". >vim +--- echo v:oldfiles->matchfuzzy("test") +--- <results in a list of file names fuzzy matching "test". >vim +--- let l = readfile("buffer.c")->matchfuzzy("str") +--- <results in a list of lines in "buffer.c" fuzzy matching "str". >vim +--- echo ['one two', 'two one']->matchfuzzy('two one') +--- <results in `['two one', 'one two']` . >vim +--- echo ['one two', 'two one']->matchfuzzy('two one', +--- \ {'matchseq': 1}) +--- <results in `['two one']`. +--- +--- @param list any +--- @param str any +--- @param dict? any +--- @return any +function vim.fn.matchfuzzy(list, str, dict) end + +--- Same as |matchfuzzy()|, but returns the list of matched +--- strings, the list of character positions where characters +--- in {str} matches and a list of matching scores. You can +--- use |byteidx()| to convert a character position to a byte +--- position. +--- +--- If {str} matches multiple times in a string, then only the +--- positions for the best match is returned. +--- +--- If there are no matching strings or there is an error, then a +--- list with three empty list items is returned. +--- +--- Example: >vim +--- echo matchfuzzypos(['testing'], 'tsg') +--- <results in [["testing"], [[0, 2, 6]], [99]] >vim +--- echo matchfuzzypos(['clay', 'lacy'], 'la') +--- <results in [["lacy", "clay"], [[0, 1], [1, 2]], [153, 133]] >vim +--- echo [{'text': 'hello', 'id' : 10}] +--- \ ->matchfuzzypos('ll', {'key' : 'text'}) +--- <results in `[[{"id": 10, "text": "hello"}], [[2, 3]], [127]]` +--- +--- @param list any +--- @param str any +--- @param dict? any +--- @return any +function vim.fn.matchfuzzypos(list, str, dict) end + +--- Same as |match()|, but return a |List|. The first item in the +--- list is the matched string, same as what matchstr() would +--- return. Following items are submatches, like "\1", "\2", etc. +--- in |:substitute|. When an optional submatch didn't match an +--- empty string is used. Example: >vim +--- echo matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)') +--- <Results in: ['acd', 'a', '', 'c', 'd', '', '', '', '', ''] +--- When there is no match an empty list is returned. +--- +--- You can pass in a List, but that is not very useful. +--- +--- @param expr any +--- @param pat any +--- @param start? any +--- @param count? any +--- @return any +function vim.fn.matchlist(expr, pat, start, count) end + +--- Same as |match()|, but return the matched string. Example: >vim +--- echo matchstr("testing", "ing") +--- <results in "ing". +--- When there is no match "" is returned. +--- The {start}, if given, has the same meaning as for |match()|. >vim +--- echo matchstr("testing", "ing", 2) +--- <results in "ing". >vim +--- echo matchstr("testing", "ing", 5) +--- <result is "". +--- When {expr} is a |List| then the matching item is returned. +--- The type isn't changed, it's not necessarily a String. +--- +--- @param expr any +--- @param pat any +--- @param start? any +--- @param count? any +--- @return any +function vim.fn.matchstr(expr, pat, start, count) end + +--- Same as |matchstr()|, but return the matched string, the start +--- position and the end position of the match. Example: >vim +--- echo matchstrpos("testing", "ing") +--- <results in ["ing", 4, 7]. +--- When there is no match ["", -1, -1] is returned. +--- The {start}, if given, has the same meaning as for |match()|. >vim +--- echo matchstrpos("testing", "ing", 2) +--- <results in ["ing", 4, 7]. >vim +--- echo matchstrpos("testing", "ing", 5) +--- <result is ["", -1, -1]. +--- When {expr} is a |List| then the matching item, the index +--- of first item where {pat} matches, the start position and the +--- end position of the match are returned. >vim +--- echo matchstrpos([1, '__x'], '\a') +--- <result is ["x", 1, 2, 3]. +--- The type isn't changed, it's not necessarily a String. +--- +--- @param expr any +--- @param pat any +--- @param start? any +--- @param count? any +--- @return any +function vim.fn.matchstrpos(expr, pat, start, count) end + +--- Return the maximum value of all items in {expr}. Example: >vim +--- echo max([apples, pears, oranges]) +--- +--- <{expr} can be a |List| or a |Dictionary|. For a Dictionary, +--- it returns the maximum of all values in the Dictionary. +--- If {expr} is neither a List nor a Dictionary, or one of the +--- items in {expr} cannot be used as a Number this results in +--- an error. An empty |List| or |Dictionary| results in zero. +--- +--- @param expr any +--- @return any +function vim.fn.max(expr) end + +--- Returns a |List| of |Dictionaries| describing |menus| (defined +--- by |:menu|, |:amenu|, …), including |hidden-menus|. +--- +--- {path} matches a menu by name, or all menus if {path} is an +--- empty string. Example: >vim +--- echo menu_get('File','') +--- echo menu_get('') +--- < +--- {modes} is a string of zero or more modes (see |maparg()| or +--- |creating-menus| for the list of modes). "a" means "all". +--- +--- Example: >vim +--- nnoremenu &Test.Test inormal +--- inoremenu Test.Test insert +--- vnoremenu Test.Test x +--- echo menu_get("") +--- +--- <returns something like this: > +--- +--- [ { +--- "hidden": 0, +--- "name": "Test", +--- "priority": 500, +--- "shortcut": 84, +--- "submenus": [ { +--- "hidden": 0, +--- "mappings": { +--- i": { +--- "enabled": 1, +--- "noremap": 1, +--- "rhs": "insert", +--- "sid": 1, +--- "silent": 0 +--- }, +--- n": { ... }, +--- s": { ... }, +--- v": { ... } +--- }, +--- "name": "Test", +--- "priority": 500, +--- "shortcut": 0 +--- } ] +--- } ] +--- < +--- +--- @param path string +--- @param modes? any +--- @return any +function vim.fn.menu_get(path, modes) end + +--- Return information about the specified menu {name} in +--- mode {mode}. The menu name should be specified without the +--- shortcut character ('&'). If {name} is "", then the top-level +--- menu names are returned. +--- +--- {mode} can be one of these strings: +--- "n" Normal +--- "v" Visual (including Select) +--- "o" Operator-pending +--- "i" Insert +--- "c" Cmd-line +--- "s" Select +--- "x" Visual +--- "t" Terminal-Job +--- "" Normal, Visual and Operator-pending +--- "!" Insert and Cmd-line +--- When {mode} is omitted, the modes for "" are used. +--- +--- Returns a |Dictionary| containing the following items: +--- accel menu item accelerator text |menu-text| +--- display display name (name without '&') +--- enabled v:true if this menu item is enabled +--- Refer to |:menu-enable| +--- icon name of the icon file (for toolbar) +--- |toolbar-icon| +--- iconidx index of a built-in icon +--- modes modes for which the menu is defined. In +--- addition to the modes mentioned above, these +--- characters will be used: +--- " " Normal, Visual and Operator-pending +--- name menu item name. +--- noremenu v:true if the {rhs} of the menu item is not +--- remappable else v:false. +--- priority menu order priority |menu-priority| +--- rhs right-hand-side of the menu item. The returned +--- string has special characters translated like +--- in the output of the ":menu" command listing. +--- When the {rhs} of a menu item is empty, then +--- "<Nop>" is returned. +--- script v:true if script-local remapping of {rhs} is +--- allowed else v:false. See |:menu-script|. +--- shortcut shortcut key (character after '&' in +--- the menu name) |menu-shortcut| +--- silent v:true if the menu item is created +--- with <silent> argument |:menu-silent| +--- submenus |List| containing the names of +--- all the submenus. Present only if the menu +--- item has submenus. +--- +--- Returns an empty dictionary if the menu item is not found. +--- +--- Examples: >vim +--- echo menu_info('Edit.Cut') +--- echo menu_info('File.Save', 'n') +--- +--- " Display the entire menu hierarchy in a buffer +--- func ShowMenu(name, pfx) +--- let m = menu_info(a:name) +--- call append(line('$'), a:pfx .. m.display) +--- for child in m->get('submenus', []) +--- call ShowMenu(a:name .. '.' .. escape(child, '.'), +--- \ a:pfx .. ' ') +--- endfor +--- endfunc +--- new +--- for topmenu in menu_info('').submenus +--- call ShowMenu(topmenu, '') +--- endfor +--- < +--- +--- @param name string +--- @param mode? string +--- @return any +function vim.fn.menu_info(name, mode) end + +--- Return the minimum value of all items in {expr}. Example: >vim +--- echo min([apples, pears, oranges]) +--- +--- <{expr} can be a |List| or a |Dictionary|. For a Dictionary, +--- it returns the minimum of all values in the Dictionary. +--- If {expr} is neither a List nor a Dictionary, or one of the +--- items in {expr} cannot be used as a Number this results in +--- an error. An empty |List| or |Dictionary| results in zero. +--- +--- @param expr any +--- @return any +function vim.fn.min(expr) end + +--- Create directory {name}. +--- +--- When {flags} is present it must be a string. An empty string +--- has no effect. +--- +--- If {flags} contains "p" then intermediate directories are +--- created as necessary. +--- +--- If {flags} contains "D" then {name} is deleted at the end of +--- the current function, as with: >vim +--- defer delete({name}, 'd') +--- < +--- If {flags} contains "R" then {name} is deleted recursively at +--- the end of the current function, as with: >vim +--- defer delete({name}, 'rf') +--- <Note that when {name} has more than one part and "p" is used +--- some directories may already exist. Only the first one that +--- is created and what it contains is scheduled to be deleted. +--- E.g. when using: >vim +--- call mkdir('subdir/tmp/autoload', 'pR') +--- <and "subdir" already exists then "subdir/tmp" will be +--- scheduled for deletion, like with: >vim +--- defer delete('subdir/tmp', 'rf') +--- < +--- If {prot} is given it is used to set the protection bits of +--- the new directory. The default is 0o755 (rwxr-xr-x: r/w for +--- the user, readable for others). Use 0o700 to make it +--- unreadable for others. +--- +--- {prot} is applied for all parts of {name}. Thus if you create +--- /tmp/foo/bar then /tmp/foo will be created with 0o700. Example: >vim +--- call mkdir($HOME .. "/tmp/foo/bar", "p", 0o700) +--- +--- <This function is not available in the |sandbox|. +--- +--- If you try to create an existing directory with {flags} set to +--- "p" mkdir() will silently exit. +--- +--- The function result is a Number, which is TRUE if the call was +--- successful or FALSE if the directory creation failed or partly +--- failed. +--- +--- @param name string +--- @param flags? string +--- @param prot? any +--- @return any +function vim.fn.mkdir(name, flags, prot) end + +--- Return a string that indicates the current mode. +--- If [expr] is supplied and it evaluates to a non-zero Number or +--- a non-empty String (|non-zero-arg|), then the full mode is +--- returned, otherwise only the first letter is returned. +--- Also see |state()|. +--- +--- n Normal +--- no Operator-pending +--- nov Operator-pending (forced charwise |o_v|) +--- noV Operator-pending (forced linewise |o_V|) +--- noCTRL-V Operator-pending (forced blockwise |o_CTRL-V|) +--- CTRL-V is one character +--- niI Normal using |i_CTRL-O| in |Insert-mode| +--- niR Normal using |i_CTRL-O| in |Replace-mode| +--- niV Normal using |i_CTRL-O| in |Virtual-Replace-mode| +--- nt Normal in |terminal-emulator| (insert goes to +--- Terminal mode) +--- ntT Normal using |t_CTRL-\_CTRL-O| in |Terminal-mode| +--- v Visual by character +--- vs Visual by character using |v_CTRL-O| in Select mode +--- V Visual by line +--- Vs Visual by line using |v_CTRL-O| in Select mode +--- CTRL-V Visual blockwise +--- CTRL-Vs Visual blockwise using |v_CTRL-O| in Select mode +--- s Select by character +--- S Select by line +--- CTRL-S Select blockwise +--- i Insert +--- ic Insert mode completion |compl-generic| +--- ix Insert mode |i_CTRL-X| completion +--- R Replace |R| +--- Rc Replace mode completion |compl-generic| +--- Rx Replace mode |i_CTRL-X| completion +--- Rv Virtual Replace |gR| +--- Rvc Virtual Replace mode completion |compl-generic| +--- Rvx Virtual Replace mode |i_CTRL-X| completion +--- c Command-line editing +--- cr Command-line editing overstrike mode |c_<Insert>| +--- cv Vim Ex mode |gQ| +--- cvr Vim Ex mode while in overstrike mode |c_<Insert>| +--- r Hit-enter prompt +--- rm The -- more -- prompt +--- r? A |:confirm| query of some sort +--- ! Shell or external command is executing +--- t Terminal mode: keys go to the job +--- +--- This is useful in the 'statusline' option or RPC calls. In +--- most other places it always returns "c" or "n". +--- Note that in the future more modes and more specific modes may +--- be added. It's better not to compare the whole string but only +--- the leading character(s). +--- Also see |visualmode()|. +--- +--- @return any +function vim.fn.mode() end + +--- Convert a list of Vimscript objects to msgpack. Returned value is a +--- |readfile()|-style list. When {type} contains "B", a |Blob| is +--- returned instead. Example: >vim +--- call writefile(msgpackdump([{}]), 'fname.mpack', 'b') +--- <or, using a |Blob|: >vim +--- call writefile(msgpackdump([{}], 'B'), 'fname.mpack') +--- < +--- This will write the single 0x80 byte to a `fname.mpack` file +--- (dictionary with zero items is represented by 0x80 byte in +--- messagepack). +--- +--- Limitations: *E5004* *E5005* +--- 1. |Funcref|s cannot be dumped. +--- 2. Containers that reference themselves cannot be dumped. +--- 3. Dictionary keys are always dumped as STR strings. +--- 4. Other strings and |Blob|s are always dumped as BIN strings. +--- 5. Points 3. and 4. do not apply to |msgpack-special-dict|s. +--- +--- @param list any +--- @param type? any +--- @return any +function vim.fn.msgpackdump(list, type) end + +--- Convert a |readfile()|-style list or a |Blob| to a list of +--- Vimscript objects. +--- Example: >vim +--- let fname = expand('~/.config/nvim/shada/main.shada') +--- let mpack = readfile(fname, 'b') +--- let shada_objects = msgpackparse(mpack) +--- <This will read ~/.config/nvim/shada/main.shada file to +--- `shada_objects` list. +--- +--- Limitations: +--- 1. Mapping ordering is not preserved unless messagepack +--- mapping is dumped using generic mapping +--- (|msgpack-special-map|). +--- 2. Since the parser aims to preserve all data untouched +--- (except for 1.) some strings are parsed to +--- |msgpack-special-dict| format which is not convenient to +--- use. +--- *msgpack-special-dict* +--- Some messagepack strings may be parsed to special +--- dictionaries. Special dictionaries are dictionaries which +--- +--- 1. Contain exactly two keys: `_TYPE` and `_VAL`. +--- 2. `_TYPE` key is one of the types found in |v:msgpack_types| +--- variable. +--- 3. Value for `_VAL` has the following format (Key column +--- contains name of the key from |v:msgpack_types|): +--- +--- Key Value ~ +--- nil Zero, ignored when dumping. Not returned by +--- |msgpackparse()| since |v:null| was introduced. +--- boolean One or zero. When dumping it is only checked that +--- value is a |Number|. Not returned by |msgpackparse()| +--- since |v:true| and |v:false| were introduced. +--- integer |List| with four numbers: sign (-1 or 1), highest two +--- bits, number with bits from 62nd to 31st, lowest 31 +--- bits. I.e. to get actual number one will need to use +--- code like > +--- _VAL[0] * ((_VAL[1] << 62) +--- & (_VAL[2] << 31) +--- & _VAL[3]) +--- < Special dictionary with this type will appear in +--- |msgpackparse()| output under one of the following +--- circumstances: +--- 1. |Number| is 32-bit and value is either above +--- INT32_MAX or below INT32_MIN. +--- 2. |Number| is 64-bit and value is above INT64_MAX. It +--- cannot possibly be below INT64_MIN because msgpack +--- C parser does not support such values. +--- float |Float|. This value cannot possibly appear in +--- |msgpackparse()| output. +--- string |readfile()|-style list of strings. This value will +--- appear in |msgpackparse()| output if string contains +--- zero byte or if string is a mapping key and mapping is +--- being represented as special dictionary for other +--- reasons. +--- binary |String|, or |Blob| if binary string contains zero +--- byte. This value cannot appear in |msgpackparse()| +--- output since blobs were introduced. +--- array |List|. This value cannot appear in |msgpackparse()| +--- output. +--- *msgpack-special-map* +--- map |List| of |List|s with two items (key and value) each. +--- This value will appear in |msgpackparse()| output if +--- parsed mapping contains one of the following keys: +--- 1. Any key that is not a string (including keys which +--- are binary strings). +--- 2. String with NUL byte inside. +--- 3. Duplicate key. +--- 4. Empty key. +--- ext |List| with two values: first is a signed integer +--- representing extension type. Second is +--- |readfile()|-style list of strings. +--- +--- @param data any +--- @return any +function vim.fn.msgpackparse(data) end + +--- Return the line number of the first line at or below {lnum} +--- that is not blank. Example: >vim +--- if getline(nextnonblank(1)) =~ "Java" | endif +--- <When {lnum} is invalid or there is no non-blank line at or +--- below it, zero is returned. +--- {lnum} is used like with |getline()|. +--- See also |prevnonblank()|. +--- +--- @param lnum integer +--- @return any +function vim.fn.nextnonblank(lnum) end + +--- Return a string with a single character, which has the number +--- value {expr}. Examples: >vim +--- echo nr2char(64) " returns '\@' +--- echo nr2char(32) " returns ' ' +--- <Example for "utf-8": >vim +--- echo nr2char(300) " returns I with bow character +--- < +--- UTF-8 encoding is always used, {utf8} option has no effect, +--- and exists only for backwards-compatibility. +--- Note that a NUL character in the file is specified with +--- nr2char(10), because NULs are represented with newline +--- characters. nr2char(0) is a real NUL and terminates the +--- string, thus results in an empty string. +--- +--- @param expr any +--- @param utf8? any +--- @return any +function vim.fn.nr2char(expr, utf8) end + +--- Bitwise OR on the two arguments. The arguments are converted +--- to a number. A List, Dict or Float argument causes an error. +--- Also see `and()` and `xor()`. +--- Example: >vim +--- let bits = or(bits, 0x80) +--- +--- <Rationale: The reason this is a function and not using the "|" +--- character like many languages, is that Vi has always used "|" +--- to separate commands. In many places it would not be clear if +--- "|" is an operator or a command separator. +--- +--- @param expr any +--- @param expr1 any +--- @return any +vim.fn['or'] = function(expr, expr1) end + +--- Shorten directory names in the path {path} and return the +--- result. The tail, the file name, is kept as-is. The other +--- components in the path are reduced to {len} letters in length. +--- If {len} is omitted or smaller than 1 then 1 is used (single +--- letters). Leading '~' and '.' characters are kept. Examples: >vim +--- echo pathshorten('~/.config/nvim/autoload/file1.vim') +--- < ~/.c/n/a/file1.vim ~ +--- >vim +--- echo pathshorten('~/.config/nvim/autoload/file2.vim', 2) +--- < ~/.co/nv/au/file2.vim ~ +--- It doesn't matter if the path exists or not. +--- Returns an empty string on error. +--- +--- @param path string +--- @param len? any +--- @return any +function vim.fn.pathshorten(path, len) end + +--- Evaluate |perl| expression {expr} and return its result +--- converted to Vim data structures. +--- Numbers and strings are returned as they are (strings are +--- copied though). +--- Lists are represented as Vim |List| type. +--- Dictionaries are represented as Vim |Dictionary| type, +--- non-string keys result in error. +--- +--- Note: If you want an array or hash, {expr} must return a +--- reference to it. +--- Example: >vim +--- echo perleval('[1 .. 4]') +--- < [1, 2, 3, 4] +--- +--- @param expr any +--- @return any +function vim.fn.perleval(expr) end + +--- Return the power of {x} to the exponent {y} as a |Float|. +--- {x} and {y} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {x} or {y} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo pow(3, 3) +--- < 27.0 >vim +--- echo pow(2, 16) +--- < 65536.0 >vim +--- echo pow(32, 0.20) +--- < 2.0 +--- +--- @param x any +--- @param y any +--- @return any +function vim.fn.pow(x, y) end + +--- Return the line number of the first line at or above {lnum} +--- that is not blank. Example: >vim +--- let ind = indent(prevnonblank(v:lnum - 1)) +--- <When {lnum} is invalid or there is no non-blank line at or +--- above it, zero is returned. +--- {lnum} is used like with |getline()|. +--- Also see |nextnonblank()|. +--- +--- @param lnum integer +--- @return any +function vim.fn.prevnonblank(lnum) end + +--- Return a String with {fmt}, where "%" items are replaced by +--- the formatted form of their respective arguments. Example: >vim +--- echo printf("%4d: E%d %.30s", lnum, errno, msg) +--- <May result in: +--- " 99: E42 asdfasdfasdfasdfasdfasdfasdfas" ~ +--- +--- When used as a |method| the base is passed as the second +--- argument: >vim +--- Compute()->printf("result: %d") +--- < +--- You can use `call()` to pass the items as a list. +--- +--- Often used items are: +--- %s string +--- %6S string right-aligned in 6 display cells +--- %6s string right-aligned in 6 bytes +--- %.9s string truncated to 9 bytes +--- %c single byte +--- %d decimal number +--- %5d decimal number padded with spaces to 5 characters +--- %b binary number +--- %08b binary number padded with zeros to at least 8 characters +--- %B binary number using upper case letters +--- %x hex number +--- %04x hex number padded with zeros to at least 4 characters +--- %X hex number using upper case letters +--- %o octal number +--- %f floating point number as 12.23, inf, -inf or nan +--- %F floating point number as 12.23, INF, -INF or NAN +--- %e floating point number as 1.23e3, inf, -inf or nan +--- %E floating point number as 1.23E3, INF, -INF or NAN +--- %g floating point number, as %f or %e depending on value +--- %G floating point number, as %F or %E depending on value +--- %% the % character itself +--- %p representation of the pointer to the container +--- +--- Conversion specifications start with '%' and end with the +--- conversion type. All other characters are copied unchanged to +--- the result. +--- +--- The "%" starts a conversion specification. The following +--- arguments appear in sequence: +--- +--- % [pos-argument] [flags] [field-width] [.precision] type +--- +--- pos-argument +--- At most one positional argument specifier. These +--- take the form {n$}, where n is >= 1. +--- +--- flags +--- Zero or more of the following flags: +--- +--- # The value should be converted to an "alternate +--- form". For c, d, and s conversions, this option +--- has no effect. For o conversions, the precision +--- of the number is increased to force the first +--- character of the output string to a zero (except +--- if a zero value is printed with an explicit +--- precision of zero). +--- For x and X conversions, a non-zero result has +--- the string "0x" (or "0X" for X conversions) +--- prepended to it. +--- +--- 0 (zero) Zero padding. For all conversions the converted +--- value is padded on the left with zeros rather +--- than blanks. If a precision is given with a +--- numeric conversion (d, o, x, and X), the 0 flag +--- is ignored. +--- +--- - A negative field width flag; the converted value +--- is to be left adjusted on the field boundary. +--- The converted value is padded on the right with +--- blanks, rather than on the left with blanks or +--- zeros. A - overrides a 0 if both are given. +--- +--- ' ' (space) A blank should be left before a positive +--- number produced by a signed conversion (d). +--- +--- + A sign must always be placed before a number +--- produced by a signed conversion. A + overrides +--- a space if both are used. +--- +--- field-width +--- An optional decimal digit string specifying a minimum +--- field width. If the converted value has fewer bytes +--- than the field width, it will be padded with spaces on +--- the left (or right, if the left-adjustment flag has +--- been given) to fill out the field width. For the S +--- conversion the count is in cells. +--- +--- .precision +--- An optional precision, in the form of a period '.' +--- followed by an optional digit string. If the digit +--- string is omitted, the precision is taken as zero. +--- This gives the minimum number of digits to appear for +--- d, o, x, and X conversions, the maximum number of +--- bytes to be printed from a string for s conversions, +--- or the maximum number of cells to be printed from a +--- string for S conversions. +--- For floating point it is the number of digits after +--- the decimal point. +--- +--- type +--- A character that specifies the type of conversion to +--- be applied, see below. +--- +--- A field width or precision, or both, may be indicated by an +--- asterisk "*" instead of a digit string. In this case, a +--- Number argument supplies the field width or precision. A +--- negative field width is treated as a left adjustment flag +--- followed by a positive field width; a negative precision is +--- treated as though it were missing. Example: >vim +--- echo printf("%d: %.*s", nr, width, line) +--- <This limits the length of the text used from "line" to +--- "width" bytes. +--- +--- If the argument to be formatted is specified using a posional +--- argument specifier, and a '*' is used to indicate that a +--- number argument is to be used to specify the width or +--- precision, the argument(s) to be used must also be specified +--- using a {n$} positional argument specifier. See |printf-$|. +--- +--- The conversion specifiers and their meanings are: +--- +--- *printf-d* *printf-b* *printf-B* *printf-o* *printf-x* *printf-X* +--- dbBoxX The Number argument is converted to signed decimal (d), +--- unsigned binary (b and B), unsigned octal (o), or +--- unsigned hexadecimal (x and X) notation. The letters +--- "abcdef" are used for x conversions; the letters +--- "ABCDEF" are used for X conversions. The precision, if +--- any, gives the minimum number of digits that must +--- appear; if the converted value requires fewer digits, it +--- is padded on the left with zeros. In no case does a +--- non-existent or small field width cause truncation of a +--- numeric field; if the result of a conversion is wider +--- than the field width, the field is expanded to contain +--- the conversion result. +--- The 'h' modifier indicates the argument is 16 bits. +--- The 'l' modifier indicates the argument is a long +--- integer. The size will be 32 bits or 64 bits +--- depending on your platform. +--- The "ll" modifier indicates the argument is 64 bits. +--- The b and B conversion specifiers never take a width +--- modifier and always assume their argument is a 64 bit +--- integer. +--- Generally, these modifiers are not useful. They are +--- ignored when type is known from the argument. +--- +--- i alias for d +--- D alias for ld +--- U alias for lu +--- O alias for lo +--- +--- *printf-c* +--- c The Number argument is converted to a byte, and the +--- resulting character is written. +--- +--- *printf-s* +--- s The text of the String argument is used. If a +--- precision is specified, no more bytes than the number +--- specified are used. +--- If the argument is not a String type, it is +--- automatically converted to text with the same format +--- as ":echo". +--- *printf-S* +--- S The text of the String argument is used. If a +--- precision is specified, no more display cells than the +--- number specified are used. +--- +--- *printf-f* *E807* +--- f F The Float argument is converted into a string of the +--- form 123.456. The precision specifies the number of +--- digits after the decimal point. When the precision is +--- zero the decimal point is omitted. When the precision +--- is not specified 6 is used. A really big number +--- (out of range or dividing by zero) results in "inf" +--- or "-inf" with %f (INF or -INF with %F). +--- "0.0 / 0.0" results in "nan" with %f (NAN with %F). +--- Example: >vim +--- echo printf("%.2f", 12.115) +--- < 12.12 +--- Note that roundoff depends on the system libraries. +--- Use |round()| when in doubt. +--- +--- *printf-e* *printf-E* +--- e E The Float argument is converted into a string of the +--- form 1.234e+03 or 1.234E+03 when using 'E'. The +--- precision specifies the number of digits after the +--- decimal point, like with 'f'. +--- +--- *printf-g* *printf-G* +--- g G The Float argument is converted like with 'f' if the +--- value is between 0.001 (inclusive) and 10000000.0 +--- (exclusive). Otherwise 'e' is used for 'g' and 'E' +--- for 'G'. When no precision is specified superfluous +--- zeroes and '+' signs are removed, except for the zero +--- immediately after the decimal point. Thus 10000000.0 +--- results in 1.0e7. +--- +--- *printf-%* +--- % A '%' is written. No argument is converted. The +--- complete conversion specification is "%%". +--- +--- When a Number argument is expected a String argument is also +--- accepted and automatically converted. +--- When a Float or String argument is expected a Number argument +--- is also accepted and automatically converted. +--- Any other argument type results in an error message. +--- +--- *E766* *E767* +--- The number of {exprN} arguments must exactly match the number +--- of "%" items. If there are not sufficient or too many +--- arguments an error is given. Up to 18 arguments can be used. +--- +--- *printf-$* +--- In certain languages, error and informative messages are +--- more readable when the order of words is different from the +--- corresponding message in English. To accommodate translations +--- having a different word order, positional arguments may be +--- used to indicate this. For instance: >vim +--- +--- #, c-format +--- msgid "%s returning %s" +--- msgstr "waarde %2$s komt terug van %1$s" +--- < +--- In this example, the sentence has its 2 string arguments +--- reversed in the output. >vim +--- +--- echo printf( +--- "In The Netherlands, vim's creator's name is: %1$s %2$s", +--- "Bram", "Moolenaar") +--- < In The Netherlands, vim's creator's name is: Bram Moolenaar >vim +--- +--- echo printf( +--- "In Belgium, vim's creator's name is: %2$s %1$s", +--- "Bram", "Moolenaar") +--- < In Belgium, vim's creator's name is: Moolenaar Bram +--- +--- Width (and precision) can be specified using the '*' specifier. +--- In this case, you must specify the field width position in the +--- argument list. >vim +--- +--- echo printf("%1$*2$.*3$d", 1, 2, 3) +--- < 001 >vim +--- echo printf("%2$*3$.*1$d", 1, 2, 3) +--- < 2 >vim +--- echo printf("%3$*1$.*2$d", 1, 2, 3) +--- < 03 >vim +--- echo printf("%1$*2$.*3$g", 1.4142, 2, 3) +--- < 1.414 +--- +--- You can mix specifying the width and/or precision directly +--- and via positional arguments: >vim +--- +--- echo printf("%1$4.*2$f", 1.4142135, 6) +--- < 1.414214 >vim +--- echo printf("%1$*2$.4f", 1.4142135, 6) +--- < 1.4142 >vim +--- echo printf("%1$*2$.*3$f", 1.4142135, 6, 2) +--- < 1.41 +--- +--- *E1500* +--- You cannot mix positional and non-positional arguments: >vim +--- echo printf("%s%1$s", "One", "Two") +--- < E1500: Cannot mix positional and non-positional arguments: +--- %s%1$s +--- +--- *E1501* +--- You cannot skip a positional argument in a format string: >vim +--- echo printf("%3$s%1$s", "One", "Two", "Three") +--- < E1501: format argument 2 unused in $-style format: +--- %3$s%1$s +--- +--- *E1502* +--- You can re-use a [field-width] (or [precision]) argument: >vim +--- echo printf("%1$d at width %2$d is: %01$*2$d", 1, 2) +--- < 1 at width 2 is: 01 +--- +--- However, you can't use it as a different type: >vim +--- echo printf("%1$d at width %2$ld is: %01$*2$d", 1, 2) +--- < E1502: Positional argument 2 used as field width reused as +--- different type: long int/int +--- +--- *E1503* +--- When a positional argument is used, but not the correct number +--- or arguments is given, an error is raised: >vim +--- echo printf("%1$d at width %2$d is: %01$*2$.*3$d", 1, 2) +--- < E1503: Positional argument 3 out of bounds: %1$d at width +--- %2$d is: %01$*2$.*3$d +--- +--- Only the first error is reported: >vim +--- echo printf("%01$*2$.*3$d %4$d", 1, 2) +--- < E1503: Positional argument 3 out of bounds: %01$*2$.*3$d +--- %4$d +--- +--- *E1504* +--- A positional argument can be used more than once: >vim +--- echo printf("%1$s %2$s %1$s", "One", "Two") +--- < One Two One +--- +--- However, you can't use a different type the second time: >vim +--- echo printf("%1$s %2$s %1$d", "One", "Two") +--- < E1504: Positional argument 1 type used inconsistently: +--- int/string +--- +--- *E1505* +--- Various other errors that lead to a format string being +--- wrongly formatted lead to: >vim +--- echo printf("%1$d at width %2$d is: %01$*2$.3$d", 1, 2) +--- < E1505: Invalid format specifier: %1$d at width %2$d is: +--- %01$*2$.3$d +--- +--- *E1507* +--- This internal error indicates that the logic to parse a +--- positional format argument ran into a problem that couldn't be +--- otherwise reported. Please file a bug against Vim if you run +--- into this, copying the exact format string and parameters that +--- were used. +--- +--- @param fmt any +--- @param expr1? any +--- @return any +function vim.fn.printf(fmt, expr1) end + +--- Returns the effective prompt text for buffer {buf}. {buf} can +--- be a buffer name or number. See |prompt-buffer|. +--- +--- If the buffer doesn't exist or isn't a prompt buffer, an empty +--- string is returned. +--- +--- @param buf any +--- @return any +function vim.fn.prompt_getprompt(buf) end + +--- Set prompt callback for buffer {buf} to {expr}. When {expr} +--- is an empty string the callback is removed. This has only +--- effect if {buf} has 'buftype' set to "prompt". +--- +--- The callback is invoked when pressing Enter. The current +--- buffer will always be the prompt buffer. A new line for a +--- prompt is added before invoking the callback, thus the prompt +--- for which the callback was invoked will be in the last but one +--- line. +--- If the callback wants to add text to the buffer, it must +--- insert it above the last line, since that is where the current +--- prompt is. This can also be done asynchronously. +--- The callback is invoked with one argument, which is the text +--- that was entered at the prompt. This can be an empty string +--- if the user only typed Enter. +--- Example: >vim +--- func s:TextEntered(text) +--- if a:text == 'exit' || a:text == 'quit' +--- stopinsert +--- " Reset 'modified' to allow the buffer to be closed. +--- " We assume there is nothing useful to be saved. +--- set nomodified +--- close +--- else +--- " Do something useful with "a:text". In this example +--- " we just repeat it. +--- call append(line('$') - 1, 'Entered: "' .. a:text .. '"') +--- endif +--- endfunc +--- call prompt_setcallback(bufnr(), function('s:TextEntered')) +--- +--- @param buf any +--- @param expr any +--- @return any +function vim.fn.prompt_setcallback(buf, expr) end + +--- Set a callback for buffer {buf} to {expr}. When {expr} is an +--- empty string the callback is removed. This has only effect if +--- {buf} has 'buftype' set to "prompt". +--- +--- This callback will be invoked when pressing CTRL-C in Insert +--- mode. Without setting a callback Vim will exit Insert mode, +--- as in any buffer. +--- +--- @param buf any +--- @param expr any +--- @return any +function vim.fn.prompt_setinterrupt(buf, expr) end + +--- Set prompt for buffer {buf} to {text}. You most likely want +--- {text} to end in a space. +--- The result is only visible if {buf} has 'buftype' set to +--- "prompt". Example: >vim +--- call prompt_setprompt(bufnr(''), 'command: ') +--- < +--- +--- @param buf any +--- @param text any +--- @return any +function vim.fn.prompt_setprompt(buf, text) end + +--- If the popup menu (see |ins-completion-menu|) is not visible, +--- returns an empty |Dictionary|, otherwise, returns a +--- |Dictionary| with the following keys: +--- height nr of items visible +--- width screen cells +--- row top screen row (0 first row) +--- col leftmost screen column (0 first col) +--- size total nr of items +--- scrollbar |TRUE| if scrollbar is visible +--- +--- The values are the same as in |v:event| during |CompleteChanged|. +--- +--- @return any +function vim.fn.pum_getpos() end + +--- Returns non-zero when the popup menu is visible, zero +--- otherwise. See |ins-completion-menu|. +--- This can be used to avoid some things that would remove the +--- popup menu. +--- +--- @return any +function vim.fn.pumvisible() end + +--- Evaluate Python expression {expr} and return its result +--- converted to Vim data structures. +--- Numbers and strings are returned as they are (strings are +--- copied though, Unicode strings are additionally converted to +--- UTF-8). +--- Lists are represented as Vim |List| type. +--- Dictionaries are represented as Vim |Dictionary| type with +--- keys converted to strings. +--- +--- @param expr any +--- @return any +function vim.fn.py3eval(expr) end + +--- Evaluate Python expression {expr} and return its result +--- converted to Vim data structures. +--- Numbers and strings are returned as they are (strings are +--- copied though). +--- Lists are represented as Vim |List| type. +--- Dictionaries are represented as Vim |Dictionary| type, +--- non-string keys result in error. +--- +--- @param expr any +--- @return any +function vim.fn.pyeval(expr) end + +--- Evaluate Python expression {expr} and return its result +--- converted to Vim data structures. +--- Uses Python 2 or 3, see |python_x| and 'pyxversion'. +--- See also: |pyeval()|, |py3eval()| +--- +--- @param expr any +--- @return any +function vim.fn.pyxeval(expr) end + +--- Return a pseudo-random Number generated with an xoshiro128** +--- algorithm using seed {expr}. The returned number is 32 bits, +--- also on 64 bits systems, for consistency. +--- {expr} can be initialized by |srand()| and will be updated by +--- rand(). If {expr} is omitted, an internal seed value is used +--- and updated. +--- Returns -1 if {expr} is invalid. +--- +--- Examples: >vim +--- echo rand() +--- let seed = srand() +--- echo rand(seed) +--- echo rand(seed) % 16 " random number 0 - 15 +--- < +--- +--- @param expr? any +--- @return any +function vim.fn.rand(expr) end + +--- Returns a |List| with Numbers: +--- - If only {expr} is specified: [0, 1, ..., {expr} - 1] +--- - If {max} is specified: [{expr}, {expr} + 1, ..., {max}] +--- - If {stride} is specified: [{expr}, {expr} + {stride}, ..., +--- {max}] (increasing {expr} with {stride} each time, not +--- producing a value past {max}). +--- When the maximum is one before the start the result is an +--- empty list. When the maximum is more than one before the +--- start this is an error. +--- Examples: >vim +--- echo range(4) " [0, 1, 2, 3] +--- echo range(2, 4) " [2, 3, 4] +--- echo range(2, 9, 3) " [2, 5, 8] +--- echo range(2, -2, -1) " [2, 1, 0, -1, -2] +--- echo range(0) " [] +--- echo range(2, 0) " error! +--- < +--- +--- @param expr any +--- @param max? any +--- @param stride? any +--- @return any +function vim.fn.range(expr, max, stride) end + +--- Read file {fname} in binary mode and return a |Blob|. +--- If {offset} is specified, read the file from the specified +--- offset. If it is a negative value, it is used as an offset +--- from the end of the file. E.g., to read the last 12 bytes: >vim +--- echo readblob('file.bin', -12) +--- <If {size} is specified, only the specified size will be read. +--- E.g. to read the first 100 bytes of a file: >vim +--- echo readblob('file.bin', 0, 100) +--- <If {size} is -1 or omitted, the whole data starting from +--- {offset} will be read. +--- This can be also used to read the data from a character device +--- on Unix when {size} is explicitly set. Only if the device +--- supports seeking {offset} can be used. Otherwise it should be +--- zero. E.g. to read 10 bytes from a serial console: >vim +--- echo readblob('/dev/ttyS0', 0, 10) +--- <When the file can't be opened an error message is given and +--- the result is an empty |Blob|. +--- When the offset is beyond the end of the file the result is an +--- empty blob. +--- When trying to read more bytes than are available the result +--- is truncated. +--- Also see |readfile()| and |writefile()|. +--- +--- @param fname string +--- @param offset? any +--- @param size? any +--- @return any +function vim.fn.readblob(fname, offset, size) end + +--- Return a list with file and directory names in {directory}. +--- You can also use |glob()| if you don't need to do complicated +--- things, such as limiting the number of matches. +--- +--- When {expr} is omitted all entries are included. +--- When {expr} is given, it is evaluated to check what to do: +--- If {expr} results in -1 then no further entries will +--- be handled. +--- If {expr} results in 0 then this entry will not be +--- added to the list. +--- If {expr} results in 1 then this entry will be added +--- to the list. +--- Each time {expr} is evaluated |v:val| is set to the entry name. +--- When {expr} is a function the name is passed as the argument. +--- For example, to get a list of files ending in ".txt": >vim +--- echo readdir(dirname, {n -> n =~ '.txt$'}) +--- <To skip hidden and backup files: >vim +--- echo readdir(dirname, {n -> n !~ '^\.\|\~$'}) +--- +--- <If you want to get a directory tree: >vim +--- function! s:tree(dir) +--- return {a:dir : map(readdir(a:dir), +--- \ {_, x -> isdirectory(x) ? +--- \ {x : s:tree(a:dir .. '/' .. x)} : x})} +--- endfunction +--- echo s:tree(".") +--- < +--- Returns an empty List on error. +--- +--- @param directory any +--- @param expr? any +--- @return any +function vim.fn.readdir(directory, expr) end + +--- Read file {fname} and return a |List|, each line of the file +--- as an item. Lines are broken at NL characters. Macintosh +--- files separated with CR will result in a single long line +--- (unless a NL appears somewhere). +--- All NUL characters are replaced with a NL character. +--- When {type} contains "b" binary mode is used: +--- - When the last line ends in a NL an extra empty list item is +--- added. +--- - No CR characters are removed. +--- Otherwise: +--- - CR characters that appear before a NL are removed. +--- - Whether the last line ends in a NL or not does not matter. +--- - Any UTF-8 byte order mark is removed from the text. +--- When {max} is given this specifies the maximum number of lines +--- to be read. Useful if you only want to check the first ten +--- lines of a file: >vim +--- for line in readfile(fname, '', 10) +--- if line =~ 'Date' | echo line | endif +--- endfor +--- <When {max} is negative -{max} lines from the end of the file +--- are returned, or as many as there are. +--- When {max} is zero the result is an empty list. +--- Note that without {max} the whole file is read into memory. +--- Also note that there is no recognition of encoding. Read a +--- file into a buffer if you need to. +--- Deprecated (use |readblob()| instead): When {type} contains +--- "B" a |Blob| is returned with the binary data of the file +--- unmodified. +--- When the file can't be opened an error message is given and +--- the result is an empty list. +--- Also see |writefile()|. +--- +--- @param fname string +--- @param type? any +--- @param max? any +--- @return any +function vim.fn.readfile(fname, type, max) end + +--- {func} is called for every item in {object}, which can be a +--- |String|, |List| or a |Blob|. {func} is called with two +--- arguments: the result so far and current item. After +--- processing all items the result is returned. +--- +--- {initial} is the initial result. When omitted, the first item +--- in {object} is used and {func} is first called for the second +--- item. If {initial} is not given and {object} is empty no +--- result can be computed, an E998 error is given. +--- +--- Examples: >vim +--- echo reduce([1, 3, 5], { acc, val -> acc + val }) +--- echo reduce(['x', 'y'], { acc, val -> acc .. val }, 'a') +--- echo reduce(0z1122, { acc, val -> 2 * acc + val }) +--- echo reduce('xyz', { acc, val -> acc .. ',' .. val }) +--- < +--- +--- @param object any +--- @param func any +--- @param initial? any +--- @return any +function vim.fn.reduce(object, func, initial) end + +--- Returns the single letter name of the register being executed. +--- Returns an empty string when no register is being executed. +--- See |\@|. +--- +--- @return any +function vim.fn.reg_executing() end + +--- Returns the single letter name of the last recorded register. +--- Returns an empty string when nothing was recorded yet. +--- See |q| and |Q|. +--- +--- @return any +function vim.fn.reg_recorded() end + +--- Returns the single letter name of the register being recorded. +--- Returns an empty string when not recording. See |q|. +--- +--- @return any +function vim.fn.reg_recording() end + +--- @return any +function vim.fn.reltime() end + +--- @param start? any +--- @return any +function vim.fn.reltime(start) end + +--- Return an item that represents a time value. The item is a +--- list with items that depend on the system. +--- The item can be passed to |reltimestr()| to convert it to a +--- string or |reltimefloat()| to convert to a Float. +--- +--- Without an argument it returns the current "relative time", an +--- implementation-defined value meaningful only when used as an +--- argument to |reltime()|, |reltimestr()| and |reltimefloat()|. +--- +--- With one argument it returns the time passed since the time +--- specified in the argument. +--- With two arguments it returns the time passed between {start} +--- and {end}. +--- +--- The {start} and {end} arguments must be values returned by +--- reltime(). Returns zero on error. +--- +--- Note: |localtime()| returns the current (non-relative) time. +--- +--- @param start? any +--- @param end_? any +--- @return any +function vim.fn.reltime(start, end_) end + +--- Return a Float that represents the time value of {time}. +--- Unit of time is seconds. +--- Example: +--- let start = reltime() +--- call MyFunction() +--- let seconds = reltimefloat(reltime(start)) +--- See the note of reltimestr() about overhead. +--- Also see |profiling|. +--- If there is an error an empty string is returned +--- +--- @param time any +--- @return any +function vim.fn.reltimefloat(time) end + +--- Return a String that represents the time value of {time}. +--- This is the number of seconds, a dot and the number of +--- microseconds. Example: >vim +--- let start = reltime() +--- call MyFunction() +--- echo reltimestr(reltime(start)) +--- <Note that overhead for the commands will be added to the time. +--- Leading spaces are used to make the string align nicely. You +--- can use split() to remove it. >vim +--- echo split(reltimestr(reltime(start)))[0] +--- <Also see |profiling|. +--- If there is an error an empty string is returned +--- +--- @param time any +--- @return any +function vim.fn.reltimestr(time) end + +--- @param list any +--- @param idx integer +--- @return any +function vim.fn.remove(list, idx) end + +--- Without {end}: Remove the item at {idx} from |List| {list} and +--- return the item. +--- With {end}: Remove items from {idx} to {end} (inclusive) and +--- return a |List| with these items. When {idx} points to the same +--- item as {end} a list with one item is returned. When {end} +--- points to an item before {idx} this is an error. +--- See |list-index| for possible values of {idx} and {end}. +--- Returns zero on error. +--- Example: >vim +--- echo "last item: " .. remove(mylist, -1) +--- call remove(mylist, 0, 9) +--- < +--- Use |delete()| to remove a file. +--- +--- @param list any +--- @param idx integer +--- @param end_? any +--- @return any +function vim.fn.remove(list, idx, end_) end + +--- @param blob any +--- @param idx integer +--- @return any +function vim.fn.remove(blob, idx) end + +--- Without {end}: Remove the byte at {idx} from |Blob| {blob} and +--- return the byte. +--- With {end}: Remove bytes from {idx} to {end} (inclusive) and +--- return a |Blob| with these bytes. When {idx} points to the same +--- byte as {end} a |Blob| with one byte is returned. When {end} +--- points to a byte before {idx} this is an error. +--- Returns zero on error. +--- Example: >vim +--- echo "last byte: " .. remove(myblob, -1) +--- call remove(mylist, 0, 9) +--- < +--- +--- @param blob any +--- @param idx integer +--- @param end_? any +--- @return any +function vim.fn.remove(blob, idx, end_) end + +--- Remove the entry from {dict} with key {key} and return it. +--- Example: >vim +--- echo "removed " .. remove(dict, "one") +--- <If there is no {key} in {dict} this is an error. +--- Returns zero on error. +--- +--- @param dict any +--- @param key any +--- @return any +function vim.fn.remove(dict, key) end + +--- Rename the file by the name {from} to the name {to}. This +--- should also work to move files across file systems. The +--- result is a Number, which is 0 if the file was renamed +--- successfully, and non-zero when the renaming failed. +--- NOTE: If {to} exists it is overwritten without warning. +--- This function is not available in the |sandbox|. +--- +--- @param from any +--- @param to any +--- @return any +function vim.fn.rename(from, to) end + +--- Repeat {expr} {count} times and return the concatenated +--- result. Example: >vim +--- let separator = repeat('-', 80) +--- <When {count} is zero or negative the result is empty. +--- When {expr} is a |List| or a |Blob| the result is {expr} +--- concatenated {count} times. Example: >vim +--- let longlist = repeat(['a', 'b'], 3) +--- <Results in ['a', 'b', 'a', 'b', 'a', 'b']. +--- +--- @param expr any +--- @param count any +--- @return any +vim.fn['repeat'] = function(expr, count) end + +--- On MS-Windows, when {filename} is a shortcut (a .lnk file), +--- returns the path the shortcut points to in a simplified form. +--- On Unix, repeat resolving symbolic links in all path +--- components of {filename} and return the simplified result. +--- To cope with link cycles, resolving of symbolic links is +--- stopped after 100 iterations. +--- On other systems, return the simplified {filename}. +--- The simplification step is done as by |simplify()|. +--- resolve() keeps a leading path component specifying the +--- current directory (provided the result is still a relative +--- path name) and also keeps a trailing path separator. +--- +--- @param filename any +--- @return any +function vim.fn.resolve(filename) end + +--- Reverse the order of items in {object}. {object} can be a +--- |List|, a |Blob| or a |String|. For a List and a Blob the +--- items are reversed in-place and {object} is returned. +--- For a String a new String is returned. +--- Returns zero if {object} is not a List, Blob or a String. +--- If you want a List or Blob to remain unmodified make a copy +--- first: >vim +--- let revlist = reverse(copy(mylist)) +--- < +--- +--- @param object any +--- @return any +function vim.fn.reverse(object) end + +--- Round off {expr} to the nearest integral value and return it +--- as a |Float|. If {expr} lies halfway between two integral +--- values, then use the larger one (away from zero). +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo round(0.456) +--- < 0.0 >vim +--- echo round(4.5) +--- < 5.0 >vim +--- echo round(-4.5) +--- < -5.0 +--- +--- @param expr any +--- @return any +function vim.fn.round(expr) end + +--- Sends {event} to {channel} via |RPC| and returns immediately. +--- If {channel} is 0, the event is broadcast to all channels. +--- Example: >vim +--- au VimLeave call rpcnotify(0, "leaving") +--- < +--- +--- @param channel any +--- @param event any +--- @param args? any +--- @return any +function vim.fn.rpcnotify(channel, event, args) end + +--- Sends a request to {channel} to invoke {method} via +--- |RPC| and blocks until a response is received. +--- Example: >vim +--- let result = rpcrequest(rpc_chan, "func", 1, 2, 3) +--- < +--- +--- @param channel any +--- @param method any +--- @param args? any +--- @return any +function vim.fn.rpcrequest(channel, method, args) end + +--- Deprecated. Replace >vim +--- let id = rpcstart('prog', ['arg1', 'arg2']) +--- <with >vim +--- let id = jobstart(['prog', 'arg1', 'arg2'], {'rpc': v:true}) +--- < +--- +--- @param prog any +--- @param argv? any +--- @return any +function vim.fn.rpcstart(prog, argv) end + +--- @deprecated +--- Use |jobstop()| instead to stop any job, or +--- `chanclose(id, "rpc")` to close RPC communication +--- without stopping the job. Use chanclose(id) to close +--- any socket. +--- +--- @param ... any +--- @return any +function vim.fn.rpcstop(...) end + +--- Evaluate Ruby expression {expr} and return its result +--- converted to Vim data structures. +--- Numbers, floats and strings are returned as they are (strings +--- are copied though). +--- Arrays are represented as Vim |List| type. +--- Hashes are represented as Vim |Dictionary| type. +--- Other objects are represented as strings resulted from their +--- "Object#to_s" method. +--- +--- @param expr any +--- @return any +function vim.fn.rubyeval(expr) end + +--- Like |screenchar()|, but return the attribute. This is a rather +--- arbitrary number that can only be used to compare to the +--- attribute at other positions. +--- Returns -1 when row or col is out of range. +--- +--- @param row any +--- @param col integer +--- @return any +function vim.fn.screenattr(row, col) end + +--- The result is a Number, which is the character at position +--- [row, col] on the screen. This works for every possible +--- screen position, also status lines, window separators and the +--- command line. The top left position is row one, column one +--- The character excludes composing characters. For double-byte +--- encodings it may only be the first byte. +--- This is mainly to be used for testing. +--- Returns -1 when row or col is out of range. +--- +--- @param row any +--- @param col integer +--- @return any +function vim.fn.screenchar(row, col) end + +--- The result is a |List| of Numbers. The first number is the same +--- as what |screenchar()| returns. Further numbers are +--- composing characters on top of the base character. +--- This is mainly to be used for testing. +--- Returns an empty List when row or col is out of range. +--- +--- @param row any +--- @param col integer +--- @return any +function vim.fn.screenchars(row, col) end + +--- The result is a Number, which is the current screen column of +--- the cursor. The leftmost column has number 1. +--- This function is mainly used for testing. +--- +--- Note: Always returns the current screen column, thus if used +--- in a command (e.g. ":echo screencol()") it will return the +--- column inside the command line, which is 1 when the command is +--- executed. To get the cursor position in the file use one of +--- the following mappings: >vim +--- nnoremap <expr> GG ":echom " .. screencol() .. "\n" +--- nnoremap <silent> GG :echom screencol()<CR> +--- noremap GG <Cmd>echom screencol()<Cr> +--- < +--- +--- @return any +function vim.fn.screencol() end + +--- The result is a Dict with the screen position of the text +--- character in window {winid} at buffer line {lnum} and column +--- {col}. {col} is a one-based byte index. +--- The Dict has these members: +--- row screen row +--- col first screen column +--- endcol last screen column +--- curscol cursor screen column +--- If the specified position is not visible, all values are zero. +--- The "endcol" value differs from "col" when the character +--- occupies more than one screen cell. E.g. for a Tab "col" can +--- be 1 and "endcol" can be 8. +--- The "curscol" value is where the cursor would be placed. For +--- a Tab it would be the same as "endcol", while for a double +--- width character it would be the same as "col". +--- The |conceal| feature is ignored here, the column numbers are +--- as if 'conceallevel' is zero. You can set the cursor to the +--- right position and use |screencol()| to get the value with +--- |conceal| taken into account. +--- If the position is in a closed fold the screen position of the +--- first character is returned, {col} is not used. +--- Returns an empty Dict if {winid} is invalid. +--- +--- @param winid integer +--- @param lnum integer +--- @param col integer +--- @return any +function vim.fn.screenpos(winid, lnum, col) end + +--- The result is a Number, which is the current screen row of the +--- cursor. The top line has number one. +--- This function is mainly used for testing. +--- Alternatively you can use |winline()|. +--- +--- Note: Same restrictions as with |screencol()|. +--- +--- @return any +function vim.fn.screenrow() end + +--- The result is a String that contains the base character and +--- any composing characters at position [row, col] on the screen. +--- This is like |screenchars()| but returning a String with the +--- characters. +--- This is mainly to be used for testing. +--- Returns an empty String when row or col is out of range. +--- +--- @param row any +--- @param col integer +--- @return any +function vim.fn.screenstring(row, col) end + +--- Search for regexp pattern {pattern}. The search starts at the +--- cursor position (you can use |cursor()| to set it). +--- +--- When a match has been found its line number is returned. +--- If there is no match a 0 is returned and the cursor doesn't +--- move. No error message is given. +--- +--- {flags} is a String, which can contain these character flags: +--- 'b' search Backward instead of forward +--- 'c' accept a match at the Cursor position +--- 'e' move to the End of the match +--- 'n' do Not move the cursor +--- 'p' return number of matching sub-Pattern (see below) +--- 's' Set the ' mark at the previous location of the cursor +--- 'w' Wrap around the end of the file +--- 'W' don't Wrap around the end of the file +--- 'z' start searching at the cursor column instead of Zero +--- If neither 'w' or 'W' is given, the 'wrapscan' option applies. +--- +--- If the 's' flag is supplied, the ' mark is set, only if the +--- cursor is moved. The 's' flag cannot be combined with the 'n' +--- flag. +--- +--- 'ignorecase', 'smartcase' and 'magic' are used. +--- +--- When the 'z' flag is not given, forward searching always +--- starts in column zero and then matches before the cursor are +--- skipped. When the 'c' flag is present in 'cpo' the next +--- search starts after the match. Without the 'c' flag the next +--- search starts one column after the start of the match. This +--- matters for overlapping matches. See |cpo-c|. You can also +--- insert "\ze" to change where the match ends, see |/\ze|. +--- +--- When searching backwards and the 'z' flag is given then the +--- search starts in column zero, thus no match in the current +--- line will be found (unless wrapping around the end of the +--- file). +--- +--- When the {stopline} argument is given then the search stops +--- after searching this line. This is useful to restrict the +--- search to a range of lines. Examples: >vim +--- let match = search('(', 'b', line("w0")) +--- let end = search('END', '', line("w$")) +--- <When {stopline} is used and it is not zero this also implies +--- that the search does not wrap around the end of the file. +--- A zero value is equal to not giving the argument. +--- +--- When the {timeout} argument is given the search stops when +--- more than this many milliseconds have passed. Thus when +--- {timeout} is 500 the search stops after half a second. +--- The value must not be negative. A zero value is like not +--- giving the argument. +--- +--- If the {skip} expression is given it is evaluated with the +--- cursor positioned on the start of a match. If it evaluates to +--- non-zero this match is skipped. This can be used, for +--- example, to skip a match in a comment or a string. +--- {skip} can be a string, which is evaluated as an expression, a +--- function reference or a lambda. +--- When {skip} is omitted or empty, every match is accepted. +--- When evaluating {skip} causes an error the search is aborted +--- and -1 returned. +--- *search()-sub-match* +--- With the 'p' flag the returned value is one more than the +--- first sub-match in \(\). One if none of them matched but the +--- whole pattern did match. +--- To get the column number too use |searchpos()|. +--- +--- The cursor will be positioned at the match, unless the 'n' +--- flag is used. +--- +--- Example (goes over all files in the argument list): >vim +--- let n = 1 +--- while n <= argc() " loop over all files in arglist +--- exe "argument " .. n +--- " start at the last char in the file and wrap for the +--- " first search to find match at start of file +--- normal G$ +--- let flags = "w" +--- while search("foo", flags) > 0 +--- s/foo/bar/g +--- let flags = "W" +--- endwhile +--- update " write the file if modified +--- let n = n + 1 +--- endwhile +--- < +--- Example for using some flags: >vim +--- echo search('\<if\|\(else\)\|\(endif\)', 'ncpe') +--- <This will search for the keywords "if", "else", and "endif" +--- under or after the cursor. Because of the 'p' flag, it +--- returns 1, 2, or 3 depending on which keyword is found, or 0 +--- if the search fails. With the cursor on the first word of the +--- line: +--- if (foo == 0) | let foo = foo + 1 | endif ~ +--- the function returns 1. Without the 'c' flag, the function +--- finds the "endif" and returns 3. The same thing happens +--- without the 'e' flag if the cursor is on the "f" of "if". +--- The 'n' flag tells the function not to move the cursor. +--- +--- @param pattern any +--- @param flags? string +--- @param stopline? any +--- @param timeout? integer +--- @param skip? any +--- @return any +function vim.fn.search(pattern, flags, stopline, timeout, skip) end + +--- Get or update the last search count, like what is displayed +--- without the "S" flag in 'shortmess'. This works even if +--- 'shortmess' does contain the "S" flag. +--- +--- This returns a |Dictionary|. The dictionary is empty if the +--- previous pattern was not set and "pattern" was not specified. +--- +--- key type meaning ~ +--- current |Number| current position of match; +--- 0 if the cursor position is +--- before the first match +--- exact_match |Boolean| 1 if "current" is matched on +--- "pos", otherwise 0 +--- total |Number| total count of matches found +--- incomplete |Number| 0: search was fully completed +--- 1: recomputing was timed out +--- 2: max count exceeded +--- +--- For {options} see further down. +--- +--- To get the last search count when |n| or |N| was pressed, call +--- this function with `recompute: 0` . This sometimes returns +--- wrong information because |n| and |N|'s maximum count is 99. +--- If it exceeded 99 the result must be max count + 1 (100). If +--- you want to get correct information, specify `recompute: 1`: >vim +--- +--- " result == maxcount + 1 (100) when many matches +--- let result = searchcount(#{recompute: 0}) +--- +--- " Below returns correct result (recompute defaults +--- " to 1) +--- let result = searchcount() +--- < +--- The function is useful to add the count to 'statusline': >vim +--- function! LastSearchCount() abort +--- let result = searchcount(#{recompute: 0}) +--- if empty(result) +--- return '' +--- endif +--- if result.incomplete ==# 1 " timed out +--- return printf(' /%s [?/??]', \@/) +--- elseif result.incomplete ==# 2 " max count exceeded +--- if result.total > result.maxcount && +--- \ result.current > result.maxcount +--- return printf(' /%s [>%d/>%d]', \@/, +--- \ result.current, result.total) +--- elseif result.total > result.maxcount +--- return printf(' /%s [%d/>%d]', \@/, +--- \ result.current, result.total) +--- endif +--- endif +--- return printf(' /%s [%d/%d]', \@/, +--- \ result.current, result.total) +--- endfunction +--- let &statusline ..= '%{LastSearchCount()}' +--- +--- " Or if you want to show the count only when +--- " 'hlsearch' was on +--- " let &statusline ..= +--- " \ '%{v:hlsearch ? LastSearchCount() : ""}' +--- < +--- You can also update the search count, which can be useful in a +--- |CursorMoved| or |CursorMovedI| autocommand: >vim +--- +--- autocmd CursorMoved,CursorMovedI * +--- \ let s:searchcount_timer = timer_start( +--- \ 200, function('s:update_searchcount')) +--- function! s:update_searchcount(timer) abort +--- if a:timer ==# s:searchcount_timer +--- call searchcount(#{ +--- \ recompute: 1, maxcount: 0, timeout: 100}) +--- redrawstatus +--- endif +--- endfunction +--- < +--- This can also be used to count matched texts with specified +--- pattern in the current buffer using "pattern": >vim +--- +--- " Count '\<foo\>' in this buffer +--- " (Note that it also updates search count) +--- let result = searchcount(#{pattern: '\<foo\>'}) +--- +--- " To restore old search count by old pattern, +--- " search again +--- call searchcount() +--- < +--- {options} must be a |Dictionary|. It can contain: +--- key type meaning ~ +--- recompute |Boolean| if |TRUE|, recompute the count +--- like |n| or |N| was executed. +--- otherwise returns the last +--- computed result (when |n| or +--- |N| was used when "S" is not +--- in 'shortmess', or this +--- function was called). +--- (default: |TRUE|) +--- pattern |String| recompute if this was given +--- and different with |\@/|. +--- this works as same as the +--- below command is executed +--- before calling this function >vim +--- let \@/ = pattern +--- < (default: |\@/|) +--- timeout |Number| 0 or negative number is no +--- timeout. timeout milliseconds +--- for recomputing the result +--- (default: 0) +--- maxcount |Number| 0 or negative number is no +--- limit. max count of matched +--- text while recomputing the +--- result. if search exceeded +--- total count, "total" value +--- becomes `maxcount + 1` +--- (default: 0) +--- pos |List| `[lnum, col, off]` value +--- when recomputing the result. +--- this changes "current" result +--- value. see |cursor()|, |getpos()| +--- (default: cursor's position) +--- +--- @param options? table +--- @return any +function vim.fn.searchcount(options) end + +--- Search for the declaration of {name}. +--- +--- With a non-zero {global} argument it works like |gD|, find +--- first match in the file. Otherwise it works like |gd|, find +--- first match in the function. +--- +--- With a non-zero {thisblock} argument matches in a {} block +--- that ends before the cursor position are ignored. Avoids +--- finding variable declarations only valid in another scope. +--- +--- Moves the cursor to the found match. +--- Returns zero for success, non-zero for failure. +--- Example: >vim +--- if searchdecl('myvar') == 0 +--- echo getline('.') +--- endif +--- < +--- +--- @param name string +--- @param global? any +--- @param thisblock? any +--- @return any +function vim.fn.searchdecl(name, global, thisblock) end + +--- Search for the match of a nested start-end pair. This can be +--- used to find the "endif" that matches an "if", while other +--- if/endif pairs in between are ignored. +--- The search starts at the cursor. The default is to search +--- forward, include 'b' in {flags} to search backward. +--- If a match is found, the cursor is positioned at it and the +--- line number is returned. If no match is found 0 or -1 is +--- returned and the cursor doesn't move. No error message is +--- given. +--- +--- {start}, {middle} and {end} are patterns, see |pattern|. They +--- must not contain \( \) pairs. Use of \%( \) is allowed. When +--- {middle} is not empty, it is found when searching from either +--- direction, but only when not in a nested start-end pair. A +--- typical use is: >vim +--- echo searchpair('\<if\>', '\<else\>', '\<endif\>') +--- <By leaving {middle} empty the "else" is skipped. +--- +--- {flags} 'b', 'c', 'n', 's', 'w' and 'W' are used like with +--- |search()|. Additionally: +--- 'r' Repeat until no more matches found; will find the +--- outer pair. Implies the 'W' flag. +--- 'm' Return number of matches instead of line number with +--- the match; will be > 1 when 'r' is used. +--- Note: it's nearly always a good idea to use the 'W' flag, to +--- avoid wrapping around the end of the file. +--- +--- When a match for {start}, {middle} or {end} is found, the +--- {skip} expression is evaluated with the cursor positioned on +--- the start of the match. It should return non-zero if this +--- match is to be skipped. E.g., because it is inside a comment +--- or a string. +--- When {skip} is omitted or empty, every match is accepted. +--- When evaluating {skip} causes an error the search is aborted +--- and -1 returned. +--- {skip} can be a string, a lambda, a funcref or a partial. +--- Anything else makes the function fail. +--- +--- For {stopline} and {timeout} see |search()|. +--- +--- The value of 'ignorecase' is used. 'magic' is ignored, the +--- patterns are used like it's on. +--- +--- The search starts exactly at the cursor. A match with +--- {start}, {middle} or {end} at the next character, in the +--- direction of searching, is the first one found. Example: >vim +--- if 1 +--- if 2 +--- endif 2 +--- endif 1 +--- <When starting at the "if 2", with the cursor on the "i", and +--- searching forwards, the "endif 2" is found. When starting on +--- the character just before the "if 2", the "endif 1" will be +--- found. That's because the "if 2" will be found first, and +--- then this is considered to be a nested if/endif from "if 2" to +--- "endif 2". +--- When searching backwards and {end} is more than one character, +--- it may be useful to put "\zs" at the end of the pattern, so +--- that when the cursor is inside a match with the end it finds +--- the matching start. +--- +--- Example, to find the "endif" command in a Vim script: >vim +--- +--- echo searchpair('\<if\>', '\<el\%[seif]\>', '\<en\%[dif]\>', 'W', +--- \ 'getline(".") =~ "^\\s*\""') +--- +--- <The cursor must be at or after the "if" for which a match is +--- to be found. Note that single-quote strings are used to avoid +--- having to double the backslashes. The skip expression only +--- catches comments at the start of a line, not after a command. +--- Also, a word "en" or "if" halfway through a line is considered +--- a match. +--- Another example, to search for the matching "{" of a "}": >vim +--- +--- echo searchpair('{', '', '}', 'bW') +--- +--- <This works when the cursor is at or before the "}" for which a +--- match is to be found. To reject matches that syntax +--- highlighting recognized as strings: >vim +--- +--- echo searchpair('{', '', '}', 'bW', +--- \ 'synIDattr(synID(line("."), col("."), 0), "name") =~? "string"') +--- < +--- +--- @return any +function vim.fn.searchpair() end + +--- Same as |searchpair()|, but returns a |List| with the line and +--- column position of the match. The first element of the |List| +--- is the line number and the second element is the byte index of +--- the column position of the match. If no match is found, +--- returns [0, 0]. >vim +--- +--- let [lnum,col] = searchpairpos('{', '', '}', 'n') +--- < +--- See |match-parens| for a bigger and more useful example. +--- +--- @return any +function vim.fn.searchpairpos() end + +--- Same as |search()|, but returns a |List| with the line and +--- column position of the match. The first element of the |List| +--- is the line number and the second element is the byte index of +--- the column position of the match. If no match is found, +--- returns [0, 0]. +--- Example: >vim +--- let [lnum, col] = searchpos('mypattern', 'n') +--- +--- <When the 'p' flag is given then there is an extra item with +--- the sub-pattern match number |search()-sub-match|. Example: >vim +--- let [lnum, col, submatch] = searchpos('\(\l\)\|\(\u\)', 'np') +--- <In this example "submatch" is 2 when a lowercase letter is +--- found |/\l|, 3 when an uppercase letter is found |/\u|. +--- +--- @param pattern any +--- @param flags? string +--- @param stopline? any +--- @param timeout? integer +--- @param skip? any +--- @return any +function vim.fn.searchpos(pattern, flags, stopline, timeout, skip) end + +--- Returns a list of server addresses, or empty if all servers +--- were stopped. |serverstart()| |serverstop()| +--- Example: >vim +--- echo serverlist() +--- < +--- +--- @return any +function vim.fn.serverlist() end + +--- Opens a socket or named pipe at {address} and listens for +--- |RPC| messages. Clients can send |API| commands to the +--- returned address to control Nvim. +--- +--- Returns the address string (which may differ from the +--- {address} argument, see below). +--- +--- - If {address} has a colon (":") it is a TCP/IPv4/IPv6 address +--- where the last ":" separates host and port (empty or zero +--- assigns a random port). +--- - Else {address} is the path to a named pipe (except on Windows). +--- - If {address} has no slashes ("/") it is treated as the +--- "name" part of a generated path in this format: >vim +--- stdpath("run").."/{name}.{pid}.{counter}" +--- < - If {address} is omitted the name is "nvim". >vim +--- echo serverstart() +--- < > +--- => /tmp/nvim.bram/oknANW/nvim.15430.5 +--- < +--- Example bash command to list all Nvim servers: >bash +--- ls ${XDG_RUNTIME_DIR:-${TMPDIR}nvim.${USER}}/*/nvim.*.0 +--- +--- <Example named pipe: >vim +--- if has('win32') +--- echo serverstart('\\.\pipe\nvim-pipe-1234') +--- else +--- echo serverstart('nvim.sock') +--- endif +--- < +--- Example TCP/IP address: >vim +--- echo serverstart('::1:12345') +--- < +--- +--- @param address? any +--- @return any +function vim.fn.serverstart(address) end + +--- Closes the pipe or socket at {address}. +--- Returns TRUE if {address} is valid, else FALSE. +--- If |v:servername| is stopped it is set to the next available +--- address in |serverlist()|. +--- +--- @param address any +--- @return any +function vim.fn.serverstop(address) end + +--- Set line {lnum} to {text} in buffer {buf}. This works like +--- |setline()| for the specified buffer. +--- +--- This function works only for loaded buffers. First call +--- |bufload()| if needed. +--- +--- To insert lines use |appendbufline()|. +--- +--- {text} can be a string to set one line, or a List of strings +--- to set multiple lines. If the List extends below the last +--- line then those lines are added. If the List is empty then +--- nothing is changed and zero is returned. +--- +--- For the use of {buf}, see |bufname()| above. +--- +--- {lnum} is used like with |setline()|. +--- Use "$" to refer to the last line in buffer {buf}. +--- When {lnum} is just below the last line the {text} will be +--- added below the last line. +--- On success 0 is returned, on failure 1 is returned. +--- +--- If {buf} is not a valid buffer or {lnum} is not valid, an +--- error message is given. +--- +--- @param buf any +--- @param lnum integer +--- @param text any +--- @return any +function vim.fn.setbufline(buf, lnum, text) end + +--- Set option or local variable {varname} in buffer {buf} to +--- {val}. +--- This also works for a global or local window option, but it +--- doesn't work for a global or local window variable. +--- For a local window option the global value is unchanged. +--- For the use of {buf}, see |bufname()| above. +--- The {varname} argument is a string. +--- Note that the variable name without "b:" must be used. +--- Examples: >vim +--- call setbufvar(1, "&mod", 1) +--- call setbufvar("todo", "myvar", "foobar") +--- <This function is not available in the |sandbox|. +--- +--- @param buf any +--- @param varname string +--- @param val any +--- @return any +function vim.fn.setbufvar(buf, varname, val) end + +--- Specify overrides for cell widths of character ranges. This +--- tells Vim how wide characters are when displayed in the +--- terminal, counted in screen cells. The values override +--- 'ambiwidth'. Example: >vim +--- call setcellwidths([ +--- \ [0x111, 0x111, 1], +--- \ [0x2194, 0x2199, 2], +--- \ ]) +--- +--- <The {list} argument is a List of Lists with each three +--- numbers: [{low}, {high}, {width}]. *E1109* *E1110* +--- {low} and {high} can be the same, in which case this refers to +--- one character. Otherwise it is the range of characters from +--- {low} to {high} (inclusive). *E1111* *E1114* +--- Only characters with value 0x80 and higher can be used. +--- +--- {width} must be either 1 or 2, indicating the character width +--- in screen cells. *E1112* +--- An error is given if the argument is invalid, also when a +--- range overlaps with another. *E1113* +--- +--- If the new value causes 'fillchars' or 'listchars' to become +--- invalid it is rejected and an error is given. +--- +--- To clear the overrides pass an empty {list}: >vim +--- call setcellwidths([]) +--- +--- <You can use the script $VIMRUNTIME/tools/emoji_list.vim to see +--- the effect for known emoji characters. Move the cursor +--- through the text to check if the cell widths of your terminal +--- match with what Vim knows about each emoji. If it doesn't +--- look right you need to adjust the {list} argument. +--- +--- @param list any +--- @return any +function vim.fn.setcellwidths(list) end + +--- Same as |setpos()| but uses the specified column number as the +--- character index instead of the byte index in the line. +--- +--- Example: +--- With the text "여보세요" in line 8: >vim +--- call setcharpos('.', [0, 8, 4, 0]) +--- <positions the cursor on the fourth character '요'. >vim +--- call setpos('.', [0, 8, 4, 0]) +--- <positions the cursor on the second character '보'. +--- +--- @param expr any +--- @param list any +--- @return any +function vim.fn.setcharpos(expr, list) end + +--- Set the current character search information to {dict}, +--- which contains one or more of the following entries: +--- +--- char character which will be used for a subsequent +--- |,| or |;| command; an empty string clears the +--- character search +--- forward direction of character search; 1 for forward, +--- 0 for backward +--- until type of character search; 1 for a |t| or |T| +--- character search, 0 for an |f| or |F| +--- character search +--- +--- This can be useful to save/restore a user's character search +--- from a script: >vim +--- let prevsearch = getcharsearch() +--- " Perform a command which clobbers user's search +--- call setcharsearch(prevsearch) +--- <Also see |getcharsearch()|. +--- +--- @param dict any +--- @return any +function vim.fn.setcharsearch(dict) end + +--- Set the command line to {str} and set the cursor position to +--- {pos}. +--- If {pos} is omitted, the cursor is positioned after the text. +--- Returns 0 when successful, 1 when not editing the command +--- line. +--- +--- @param str any +--- @param pos? any +--- @return any +function vim.fn.setcmdline(str, pos) end + +--- Set the cursor position in the command line to byte position +--- {pos}. The first position is 1. +--- Use |getcmdpos()| to obtain the current position. +--- Only works while editing the command line, thus you must use +--- |c_CTRL-\_e|, |c_CTRL-R_=| or |c_CTRL-R_CTRL-R| with '='. For +--- |c_CTRL-\_e| and |c_CTRL-R_CTRL-R| with '=' the position is +--- set after the command line is set to the expression. For +--- |c_CTRL-R_=| it is set after evaluating the expression but +--- before inserting the resulting text. +--- When the number is too big the cursor is put at the end of the +--- line. A number smaller than one has undefined results. +--- Returns 0 when successful, 1 when not editing the command +--- line. +--- +--- @param pos any +--- @return any +function vim.fn.setcmdpos(pos) end + +--- @param lnum integer +--- @param col? integer +--- @param off? any +--- @return any +function vim.fn.setcursorcharpos(lnum, col, off) end + +--- Same as |cursor()| but uses the specified column number as the +--- character index instead of the byte index in the line. +--- +--- Example: +--- With the text "여보세요" in line 4: >vim +--- call setcursorcharpos(4, 3) +--- <positions the cursor on the third character '세'. >vim +--- call cursor(4, 3) +--- <positions the cursor on the first character '여'. +--- +--- @param list any +--- @return any +function vim.fn.setcursorcharpos(list) end + +--- Set environment variable {name} to {val}. Example: >vim +--- call setenv('HOME', '/home/myhome') +--- +--- <When {val} is |v:null| the environment variable is deleted. +--- See also |expr-env|. +--- +--- @param name string +--- @param val any +--- @return any +function vim.fn.setenv(name, val) end + +--- Set the file permissions for {fname} to {mode}. +--- {mode} must be a string with 9 characters. It is of the form +--- "rwxrwxrwx", where each group of "rwx" flags represent, in +--- turn, the permissions of the owner of the file, the group the +--- file belongs to, and other users. A '-' character means the +--- permission is off, any other character means on. Multi-byte +--- characters are not supported. +--- +--- For example "rw-r-----" means read-write for the user, +--- readable by the group, not accessible by others. "xx-x-----" +--- would do the same thing. +--- +--- Returns non-zero for success, zero for failure. +--- +--- To read permissions see |getfperm()|. +--- +--- @param fname string +--- @param mode string +--- @return any +function vim.fn.setfperm(fname, mode) end + +--- Set line {lnum} of the current buffer to {text}. To insert +--- lines use |append()|. To set lines in another buffer use +--- |setbufline()|. +--- +--- {lnum} is used like with |getline()|. +--- When {lnum} is just below the last line the {text} will be +--- added below the last line. +--- {text} can be any type or a List of any type, each item is +--- converted to a String. When {text} is an empty List then +--- nothing is changed and FALSE is returned. +--- +--- If this succeeds, FALSE is returned. If this fails (most likely +--- because {lnum} is invalid) TRUE is returned. +--- +--- Example: >vim +--- call setline(5, strftime("%c")) +--- +--- <When {text} is a |List| then line {lnum} and following lines +--- will be set to the items in the list. Example: >vim +--- call setline(5, ['aaa', 'bbb', 'ccc']) +--- <This is equivalent to: >vim +--- for [n, l] in [[5, 'aaa'], [6, 'bbb'], [7, 'ccc']] +--- call setline(n, l) +--- endfor +--- +--- <Note: The '[ and '] marks are not set. +--- +--- @param lnum integer +--- @param text any +--- @return any +function vim.fn.setline(lnum, text) end + +--- Create or replace or add to the location list for window {nr}. +--- {nr} can be the window number or the |window-ID|. +--- When {nr} is zero the current window is used. +--- +--- For a location list window, the displayed location list is +--- modified. For an invalid window number {nr}, -1 is returned. +--- Otherwise, same as |setqflist()|. +--- Also see |location-list|. +--- +--- For {action} see |setqflist-action|. +--- +--- If the optional {what} dictionary argument is supplied, then +--- only the items listed in {what} are set. Refer to |setqflist()| +--- for the list of supported keys in {what}. +--- +--- @param nr integer +--- @param list any +--- @param action? any +--- @param what? any +--- @return any +function vim.fn.setloclist(nr, list, action, what) end + +--- Restores a list of matches saved by |getmatches()| for the +--- current window. Returns 0 if successful, otherwise -1. All +--- current matches are cleared before the list is restored. See +--- example for |getmatches()|. +--- If {win} is specified, use the window with this number or +--- window ID instead of the current window. +--- +--- @param list any +--- @param win? any +--- @return any +function vim.fn.setmatches(list, win) end + +--- Set the position for String {expr}. Possible values: +--- . the cursor +--- 'x mark x +--- +--- {list} must be a |List| with four or five numbers: +--- [bufnum, lnum, col, off] +--- [bufnum, lnum, col, off, curswant] +--- +--- "bufnum" is the buffer number. Zero can be used for the +--- current buffer. When setting an uppercase mark "bufnum" is +--- used for the mark position. For other marks it specifies the +--- buffer to set the mark in. You can use the |bufnr()| function +--- to turn a file name into a buffer number. +--- For setting the cursor and the ' mark "bufnum" is ignored, +--- since these are associated with a window, not a buffer. +--- Does not change the jumplist. +--- +--- "lnum" and "col" are the position in the buffer. The first +--- column is 1. Use a zero "lnum" to delete a mark. If "col" is +--- smaller than 1 then 1 is used. To use the character count +--- instead of the byte count, use |setcharpos()|. +--- +--- The "off" number is only used when 'virtualedit' is set. Then +--- it is the offset in screen columns from the start of the +--- character. E.g., a position within a <Tab> or after the last +--- character. +--- +--- The "curswant" number is only used when setting the cursor +--- position. It sets the preferred column for when moving the +--- cursor vertically. When the "curswant" number is missing the +--- preferred column is not set. When it is present and setting a +--- mark position it is not used. +--- +--- Note that for '< and '> changing the line number may result in +--- the marks to be effectively be swapped, so that '< is always +--- before '>. +--- +--- Returns 0 when the position could be set, -1 otherwise. +--- An error message is given if {expr} is invalid. +--- +--- Also see |setcharpos()|, |getpos()| and |getcurpos()|. +--- +--- This does not restore the preferred column for moving +--- vertically; if you set the cursor position with this, |j| and +--- |k| motions will jump to previous columns! Use |cursor()| to +--- also set the preferred column. Also see the "curswant" key in +--- |winrestview()|. +--- +--- @param expr any +--- @param list any +--- @return any +function vim.fn.setpos(expr, list) end + +--- Create or replace or add to the quickfix list. +--- +--- If the optional {what} dictionary argument is supplied, then +--- only the items listed in {what} are set. The first {list} +--- argument is ignored. See below for the supported items in +--- {what}. +--- *setqflist-what* +--- When {what} is not present, the items in {list} are used. Each +--- item must be a dictionary. Non-dictionary items in {list} are +--- ignored. Each dictionary item can contain the following +--- entries: +--- +--- bufnr buffer number; must be the number of a valid +--- buffer +--- filename name of a file; only used when "bufnr" is not +--- present or it is invalid. +--- module name of a module; if given it will be used in +--- quickfix error window instead of the filename. +--- lnum line number in the file +--- end_lnum end of lines, if the item spans multiple lines +--- pattern search pattern used to locate the error +--- col column number +--- vcol when non-zero: "col" is visual column +--- when zero: "col" is byte index +--- end_col end column, if the item spans multiple columns +--- nr error number +--- text description of the error +--- type single-character error type, 'E', 'W', etc. +--- valid recognized error message +--- user_data +--- custom data associated with the item, can be +--- any type. +--- +--- The "col", "vcol", "nr", "type" and "text" entries are +--- optional. Either "lnum" or "pattern" entry can be used to +--- locate a matching error line. +--- If the "filename" and "bufnr" entries are not present or +--- neither the "lnum" or "pattern" entries are present, then the +--- item will not be handled as an error line. +--- If both "pattern" and "lnum" are present then "pattern" will +--- be used. +--- If the "valid" entry is not supplied, then the valid flag is +--- set when "bufnr" is a valid buffer or "filename" exists. +--- If you supply an empty {list}, the quickfix list will be +--- cleared. +--- Note that the list is not exactly the same as what +--- |getqflist()| returns. +--- +--- {action} values: *setqflist-action* *E927* +--- 'a' The items from {list} are added to the existing +--- quickfix list. If there is no existing list, then a +--- new list is created. +--- +--- 'r' The items from the current quickfix list are replaced +--- with the items from {list}. This can also be used to +--- clear the list: >vim +--- call setqflist([], 'r') +--- < +--- 'f' All the quickfix lists in the quickfix stack are +--- freed. +--- +--- If {action} is not present or is set to ' ', then a new list +--- is created. The new quickfix list is added after the current +--- quickfix list in the stack and all the following lists are +--- freed. To add a new quickfix list at the end of the stack, +--- set "nr" in {what} to "$". +--- +--- The following items can be specified in dictionary {what}: +--- context quickfix list context. See |quickfix-context| +--- efm errorformat to use when parsing text from +--- "lines". If this is not present, then the +--- 'errorformat' option value is used. +--- See |quickfix-parse| +--- id quickfix list identifier |quickfix-ID| +--- idx index of the current entry in the quickfix +--- list specified by "id" or "nr". If set to '$', +--- then the last entry in the list is set as the +--- current entry. See |quickfix-index| +--- items list of quickfix entries. Same as the {list} +--- argument. +--- lines use 'errorformat' to parse a list of lines and +--- add the resulting entries to the quickfix list +--- {nr} or {id}. Only a |List| value is supported. +--- See |quickfix-parse| +--- nr list number in the quickfix stack; zero +--- means the current quickfix list and "$" means +--- the last quickfix list. +--- quickfixtextfunc +--- function to get the text to display in the +--- quickfix window. The value can be the name of +--- a function or a funcref or a lambda. Refer to +--- |quickfix-window-function| for an explanation +--- of how to write the function and an example. +--- title quickfix list title text. See |quickfix-title| +--- Unsupported keys in {what} are ignored. +--- If the "nr" item is not present, then the current quickfix list +--- is modified. When creating a new quickfix list, "nr" can be +--- set to a value one greater than the quickfix stack size. +--- When modifying a quickfix list, to guarantee that the correct +--- list is modified, "id" should be used instead of "nr" to +--- specify the list. +--- +--- Examples (See also |setqflist-examples|): >vim +--- call setqflist([], 'r', {'title': 'My search'}) +--- call setqflist([], 'r', {'nr': 2, 'title': 'Errors'}) +--- call setqflist([], 'a', {'id':qfid, 'lines':["F1:10:L10"]}) +--- < +--- Returns zero for success, -1 for failure. +--- +--- This function can be used to create a quickfix list +--- independent of the 'errorformat' setting. Use a command like +--- `:cc 1` to jump to the first position. +--- +--- @param list any +--- @param action? any +--- @param what? any +--- @return any +function vim.fn.setqflist(list, action, what) end + +--- Set the register {regname} to {value}. +--- If {regname} is "" or "\@", the unnamed register '"' is used. +--- The {regname} argument is a string. +--- +--- {value} may be any value returned by |getreg()| or +--- |getreginfo()|, including a |List| or |Dict|. +--- If {options} contains "a" or {regname} is upper case, +--- then the value is appended. +--- +--- {options} can also contain a register type specification: +--- "c" or "v" |charwise| mode +--- "l" or "V" |linewise| mode +--- "b" or "<CTRL-V>" |blockwise-visual| mode +--- If a number immediately follows "b" or "<CTRL-V>" then this is +--- used as the width of the selection - if it is not specified +--- then the width of the block is set to the number of characters +--- in the longest line (counting a <Tab> as 1 character). +--- If {options} contains "u" or '"', then the unnamed register is +--- set to point to register {regname}. +--- +--- If {options} contains no register settings, then the default +--- is to use character mode unless {value} ends in a <NL> for +--- string {value} and linewise mode for list {value}. Blockwise +--- mode is never selected automatically. +--- Returns zero for success, non-zero for failure. +--- +--- *E883* +--- Note: you may not use |List| containing more than one item to +--- set search and expression registers. Lists containing no +--- items act like empty strings. +--- +--- Examples: >vim +--- call setreg(v:register, \@*) +--- call setreg('*', \@%, 'ac') +--- call setreg('a', "1\n2\n3", 'b5') +--- call setreg('"', { 'points_to': 'a'}) +--- +--- <This example shows using the functions to save and restore a +--- register: >vim +--- let var_a = getreginfo() +--- call setreg('a', var_a) +--- <or: >vim +--- let var_a = getreg('a', 1, 1) +--- let var_amode = getregtype('a') +--- " .... +--- call setreg('a', var_a, var_amode) +--- <Note: you may not reliably restore register value +--- without using the third argument to |getreg()| as without it +--- newlines are represented as newlines AND Nul bytes are +--- represented as newlines as well, see |NL-used-for-Nul|. +--- +--- You can also change the type of a register by appending +--- nothing: >vim +--- call setreg('a', '', 'al') +--- +--- @param regname string +--- @param value any +--- @param options? table +--- @return any +function vim.fn.setreg(regname, value, options) end + +--- Set tab-local variable {varname} to {val} in tab page {tabnr}. +--- |t:var| +--- The {varname} argument is a string. +--- Note that the variable name without "t:" must be used. +--- Tabs are numbered starting with one. +--- This function is not available in the |sandbox|. +--- +--- @param tabnr integer +--- @param varname string +--- @param val any +--- @return any +function vim.fn.settabvar(tabnr, varname, val) end + +--- Set option or local variable {varname} in window {winnr} to +--- {val}. +--- Tabs are numbered starting with one. For the current tabpage +--- use |setwinvar()|. +--- {winnr} can be the window number or the |window-ID|. +--- When {winnr} is zero the current window is used. +--- This also works for a global or local buffer option, but it +--- doesn't work for a global or local buffer variable. +--- For a local buffer option the global value is unchanged. +--- Note that the variable name without "w:" must be used. +--- Examples: >vim +--- call settabwinvar(1, 1, "&list", 0) +--- call settabwinvar(3, 2, "myvar", "foobar") +--- <This function is not available in the |sandbox|. +--- +--- @param tabnr integer +--- @param winnr integer +--- @param varname string +--- @param val any +--- @return any +function vim.fn.settabwinvar(tabnr, winnr, varname, val) end + +--- Modify the tag stack of the window {nr} using {dict}. +--- {nr} can be the window number or the |window-ID|. +--- +--- For a list of supported items in {dict}, refer to +--- |gettagstack()|. "curidx" takes effect before changing the tag +--- stack. +--- *E962* +--- How the tag stack is modified depends on the {action} +--- argument: +--- - If {action} is not present or is set to 'r', then the tag +--- stack is replaced. +--- - If {action} is set to 'a', then new entries from {dict} are +--- pushed (added) onto the tag stack. +--- - If {action} is set to 't', then all the entries from the +--- current entry in the tag stack or "curidx" in {dict} are +--- removed and then new entries are pushed to the stack. +--- +--- The current index is set to one after the length of the tag +--- stack after the modification. +--- +--- Returns zero for success, -1 for failure. +--- +--- Examples (for more examples see |tagstack-examples|): +--- Empty the tag stack of window 3: >vim +--- call settagstack(3, {'items' : []}) +--- +--- < Save and restore the tag stack: >vim +--- let stack = gettagstack(1003) +--- " do something else +--- call settagstack(1003, stack) +--- unlet stack +--- < +--- +--- @param nr integer +--- @param dict any +--- @param action? any +--- @return any +function vim.fn.settagstack(nr, dict, action) end + +--- Like |settabwinvar()| for the current tab page. +--- Examples: >vim +--- call setwinvar(1, "&list", 0) +--- call setwinvar(2, "myvar", "foobar") +--- +--- @param nr integer +--- @param varname string +--- @param val any +--- @return any +function vim.fn.setwinvar(nr, varname, val) end + +--- Returns a String with 64 hex characters, which is the SHA256 +--- checksum of {string}. +--- +--- @param string string +--- @return any +function vim.fn.sha256(string) end + +--- Escape {string} for use as a shell command argument. +--- +--- On Windows when 'shellslash' is not set, encloses {string} in +--- double-quotes and doubles all double-quotes within {string}. +--- Otherwise encloses {string} in single-quotes and replaces all +--- "'" with "'\''". +--- +--- If {special} is a |non-zero-arg|: +--- - Special items such as "!", "%", "#" and "<cword>" will be +--- preceded by a backslash. The backslash will be removed again +--- by the |:!| command. +--- - The <NL> character is escaped. +--- +--- If 'shell' contains "csh" in the tail: +--- - The "!" character will be escaped. This is because csh and +--- tcsh use "!" for history replacement even in single-quotes. +--- - The <NL> character is escaped (twice if {special} is +--- a |non-zero-arg|). +--- +--- If 'shell' contains "fish" in the tail, the "\" character will +--- be escaped because in fish it is used as an escape character +--- inside single quotes. +--- +--- Example of use with a |:!| command: >vim +--- exe '!dir ' .. shellescape(expand('<cfile>'), 1) +--- <This results in a directory listing for the file under the +--- cursor. Example of use with |system()|: >vim +--- call system("chmod +w -- " .. shellescape(expand("%"))) +--- <See also |::S|. +--- +--- @param string string +--- @param special? any +--- @return any +function vim.fn.shellescape(string, special) end + +--- Returns the effective value of 'shiftwidth'. This is the +--- 'shiftwidth' value unless it is zero, in which case it is the +--- 'tabstop' value. To be backwards compatible in indent +--- plugins, use this: >vim +--- if exists('*shiftwidth') +--- func s:sw() +--- return shiftwidth() +--- endfunc +--- else +--- func s:sw() +--- return &sw +--- endfunc +--- endif +--- <And then use s:sw() instead of &sw. +--- +--- When there is one argument {col} this is used as column number +--- for which to return the 'shiftwidth' value. This matters for the +--- 'vartabstop' feature. If no {col} argument is given, column 1 +--- will be assumed. +--- +--- @param col? integer +--- @return integer +function vim.fn.shiftwidth(col) end + +--- @param name string +--- @param dict? vim.fn.sign_define.dict +--- @return 0|-1 +function vim.fn.sign_define(name, dict) end + +--- Define a new sign named {name} or modify the attributes of an +--- existing sign. This is similar to the |:sign-define| command. +--- +--- Prefix {name} with a unique text to avoid name collisions. +--- There is no {group} like with placing signs. +--- +--- The {name} can be a String or a Number. The optional {dict} +--- argument specifies the sign attributes. The following values +--- are supported: +--- icon full path to the bitmap file for the sign. +--- linehl highlight group used for the whole line the +--- sign is placed in. +--- numhl highlight group used for the line number where +--- the sign is placed. +--- text text that is displayed when there is no icon +--- or the GUI is not being used. +--- texthl highlight group used for the text item +--- culhl highlight group used for the text item when +--- the cursor is on the same line as the sign and +--- 'cursorline' is enabled. +--- +--- If the sign named {name} already exists, then the attributes +--- of the sign are updated. +--- +--- The one argument {list} can be used to define a list of signs. +--- Each list item is a dictionary with the above items in {dict} +--- and a "name" item for the sign name. +--- +--- Returns 0 on success and -1 on failure. When the one argument +--- {list} is used, then returns a List of values one for each +--- defined sign. +--- +--- Examples: >vim +--- call sign_define("mySign", { +--- \ "text" : "=>", +--- \ "texthl" : "Error", +--- \ "linehl" : "Search"}) +--- call sign_define([ +--- \ {'name' : 'sign1', +--- \ 'text' : '=>'}, +--- \ {'name' : 'sign2', +--- \ 'text' : '!!'} +--- \ ]) +--- < +--- +--- @param list vim.fn.sign_define.dict[] +--- @return (0|-1)[] +function vim.fn.sign_define(list) end + +--- Get a list of defined signs and their attributes. +--- This is similar to the |:sign-list| command. +--- +--- If the {name} is not supplied, then a list of all the defined +--- signs is returned. Otherwise the attribute of the specified +--- sign is returned. +--- +--- Each list item in the returned value is a dictionary with the +--- following entries: +--- icon full path to the bitmap file of the sign +--- linehl highlight group used for the whole line the +--- sign is placed in; not present if not set. +--- name name of the sign +--- numhl highlight group used for the line number where +--- the sign is placed; not present if not set. +--- text text that is displayed when there is no icon +--- or the GUI is not being used. +--- texthl highlight group used for the text item; not +--- present if not set. +--- culhl highlight group used for the text item when +--- the cursor is on the same line as the sign and +--- 'cursorline' is enabled; not present if not +--- set. +--- +--- Returns an empty List if there are no signs and when {name} is +--- not found. +--- +--- Examples: >vim +--- " Get a list of all the defined signs +--- echo sign_getdefined() +--- +--- " Get the attribute of the sign named mySign +--- echo sign_getdefined("mySign") +--- < +--- +--- @param name? string +--- @return vim.fn.sign_getdefined.ret.item[] +function vim.fn.sign_getdefined(name) end + +--- Return a list of signs placed in a buffer or all the buffers. +--- This is similar to the |:sign-place-list| command. +--- +--- If the optional buffer name {buf} is specified, then only the +--- list of signs placed in that buffer is returned. For the use +--- of {buf}, see |bufname()|. The optional {dict} can contain +--- the following entries: +--- group select only signs in this group +--- id select sign with this identifier +--- lnum select signs placed in this line. For the use +--- of {lnum}, see |line()|. +--- If {group} is "*", then signs in all the groups including the +--- global group are returned. If {group} is not supplied or is an +--- empty string, then only signs in the global group are +--- returned. If no arguments are supplied, then signs in the +--- global group placed in all the buffers are returned. +--- See |sign-group|. +--- +--- Each list item in the returned value is a dictionary with the +--- following entries: +--- bufnr number of the buffer with the sign +--- signs list of signs placed in {bufnr}. Each list +--- item is a dictionary with the below listed +--- entries +--- +--- The dictionary for each sign contains the following entries: +--- group sign group. Set to '' for the global group. +--- id identifier of the sign +--- lnum line number where the sign is placed +--- name name of the defined sign +--- priority sign priority +--- +--- The returned signs in a buffer are ordered by their line +--- number and priority. +--- +--- Returns an empty list on failure or if there are no placed +--- signs. +--- +--- Examples: >vim +--- " Get a List of signs placed in eval.c in the +--- " global group +--- echo sign_getplaced("eval.c") +--- +--- " Get a List of signs in group 'g1' placed in eval.c +--- echo sign_getplaced("eval.c", {'group' : 'g1'}) +--- +--- " Get a List of signs placed at line 10 in eval.c +--- echo sign_getplaced("eval.c", {'lnum' : 10}) +--- +--- " Get sign with identifier 10 placed in a.py +--- echo sign_getplaced("a.py", {'id' : 10}) +--- +--- " Get sign with id 20 in group 'g1' placed in a.py +--- echo sign_getplaced("a.py", {'group' : 'g1', +--- \ 'id' : 20}) +--- +--- " Get a List of all the placed signs +--- echo sign_getplaced() +--- < +--- +--- @param buf? any +--- @param dict? vim.fn.sign_getplaced.dict +--- @return vim.fn.sign_getplaced.ret.item[] +function vim.fn.sign_getplaced(buf, dict) end + +--- Open the buffer {buf} or jump to the window that contains +--- {buf} and position the cursor at sign {id} in group {group}. +--- This is similar to the |:sign-jump| command. +--- +--- If {group} is an empty string, then the global group is used. +--- For the use of {buf}, see |bufname()|. +--- +--- Returns the line number of the sign. Returns -1 if the +--- arguments are invalid. +--- +--- Example: >vim +--- " Jump to sign 10 in the current buffer +--- call sign_jump(10, '', '') +--- < +--- +--- @param id integer +--- @param group string +--- @param buf integer|string +--- @return integer +function vim.fn.sign_jump(id, group, buf) end + +--- Place the sign defined as {name} at line {lnum} in file or +--- buffer {buf} and assign {id} and {group} to sign. This is +--- similar to the |:sign-place| command. +--- +--- If the sign identifier {id} is zero, then a new identifier is +--- allocated. Otherwise the specified number is used. {group} is +--- the sign group name. To use the global sign group, use an +--- empty string. {group} functions as a namespace for {id}, thus +--- two groups can use the same IDs. Refer to |sign-identifier| +--- and |sign-group| for more information. +--- +--- {name} refers to a defined sign. +--- {buf} refers to a buffer name or number. For the accepted +--- values, see |bufname()|. +--- +--- The optional {dict} argument supports the following entries: +--- lnum line number in the file or buffer +--- {buf} where the sign is to be placed. +--- For the accepted values, see |line()|. +--- priority priority of the sign. See +--- |sign-priority| for more information. +--- +--- If the optional {dict} is not specified, then it modifies the +--- placed sign {id} in group {group} to use the defined sign +--- {name}. +--- +--- Returns the sign identifier on success and -1 on failure. +--- +--- Examples: >vim +--- " Place a sign named sign1 with id 5 at line 20 in +--- " buffer json.c +--- call sign_place(5, '', 'sign1', 'json.c', +--- \ {'lnum' : 20}) +--- +--- " Updates sign 5 in buffer json.c to use sign2 +--- call sign_place(5, '', 'sign2', 'json.c') +--- +--- " Place a sign named sign3 at line 30 in +--- " buffer json.c with a new identifier +--- let id = sign_place(0, '', 'sign3', 'json.c', +--- \ {'lnum' : 30}) +--- +--- " Place a sign named sign4 with id 10 in group 'g3' +--- " at line 40 in buffer json.c with priority 90 +--- call sign_place(10, 'g3', 'sign4', 'json.c', +--- \ {'lnum' : 40, 'priority' : 90}) +--- < +--- +--- @param id any +--- @param group any +--- @param name string +--- @param buf any +--- @param dict? vim.fn.sign_place.dict +--- @return integer +function vim.fn.sign_place(id, group, name, buf, dict) end + +--- Place one or more signs. This is similar to the +--- |sign_place()| function. The {list} argument specifies the +--- List of signs to place. Each list item is a dict with the +--- following sign attributes: +--- buffer Buffer name or number. For the accepted +--- values, see |bufname()|. +--- group Sign group. {group} functions as a namespace +--- for {id}, thus two groups can use the same +--- IDs. If not specified or set to an empty +--- string, then the global group is used. See +--- |sign-group| for more information. +--- id Sign identifier. If not specified or zero, +--- then a new unique identifier is allocated. +--- Otherwise the specified number is used. See +--- |sign-identifier| for more information. +--- lnum Line number in the buffer where the sign is to +--- be placed. For the accepted values, see +--- |line()|. +--- name Name of the sign to place. See |sign_define()| +--- for more information. +--- priority Priority of the sign. When multiple signs are +--- placed on a line, the sign with the highest +--- priority is used. If not specified, the +--- default value of 10 is used. See +--- |sign-priority| for more information. +--- +--- If {id} refers to an existing sign, then the existing sign is +--- modified to use the specified {name} and/or {priority}. +--- +--- Returns a List of sign identifiers. If failed to place a +--- sign, the corresponding list item is set to -1. +--- +--- Examples: >vim +--- " Place sign s1 with id 5 at line 20 and id 10 at line +--- " 30 in buffer a.c +--- let [n1, n2] = sign_placelist([ +--- \ {'id' : 5, +--- \ 'name' : 's1', +--- \ 'buffer' : 'a.c', +--- \ 'lnum' : 20}, +--- \ {'id' : 10, +--- \ 'name' : 's1', +--- \ 'buffer' : 'a.c', +--- \ 'lnum' : 30} +--- \ ]) +--- +--- " Place sign s1 in buffer a.c at line 40 and 50 +--- " with auto-generated identifiers +--- let [n1, n2] = sign_placelist([ +--- \ {'name' : 's1', +--- \ 'buffer' : 'a.c', +--- \ 'lnum' : 40}, +--- \ {'name' : 's1', +--- \ 'buffer' : 'a.c', +--- \ 'lnum' : 50} +--- \ ]) +--- < +--- +--- @param list vim.fn.sign_placelist.list.item[] +--- @return integer[] +function vim.fn.sign_placelist(list) end + +--- @param name? string +--- @return 0|-1 +function vim.fn.sign_undefine(name) end + +--- Deletes a previously defined sign {name}. This is similar to +--- the |:sign-undefine| command. If {name} is not supplied, then +--- deletes all the defined signs. +--- +--- The one argument {list} can be used to undefine a list of +--- signs. Each list item is the name of a sign. +--- +--- Returns 0 on success and -1 on failure. For the one argument +--- {list} call, returns a list of values one for each undefined +--- sign. +--- +--- Examples: >vim +--- " Delete a sign named mySign +--- call sign_undefine("mySign") +--- +--- " Delete signs 'sign1' and 'sign2' +--- call sign_undefine(["sign1", "sign2"]) +--- +--- " Delete all the signs +--- call sign_undefine() +--- < +--- +--- @param list? string[] +--- @return integer[] +function vim.fn.sign_undefine(list) end + +--- Remove a previously placed sign in one or more buffers. This +--- is similar to the |:sign-unplace| command. +--- +--- {group} is the sign group name. To use the global sign group, +--- use an empty string. If {group} is set to "*", then all the +--- groups including the global group are used. +--- The signs in {group} are selected based on the entries in +--- {dict}. The following optional entries in {dict} are +--- supported: +--- buffer buffer name or number. See |bufname()|. +--- id sign identifier +--- If {dict} is not supplied, then all the signs in {group} are +--- removed. +--- +--- Returns 0 on success and -1 on failure. +--- +--- Examples: >vim +--- " Remove sign 10 from buffer a.vim +--- call sign_unplace('', {'buffer' : "a.vim", 'id' : 10}) +--- +--- " Remove sign 20 in group 'g1' from buffer 3 +--- call sign_unplace('g1', {'buffer' : 3, 'id' : 20}) +--- +--- " Remove all the signs in group 'g2' from buffer 10 +--- call sign_unplace('g2', {'buffer' : 10}) +--- +--- " Remove sign 30 in group 'g3' from all the buffers +--- call sign_unplace('g3', {'id' : 30}) +--- +--- " Remove all the signs placed in buffer 5 +--- call sign_unplace('*', {'buffer' : 5}) +--- +--- " Remove the signs in group 'g4' from all the buffers +--- call sign_unplace('g4') +--- +--- " Remove sign 40 from all the buffers +--- call sign_unplace('*', {'id' : 40}) +--- +--- " Remove all the placed signs from all the buffers +--- call sign_unplace('*') +--- +--- @param group string +--- @param dict? vim.fn.sign_unplace.dict +--- @return 0|-1 +function vim.fn.sign_unplace(group, dict) end + +--- Remove previously placed signs from one or more buffers. This +--- is similar to the |sign_unplace()| function. +--- +--- The {list} argument specifies the List of signs to remove. +--- Each list item is a dict with the following sign attributes: +--- buffer buffer name or number. For the accepted +--- values, see |bufname()|. If not specified, +--- then the specified sign is removed from all +--- the buffers. +--- group sign group name. If not specified or set to an +--- empty string, then the global sign group is +--- used. If set to "*", then all the groups +--- including the global group are used. +--- id sign identifier. If not specified, then all +--- the signs in the specified group are removed. +--- +--- Returns a List where an entry is set to 0 if the corresponding +--- sign was successfully removed or -1 on failure. +--- +--- Example: >vim +--- " Remove sign with id 10 from buffer a.vim and sign +--- " with id 20 from buffer b.vim +--- call sign_unplacelist([ +--- \ {'id' : 10, 'buffer' : "a.vim"}, +--- \ {'id' : 20, 'buffer' : 'b.vim'}, +--- \ ]) +--- < +--- +--- @param list vim.fn.sign_unplacelist.list.item +--- @return (0|-1)[] +function vim.fn.sign_unplacelist(list) end + +--- Simplify the file name as much as possible without changing +--- the meaning. Shortcuts (on MS-Windows) or symbolic links (on +--- Unix) are not resolved. If the first path component in +--- {filename} designates the current directory, this will be +--- valid for the result as well. A trailing path separator is +--- not removed either. On Unix "//path" is unchanged, but +--- "///path" is simplified to "/path" (this follows the Posix +--- standard). +--- Example: >vim +--- simplify("./dir/.././/file/") == "./file/" +--- <Note: The combination "dir/.." is only removed if "dir" is +--- a searchable directory or does not exist. On Unix, it is also +--- removed when "dir" is a symbolic link within the same +--- directory. In order to resolve all the involved symbolic +--- links before simplifying the path name, use |resolve()|. +--- +--- @param filename any +--- @return any +function vim.fn.simplify(filename) end + +--- Return the sine of {expr}, measured in radians, as a |Float|. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo sin(100) +--- < -0.506366 >vim +--- echo sin(-4.01) +--- < 0.763301 +--- +--- @param expr any +--- @return any +function vim.fn.sin(expr) end + +--- Return the hyperbolic sine of {expr} as a |Float| in the range +--- [-inf, inf]. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo sinh(0.5) +--- < 0.521095 >vim +--- echo sinh(-0.9) +--- < -1.026517 +--- +--- @param expr any +--- @return any +function vim.fn.sinh(expr) end + +--- Similar to using a |slice| "expr[start : end]", but "end" is +--- used exclusive. And for a string the indexes are used as +--- character indexes instead of byte indexes. +--- Also, composing characters are not counted. +--- When {end} is omitted the slice continues to the last item. +--- When {end} is -1 the last item is omitted. +--- Returns an empty value if {start} or {end} are invalid. +--- +--- @param expr any +--- @param start any +--- @param end_? any +--- @return any +function vim.fn.slice(expr, start, end_) end + +--- Connect a socket to an address. If {mode} is "pipe" then +--- {address} should be the path of a local domain socket (on +--- unix) or named pipe (on Windows). If {mode} is "tcp" then +--- {address} should be of the form "host:port" where the host +--- should be an ip address or host name, and port the port +--- number. +--- +--- For "pipe" mode, see |luv-pipe-handle|. For "tcp" mode, see +--- |luv-tcp-handle|. +--- +--- Returns a |channel| ID. Close the socket with |chanclose()|. +--- Use |chansend()| to send data over a bytes socket, and +--- |rpcrequest()| and |rpcnotify()| to communicate with a RPC +--- socket. +--- +--- {opts} is an optional dictionary with these keys: +--- |on_data| : callback invoked when data was read from socket +--- data_buffered : read socket data in |channel-buffered| mode. +--- rpc : If set, |msgpack-rpc| will be used to communicate +--- over the socket. +--- Returns: +--- - The channel ID on success (greater than zero) +--- - 0 on invalid arguments or connection failure. +--- +--- @param mode string +--- @param address any +--- @param opts? table +--- @return any +function vim.fn.sockconnect(mode, address, opts) end + +--- Sort the items in {list} in-place. Returns {list}. +--- +--- If you want a list to remain unmodified make a copy first: >vim +--- let sortedlist = sort(copy(mylist)) +--- +--- <When {how} is omitted or is a string, then sort() uses the +--- string representation of each item to sort on. Numbers sort +--- after Strings, |Lists| after Numbers. For sorting text in the +--- current buffer use |:sort|. +--- +--- When {how} is given and it is 'i' then case is ignored. +--- For backwards compatibility, the value one can be used to +--- ignore case. Zero means to not ignore case. +--- +--- When {how} is given and it is 'l' then the current collation +--- locale is used for ordering. Implementation details: strcoll() +--- is used to compare strings. See |:language| check or set the +--- collation locale. |v:collate| can also be used to check the +--- current locale. Sorting using the locale typically ignores +--- case. Example: >vim +--- " ö is sorted similarly to o with English locale. +--- language collate en_US.UTF8 +--- echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l') +--- < ['n', 'o', 'O', 'ö', 'p', 'z'] ~ +--- >vim +--- " ö is sorted after z with Swedish locale. +--- language collate sv_SE.UTF8 +--- echo sort(['n', 'o', 'O', 'ö', 'p', 'z'], 'l') +--- < ['n', 'o', 'O', 'p', 'z', 'ö'] ~ +--- This does not work properly on Mac. +--- +--- When {how} is given and it is 'n' then all items will be +--- sorted numerical (Implementation detail: this uses the +--- strtod() function to parse numbers, Strings, Lists, Dicts and +--- Funcrefs will be considered as being 0). +--- +--- When {how} is given and it is 'N' then all items will be +--- sorted numerical. This is like 'n' but a string containing +--- digits will be used as the number they represent. +--- +--- When {how} is given and it is 'f' then all items will be +--- sorted numerical. All values must be a Number or a Float. +--- +--- When {how} is a |Funcref| or a function name, this function +--- is called to compare items. The function is invoked with two +--- items as argument and must return zero if they are equal, 1 or +--- bigger if the first one sorts after the second one, -1 or +--- smaller if the first one sorts before the second one. +--- +--- {dict} is for functions with the "dict" attribute. It will be +--- used to set the local variable "self". |Dictionary-function| +--- +--- The sort is stable, items which compare equal (as number or as +--- string) will keep their relative position. E.g., when sorting +--- on numbers, text strings will sort next to each other, in the +--- same order as they were originally. +--- +--- +--- Example: >vim +--- func MyCompare(i1, i2) +--- return a:i1 == a:i2 ? 0 : a:i1 > a:i2 ? 1 : -1 +--- endfunc +--- eval mylist->sort("MyCompare") +--- <A shorter compare version for this specific simple case, which +--- ignores overflow: >vim +--- func MyCompare(i1, i2) +--- return a:i1 - a:i2 +--- endfunc +--- <For a simple expression you can use a lambda: >vim +--- eval mylist->sort({i1, i2 -> i1 - i2}) +--- < +--- +--- @param list any +--- @param how? any +--- @param dict? any +--- @return any +function vim.fn.sort(list, how, dict) end + +--- Return the sound-folded equivalent of {word}. Uses the first +--- language in 'spelllang' for the current window that supports +--- soundfolding. 'spell' must be set. When no sound folding is +--- possible the {word} is returned unmodified. +--- This can be used for making spelling suggestions. Note that +--- the method can be quite slow. +--- +--- @param word any +--- @return any +function vim.fn.soundfold(word) end + +--- Without argument: The result is the badly spelled word under +--- or after the cursor. The cursor is moved to the start of the +--- bad word. When no bad word is found in the cursor line the +--- result is an empty string and the cursor doesn't move. +--- +--- With argument: The result is the first word in {sentence} that +--- is badly spelled. If there are no spelling mistakes the +--- result is an empty string. +--- +--- The return value is a list with two items: +--- - The badly spelled word or an empty string. +--- - The type of the spelling error: +--- "bad" spelling mistake +--- "rare" rare word +--- "local" word only valid in another region +--- "caps" word should start with Capital +--- Example: >vim +--- echo spellbadword("the quik brown fox") +--- < ['quik', 'bad'] ~ +--- +--- The spelling information for the current window and the value +--- of 'spelllang' are used. +--- +--- @param sentence? any +--- @return any +function vim.fn.spellbadword(sentence) end + +--- Return a |List| with spelling suggestions to replace {word}. +--- When {max} is given up to this number of suggestions are +--- returned. Otherwise up to 25 suggestions are returned. +--- +--- When the {capital} argument is given and it's non-zero only +--- suggestions with a leading capital will be given. Use this +--- after a match with 'spellcapcheck'. +--- +--- {word} can be a badly spelled word followed by other text. +--- This allows for joining two words that were split. The +--- suggestions also include the following text, thus you can +--- replace a line. +--- +--- {word} may also be a good word. Similar words will then be +--- returned. {word} itself is not included in the suggestions, +--- although it may appear capitalized. +--- +--- The spelling information for the current window is used. The +--- values of 'spelllang' and 'spellsuggest' are used. +--- +--- @param word any +--- @param max? any +--- @param capital? any +--- @return any +function vim.fn.spellsuggest(word, max, capital) end + +--- Make a |List| out of {string}. When {pattern} is omitted or +--- empty each white-separated sequence of characters becomes an +--- item. +--- Otherwise the string is split where {pattern} matches, +--- removing the matched characters. 'ignorecase' is not used +--- here, add \c to ignore case. |/\c| +--- When the first or last item is empty it is omitted, unless the +--- {keepempty} argument is given and it's non-zero. +--- Other empty items are kept when {pattern} matches at least one +--- character or when {keepempty} is non-zero. +--- Example: >vim +--- let words = split(getline('.'), '\W\+') +--- <To split a string in individual characters: >vim +--- for c in split(mystring, '\zs') | endfor +--- <If you want to keep the separator you can also use '\zs' at +--- the end of the pattern: >vim +--- echo split('abc:def:ghi', ':\zs') +--- < > +--- ['abc:', 'def:', 'ghi'] +--- < +--- Splitting a table where the first element can be empty: >vim +--- let items = split(line, ':', 1) +--- <The opposite function is |join()|. +--- +--- @param string string +--- @param pattern? any +--- @param keepempty? any +--- @return any +function vim.fn.split(string, pattern, keepempty) end + +--- Return the non-negative square root of Float {expr} as a +--- |Float|. +--- {expr} must evaluate to a |Float| or a |Number|. When {expr} +--- is negative the result is NaN (Not a Number). Returns 0.0 if +--- {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo sqrt(100) +--- < 10.0 >vim +--- echo sqrt(-4.01) +--- < str2float("nan") +--- NaN may be different, it depends on system libraries. +--- +--- @param expr any +--- @return any +function vim.fn.sqrt(expr) end + +--- Initialize seed used by |rand()|: +--- - If {expr} is not given, seed values are initialized by +--- reading from /dev/urandom, if possible, or using time(NULL) +--- a.k.a. epoch time otherwise; this only has second accuracy. +--- - If {expr} is given it must be a Number. It is used to +--- initialize the seed values. This is useful for testing or +--- when a predictable sequence is intended. +--- +--- Examples: >vim +--- let seed = srand() +--- let seed = srand(userinput) +--- echo rand(seed) +--- < +--- +--- @param expr? any +--- @return any +function vim.fn.srand(expr) end + +--- Return a string which contains characters indicating the +--- current state. Mostly useful in callbacks that want to do +--- work that may not always be safe. Roughly this works like: +--- - callback uses state() to check if work is safe to do. +--- Yes: then do it right away. +--- No: add to work queue and add a |SafeState| autocommand. +--- - When SafeState is triggered and executes your autocommand, +--- check with `state()` if the work can be done now, and if yes +--- remove it from the queue and execute. +--- Remove the autocommand if the queue is now empty. +--- Also see |mode()|. +--- +--- When {what} is given only characters in this string will be +--- added. E.g, this checks if the screen has scrolled: >vim +--- if state('s') == '' +--- " screen has not scrolled +--- < +--- These characters indicate the state, generally indicating that +--- something is busy: +--- m halfway a mapping, :normal command, feedkeys() or +--- stuffed command +--- o operator pending, e.g. after |d| +--- a Insert mode autocomplete active +--- x executing an autocommand +--- S not triggering SafeState, e.g. after |f| or a count +--- c callback invoked, including timer (repeats for +--- recursiveness up to "ccc") +--- s screen has scrolled for messages +--- +--- @param what? string +--- @return any +function vim.fn.state(what) end + +--- With |--headless| this opens stdin and stdout as a |channel|. +--- May be called only once. See |channel-stdio|. stderr is not +--- handled by this function, see |v:stderr|. +--- +--- Close the stdio handles with |chanclose()|. Use |chansend()| +--- to send data to stdout, and |rpcrequest()| and |rpcnotify()| +--- to communicate over RPC. +--- +--- {opts} is a dictionary with these keys: +--- |on_stdin| : callback invoked when stdin is written to. +--- on_print : callback invoked when Nvim needs to print a +--- message, with the message (whose type is string) +--- as sole argument. +--- stdin_buffered : read stdin in |channel-buffered| mode. +--- rpc : If set, |msgpack-rpc| will be used to communicate +--- over stdio +--- Returns: +--- - |channel-id| on success (value is always 1) +--- - 0 on invalid arguments +--- +--- @param opts table +--- @return any +function vim.fn.stdioopen(opts) end + +--- Returns |standard-path| locations of various default files and +--- directories. +--- +--- {what} Type Description ~ +--- cache String Cache directory: arbitrary temporary +--- storage for plugins, etc. +--- config String User configuration directory. |init.vim| +--- is stored here. +--- config_dirs List Other configuration directories. +--- data String User data directory. +--- data_dirs List Other data directories. +--- log String Logs directory (for use by plugins too). +--- run String Run directory: temporary, local storage +--- for sockets, named pipes, etc. +--- state String Session state directory: storage for file +--- drafts, swap, undo, |shada|. +--- +--- Example: >vim +--- echo stdpath("config") +--- < +--- +--- @param what 'cache'|'config'|'config_dirs'|'data'|'data_dirs'|'log'|'run'|'state' +--- @return string|string[] +function vim.fn.stdpath(what) end + +--- Convert String {string} to a Float. This mostly works the +--- same as when using a floating point number in an expression, +--- see |floating-point-format|. But it's a bit more permissive. +--- E.g., "1e40" is accepted, while in an expression you need to +--- write "1.0e40". The hexadecimal form "0x123" is also +--- accepted, but not others, like binary or octal. +--- When {quoted} is present and non-zero then embedded single +--- quotes before the dot are ignored, thus "1'000.0" is a +--- thousand. +--- Text after the number is silently ignored. +--- The decimal point is always '.', no matter what the locale is +--- set to. A comma ends the number: "12,345.67" is converted to +--- 12.0. You can strip out thousands separators with +--- |substitute()|: >vim +--- let f = str2float(substitute(text, ',', '', 'g')) +--- < +--- Returns 0.0 if the conversion fails. +--- +--- @param string string +--- @param quoted? any +--- @return any +function vim.fn.str2float(string, quoted) end + +--- Return a list containing the number values which represent +--- each character in String {string}. Examples: >vim +--- echo str2list(" ") " returns [32] +--- echo str2list("ABC") " returns [65, 66, 67] +--- <|list2str()| does the opposite. +--- +--- UTF-8 encoding is always used, {utf8} option has no effect, +--- and exists only for backwards-compatibility. +--- With UTF-8 composing characters are handled properly: >vim +--- echo str2list("á") " returns [97, 769] +--- +--- @param string string +--- @param utf8? any +--- @return any +function vim.fn.str2list(string, utf8) end + +--- Convert string {string} to a number. +--- {base} is the conversion base, it can be 2, 8, 10 or 16. +--- When {quoted} is present and non-zero then embedded single +--- quotes are ignored, thus "1'000'000" is a million. +--- +--- When {base} is omitted base 10 is used. This also means that +--- a leading zero doesn't cause octal conversion to be used, as +--- with the default String to Number conversion. Example: >vim +--- let nr = str2nr('0123') +--- < +--- When {base} is 16 a leading "0x" or "0X" is ignored. With a +--- different base the result will be zero. Similarly, when +--- {base} is 8 a leading "0", "0o" or "0O" is ignored, and when +--- {base} is 2 a leading "0b" or "0B" is ignored. +--- Text after the number is silently ignored. +--- +--- Returns 0 if {string} is empty or on error. +--- +--- @param string string +--- @param base? any +--- @return any +function vim.fn.str2nr(string, base) end + +--- The result is a Number, which is the number of characters +--- in String {string}. Composing characters are ignored. +--- |strchars()| can count the number of characters, counting +--- composing characters separately. +--- +--- Returns 0 if {string} is empty or on error. +--- +--- Also see |strlen()|, |strdisplaywidth()| and |strwidth()|. +--- +--- @param string string +--- @return any +function vim.fn.strcharlen(string) end + +--- Like |strpart()| but using character index and length instead +--- of byte index and length. +--- When {skipcc} is omitted or zero, composing characters are +--- counted separately. +--- When {skipcc} set to 1, Composing characters are ignored, +--- similar to |slice()|. +--- When a character index is used where a character does not +--- exist it is omitted and counted as one character. For +--- example: >vim +--- echo strcharpart('abc', -1, 2) +--- <results in 'a'. +--- +--- Returns an empty string on error. +--- +--- @param src any +--- @param start any +--- @param len? any +--- @param skipcc? any +--- @return any +function vim.fn.strcharpart(src, start, len, skipcc) end + +--- The result is a Number, which is the number of characters +--- in String {string}. +--- When {skipcc} is omitted or zero, composing characters are +--- counted separately. +--- When {skipcc} set to 1, Composing characters are ignored. +--- |strcharlen()| always does this. +--- +--- Returns zero on error. +--- +--- Also see |strlen()|, |strdisplaywidth()| and |strwidth()|. +--- +--- {skipcc} is only available after 7.4.755. For backward +--- compatibility, you can define a wrapper function: >vim +--- if has("patch-7.4.755") +--- function s:strchars(str, skipcc) +--- return strchars(a:str, a:skipcc) +--- endfunction +--- else +--- function s:strchars(str, skipcc) +--- if a:skipcc +--- return strlen(substitute(a:str, ".", "x", "g")) +--- else +--- return strchars(a:str) +--- endif +--- endfunction +--- endif +--- < +--- +--- @param string string +--- @param skipcc? any +--- @return integer +function vim.fn.strchars(string, skipcc) end + +--- The result is a Number, which is the number of display cells +--- String {string} occupies on the screen when it starts at {col} +--- (first column is zero). When {col} is omitted zero is used. +--- Otherwise it is the screen column where to start. This +--- matters for Tab characters. +--- The option settings of the current window are used. This +--- matters for anything that's displayed differently, such as +--- 'tabstop' and 'display'. +--- When {string} contains characters with East Asian Width Class +--- Ambiguous, this function's return value depends on 'ambiwidth'. +--- Returns zero on error. +--- Also see |strlen()|, |strwidth()| and |strchars()|. +--- +--- @param string string +--- @param col? integer +--- @return integer +function vim.fn.strdisplaywidth(string, col) end + +--- The result is a String, which is a formatted date and time, as +--- specified by the {format} string. The given {time} is used, +--- or the current time if no time is given. The accepted +--- {format} depends on your system, thus this is not portable! +--- See the manual page of the C function strftime() for the +--- format. The maximum length of the result is 80 characters. +--- See also |localtime()|, |getftime()| and |strptime()|. +--- The language can be changed with the |:language| command. +--- Examples: >vim +--- echo strftime("%c") " Sun Apr 27 11:49:23 1997 +--- echo strftime("%Y %b %d %X") " 1997 Apr 27 11:53:25 +--- echo strftime("%y%m%d %T") " 970427 11:53:55 +--- echo strftime("%H:%M") " 11:55 +--- echo strftime("%c", getftime("file.c")) +--- " Show mod time of file.c. +--- +--- @param format any +--- @param time? any +--- @return string +function vim.fn.strftime(format, time) end + +--- Get a Number corresponding to the character at {index} in +--- {str}. This uses a zero-based character index, not a byte +--- index. Composing characters are considered separate +--- characters here. Use |nr2char()| to convert the Number to a +--- String. +--- Returns -1 if {index} is invalid. +--- Also see |strcharpart()| and |strchars()|. +--- +--- @param str string +--- @param index integer +--- @return integer +function vim.fn.strgetchar(str, index) end + +--- The result is a Number, which gives the byte index in +--- {haystack} of the first occurrence of the String {needle}. +--- If {start} is specified, the search starts at index {start}. +--- This can be used to find a second match: >vim +--- let colon1 = stridx(line, ":") +--- let colon2 = stridx(line, ":", colon1 + 1) +--- <The search is done case-sensitive. +--- For pattern searches use |match()|. +--- -1 is returned if the {needle} does not occur in {haystack}. +--- See also |strridx()|. +--- Examples: >vim +--- echo stridx("An Example", "Example") " 3 +--- echo stridx("Starting point", "Start") " 0 +--- echo stridx("Starting point", "start") " -1 +--- < *strstr()* *strchr()* +--- stridx() works similar to the C function strstr(). When used +--- with a single character it works similar to strchr(). +--- +--- @param haystack string +--- @param needle string +--- @param start? integer +--- @return integer +function vim.fn.stridx(haystack, needle, start) end + +--- Return {expr} converted to a String. If {expr} is a Number, +--- Float, String, Blob or a composition of them, then the result +--- can be parsed back with |eval()|. +--- {expr} type result ~ +--- String 'string' +--- Number 123 +--- Float 123.123456 or 1.123456e8 or +--- `str2float('inf')` +--- Funcref `function('name')` +--- Blob 0z00112233.44556677.8899 +--- List [item, item] +--- Dictionary `{key: value, key: value}` +--- Note that in String values the ' character is doubled. +--- Also see |strtrans()|. +--- Note 2: Output format is mostly compatible with YAML, except +--- for infinite and NaN floating-point values representations +--- which use |str2float()|. Strings are also dumped literally, +--- only single quote is escaped, which does not allow using YAML +--- for parsing back binary strings. |eval()| should always work for +--- strings and floats though and this is the only official +--- method, use |msgpackdump()| or |json_encode()| if you need to +--- share data with other application. +--- +--- @param expr any +--- @return string +function vim.fn.string(expr) end + +--- The result is a Number, which is the length of the String +--- {string} in bytes. +--- If the argument is a Number it is first converted to a String. +--- For other types an error is given and zero is returned. +--- If you want to count the number of multibyte characters use +--- |strchars()|. +--- Also see |len()|, |strdisplaywidth()| and |strwidth()|. +--- +--- @param string string +--- @return integer +function vim.fn.strlen(string) end + +--- The result is a String, which is part of {src}, starting from +--- byte {start}, with the byte length {len}. +--- When {chars} is present and TRUE then {len} is the number of +--- characters positions (composing characters are not counted +--- separately, thus "1" means one base character and any +--- following composing characters). +--- To count {start} as characters instead of bytes use +--- |strcharpart()|. +--- +--- When bytes are selected which do not exist, this doesn't +--- result in an error, the bytes are simply omitted. +--- If {len} is missing, the copy continues from {start} till the +--- end of the {src}. >vim +--- echo strpart("abcdefg", 3, 2) " returns 'de' +--- echo strpart("abcdefg", -2, 4) " returns 'ab' +--- echo strpart("abcdefg", 5, 4) " returns 'fg' +--- echo strpart("abcdefg", 3) " returns 'defg' +--- +--- <Note: To get the first character, {start} must be 0. For +--- example, to get the character under the cursor: >vim +--- strpart(getline("."), col(".") - 1, 1, v:true) +--- < +--- Returns an empty string on error. +--- +--- @param src string +--- @param start integer +--- @param len? integer +--- @param chars? 0|1 +--- @return string +function vim.fn.strpart(src, start, len, chars) end + +--- The result is a Number, which is a unix timestamp representing +--- the date and time in {timestring}, which is expected to match +--- the format specified in {format}. +--- +--- The accepted {format} depends on your system, thus this is not +--- portable! See the manual page of the C function strptime() +--- for the format. Especially avoid "%c". The value of $TZ also +--- matters. +--- +--- If the {timestring} cannot be parsed with {format} zero is +--- returned. If you do not know the format of {timestring} you +--- can try different {format} values until you get a non-zero +--- result. +--- +--- See also |strftime()|. +--- Examples: >vim +--- echo strptime("%Y %b %d %X", "1997 Apr 27 11:49:23") +--- < 862156163 >vim +--- echo strftime("%c", strptime("%y%m%d %T", "970427 11:53:55")) +--- < Sun Apr 27 11:53:55 1997 >vim +--- echo strftime("%c", strptime("%Y%m%d%H%M%S", "19970427115355") + 3600) +--- < Sun Apr 27 12:53:55 1997 +--- +--- @param format string +--- @param timestring string +--- @return integer +function vim.fn.strptime(format, timestring) end + +--- The result is a Number, which gives the byte index in +--- {haystack} of the last occurrence of the String {needle}. +--- When {start} is specified, matches beyond this index are +--- ignored. This can be used to find a match before a previous +--- match: >vim +--- let lastcomma = strridx(line, ",") +--- let comma2 = strridx(line, ",", lastcomma - 1) +--- <The search is done case-sensitive. +--- For pattern searches use |match()|. +--- -1 is returned if the {needle} does not occur in {haystack}. +--- If the {needle} is empty the length of {haystack} is returned. +--- See also |stridx()|. Examples: >vim +--- echo strridx("an angry armadillo", "an") 3 +--- < *strrchr()* +--- When used with a single character it works similar to the C +--- function strrchr(). +--- +--- @param haystack string +--- @param needle string +--- @param start? integer +--- @return integer +function vim.fn.strridx(haystack, needle, start) end + +--- The result is a String, which is {string} with all unprintable +--- characters translated into printable characters |'isprint'|. +--- Like they are shown in a window. Example: >vim +--- echo strtrans(\@a) +--- <This displays a newline in register a as "^\@" instead of +--- starting a new line. +--- +--- Returns an empty string on error. +--- +--- @param string string +--- @return string +function vim.fn.strtrans(string) end + +--- The result is a Number, which is the number of UTF-16 code +--- units in String {string} (after converting it to UTF-16). +--- +--- When {countcc} is TRUE, composing characters are counted +--- separately. +--- When {countcc} is omitted or FALSE, composing characters are +--- ignored. +--- +--- Returns zero on error. +--- +--- Also see |strlen()| and |strcharlen()|. +--- Examples: >vim +--- echo strutf16len('a') " returns 1 +--- echo strutf16len('©') " returns 1 +--- echo strutf16len('😊') " returns 2 +--- echo strutf16len('ą́') " returns 1 +--- echo strutf16len('ą́', v:true) " returns 3 +--- < +--- +--- @param string string +--- @param countcc? 0|1 +--- @return integer +function vim.fn.strutf16len(string, countcc) end + +--- The result is a Number, which is the number of display cells +--- String {string} occupies. A Tab character is counted as one +--- cell, alternatively use |strdisplaywidth()|. +--- When {string} contains characters with East Asian Width Class +--- Ambiguous, this function's return value depends on 'ambiwidth'. +--- Returns zero on error. +--- Also see |strlen()|, |strdisplaywidth()| and |strchars()|. +--- +--- @param string string +--- @return integer +function vim.fn.strwidth(string) end + +--- Only for an expression in a |:substitute| command or +--- substitute() function. +--- Returns the {nr}th submatch of the matched text. When {nr} +--- is 0 the whole matched text is returned. +--- Note that a NL in the string can stand for a line break of a +--- multi-line match or a NUL character in the text. +--- Also see |sub-replace-expression|. +--- +--- If {list} is present and non-zero then submatch() returns +--- a list of strings, similar to |getline()| with two arguments. +--- NL characters in the text represent NUL characters in the +--- text. +--- Only returns more than one item for |:substitute|, inside +--- |substitute()| this list will always contain one or zero +--- items, since there are no real line breaks. +--- +--- When substitute() is used recursively only the submatches in +--- the current (deepest) call can be obtained. +--- +--- Returns an empty string or list on error. +--- +--- Examples: >vim +--- s/\d\+/\=submatch(0) + 1/ +--- echo substitute(text, '\d\+', '\=submatch(0) + 1', '') +--- <This finds the first number in the line and adds one to it. +--- A line break is included as a newline character. +--- +--- @param nr integer +--- @param list? integer +--- @return string|string[] +function vim.fn.submatch(nr, list) end + +--- The result is a String, which is a copy of {string}, in which +--- the first match of {pat} is replaced with {sub}. +--- When {flags} is "g", all matches of {pat} in {string} are +--- replaced. Otherwise {flags} should be "". +--- +--- This works like the ":substitute" command (without any flags). +--- But the matching with {pat} is always done like the 'magic' +--- option is set and 'cpoptions' is empty (to make scripts +--- portable). 'ignorecase' is still relevant, use |/\c| or |/\C| +--- if you want to ignore or match case and ignore 'ignorecase'. +--- 'smartcase' is not used. See |string-match| for how {pat} is +--- used. +--- +--- A "~" in {sub} is not replaced with the previous {sub}. +--- Note that some codes in {sub} have a special meaning +--- |sub-replace-special|. For example, to replace something with +--- "\n" (two characters), use "\\\\n" or '\\n'. +--- +--- When {pat} does not match in {string}, {string} is returned +--- unmodified. +--- +--- Example: >vim +--- let &path = substitute(&path, ",\\=[^,]*$", "", "") +--- <This removes the last component of the 'path' option. >vim +--- echo substitute("testing", ".*", "\\U\\0", "") +--- <results in "TESTING". +--- +--- When {sub} starts with "\=", the remainder is interpreted as +--- an expression. See |sub-replace-expression|. Example: >vim +--- echo substitute(s, '%\(\x\x\)', +--- \ '\=nr2char("0x" .. submatch(1))', 'g') +--- +--- <When {sub} is a Funcref that function is called, with one +--- optional argument. Example: >vim +--- echo substitute(s, '%\(\x\x\)', SubNr, 'g') +--- <The optional argument is a list which contains the whole +--- matched string and up to nine submatches, like what +--- |submatch()| returns. Example: >vim +--- echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g') +--- +--- <Returns an empty string on error. +--- +--- @param string string +--- @param pat string +--- @param sub string +--- @param flags string +--- @return string +function vim.fn.substitute(string, pat, sub, flags) end + +--- Returns a list of swap file names, like what "vim -r" shows. +--- See the |-r| command argument. The 'directory' option is used +--- for the directories to inspect. If you only want to get a +--- list of swap files in the current directory then temporarily +--- set 'directory' to a dot: >vim +--- let save_dir = &directory +--- let &directory = '.' +--- let swapfiles = swapfilelist() +--- let &directory = save_dir +--- +--- @return string[] +function vim.fn.swapfilelist() end + +--- The result is a dictionary, which holds information about the +--- swapfile {fname}. The available fields are: +--- version Vim version +--- user user name +--- host host name +--- fname original file name +--- pid PID of the Nvim process that created the swap +--- file, or zero if not running. +--- mtime last modification time in seconds +--- inode Optional: INODE number of the file +--- dirty 1 if file was modified, 0 if not +--- In case of failure an "error" item is added with the reason: +--- Cannot open file: file not found or in accessible +--- Cannot read file: cannot read first block +--- Not a swap file: does not contain correct block ID +--- Magic number mismatch: Info in first block is invalid +--- +--- @param fname string +--- @return any +function vim.fn.swapinfo(fname) end + +--- The result is the swap file path of the buffer {buf}. +--- For the use of {buf}, see |bufname()| above. +--- If buffer {buf} is the current buffer, the result is equal to +--- |:swapname| (unless there is no swap file). +--- If buffer {buf} has no swap file, returns an empty string. +--- +--- @param buf integer|string +--- @return string +function vim.fn.swapname(buf) end + +--- The result is a Number, which is the syntax ID at the position +--- {lnum} and {col} in the current window. +--- The syntax ID can be used with |synIDattr()| and +--- |synIDtrans()| to obtain syntax information about text. +--- +--- {col} is 1 for the leftmost column, {lnum} is 1 for the first +--- line. 'synmaxcol' applies, in a longer line zero is returned. +--- Note that when the position is after the last character, +--- that's where the cursor can be in Insert mode, synID() returns +--- zero. {lnum} is used like with |getline()|. +--- +--- When {trans} is |TRUE|, transparent items are reduced to the +--- item that they reveal. This is useful when wanting to know +--- the effective color. When {trans} is |FALSE|, the transparent +--- item is returned. This is useful when wanting to know which +--- syntax item is effective (e.g. inside parens). +--- Warning: This function can be very slow. Best speed is +--- obtained by going through the file in forward direction. +--- +--- Returns zero on error. +--- +--- Example (echoes the name of the syntax item under the cursor): >vim +--- echo synIDattr(synID(line("."), col("."), 1), "name") +--- < +--- +--- @param lnum integer +--- @param col integer +--- @param trans 0|1 +--- @return integer +function vim.fn.synID(lnum, col, trans) end + +--- The result is a String, which is the {what} attribute of +--- syntax ID {synID}. This can be used to obtain information +--- about a syntax item. +--- {mode} can be "gui" or "cterm", to get the attributes +--- for that mode. When {mode} is omitted, or an invalid value is +--- used, the attributes for the currently active highlighting are +--- used (GUI or cterm). +--- Use synIDtrans() to follow linked highlight groups. +--- {what} result +--- "name" the name of the syntax item +--- "fg" foreground color (GUI: color name used to set +--- the color, cterm: color number as a string, +--- term: empty string) +--- "bg" background color (as with "fg") +--- "font" font name (only available in the GUI) +--- |highlight-font| +--- "sp" special color (as with "fg") |guisp| +--- "fg#" like "fg", but for the GUI and the GUI is +--- running the name in "#RRGGBB" form +--- "bg#" like "fg#" for "bg" +--- "sp#" like "fg#" for "sp" +--- "bold" "1" if bold +--- "italic" "1" if italic +--- "reverse" "1" if reverse +--- "inverse" "1" if inverse (= reverse) +--- "standout" "1" if standout +--- "underline" "1" if underlined +--- "undercurl" "1" if undercurled +--- "underdouble" "1" if double underlined +--- "underdotted" "1" if dotted underlined +--- "underdashed" "1" if dashed underlined +--- "strikethrough" "1" if struckthrough +--- "altfont" "1" if alternative font +--- "nocombine" "1" if nocombine +--- +--- Returns an empty string on error. +--- +--- Example (echoes the color of the syntax item under the +--- cursor): >vim +--- echo synIDattr(synIDtrans(synID(line("."), col("."), 1)), "fg") +--- < +--- Can also be used as a |method|: >vim +--- echo synID(line("."), col("."), 1)->synIDtrans()->synIDattr("fg") +--- < +--- +--- @param synID integer +--- @param what string +--- @param mode? string +--- @return string +function vim.fn.synIDattr(synID, what, mode) end + +--- The result is a Number, which is the translated syntax ID of +--- {synID}. This is the syntax group ID of what is being used to +--- highlight the character. Highlight links given with +--- ":highlight link" are followed. +--- +--- Returns zero on error. +--- +--- @param synID integer +--- @return integer +function vim.fn.synIDtrans(synID) end + +--- The result is a |List| with currently three items: +--- 1. The first item in the list is 0 if the character at the +--- position {lnum} and {col} is not part of a concealable +--- region, 1 if it is. {lnum} is used like with |getline()|. +--- 2. The second item in the list is a string. If the first item +--- is 1, the second item contains the text which will be +--- displayed in place of the concealed text, depending on the +--- current setting of 'conceallevel' and 'listchars'. +--- 3. The third and final item in the list is a number +--- representing the specific syntax region matched in the +--- line. When the character is not concealed the value is +--- zero. This allows detection of the beginning of a new +--- concealable region if there are two consecutive regions +--- with the same replacement character. For an example, if +--- the text is "123456" and both "23" and "45" are concealed +--- and replaced by the character "X", then: +--- call returns ~ +--- synconcealed(lnum, 1) [0, '', 0] +--- synconcealed(lnum, 2) [1, 'X', 1] +--- synconcealed(lnum, 3) [1, 'X', 1] +--- synconcealed(lnum, 4) [1, 'X', 2] +--- synconcealed(lnum, 5) [1, 'X', 2] +--- synconcealed(lnum, 6) [0, '', 0] +--- +--- @param lnum integer +--- @param col integer +--- @return {[1]: integer, [2]: string, [3]: integer}[] +function vim.fn.synconcealed(lnum, col) end + +--- Return a |List|, which is the stack of syntax items at the +--- position {lnum} and {col} in the current window. {lnum} is +--- used like with |getline()|. Each item in the List is an ID +--- like what |synID()| returns. +--- The first item in the List is the outer region, following are +--- items contained in that one. The last one is what |synID()| +--- returns, unless not the whole item is highlighted or it is a +--- transparent item. +--- This function is useful for debugging a syntax file. +--- Example that shows the syntax stack under the cursor: >vim +--- for id in synstack(line("."), col(".")) +--- echo synIDattr(id, "name") +--- endfor +--- <When the position specified with {lnum} and {col} is invalid +--- an empty list is returned. The position just after the last +--- character in a line and the first column in an empty line are +--- valid positions. +--- +--- @param lnum integer +--- @param col integer +--- @return integer[] +function vim.fn.synstack(lnum, col) end + +--- Note: Prefer |vim.system()| in Lua. +--- +--- Gets the output of {cmd} as a |string| (|systemlist()| returns +--- a |List|) and sets |v:shell_error| to the error code. +--- {cmd} is treated as in |jobstart()|: +--- If {cmd} is a List it runs directly (no 'shell'). +--- If {cmd} is a String it runs in the 'shell', like this: >vim +--- call jobstart(split(&shell) + split(&shellcmdflag) + ['{cmd}']) +--- +--- <Not to be used for interactive commands. +--- +--- Result is a String, filtered to avoid platform-specific quirks: +--- - <CR><NL> is replaced with <NL> +--- - NUL characters are replaced with SOH (0x01) +--- +--- Example: >vim +--- echo system(['ls', expand('%:h')]) +--- +--- <If {input} is a string it is written to a pipe and passed as +--- stdin to the command. The string is written as-is, line +--- separators are not changed. +--- If {input} is a |List| it is written to the pipe as +--- |writefile()| does with {binary} set to "b" (i.e. with +--- a newline between each list item, and newlines inside list +--- items converted to NULs). +--- When {input} is given and is a valid buffer id, the content of +--- the buffer is written to the file line by line, each line +--- terminated by NL (and NUL where the text has NL). +--- *E5677* +--- Note: system() cannot write to or read from backgrounded ("&") +--- shell commands, e.g.: >vim +--- echo system("cat - &", "foo") +--- <which is equivalent to: > +--- $ echo foo | bash -c 'cat - &' +--- <The pipes are disconnected (unless overridden by shell +--- redirection syntax) before input can reach it. Use +--- |jobstart()| instead. +--- +--- Note: Use |shellescape()| or |::S| with |expand()| or +--- |fnamemodify()| to escape special characters in a command +--- argument. 'shellquote' and 'shellxquote' must be properly +--- configured. Example: >vim +--- echo system('ls '..shellescape(expand('%:h'))) +--- echo system('ls '..expand('%:h:S')) +--- +--- <Unlike ":!cmd" there is no automatic check for changed files. +--- Use |:checktime| to force a check. +--- +--- @param cmd string|string[] +--- @param input? string|string[]|integer +--- @return string +function vim.fn.system(cmd, input) end + +--- Same as |system()|, but returns a |List| with lines (parts of +--- output separated by NL) with NULs transformed into NLs. Output +--- is the same as |readfile()| will output with {binary} argument +--- set to "b", except that a final newline is not preserved, +--- unless {keepempty} is non-zero. +--- Note that on MS-Windows you may get trailing CR characters. +--- +--- To see the difference between "echo hello" and "echo -n hello" +--- use |system()| and |split()|: >vim +--- echo split(system('echo hello'), '\n', 1) +--- < +--- Returns an empty string on error. +--- +--- @param cmd string|string[] +--- @param input? string|string[]|integer +--- @param keepempty? integer +--- @return string[] +function vim.fn.systemlist(cmd, input, keepempty) end + +--- The result is a |List|, where each item is the number of the +--- buffer associated with each window in the current tab page. +--- {arg} specifies the number of the tab page to be used. When +--- omitted the current tab page is used. +--- When {arg} is invalid the number zero is returned. +--- To get a list of all buffers in all tabs use this: >vim +--- let buflist = [] +--- for i in range(tabpagenr('$')) +--- call extend(buflist, tabpagebuflist(i + 1)) +--- endfor +--- <Note that a buffer may appear in more than one window. +--- +--- @param arg? any +--- @return any +function vim.fn.tabpagebuflist(arg) end + +--- The result is a Number, which is the number of the current +--- tab page. The first tab page has number 1. +--- +--- The optional argument {arg} supports the following values: +--- $ the number of the last tab page (the tab page +--- count). +--- # the number of the last accessed tab page +--- (where |g<Tab>| goes to). If there is no +--- previous tab page, 0 is returned. +--- The number can be used with the |:tab| command. +--- +--- Returns zero on error. +--- +--- @param arg? '$'|'#' +--- @return integer +function vim.fn.tabpagenr(arg) end + +--- Like |winnr()| but for tab page {tabarg}. +--- {tabarg} specifies the number of tab page to be used. +--- {arg} is used like with |winnr()|: +--- - When omitted the current window number is returned. This is +--- the window which will be used when going to this tab page. +--- - When "$" the number of windows is returned. +--- - When "#" the previous window nr is returned. +--- Useful examples: >vim +--- tabpagewinnr(1) " current window of tab page 1 +--- tabpagewinnr(4, '$') " number of windows in tab page 4 +--- <When {tabarg} is invalid zero is returned. +--- +--- @param tabarg integer +--- @param arg? '$'|'#' +--- @return integer +function vim.fn.tabpagewinnr(tabarg, arg) end + +--- Returns a |List| with the file names used to search for tags +--- for the current buffer. This is the 'tags' option expanded. +--- +--- @return string[] +function vim.fn.tagfiles() end + +--- Returns a |List| of tags matching the regular expression {expr}. +--- +--- If {filename} is passed it is used to prioritize the results +--- in the same way that |:tselect| does. See |tag-priority|. +--- {filename} should be the full path of the file. +--- +--- Each list item is a dictionary with at least the following +--- entries: +--- name Name of the tag. +--- filename Name of the file where the tag is +--- defined. It is either relative to the +--- current directory or a full path. +--- cmd Ex command used to locate the tag in +--- the file. +--- kind Type of the tag. The value for this +--- entry depends on the language specific +--- kind values. Only available when +--- using a tags file generated by +--- Universal/Exuberant ctags or hdrtag. +--- static A file specific tag. Refer to +--- |static-tag| for more information. +--- More entries may be present, depending on the content of the +--- tags file: access, implementation, inherits and signature. +--- Refer to the ctags documentation for information about these +--- fields. For C code the fields "struct", "class" and "enum" +--- may appear, they give the name of the entity the tag is +--- contained in. +--- +--- The ex-command "cmd" can be either an ex search pattern, a +--- line number or a line number followed by a byte number. +--- +--- If there are no matching tags, then an empty list is returned. +--- +--- To get an exact tag match, the anchors '^' and '$' should be +--- used in {expr}. This also make the function work faster. +--- Refer to |tag-regexp| for more information about the tag +--- search regular expression pattern. +--- +--- Refer to |'tags'| for information about how the tags file is +--- located by Vim. Refer to |tags-file-format| for the format of +--- the tags file generated by the different ctags tools. +--- +--- @param expr any +--- @param filename? string +--- @return any +function vim.fn.taglist(expr, filename) end + +--- Return the tangent of {expr}, measured in radians, as a |Float| +--- in the range [-inf, inf]. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo tan(10) +--- < 0.648361 >vim +--- echo tan(-4.01) +--- < -1.181502 +--- +--- @param expr number +--- @return number +function vim.fn.tan(expr) end + +--- Return the hyperbolic tangent of {expr} as a |Float| in the +--- range [-1, 1]. +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo tanh(0.5) +--- < 0.462117 >vim +--- echo tanh(-1) +--- < -0.761594 +--- +--- @param expr number +--- @return number +function vim.fn.tanh(expr) end + +--- Generates a (non-existent) filename located in the Nvim root +--- |tempdir|. Scripts can use the filename as a temporary file. +--- Example: >vim +--- let tmpfile = tempname() +--- exe "redir > " .. tmpfile +--- < +--- +--- @return string +function vim.fn.tempname() end + +--- Spawns {cmd} in a new pseudo-terminal session connected +--- to the current (unmodified) buffer. Parameters and behavior +--- are the same as |jobstart()| except "pty", "width", "height", +--- and "TERM" are ignored: "height" and "width" are taken from +--- the current window. Note that termopen() implies a "pty" arg +--- to jobstart(), and thus has the implications documented at +--- |jobstart()|. +--- +--- Returns the same values as jobstart(). +--- +--- Terminal environment is initialized as in |jobstart-env|, +--- except $TERM is set to "xterm-256color". Full behavior is +--- described in |terminal|. +--- +--- @param cmd any +--- @param opts? table +--- @return any +function vim.fn.termopen(cmd, opts) end + +--- Return a list with information about timers. +--- When {id} is given only information about this timer is +--- returned. When timer {id} does not exist an empty list is +--- returned. +--- When {id} is omitted information about all timers is returned. +--- +--- For each timer the information is stored in a |Dictionary| with +--- these items: +--- "id" the timer ID +--- "time" time the timer was started with +--- "repeat" number of times the timer will still fire; +--- -1 means forever +--- "callback" the callback +--- +--- @param id? any +--- @return any +function vim.fn.timer_info(id) end + +--- Pause or unpause a timer. A paused timer does not invoke its +--- callback when its time expires. Unpausing a timer may cause +--- the callback to be invoked almost immediately if enough time +--- has passed. +--- +--- Pausing a timer is useful to avoid the callback to be called +--- for a short time. +--- +--- If {paused} evaluates to a non-zero Number or a non-empty +--- String, then the timer is paused, otherwise it is unpaused. +--- See |non-zero-arg|. +--- +--- @param timer any +--- @param paused any +--- @return any +function vim.fn.timer_pause(timer, paused) end + +--- Create a timer and return the timer ID. +--- +--- {time} is the waiting time in milliseconds. This is the +--- minimum time before invoking the callback. When the system is +--- busy or Vim is not waiting for input the time will be longer. +--- Zero can be used to execute the callback when Vim is back in +--- the main loop. +--- +--- {callback} is the function to call. It can be the name of a +--- function or a |Funcref|. It is called with one argument, which +--- is the timer ID. The callback is only invoked when Vim is +--- waiting for input. +--- +--- {options} is a dictionary. Supported entries: +--- "repeat" Number of times to repeat the callback. +--- -1 means forever. Default is 1. +--- If the timer causes an error three times in a +--- row the repeat is cancelled. +--- +--- Returns -1 on error. +--- +--- Example: >vim +--- func MyHandler(timer) +--- echo 'Handler called' +--- endfunc +--- let timer = timer_start(500, 'MyHandler', +--- \ {'repeat': 3}) +--- <This invokes MyHandler() three times at 500 msec intervals. +--- +--- @param time any +--- @param callback any +--- @param options? table +--- @return any +function vim.fn.timer_start(time, callback, options) end + +--- Stop a timer. The timer callback will no longer be invoked. +--- {timer} is an ID returned by timer_start(), thus it must be a +--- Number. If {timer} does not exist there is no error. +--- +--- @param timer any +--- @return any +function vim.fn.timer_stop(timer) end + +--- Stop all timers. The timer callbacks will no longer be +--- invoked. Useful if some timers is misbehaving. If there are +--- no timers there is no error. +--- +--- @return any +function vim.fn.timer_stopall() end + +--- The result is a copy of the String given, with all uppercase +--- characters turned into lowercase (just like applying |gu| to +--- the string). Returns an empty string on error. +--- +--- @param expr any +--- @return string +function vim.fn.tolower(expr) end + +--- The result is a copy of the String given, with all lowercase +--- characters turned into uppercase (just like applying |gU| to +--- the string). Returns an empty string on error. +--- +--- @param expr any +--- @return string +function vim.fn.toupper(expr) end + +--- The result is a copy of the {src} string with all characters +--- which appear in {fromstr} replaced by the character in that +--- position in the {tostr} string. Thus the first character in +--- {fromstr} is translated into the first character in {tostr} +--- and so on. Exactly like the unix "tr" command. +--- This code also deals with multibyte characters properly. +--- +--- Returns an empty string on error. +--- +--- Examples: >vim +--- echo tr("hello there", "ht", "HT") +--- <returns "Hello THere" >vim +--- echo tr("<blob>", "<>", "{}") +--- <returns "{blob}" +--- +--- @param src string +--- @param fromstr string +--- @param tostr string +--- @return string +function vim.fn.tr(src, fromstr, tostr) end + +--- Return {text} as a String where any character in {mask} is +--- removed from the beginning and/or end of {text}. +--- +--- If {mask} is not given, or is an empty string, {mask} is all +--- characters up to 0x20, which includes Tab, space, NL and CR, +--- plus the non-breaking space character 0xa0. +--- +--- The optional {dir} argument specifies where to remove the +--- characters: +--- 0 remove from the beginning and end of {text} +--- 1 remove only at the beginning of {text} +--- 2 remove only at the end of {text} +--- When omitted both ends are trimmed. +--- +--- This function deals with multibyte characters properly. +--- Returns an empty string on error. +--- +--- Examples: >vim +--- echo trim(" some text ") +--- <returns "some text" >vim +--- echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") .. "_TAIL" +--- <returns "RESERVE_TAIL" >vim +--- echo trim("rm<Xrm<>X>rrm", "rm<>") +--- <returns "Xrm<>X" (characters in the middle are not removed) >vim +--- echo trim(" vim ", " ", 2) +--- <returns " vim" +--- +--- @param text any +--- @param mask? string +--- @param dir? 0|1|2 +--- @return string +function vim.fn.trim(text, mask, dir) end + +--- Return the largest integral value with magnitude less than or +--- equal to {expr} as a |Float| (truncate towards zero). +--- {expr} must evaluate to a |Float| or a |Number|. +--- Returns 0.0 if {expr} is not a |Float| or a |Number|. +--- Examples: >vim +--- echo trunc(1.456) +--- < 1.0 >vim +--- echo trunc(-5.456) +--- < -5.0 >vim +--- echo trunc(4.0) +--- < 4.0 +--- +--- @param expr any +--- @return integer +function vim.fn.trunc(expr) end + +--- The result is a Number representing the type of {expr}. +--- Instead of using the number directly, it is better to use the +--- v:t_ variable that has the value: +--- Number: 0 |v:t_number| +--- String: 1 |v:t_string| +--- Funcref: 2 |v:t_func| +--- List: 3 |v:t_list| +--- Dictionary: 4 |v:t_dict| +--- Float: 5 |v:t_float| +--- Boolean: 6 |v:t_bool| (|v:false| and |v:true|) +--- Null: 7 (|v:null|) +--- Blob: 10 |v:t_blob| +--- For backward compatibility, this method can be used: >vim +--- if type(myvar) == type(0) | endif +--- if type(myvar) == type("") | endif +--- if type(myvar) == type(function("tr")) | endif +--- if type(myvar) == type([]) | endif +--- if type(myvar) == type({}) | endif +--- if type(myvar) == type(0.0) | endif +--- if type(myvar) == type(v:true) | endif +--- <In place of checking for |v:null| type it is better to check +--- for |v:null| directly as it is the only value of this type: >vim +--- if myvar is v:null | endif +--- <To check if the v:t_ variables exist use this: >vim +--- if exists('v:t_number') | endif +--- +--- @param expr any +--- @return integer +function vim.fn.type(expr) end + +--- Return the name of the undo file that would be used for a file +--- with name {name} when writing. This uses the 'undodir' +--- option, finding directories that exist. It does not check if +--- the undo file exists. +--- {name} is always expanded to the full path, since that is what +--- is used internally. +--- If {name} is empty undofile() returns an empty string, since a +--- buffer without a file name will not write an undo file. +--- Useful in combination with |:wundo| and |:rundo|. +--- +--- @param name string +--- @return string +function vim.fn.undofile(name) end + +--- Return the current state of the undo tree for the current +--- buffer, or for a specific buffer if {buf} is given. The +--- result is a dictionary with the following items: +--- "seq_last" The highest undo sequence number used. +--- "seq_cur" The sequence number of the current position in +--- the undo tree. This differs from "seq_last" +--- when some changes were undone. +--- "time_cur" Time last used for |:earlier| and related +--- commands. Use |strftime()| to convert to +--- something readable. +--- "save_last" Number of the last file write. Zero when no +--- write yet. +--- "save_cur" Number of the current position in the undo +--- tree. +--- "synced" Non-zero when the last undo block was synced. +--- This happens when waiting from input from the +--- user. See |undo-blocks|. +--- "entries" A list of dictionaries with information about +--- undo blocks. +--- +--- The first item in the "entries" list is the oldest undo item. +--- Each List item is a |Dictionary| with these items: +--- "seq" Undo sequence number. Same as what appears in +--- |:undolist|. +--- "time" Timestamp when the change happened. Use +--- |strftime()| to convert to something readable. +--- "newhead" Only appears in the item that is the last one +--- that was added. This marks the last change +--- and where further changes will be added. +--- "curhead" Only appears in the item that is the last one +--- that was undone. This marks the current +--- position in the undo tree, the block that will +--- be used by a redo command. When nothing was +--- undone after the last change this item will +--- not appear anywhere. +--- "save" Only appears on the last block before a file +--- write. The number is the write count. The +--- first write has number 1, the last one the +--- "save_last" mentioned above. +--- "alt" Alternate entry. This is again a List of undo +--- blocks. Each item may again have an "alt" +--- item. +--- +--- @param buf? integer|string +--- @return any +function vim.fn.undotree(buf) end + +--- Remove second and succeeding copies of repeated adjacent +--- {list} items in-place. Returns {list}. If you want a list +--- to remain unmodified make a copy first: >vim +--- let newlist = uniq(copy(mylist)) +--- <The default compare function uses the string representation of +--- each item. For the use of {func} and {dict} see |sort()|. +--- +--- Returns zero if {list} is not a |List|. +--- +--- @param list any +--- @param func? any +--- @param dict? any +--- @return any[]|0 +function vim.fn.uniq(list, func, dict) end + +--- Same as |charidx()| but returns the UTF-16 code unit index of +--- the byte at {idx} in {string} (after converting it to UTF-16). +--- +--- When {charidx} is present and TRUE, {idx} is used as the +--- character index in the String {string} instead of as the byte +--- index. +--- An {idx} in the middle of a UTF-8 sequence is rounded +--- downwards to the beginning of that sequence. +--- +--- Returns -1 if the arguments are invalid or if there are less +--- than {idx} bytes in {string}. If there are exactly {idx} bytes +--- the length of the string in UTF-16 code units is returned. +--- +--- See |byteidx()| and |byteidxcomp()| for getting the byte index +--- from the UTF-16 index and |charidx()| for getting the +--- character index from the UTF-16 index. +--- Refer to |string-offset-encoding| for more information. +--- Examples: >vim +--- echo utf16idx('a😊😊', 3) " returns 2 +--- echo utf16idx('a😊😊', 7) " returns 4 +--- echo utf16idx('a😊😊', 1, 0, 1) " returns 2 +--- echo utf16idx('a😊😊', 2, 0, 1) " returns 4 +--- echo utf16idx('aą́c', 6) " returns 2 +--- echo utf16idx('aą́c', 6, 1) " returns 4 +--- echo utf16idx('a😊😊', 9) " returns -1 +--- < +--- +--- @param string string +--- @param idx integer +--- @param countcc? any +--- @param charidx? any +--- @return integer +function vim.fn.utf16idx(string, idx, countcc, charidx) end + +--- Return a |List| with all the values of {dict}. The |List| is +--- in arbitrary order. Also see |items()| and |keys()|. +--- Returns zero if {dict} is not a |Dict|. +--- +--- @param dict any +--- @return any +function vim.fn.values(dict) end + +--- The result is a Number, which is the screen column of the file +--- position given with {expr}. That is, the last screen position +--- occupied by the character at that position, when the screen +--- would be of unlimited width. When there is a <Tab> at the +--- position, the returned Number will be the column at the end of +--- the <Tab>. For example, for a <Tab> in column 1, with 'ts' +--- set to 8, it returns 8. |conceal| is ignored. +--- For the byte position use |col()|. +--- +--- For the use of {expr} see |col()|. +--- +--- When 'virtualedit' is used {expr} can be [lnum, col, off], +--- where "off" is the offset in screen columns from the start of +--- the character. E.g., a position within a <Tab> or after the +--- last character. When "off" is omitted zero is used. When +--- Virtual editing is active in the current mode, a position +--- beyond the end of the line can be returned. Also see +--- |'virtualedit'| +--- +--- The accepted positions are: +--- . the cursor position +--- $ the end of the cursor line (the result is the +--- number of displayed characters in the cursor line +--- plus one) +--- 'x position of mark x (if the mark is not set, 0 is +--- returned) +--- v In Visual mode: the start of the Visual area (the +--- cursor is the end). When not in Visual mode +--- returns the cursor position. Differs from |'<| in +--- that it's updated right away. +--- +--- If {list} is present and non-zero then virtcol() returns a +--- List with the first and last screen position occupied by the +--- character. +--- +--- With the optional {winid} argument the values are obtained for +--- that window instead of the current window. +--- +--- Note that only marks in the current file can be used. +--- Examples: >vim +--- " With text "foo^Lbar" and cursor on the "^L": +--- +--- echo virtcol(".") " returns 5 +--- echo virtcol(".", 1) " returns [4, 5] +--- echo virtcol("$") " returns 9 +--- +--- " With text " there", with 't at 'h': +--- +--- echo virtcol("'t") " returns 6 +--- <The first column is 1. 0 or [0, 0] is returned for an error. +--- A more advanced example that echoes the maximum length of +--- all lines: >vim +--- echo max(map(range(1, line('$')), "virtcol([v:val, '$'])")) +--- +--- @param expr any +--- @param list? any +--- @param winid? integer +--- @return any +function vim.fn.virtcol(expr, list, winid) end + +--- The result is a Number, which is the byte index of the +--- character in window {winid} at buffer line {lnum} and virtual +--- column {col}. +--- +--- If buffer line {lnum} is an empty line, 0 is returned. +--- +--- If {col} is greater than the last virtual column in line +--- {lnum}, then the byte index of the character at the last +--- virtual column is returned. +--- +--- For a multi-byte character, the column number of the first +--- byte in the character is returned. +--- +--- The {winid} argument can be the window number or the +--- |window-ID|. If this is zero, then the current window is used. +--- +--- Returns -1 if the window {winid} doesn't exist or the buffer +--- line {lnum} or virtual column {col} is invalid. +--- +--- See also |screenpos()|, |virtcol()| and |col()|. +--- +--- @param winid integer +--- @param lnum integer +--- @param col integer +--- @return any +function vim.fn.virtcol2col(winid, lnum, col) end + +--- The result is a String, which describes the last Visual mode +--- used in the current buffer. Initially it returns an empty +--- string, but once Visual mode has been used, it returns "v", +--- "V", or "<CTRL-V>" (a single CTRL-V character) for +--- character-wise, line-wise, or block-wise Visual mode +--- respectively. +--- Example: >vim +--- exe "normal " .. visualmode() +--- <This enters the same Visual mode as before. It is also useful +--- in scripts if you wish to act differently depending on the +--- Visual mode that was used. +--- If Visual mode is active, use |mode()| to get the Visual mode +--- (e.g., in a |:vmap|). +--- If {expr} is supplied and it evaluates to a non-zero Number or +--- a non-empty String, then the Visual mode will be cleared and +--- the old value is returned. See |non-zero-arg|. +--- +--- @param expr? any +--- @return any +function vim.fn.visualmode(expr) end + +--- Waits until {condition} evaluates to |TRUE|, where {condition} +--- is a |Funcref| or |string| containing an expression. +--- +--- {timeout} is the maximum waiting time in milliseconds, -1 +--- means forever. +--- +--- Condition is evaluated on user events, internal events, and +--- every {interval} milliseconds (default: 200). +--- +--- Returns a status integer: +--- 0 if the condition was satisfied before timeout +--- -1 if the timeout was exceeded +--- -2 if the function was interrupted (by |CTRL-C|) +--- -3 if an error occurred +--- +--- @param timeout integer +--- @param condition any +--- @param interval? any +--- @return any +function vim.fn.wait(timeout, condition, interval) end + +--- Returns |TRUE| when the wildmenu is active and |FALSE| +--- otherwise. See 'wildmenu' and 'wildmode'. +--- This can be used in mappings to handle the 'wildcharm' option +--- gracefully. (Makes only sense with |mapmode-c| mappings). +--- +--- For example to make <c-j> work like <down> in wildmode, use: >vim +--- cnoremap <expr> <C-j> wildmenumode() ? "\<Down>\<Tab>" : "\<c-j>" +--- < +--- (Note, this needs the 'wildcharm' option set appropriately). +--- +--- @return any +function vim.fn.wildmenumode() end + +--- Like `execute()` but in the context of window {id}. +--- The window will temporarily be made the current window, +--- without triggering autocommands or changing directory. When +--- executing {command} autocommands will be triggered, this may +--- have unexpected side effects. Use `:noautocmd` if needed. +--- Example: >vim +--- call win_execute(winid, 'syntax enable') +--- <Doing the same with `setwinvar()` would not trigger +--- autocommands and not actually show syntax highlighting. +--- +--- When window {id} does not exist then no error is given and +--- an empty string is returned. +--- +--- @param id any +--- @param command any +--- @param silent? boolean +--- @return any +function vim.fn.win_execute(id, command, silent) end + +--- Returns a |List| with |window-ID|s for windows that contain +--- buffer {bufnr}. When there is none the list is empty. +--- +--- @param bufnr any +--- @return integer[] +function vim.fn.win_findbuf(bufnr) end + +--- Get the |window-ID| for the specified window. +--- When {win} is missing use the current window. +--- With {win} this is the window number. The top window has +--- number 1. +--- Without {tab} use the current tab, otherwise the tab with +--- number {tab}. The first tab has number one. +--- Return zero if the window cannot be found. +--- +--- @param win? any +--- @param tab? any +--- @return integer +function vim.fn.win_getid(win, tab) end + +--- Return the type of the window: +--- "autocmd" autocommand window. Temporary window +--- used to execute autocommands. +--- "command" command-line window |cmdwin| +--- (empty) normal window +--- "loclist" |location-list-window| +--- "popup" floating window |api-floatwin| +--- "preview" preview window |preview-window| +--- "quickfix" |quickfix-window| +--- "unknown" window {nr} not found +--- +--- When {nr} is omitted return the type of the current window. +--- When {nr} is given return the type of this window by number or +--- |window-ID|. +--- +--- Also see the 'buftype' option. +--- +--- @param nr? integer +--- @return 'autocmd'|'command'|''|'loclist'|'popup'|'preview'|'quickfix'|'unknown' +function vim.fn.win_gettype(nr) end + +--- Go to window with ID {expr}. This may also change the current +--- tabpage. +--- Return TRUE if successful, FALSE if the window cannot be found. +--- +--- @param expr any +--- @return 0|1 +function vim.fn.win_gotoid(expr) end + +--- Return a list with the tab number and window number of window +--- with ID {expr}: [tabnr, winnr]. +--- Return [0, 0] if the window cannot be found. +--- +--- @param expr any +--- @return any +function vim.fn.win_id2tabwin(expr) end + +--- Return the window number of window with ID {expr}. +--- Return 0 if the window cannot be found in the current tabpage. +--- +--- @param expr any +--- @return any +function vim.fn.win_id2win(expr) end + +--- Move window {nr}'s vertical separator (i.e., the right border) +--- by {offset} columns, as if being dragged by the mouse. {nr} +--- can be a window number or |window-ID|. A positive {offset} +--- moves right and a negative {offset} moves left. Moving a +--- window's vertical separator will change the width of the +--- window and the width of other windows adjacent to the vertical +--- separator. The magnitude of movement may be smaller than +--- specified (e.g., as a consequence of maintaining +--- 'winminwidth'). Returns TRUE if the window can be found and +--- FALSE otherwise. +--- This will fail for the rightmost window and a full-width +--- window, since it has no separator on the right. +--- Only works for the current tab page. *E1308* +--- +--- @param nr integer +--- @param offset any +--- @return any +function vim.fn.win_move_separator(nr, offset) end + +--- Move window {nr}'s status line (i.e., the bottom border) by +--- {offset} rows, as if being dragged by the mouse. {nr} can be a +--- window number or |window-ID|. A positive {offset} moves down +--- and a negative {offset} moves up. Moving a window's status +--- line will change the height of the window and the height of +--- other windows adjacent to the status line. The magnitude of +--- movement may be smaller than specified (e.g., as a consequence +--- of maintaining 'winminheight'). Returns TRUE if the window can +--- be found and FALSE otherwise. +--- Only works for the current tab page. +--- +--- @param nr integer +--- @param offset any +--- @return any +function vim.fn.win_move_statusline(nr, offset) end + +--- Return the screen position of window {nr} as a list with two +--- numbers: [row, col]. The first window always has position +--- [1, 1], unless there is a tabline, then it is [2, 1]. +--- {nr} can be the window number or the |window-ID|. Use zero +--- for the current window. +--- Returns [0, 0] if the window cannot be found in the current +--- tabpage. +--- +--- @param nr integer +--- @return any +function vim.fn.win_screenpos(nr) end + +--- Move the window {nr} to a new split of the window {target}. +--- This is similar to moving to {target}, creating a new window +--- using |:split| but having the same contents as window {nr}, and +--- then closing {nr}. +--- +--- Both {nr} and {target} can be window numbers or |window-ID|s. +--- Both must be in the current tab page. +--- +--- Returns zero for success, non-zero for failure. +--- +--- {options} is a |Dictionary| with the following optional entries: +--- "vertical" When TRUE, the split is created vertically, +--- like with |:vsplit|. +--- "rightbelow" When TRUE, the split is made below or to the +--- right (if vertical). When FALSE, it is done +--- above or to the left (if vertical). When not +--- present, the values of 'splitbelow' and +--- 'splitright' are used. +--- +--- @param nr integer +--- @param target any +--- @param options? table +--- @return any +function vim.fn.win_splitmove(nr, target, options) end + +--- The result is a Number, which is the number of the buffer +--- associated with window {nr}. {nr} can be the window number or +--- the |window-ID|. +--- When {nr} is zero, the number of the buffer in the current +--- window is returned. +--- When window {nr} doesn't exist, -1 is returned. +--- Example: >vim +--- echo "The file in the current window is " .. bufname(winbufnr(0)) +--- < +--- +--- @param nr integer +--- @return integer +function vim.fn.winbufnr(nr) end + +--- The result is a Number, which is the virtual column of the +--- cursor in the window. This is counting screen cells from the +--- left side of the window. The leftmost column is one. +--- +--- @return integer +function vim.fn.wincol() end + +--- The result is a String. For MS-Windows it indicates the OS +--- version. E.g, Windows 10 is "10.0", Windows 8 is "6.2", +--- Windows XP is "5.1". For non-MS-Windows systems the result is +--- an empty string. +--- +--- @return string +function vim.fn.windowsversion() end + +--- The result is a Number, which is the height of window {nr}. +--- {nr} can be the window number or the |window-ID|. +--- When {nr} is zero, the height of the current window is +--- returned. When window {nr} doesn't exist, -1 is returned. +--- An existing window always has a height of zero or more. +--- This excludes any window toolbar line. +--- Examples: >vim +--- echo "The current window has " .. winheight(0) .. " lines." +--- +--- @param nr integer +--- @return integer +function vim.fn.winheight(nr) end + +--- The result is a nested List containing the layout of windows +--- in a tabpage. +--- +--- Without {tabnr} use the current tabpage, otherwise the tabpage +--- with number {tabnr}. If the tabpage {tabnr} is not found, +--- returns an empty list. +--- +--- For a leaf window, it returns: > +--- ["leaf", {winid}] +--- < +--- For horizontally split windows, which form a column, it +--- returns: > +--- ["col", [{nested list of windows}]] +--- <For vertically split windows, which form a row, it returns: > +--- ["row", [{nested list of windows}]] +--- < +--- Example: >vim +--- " Only one window in the tab page +--- echo winlayout() +--- < > +--- ['leaf', 1000] +--- < >vim +--- " Two horizontally split windows +--- echo winlayout() +--- < > +--- ['col', [['leaf', 1000], ['leaf', 1001]]] +--- < >vim +--- " The second tab page, with three horizontally split +--- " windows, with two vertically split windows in the +--- " middle window +--- echo winlayout(2) +--- < > +--- ['col', [['leaf', 1002], ['row', [['leaf', 1003], +--- ['leaf', 1001]]], ['leaf', 1000]]] +--- < +--- +--- @param tabnr? integer +--- @return any +function vim.fn.winlayout(tabnr) end + +--- The result is a Number, which is the screen line of the cursor +--- in the window. This is counting screen lines from the top of +--- the window. The first line is one. +--- If the cursor was moved the view on the file will be updated +--- first, this may cause a scroll. +--- +--- @return integer +function vim.fn.winline() end + +--- The result is a Number, which is the number of the current +--- window. The top window has number 1. +--- Returns zero for a popup window. +--- +--- The optional argument {arg} supports the following values: +--- $ the number of the last window (the window +--- count). +--- # the number of the last accessed window (where +--- |CTRL-W_p| goes to). If there is no previous +--- window or it is in another tab page 0 is +--- returned. +--- {N}j the number of the Nth window below the +--- current window (where |CTRL-W_j| goes to). +--- {N}k the number of the Nth window above the current +--- window (where |CTRL-W_k| goes to). +--- {N}h the number of the Nth window left of the +--- current window (where |CTRL-W_h| goes to). +--- {N}l the number of the Nth window right of the +--- current window (where |CTRL-W_l| goes to). +--- The number can be used with |CTRL-W_w| and ":wincmd w" +--- |:wincmd|. +--- When {arg} is invalid an error is given and zero is returned. +--- Also see |tabpagewinnr()| and |win_getid()|. +--- Examples: >vim +--- let window_count = winnr('$') +--- let prev_window = winnr('#') +--- let wnum = winnr('3k') +--- +--- @param arg? any +--- @return any +function vim.fn.winnr(arg) end + +--- Returns a sequence of |:resize| commands that should restore +--- the current window sizes. Only works properly when no windows +--- are opened or closed and the current window and tab page is +--- unchanged. +--- Example: >vim +--- let cmd = winrestcmd() +--- call MessWithWindowSizes() +--- exe cmd +--- < +--- +--- @return any +function vim.fn.winrestcmd() end + +--- Uses the |Dictionary| returned by |winsaveview()| to restore +--- the view of the current window. +--- Note: The {dict} does not have to contain all values, that are +--- returned by |winsaveview()|. If values are missing, those +--- settings won't be restored. So you can use: >vim +--- call winrestview({'curswant': 4}) +--- < +--- This will only set the curswant value (the column the cursor +--- wants to move on vertical movements) of the cursor to column 5 +--- (yes, that is 5), while all other settings will remain the +--- same. This is useful, if you set the cursor position manually. +--- +--- If you have changed the values the result is unpredictable. +--- If the window size changed the result won't be the same. +--- +--- @param dict vim.fn.winrestview.dict +--- @return any +function vim.fn.winrestview(dict) end + +--- Returns a |Dictionary| that contains information to restore +--- the view of the current window. Use |winrestview()| to +--- restore the view. +--- This is useful if you have a mapping that jumps around in the +--- buffer and you want to go back to the original view. +--- This does not save fold information. Use the 'foldenable' +--- option to temporarily switch off folding, so that folds are +--- not opened when moving around. This may have side effects. +--- The return value includes: +--- lnum cursor line number +--- col cursor column (Note: the first column +--- zero, as opposed to what |getcurpos()| +--- returns) +--- coladd cursor column offset for 'virtualedit' +--- curswant column for vertical movement (Note: +--- the first column is zero, as opposed +--- to what |getcurpos()| returns). After +--- |$| command it will be a very large +--- number equal to |v:maxcol|. +--- topline first line in the window +--- topfill filler lines, only in diff mode +--- leftcol first column displayed; only used when +--- 'wrap' is off +--- skipcol columns skipped +--- Note that no option values are saved. +--- +--- @return vim.fn.winsaveview.ret +function vim.fn.winsaveview() end + +--- The result is a Number, which is the width of window {nr}. +--- {nr} can be the window number or the |window-ID|. +--- When {nr} is zero, the width of the current window is +--- returned. When window {nr} doesn't exist, -1 is returned. +--- An existing window always has a width of zero or more. +--- Examples: >vim +--- echo "The current window has " .. winwidth(0) .. " columns." +--- if winwidth(0) <= 50 +--- 50 wincmd | +--- endif +--- <For getting the terminal or screen size, see the 'columns' +--- option. +--- +--- @param nr integer +--- @return any +function vim.fn.winwidth(nr) end + +--- The result is a dictionary of byte/chars/word statistics for +--- the current buffer. This is the same info as provided by +--- |g_CTRL-G| +--- The return value includes: +--- bytes Number of bytes in the buffer +--- chars Number of chars in the buffer +--- words Number of words in the buffer +--- cursor_bytes Number of bytes before cursor position +--- (not in Visual mode) +--- cursor_chars Number of chars before cursor position +--- (not in Visual mode) +--- cursor_words Number of words before cursor position +--- (not in Visual mode) +--- visual_bytes Number of bytes visually selected +--- (only in Visual mode) +--- visual_chars Number of chars visually selected +--- (only in Visual mode) +--- visual_words Number of words visually selected +--- (only in Visual mode) +--- +--- @return any +function vim.fn.wordcount() end + +--- When {object} is a |List| write it to file {fname}. Each list +--- item is separated with a NL. Each list item must be a String +--- or Number. +--- All NL characters are replaced with a NUL character. +--- Inserting CR characters needs to be done before passing {list} +--- to writefile(). +--- +--- When {object} is a |Blob| write the bytes to file {fname} +--- unmodified, also when binary mode is not specified. +--- +--- {flags} must be a String. These characters are recognized: +--- +--- 'b' Binary mode is used: There will not be a NL after the +--- last list item. An empty item at the end does cause the +--- last line in the file to end in a NL. +--- +--- 'a' Append mode is used, lines are appended to the file: >vim +--- call writefile(["foo"], "event.log", "a") +--- call writefile(["bar"], "event.log", "a") +--- < +--- 'D' Delete the file when the current function ends. This +--- works like: >vim +--- defer delete({fname}) +--- < Fails when not in a function. Also see |:defer|. +--- +--- 's' fsync() is called after writing the file. This flushes +--- the file to disk, if possible. This takes more time but +--- avoids losing the file if the system crashes. +--- +--- 'S' fsync() is not called, even when 'fsync' is set. +--- +--- When {flags} does not contain "S" or "s" then fsync() is +--- called if the 'fsync' option is set. +--- +--- An existing file is overwritten, if possible. +--- +--- When the write fails -1 is returned, otherwise 0. There is an +--- error message if the file can't be created or when writing +--- fails. +--- +--- Also see |readfile()|. +--- To copy a file byte for byte: >vim +--- let fl = readfile("foo", "b") +--- call writefile(fl, "foocopy", "b") +--- +--- @param object any +--- @param fname string +--- @param flags? string +--- @return any +function vim.fn.writefile(object, fname, flags) end + +--- Bitwise XOR on the two arguments. The arguments are converted +--- to a number. A List, Dict or Float argument causes an error. +--- Also see `and()` and `or()`. +--- Example: >vim +--- let bits = xor(bits, 0x80) +--- < +--- +--- @param expr any +--- @param expr1 any +--- @return any +function vim.fn.xor(expr, expr1) end diff --git a/runtime/lua/vim/_options.lua b/runtime/lua/vim/_options.lua new file mode 100644 index 0000000000..b83a8dd4b1 --- /dev/null +++ b/runtime/lua/vim/_options.lua @@ -0,0 +1,910 @@ +---@defgroup lua-vimscript +--- +---@brief Nvim Lua provides an interface or "bridge" to Vimscript variables and +---functions, and editor commands and options. +--- +---Objects passed over this bridge are COPIED (marshalled): there are no +---"references". |lua-guide-variables| For example, using \`vim.fn.remove()\` on +---a Lua list copies the list object to Vimscript and does NOT modify the Lua +---list: +--- +--- ```lua +--- local list = { 1, 2, 3 } +--- vim.fn.remove(list, 0) +--- vim.print(list) --> "{ 1, 2, 3 }" +--- ``` + +---@addtogroup lua-vimscript +---@brief <pre>help +---vim.call({func}, {...}) *vim.call()* +--- Invokes |vim-function| or |user-function| {func} with arguments {...}. +--- See also |vim.fn|. +--- Equivalent to: >lua +--- vim.fn[func]({...}) +---< +---vim.cmd({command}) +--- See |vim.cmd()|. +--- +---vim.fn.{func}({...}) *vim.fn* +--- Invokes |vim-function| or |user-function| {func} with arguments {...}. +--- To call autoload functions, use the syntax: >lua +--- vim.fn['some\#function']({...}) +---< +--- Unlike vim.api.|nvim_call_function()| this converts directly between Vim +--- objects and Lua objects. If the Vim function returns a float, it will be +--- represented directly as a Lua number. Empty lists and dictionaries both +--- are represented by an empty table. +--- +--- Note: |v:null| values as part of the return value is represented as +--- |vim.NIL| special value +--- +--- Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only +--- enumerates functions that were called at least once. +--- +--- Note: The majority of functions cannot run in |api-fast| callbacks with some +--- undocumented exceptions which are allowed. +--- +--- *lua-vim-variables* +---The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed +---from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables +---described below. In this way you can easily read and modify global Vimscript +---variables from Lua. +--- +---Example: >lua +--- +--- vim.g.foo = 5 -- Set the g:foo Vimscript variable. +--- print(vim.g.foo) -- Get and print the g:foo Vimscript variable. +--- vim.g.foo = nil -- Delete (:unlet) the Vimscript variable. +--- vim.b[2].foo = 6 -- Set b:foo for buffer 2 +---< +--- +---Note that setting dictionary fields directly will not write them back into +---Nvim. This is because the index into the namespace simply returns a copy. +---Instead the whole dictionary must be written as one. This can be achieved by +---creating a short-lived temporary. +--- +---Example: >lua +--- +--- vim.g.my_dict.field1 = 'value' -- Does not work +--- +--- local my_dict = vim.g.my_dict -- +--- my_dict.field1 = 'value' -- Instead do +--- vim.g.my_dict = my_dict -- +--- +---vim.g *vim.g* +--- Global (|g:|) editor variables. +--- Key with no value returns `nil`. +--- +---vim.b *vim.b* +--- Buffer-scoped (|b:|) variables for the current buffer. +--- Invalid or unset key returns `nil`. Can be indexed with +--- an integer to access variables for a specific buffer. +--- +---vim.w *vim.w* +--- Window-scoped (|w:|) variables for the current window. +--- Invalid or unset key returns `nil`. Can be indexed with +--- an integer to access variables for a specific window. +--- +---vim.t *vim.t* +--- Tabpage-scoped (|t:|) variables for the current tabpage. +--- Invalid or unset key returns `nil`. Can be indexed with +--- an integer to access variables for a specific tabpage. +--- +---vim.v *vim.v* +--- |v:| variables. +--- Invalid or unset key returns `nil`. +---</pre> + +local api = vim.api + +-- TODO(tjdevries): Improve option metadata so that this doesn't have to be hardcoded. +-- Can be done in a separate PR. +local key_value_options = { + fillchars = true, + fcs = true, + listchars = true, + lcs = true, + winhighlight = true, + winhl = true, +} + +--- Convert a vimoption_T style dictionary to the correct OptionType associated with it. +---@return string +local function get_option_metatype(name, info) + if info.type == 'string' then + if info.flaglist then + return 'set' + elseif info.commalist then + if key_value_options[name] then + return 'map' + end + return 'array' + end + return 'string' + end + return info.type +end + +--- @param name string +local function get_options_info(name) + local info = api.nvim_get_option_info2(name, {}) + info.metatype = get_option_metatype(name, info) + return info +end + +--- Environment variables defined in the editor session. +--- See |expand-env| and |:let-environment| for the Vimscript behavior. +--- Invalid or unset key returns `nil`. +--- +--- Example: +--- +--- ```lua +--- vim.env.FOO = 'bar' +--- print(vim.env.TERM) +--- ``` +--- +---@param var string +vim.env = setmetatable({}, { + __index = function(_, k) + local v = vim.fn.getenv(k) + if v == vim.NIL then + return nil + end + return v + end, + + __newindex = function(_, k, v) + vim.fn.setenv(k, v) + end, +}) + +local function new_buf_opt_accessor(bufnr) + return setmetatable({}, { + __index = function(_, k) + if bufnr == nil and type(k) == 'number' then + return new_buf_opt_accessor(k) + end + return api.nvim_get_option_value(k, { buf = bufnr or 0 }) + end, + + __newindex = function(_, k, v) + return api.nvim_set_option_value(k, v, { buf = bufnr or 0 }) + end, + }) +end + +local function new_win_opt_accessor(winid, bufnr) + return setmetatable({}, { + __index = function(_, k) + if bufnr == nil and type(k) == 'number' then + if winid == nil then + return new_win_opt_accessor(k) + else + return new_win_opt_accessor(winid, k) + end + end + + if bufnr ~= nil and bufnr ~= 0 then + error('only bufnr=0 is supported') + end + + -- TODO(lewis6991): allow passing both buf and win to nvim_get_option_value + return api.nvim_get_option_value(k, { + scope = bufnr and 'local' or nil, + win = winid or 0, + }) + end, + + __newindex = function(_, k, v) + -- TODO(lewis6991): allow passing both buf and win to nvim_set_option_value + return api.nvim_set_option_value(k, v, { + scope = bufnr and 'local' or nil, + win = winid or 0, + }) + end, + }) +end + +---@addtogroup lua-vimscript +---@brief <pre>help +---` ` *lua-options* +--- *lua-vim-options* +--- *lua-vim-set* +--- *lua-vim-setlocal* +--- +---Vim options can be accessed through |vim.o|, which behaves like Vimscript +---|:set|. +--- +--- Examples: ~ +--- +--- To set a boolean toggle: +--- Vimscript: `set number` +--- Lua: `vim.o.number = true` +--- +--- To set a string value: +--- Vimscript: `set wildignore=*.o,*.a,__pycache__` +--- Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'` +--- +---Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and +---window-scoped options. Note that this must NOT be confused with +---|local-options| and |:setlocal|. There is also |vim.go| that only accesses the +---global value of a |global-local| option, see |:setglobal|. +---</pre> + +--- Get or set |options|. Like `:set`. Invalid key is an error. +--- +--- Note: this works on both buffer-scoped and window-scoped options using the +--- current buffer and window. +--- +--- Example: +--- +--- ```lua +--- vim.o.cmdheight = 4 +--- print(vim.o.columns) +--- print(vim.o.foo) -- error: invalid key +--- ``` +vim.o = setmetatable({}, { + __index = function(_, k) + return api.nvim_get_option_value(k, {}) + end, + __newindex = function(_, k, v) + return api.nvim_set_option_value(k, v, {}) + end, +}) + +--- Get or set global |options|. Like `:setglobal`. Invalid key is +--- an error. +--- +--- Note: this is different from |vim.o| because this accesses the global +--- option value and thus is mostly useful for use with |global-local| +--- options. +--- +--- Example: +--- +--- ```lua +--- vim.go.cmdheight = 4 +--- print(vim.go.columns) +--- print(vim.go.bar) -- error: invalid key +--- ``` +vim.go = setmetatable({}, { + __index = function(_, k) + return api.nvim_get_option_value(k, { scope = 'global' }) + end, + __newindex = function(_, k, v) + return api.nvim_set_option_value(k, v, { scope = 'global' }) + end, +}) + +--- Get or set buffer-scoped |options| for the buffer with number {bufnr}. +--- Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current +--- buffer is used. Invalid {bufnr} or key is an error. +--- +--- Note: this is equivalent to both `:set` and `:setlocal`. +--- +--- Example: +--- +--- ```lua +--- local bufnr = vim.api.nvim_get_current_buf() +--- vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true +--- print(vim.bo.comments) +--- print(vim.bo.baz) -- error: invalid key +--- ``` +vim.bo = new_buf_opt_accessor() + +--- Get or set window-scoped |options| for the window with handle {winid} and +--- buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like +--- `:set` otherwise. If [{winid}] is omitted then the current window is +--- used. Invalid {winid}, {bufnr} or key is an error. +--- +--- Note: only {bufnr} with value `0` (the current buffer in the window) is +--- supported. +--- +--- Example: +--- +--- ```lua +--- local winid = vim.api.nvim_get_current_win() +--- vim.wo[winid].number = true -- same as vim.wo.number = true +--- print(vim.wo.foldmarker) +--- print(vim.wo.quux) -- error: invalid key +--- vim.wo[winid][0].spell = false -- like ':setlocal nospell' +--- ``` +vim.wo = new_win_opt_accessor() + +---@brief [[ +--- vim.opt, vim.opt_local and vim.opt_global implementation +--- +--- To be used as helpers for working with options within neovim. +--- For information on how to use, see :help vim.opt +--- +---@brief ]] + +--- Preserves the order and does not mutate the original list +local function remove_duplicate_values(t) + local result, seen = {}, {} + for _, v in ipairs(t) do + if not seen[v] then + table.insert(result, v) + end + + seen[v] = true + end + + return result +end + +-- Check whether the OptionTypes is allowed for vim.opt +-- If it does not match, throw an error which indicates which option causes the error. +local function assert_valid_value(name, value, types) + local type_of_value = type(value) + for _, valid_type in ipairs(types) do + if valid_type == type_of_value then + return + end + end + + error( + string.format( + "Invalid option type '%s' for '%s', should be %s", + type_of_value, + name, + table.concat(types, ' or ') + ) + ) +end + +local function passthrough(_, x) + return x +end + +local function tbl_merge(left, right) + return vim.tbl_extend('force', left, right) +end + +local function tbl_remove(t, value) + if type(value) == 'string' then + t[value] = nil + else + for _, v in ipairs(value) do + t[v] = nil + end + end + + return t +end + +local valid_types = { + boolean = { 'boolean' }, + number = { 'number' }, + string = { 'string' }, + set = { 'string', 'table' }, + array = { 'string', 'table' }, + map = { 'string', 'table' }, +} + +-- Map of functions to take a Lua style value and convert to vimoption_T style value. +-- Each function takes (info, lua_value) -> vim_value +local to_vim_value = { + boolean = passthrough, + number = passthrough, + string = passthrough, + + set = function(info, value) + if type(value) == 'string' then + return value + end + + if info.flaglist and info.commalist then + local keys = {} + for k, v in pairs(value) do + if v then + table.insert(keys, k) + end + end + + table.sort(keys) + return table.concat(keys, ',') + else + local result = '' + for k, v in pairs(value) do + if v then + result = result .. k + end + end + + return result + end + end, + + array = function(info, value) + if type(value) == 'string' then + return value + end + if not info.allows_duplicates then + value = remove_duplicate_values(value) + end + return table.concat(value, ',') + end, + + map = function(_, value) + if type(value) == 'string' then + return value + end + + local result = {} + for opt_key, opt_value in pairs(value) do + table.insert(result, string.format('%s:%s', opt_key, opt_value)) + end + + table.sort(result) + return table.concat(result, ',') + end, +} + +--- Convert a Lua value to a vimoption_T value +local function convert_value_to_vim(name, info, value) + if value == nil then + return vim.NIL + end + + assert_valid_value(name, value, valid_types[info.metatype]) + + return to_vim_value[info.metatype](info, value) +end + +-- Map of OptionType to functions that take vimoption_T values and convert to Lua values. +-- Each function takes (info, vim_value) -> lua_value +local to_lua_value = { + boolean = passthrough, + number = passthrough, + string = passthrough, + + array = function(info, value) + if type(value) == 'table' then + if not info.allows_duplicates then + value = remove_duplicate_values(value) + end + + return value + end + + -- Empty strings mean that there is nothing there, + -- so empty table should be returned. + if value == '' then + return {} + end + + -- Handles unescaped commas in a list. + if string.find(value, ',,,') then + local left, right = unpack(vim.split(value, ',,,')) + + local result = {} + vim.list_extend(result, vim.split(left, ',')) + table.insert(result, ',') + vim.list_extend(result, vim.split(right, ',')) + + table.sort(result) + + return result + end + + if string.find(value, ',^,,', 1, true) then + local left, right = unpack(vim.split(value, ',^,,', true)) + + local result = {} + vim.list_extend(result, vim.split(left, ',')) + table.insert(result, '^,') + vim.list_extend(result, vim.split(right, ',')) + + table.sort(result) + + return result + end + + return vim.split(value, ',') + end, + + set = function(info, value) + if type(value) == 'table' then + return value + end + + -- Empty strings mean that there is nothing there, + -- so empty table should be returned. + if value == '' then + return {} + end + + assert(info.flaglist, 'That is the only one I know how to handle') + + if info.flaglist and info.commalist then + local split_value = vim.split(value, ',') + local result = {} + for _, v in ipairs(split_value) do + result[v] = true + end + + return result + else + local result = {} + for i = 1, #value do + result[value:sub(i, i)] = true + end + + return result + end + end, + + map = function(info, raw_value) + if type(raw_value) == 'table' then + return raw_value + end + + assert(info.commalist, 'Only commas are supported currently') + + local result = {} + + local comma_split = vim.split(raw_value, ',') + for _, key_value_str in ipairs(comma_split) do + local key, value = unpack(vim.split(key_value_str, ':')) + key = vim.trim(key) + + result[key] = value + end + + return result + end, +} + +--- Converts a vimoption_T style value to a Lua value +local function convert_value_to_lua(info, option_value) + return to_lua_value[info.metatype](info, option_value) +end + +local prepend_methods = { + number = function() + error("The '^' operator is not currently supported for") + end, + + string = function(left, right) + return right .. left + end, + + array = function(left, right) + for i = #right, 1, -1 do + table.insert(left, 1, right[i]) + end + + return left + end, + + map = tbl_merge, + set = tbl_merge, +} + +--- Handles the '^' operator +local function prepend_value(info, current, new) + return prepend_methods[info.metatype]( + convert_value_to_lua(info, current), + convert_value_to_lua(info, new) + ) +end + +local add_methods = { + number = function(left, right) + return left + right + end, + + string = function(left, right) + return left .. right + end, + + array = function(left, right) + for _, v in ipairs(right) do + table.insert(left, v) + end + + return left + end, + + map = tbl_merge, + set = tbl_merge, +} + +--- Handles the '+' operator +local function add_value(info, current, new) + return add_methods[info.metatype]( + convert_value_to_lua(info, current), + convert_value_to_lua(info, new) + ) +end + +local function remove_one_item(t, val) + if vim.tbl_islist(t) then + local remove_index = nil + for i, v in ipairs(t) do + if v == val then + remove_index = i + end + end + + if remove_index then + table.remove(t, remove_index) + end + else + t[val] = nil + end +end + +local remove_methods = { + number = function(left, right) + return left - right + end, + + string = function() + error('Subtraction not supported for strings.') + end, + + array = function(left, right) + if type(right) == 'string' then + remove_one_item(left, right) + else + for _, v in ipairs(right) do + remove_one_item(left, v) + end + end + + return left + end, + + map = tbl_remove, + set = tbl_remove, +} + +--- Handles the '-' operator +local function remove_value(info, current, new) + return remove_methods[info.metatype](convert_value_to_lua(info, current), new) +end + +local function create_option_accessor(scope) + local option_mt + + local function make_option(name, value) + local info = assert(get_options_info(name), 'Not a valid option name: ' .. name) + + if type(value) == 'table' and getmetatable(value) == option_mt then + assert(name == value._name, "must be the same value, otherwise that's weird.") + + value = value._value + end + + return setmetatable({ + _name = name, + _value = value, + _info = info, + }, option_mt) + end + + option_mt = { + -- To set a value, instead use: + -- opt[my_option] = value + _set = function(self) + local value = convert_value_to_vim(self._name, self._info, self._value) + api.nvim_set_option_value(self._name, value, { scope = scope }) + end, + + get = function(self) + return convert_value_to_lua(self._info, self._value) + end, + + append = function(self, right) + self._value = add_value(self._info, self._value, right) + self:_set() + end, + + __add = function(self, right) + return make_option(self._name, add_value(self._info, self._value, right)) + end, + + prepend = function(self, right) + self._value = prepend_value(self._info, self._value, right) + self:_set() + end, + + __pow = function(self, right) + return make_option(self._name, prepend_value(self._info, self._value, right)) + end, + + remove = function(self, right) + self._value = remove_value(self._info, self._value, right) + self:_set() + end, + + __sub = function(self, right) + return make_option(self._name, remove_value(self._info, self._value, right)) + end, + } + option_mt.__index = option_mt + + return setmetatable({}, { + __index = function(_, k) + -- vim.opt_global must get global value only + -- vim.opt_local may fall back to global value like vim.opt + local opts = { scope = scope == 'global' and 'global' or nil } + return make_option(k, api.nvim_get_option_value(k, opts)) + end, + + __newindex = function(_, k, v) + make_option(k, v):_set() + end, + }) +end + +---@addtogroup lua-vimscript +---@brief <pre>help +---` ` *vim.opt_local* +--- *vim.opt_global* +--- *vim.opt* +--- +--- +---A special interface |vim.opt| exists for conveniently interacting with list- +---and map-style option from Lua: It allows accessing them as Lua tables and +---offers object-oriented method for adding and removing entries. +--- +--- Examples: ~ +--- +--- The following methods of setting a list-style option are equivalent: +--- In Vimscript: >vim +--- set wildignore=*.o,*.a,__pycache__ +---< +--- In Lua using `vim.o`: >lua +--- vim.o.wildignore = '*.o,*.a,__pycache__' +---< +--- In Lua using `vim.opt`: >lua +--- vim.opt.wildignore = { '*.o', '*.a', '__pycache__' } +---< +--- To replicate the behavior of |:set+=|, use: >lua +--- +--- vim.opt.wildignore:append { "*.pyc", "node_modules" } +---< +--- To replicate the behavior of |:set^=|, use: >lua +--- +--- vim.opt.wildignore:prepend { "new_first_value" } +---< +--- To replicate the behavior of |:set-=|, use: >lua +--- +--- vim.opt.wildignore:remove { "node_modules" } +---< +--- The following methods of setting a map-style option are equivalent: +--- In Vimscript: >vim +--- set listchars=space:_,tab:>~ +---< +--- In Lua using `vim.o`: >lua +--- vim.o.listchars = 'space:_,tab:>~' +---< +--- In Lua using `vim.opt`: >lua +--- vim.opt.listchars = { space = '_', tab = '>~' } +---< +--- +---Note that |vim.opt| returns an `Option` object, not the value of the option, +---which is accessed through |vim.opt:get()|: +--- +--- Examples: ~ +--- +--- The following methods of getting a list-style option are equivalent: +--- In Vimscript: >vim +--- echo wildignore +---< +--- In Lua using `vim.o`: >lua +--- print(vim.o.wildignore) +---< +--- In Lua using `vim.opt`: >lua +--- vim.print(vim.opt.wildignore:get()) +---< +--- +---In any of the above examples, to replicate the behavior |:setlocal|, use +---`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use +---`vim.opt_global`. +---</pre> + +--- @diagnostic disable-next-line:unused-local used for gen_vimdoc +local Option = {} -- luacheck: no unused + +--- Returns a Lua-representation of the option. Boolean, number and string +--- values will be returned in exactly the same fashion. +--- +--- For values that are comma-separated lists, an array will be returned with +--- the values as entries in the array: +--- +--- ```lua +--- vim.cmd [[set wildignore=*.pyc,*.o]] +--- +--- vim.print(vim.opt.wildignore:get()) +--- -- { "*.pyc", "*.o", } +--- +--- for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do +--- print("Will ignore:", ignore_pattern) +--- end +--- -- Will ignore: *.pyc +--- -- Will ignore: *.o +--- ``` +--- +--- For values that are comma-separated maps, a table will be returned with +--- the names as keys and the values as entries: +--- +--- ```lua +--- vim.cmd [[set listchars=space:_,tab:>~]] +--- +--- vim.print(vim.opt.listchars:get()) +--- -- { space = "_", tab = ">~", } +--- +--- for char, representation in pairs(vim.opt.listchars:get()) do +--- print(char, "=>", representation) +--- end +--- ``` +--- +--- For values that are lists of flags, a set will be returned with the flags +--- as keys and `true` as entries. +--- +--- ```lua +--- vim.cmd [[set formatoptions=njtcroql]] +--- +--- vim.print(vim.opt.formatoptions:get()) +--- -- { n = true, j = true, c = true, ... } +--- +--- local format_opts = vim.opt.formatoptions:get() +--- if format_opts.j then +--- print("J is enabled!") +--- end +--- ``` +--- +---@return string|integer|boolean|nil value of option +---@diagnostic disable-next-line:unused-local used for gen_vimdoc +function Option:get() end + +--- Append a value to string-style options. See |:set+=| +--- +--- These are equivalent: +--- +--- ```lua +--- vim.opt.formatoptions:append('j') +--- vim.opt.formatoptions = vim.opt.formatoptions + 'j' +--- ``` +--- +---@param value string Value to append +---@diagnostic disable-next-line:unused-local used for gen_vimdoc +function Option:append(value) end -- luacheck: no unused + +--- Prepend a value to string-style options. See |:set^=| +--- +--- These are equivalent: +--- +--- ```lua +--- vim.opt.wildignore:prepend('*.o') +--- vim.opt.wildignore = vim.opt.wildignore ^ '*.o' +--- ``` +--- +---@param value string Value to prepend +---@diagnostic disable-next-line:unused-local used for gen_vimdoc +function Option:prepend(value) end -- luacheck: no unused + +--- Remove a value from string-style options. See |:set-=| +--- +--- These are equivalent: +--- +--- ```lua +--- vim.opt.wildignore:remove('*.pyc') +--- vim.opt.wildignore = vim.opt.wildignore - '*.pyc' +--- ``` +--- +---@param value string Value to remove +---@diagnostic disable-next-line:unused-local used for gen_vimdoc +function Option:remove(value) end -- luacheck: no unused + +---@private +vim.opt = create_option_accessor() + +---@private +vim.opt_local = create_option_accessor('local') + +---@private +vim.opt_global = create_option_accessor('global') diff --git a/runtime/lua/vim/_system.lua b/runtime/lua/vim/_system.lua new file mode 100644 index 0000000000..9279febddf --- /dev/null +++ b/runtime/lua/vim/_system.lua @@ -0,0 +1,374 @@ +local uv = vim.uv + +--- @class SystemOpts +--- @field stdin? string|string[]|true +--- @field stdout? fun(err:string?, data: string?)|false +--- @field stderr? fun(err:string?, data: string?)|false +--- @field cwd? string +--- @field env? table<string,string|number> +--- @field clear_env? boolean +--- @field text? boolean +--- @field timeout? integer Timeout in ms +--- @field detach? boolean + +--- @class vim.SystemCompleted +--- @field code integer +--- @field signal integer +--- @field stdout? string +--- @field stderr? string + +--- @class vim.SystemState +--- @field handle? uv.uv_process_t +--- @field timer? uv.uv_timer_t +--- @field pid? integer +--- @field timeout? integer +--- @field done? boolean|'timeout' +--- @field stdin? uv.uv_stream_t +--- @field stdout? uv.uv_stream_t +--- @field stderr? uv.uv_stream_t +--- @field stdout_data? string[] +--- @field stderr_data? string[] +--- @field result? vim.SystemCompleted + +--- @enum vim.SystemSig +local SIG = { + HUP = 1, -- Hangup + INT = 2, -- Interrupt from keyboard + KILL = 9, -- Kill signal + TERM = 15, -- Termination signal + -- STOP = 17,19,23 -- Stop the process +} + +---@param handle uv.uv_handle_t? +local function close_handle(handle) + if handle and not handle:is_closing() then + handle:close() + end +end + +---@param state vim.SystemState +local function close_handles(state) + close_handle(state.handle) + close_handle(state.stdin) + close_handle(state.stdout) + close_handle(state.stderr) + close_handle(state.timer) +end + +--- @class vim.SystemObj +--- @field pid integer +--- @field private _state vim.SystemState +--- @field wait fun(self: vim.SystemObj, timeout?: integer): vim.SystemCompleted +--- @field kill fun(self: vim.SystemObj, signal: integer|string) +--- @field write fun(self: vim.SystemObj, data?: string|string[]) +--- @field is_closing fun(self: vim.SystemObj): boolean? +local SystemObj = {} + +--- @param state vim.SystemState +--- @return vim.SystemObj +local function new_systemobj(state) + return setmetatable({ + pid = state.pid, + _state = state, + }, { __index = SystemObj }) +end + +--- @param signal integer|string +function SystemObj:kill(signal) + self._state.handle:kill(signal) +end + +--- @package +--- @param signal? vim.SystemSig +function SystemObj:_timeout(signal) + self._state.done = 'timeout' + self:kill(signal or SIG.TERM) +end + +local MAX_TIMEOUT = 2 ^ 31 + +--- @param timeout? integer +--- @return vim.SystemCompleted +function SystemObj:wait(timeout) + local state = self._state + + local done = vim.wait(timeout or state.timeout or MAX_TIMEOUT, function() + return state.result ~= nil + end) + + if not done then + -- Send sigkill since this cannot be caught + self:_timeout(SIG.KILL) + vim.wait(timeout or state.timeout or MAX_TIMEOUT, function() + return state.result ~= nil + end) + end + + return state.result +end + +--- @param data string[]|string|nil +function SystemObj:write(data) + local stdin = self._state.stdin + + if not stdin then + error('stdin has not been opened on this object') + end + + if type(data) == 'table' then + for _, v in ipairs(data) do + stdin:write(v) + stdin:write('\n') + end + elseif type(data) == 'string' then + stdin:write(data) + elseif data == nil then + -- Shutdown the write side of the duplex stream and then close the pipe. + -- Note shutdown will wait for all the pending write requests to complete + -- TODO(lewis6991): apparently shutdown doesn't behave this way. + -- (https://github.com/neovim/neovim/pull/17620#discussion_r820775616) + stdin:write('', function() + stdin:shutdown(function() + if stdin then + stdin:close() + end + end) + end) + end +end + +--- @return boolean +function SystemObj:is_closing() + local handle = self._state.handle + return handle == nil or handle:is_closing() +end + +---@param output fun(err:string?, data: string?)|false +---@return uv.uv_stream_t? +---@return fun(err:string?, data: string?)? Handler +local function setup_output(output) + if output == nil then + return assert(uv.new_pipe(false)), nil + end + + if type(output) == 'function' then + return assert(uv.new_pipe(false)), output + end + + assert(output == false) + return nil, nil +end + +---@param input string|string[]|true|nil +---@return uv.uv_stream_t? +---@return string|string[]? +local function setup_input(input) + if not input then + return + end + + local towrite --- @type string|string[]? + if type(input) == 'string' or type(input) == 'table' then + towrite = input + end + + return assert(uv.new_pipe(false)), towrite +end + +--- @return table<string,string> +local function base_env() + local env = vim.fn.environ() --- @type table<string,string> + env['NVIM'] = vim.v.servername + env['NVIM_LISTEN_ADDRESS'] = nil + return env +end + +--- uv.spawn will completely overwrite the environment +--- when we just want to modify the existing one, so +--- make sure to prepopulate it with the current env. +--- @param env? table<string,string|number> +--- @param clear_env? boolean +--- @return string[]? +local function setup_env(env, clear_env) + if clear_env then + return env + end + + --- @type table<string,string|number> + env = vim.tbl_extend('force', base_env(), env or {}) + + local renv = {} --- @type string[] + for k, v in pairs(env) do + renv[#renv + 1] = string.format('%s=%s', k, tostring(v)) + end + + return renv +end + +--- @param stream uv.uv_stream_t +--- @param text? boolean +--- @param bucket string[] +--- @return fun(err: string?, data: string?) +local function default_handler(stream, text, bucket) + return function(err, data) + if err then + error(err) + end + if data ~= nil then + if text then + bucket[#bucket + 1] = data:gsub('\r\n', '\n') + else + bucket[#bucket + 1] = data + end + else + stream:read_stop() + stream:close() + end + end +end + +local M = {} + +--- @param cmd string +--- @param opts uv.spawn.options +--- @param on_exit fun(code: integer, signal: integer) +--- @param on_error fun() +--- @return uv.uv_process_t, integer +local function spawn(cmd, opts, on_exit, on_error) + local handle, pid_or_err = uv.spawn(cmd, opts, on_exit) + if not handle then + on_error() + error(pid_or_err) + end + return handle, pid_or_err --[[@as integer]] +end + +---@param timeout integer +---@param cb fun() +---@return uv.uv_timer_t +local function timer_oneshot(timeout, cb) + local timer = assert(uv.new_timer()) + timer:start(timeout, 0, function() + timer:stop() + timer:close() + cb() + end) + return timer +end + +--- @param state vim.SystemState +--- @param code integer +--- @param signal integer +--- @param on_exit fun(result: vim.SystemCompleted)? +local function _on_exit(state, code, signal, on_exit) + close_handles(state) + + local check = assert(uv.new_check()) + check:start(function() + for _, pipe in pairs({ state.stdin, state.stdout, state.stderr }) do + if not pipe:is_closing() then + return + end + end + check:stop() + check:close() + + if state.done == nil then + state.done = true + end + + if (code == 0 or code == 1) and state.done == 'timeout' then + -- Unix: code == 0 + -- Windows: code == 1 + code = 124 + end + + local stdout_data = state.stdout_data + local stderr_data = state.stderr_data + + state.result = { + code = code, + signal = signal, + stdout = stdout_data and table.concat(stdout_data) or nil, + stderr = stderr_data and table.concat(stderr_data) or nil, + } + + if on_exit then + on_exit(state.result) + end + end) +end + +--- Run a system command +--- +--- @param cmd string[] +--- @param opts? SystemOpts +--- @param on_exit? fun(out: vim.SystemCompleted) +--- @return vim.SystemObj +function M.run(cmd, opts, on_exit) + vim.validate({ + cmd = { cmd, 'table' }, + opts = { opts, 'table', true }, + on_exit = { on_exit, 'function', true }, + }) + + opts = opts or {} + + local stdout, stdout_handler = setup_output(opts.stdout) + local stderr, stderr_handler = setup_output(opts.stderr) + local stdin, towrite = setup_input(opts.stdin) + + --- @type vim.SystemState + local state = { + done = false, + cmd = cmd, + timeout = opts.timeout, + stdin = stdin, + stdout = stdout, + stderr = stderr, + } + + --- @diagnostic disable-next-line:missing-fields + state.handle, state.pid = spawn(cmd[1], { + args = vim.list_slice(cmd, 2), + stdio = { stdin, stdout, stderr }, + cwd = opts.cwd, + --- @diagnostic disable-next-line:assign-type-mismatch + env = setup_env(opts.env, opts.clear_env), + detached = opts.detach, + hide = true, + }, function(code, signal) + _on_exit(state, code, signal, on_exit) + end, function() + close_handles(state) + end) + + if stdout then + state.stdout_data = {} + stdout:read_start(stdout_handler or default_handler(stdout, opts.text, state.stdout_data)) + end + + if stderr then + state.stderr_data = {} + stderr:read_start(stderr_handler or default_handler(stderr, opts.text, state.stderr_data)) + end + + local obj = new_systemobj(state) + + if towrite then + obj:write(towrite) + obj:write(nil) -- close the stream + end + + if opts.timeout then + state.timer = timer_oneshot(opts.timeout, function() + if state.handle and state.handle:is_active() then + obj:_timeout() + end + end) + end + + return obj +end + +return M diff --git a/runtime/lua/vim/_watch.lua b/runtime/lua/vim/_watch.lua new file mode 100644 index 0000000000..43fce3bf7f --- /dev/null +++ b/runtime/lua/vim/_watch.lua @@ -0,0 +1,223 @@ +local M = {} +local uv = vim.uv + +---@enum vim._watch.FileChangeType +local FileChangeType = { + Created = 1, + Changed = 2, + Deleted = 3, +} + +--- Enumeration describing the types of events watchers will emit. +M.FileChangeType = vim.tbl_add_reverse_lookup(FileChangeType) + +--- Joins filepath elements by static '/' separator +--- +---@param ... (string) The path elements. +---@return string +local function filepath_join(...) + return table.concat({ ... }, '/') +end + +--- Stops and closes a libuv |uv_fs_event_t| or |uv_fs_poll_t| handle +--- +---@param handle (uv.uv_fs_event_t|uv.uv_fs_poll_t) The handle to stop +local function stop(handle) + local _, stop_err = handle:stop() + assert(not stop_err, stop_err) + local is_closing, close_err = handle:is_closing() + assert(not close_err, close_err) + if not is_closing then + handle:close() + end +end + +--- Initializes and starts a |uv_fs_event_t| +--- +---@param path (string) The path to watch +---@param opts (table|nil) Additional options +--- - uvflags (table|nil) +--- Same flags as accepted by |uv.fs_event_start()| +---@param callback (function) The function called when new events +---@return (function) Stops the watcher +function M.watch(path, opts, callback) + vim.validate({ + path = { path, 'string', false }, + opts = { opts, 'table', true }, + callback = { callback, 'function', false }, + }) + + path = vim.fs.normalize(path) + local uvflags = opts and opts.uvflags or {} + local handle, new_err = vim.uv.new_fs_event() + assert(not new_err, new_err) + local _, start_err = handle:start(path, uvflags, function(err, filename, events) + assert(not err, err) + local fullpath = path + if filename then + filename = filename:gsub('\\', '/') + fullpath = filepath_join(fullpath, filename) + end + local change_type = events.change and M.FileChangeType.Changed or 0 + if events.rename then + local _, staterr, staterrname = vim.uv.fs_stat(fullpath) + if staterrname == 'ENOENT' then + change_type = M.FileChangeType.Deleted + else + assert(not staterr, staterr) + change_type = M.FileChangeType.Created + end + end + callback(fullpath, change_type) + end) + assert(not start_err, start_err) + return function() + stop(handle) + end +end + +--- @class watch.PollOpts +--- @field debounce? integer +--- @field include_pattern? vim.lpeg.Pattern +--- @field exclude_pattern? vim.lpeg.Pattern + +---@param path string +---@param opts watch.PollOpts +---@param callback function Called on new events +---@return function cancel stops the watcher +local function recurse_watch(path, opts, callback) + opts = opts or {} + local debounce = opts.debounce or 500 + local uvflags = {} + ---@type table<string, uv.uv_fs_event_t> handle by fullpath + local handles = {} + + local timer = assert(uv.new_timer()) + + ---@type table[] + local changesets = {} + + local function is_included(filepath) + return opts.include_pattern and opts.include_pattern:match(filepath) + end + local function is_excluded(filepath) + return opts.exclude_pattern and opts.exclude_pattern:match(filepath) + end + + local process_changes = function() + assert(false, "Replaced later. I'm only here as forward reference") + end + + local function create_on_change(filepath) + return function(err, filename, events) + assert(not err, err) + local fullpath = vim.fs.joinpath(filepath, filename) + if is_included(fullpath) and not is_excluded(filepath) then + table.insert(changesets, { + fullpath = fullpath, + events = events, + }) + timer:start(debounce, 0, process_changes) + end + end + end + + process_changes = function() + ---@type table<string, table[]> + local filechanges = vim.defaulttable() + for i, change in ipairs(changesets) do + changesets[i] = nil + if is_included(change.fullpath) and not is_excluded(change.fullpath) then + table.insert(filechanges[change.fullpath], change.events) + end + end + for fullpath, events_list in pairs(filechanges) do + uv.fs_stat(fullpath, function(_, stat) + ---@type vim._watch.FileChangeType + local change_type + if stat then + change_type = FileChangeType.Created + for _, event in ipairs(events_list) do + if event.change then + change_type = FileChangeType.Changed + end + end + if stat.type == 'directory' then + local handle = handles[fullpath] + if not handle then + handle = assert(uv.new_fs_event()) + handles[fullpath] = handle + handle:start(fullpath, uvflags, create_on_change(fullpath)) + end + end + else + local handle = handles[fullpath] + if handle then + if not handle:is_closing() then + handle:close() + end + handles[fullpath] = nil + end + change_type = FileChangeType.Deleted + end + callback(fullpath, change_type) + end) + end + end + local root_handle = assert(uv.new_fs_event()) + handles[path] = root_handle + root_handle:start(path, uvflags, create_on_change(path)) + + --- "640K ought to be enough for anyone" + --- Who has folders this deep? + local max_depth = 100 + + for name, type in vim.fs.dir(path, { depth = max_depth }) do + local filepath = vim.fs.joinpath(path, name) + if type == 'directory' and not is_excluded(filepath) then + local handle = assert(uv.new_fs_event()) + handles[filepath] = handle + handle:start(filepath, uvflags, create_on_change(filepath)) + end + end + local function cancel() + for fullpath, handle in pairs(handles) do + if not handle:is_closing() then + handle:close() + end + handles[fullpath] = nil + end + timer:stop() + timer:close() + end + return cancel +end + +--- Initializes and starts a |uv_fs_poll_t| recursively watching every file underneath the +--- directory at path. +--- +---@param path (string) The path to watch. Must refer to a directory. +---@param opts (table|nil) Additional options +--- - debounce (number|nil) +--- Time events are debounced in ms. Defaults to 500 +--- - include_pattern (LPeg pattern|nil) +--- An |lpeg| pattern. Only changes to files whose full paths match the pattern +--- will be reported. Only matches against non-directoriess, all directories will +--- be watched for new potentially-matching files. exclude_pattern can be used to +--- filter out directories. When nil, matches any file name. +--- - exclude_pattern (LPeg pattern|nil) +--- An |lpeg| pattern. Only changes to files and directories whose full path does +--- not match the pattern will be reported. Matches against both files and +--- directories. When nil, matches nothing. +---@param callback (function) The function called when new events +---@return function Stops the watcher +function M.poll(path, opts, callback) + vim.validate({ + path = { path, 'string', false }, + opts = { opts, 'table', true }, + callback = { callback, 'function', false }, + }) + return recurse_watch(path, opts, callback) +end + +return M diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua index 6fd000a029..99448982b4 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -72,7 +72,6 @@ local bufs_waiting_to_update = setmetatable({}, bufnr_and_namespace_cacher_mt) local all_namespaces = {} ----@private local function to_severity(severity) if type(severity) == 'string' then return assert( @@ -83,7 +82,6 @@ local function to_severity(severity) return severity end ----@private local function filter_by_severity(severity, diagnostics) if not severity then return diagnostics @@ -96,15 +94,25 @@ local function filter_by_severity(severity, diagnostics) end, diagnostics) end - local min_severity = to_severity(severity.min) or M.severity.HINT - local max_severity = to_severity(severity.max) or M.severity.ERROR + if severity.min or severity.max then + local min_severity = to_severity(severity.min) or M.severity.HINT + local max_severity = to_severity(severity.max) or M.severity.ERROR + + return vim.tbl_filter(function(t) + return t.severity <= min_severity and t.severity >= max_severity + end, diagnostics) + end + + local severities = {} + for _, s in ipairs(severity) do + severities[to_severity(s)] = true + end return vim.tbl_filter(function(t) - return t.severity <= min_severity and t.severity >= max_severity + return severities[t.severity] end, diagnostics) end ----@private local function count_sources(bufnr) local seen = {} local count = 0 @@ -119,7 +127,6 @@ local function count_sources(bufnr) return count end ----@private local function prefix_source(diagnostics) return vim.tbl_map(function(d) if not d.source then @@ -132,7 +139,6 @@ local function prefix_source(diagnostics) end, diagnostics) end ----@private local function reformat_diagnostics(format, diagnostics) vim.validate({ format = { format, 'f' }, @@ -146,7 +152,6 @@ local function reformat_diagnostics(format, diagnostics) return formatted end ----@private local function enabled_value(option, namespace) local ns = namespace and M.get_namespace(namespace) or {} if ns.opts and type(ns.opts[option]) == 'table' then @@ -160,7 +165,6 @@ local function enabled_value(option, namespace) return {} end ----@private local function resolve_optional_value(option, value, namespace, bufnr) if not value then return false @@ -180,7 +184,6 @@ local function resolve_optional_value(option, value, namespace, bufnr) end end ----@private local function get_resolved_options(opts, namespace, bufnr) local ns = namespace and M.get_namespace(namespace) or {} -- Do not use tbl_deep_extend so that an empty table can be used to reset to default values @@ -202,7 +205,6 @@ local diagnostic_severities = { } -- Make a map from DiagnosticSeverity -> Highlight Name ----@private local function make_highlight_map(base_name) local result = {} for k in pairs(diagnostic_severities) do @@ -243,7 +245,6 @@ local define_default_signs = (function() end end)() ----@private local function get_bufnr(bufnr) if not bufnr or bufnr == 0 then return api.nvim_get_current_buf() @@ -251,7 +252,6 @@ local function get_bufnr(bufnr) return bufnr end ----@private local function diagnostic_lines(diagnostics) if not diagnostics then return {} @@ -269,7 +269,6 @@ local function diagnostic_lines(diagnostics) return diagnostics_by_line end ----@private local function set_diagnostic_cache(namespace, bufnr, diagnostics) for _, diagnostic in ipairs(diagnostics) do assert(diagnostic.lnum, 'Diagnostic line number is required') @@ -284,7 +283,6 @@ local function set_diagnostic_cache(namespace, bufnr, diagnostics) diagnostic_cache[bufnr][namespace] = diagnostics end ----@private local function restore_extmarks(bufnr, last) for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do local extmarks_current = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true }) @@ -306,7 +304,6 @@ local function restore_extmarks(bufnr, last) end end ----@private local function save_extmarks(namespace, bufnr) bufnr = get_bufnr(bufnr) if not diagnostic_attached_buffers[bufnr] then @@ -326,13 +323,11 @@ end local registered_autocmds = {} ----@private local function make_augroup_key(namespace, bufnr) local ns = M.get_namespace(namespace) return string.format('DiagnosticInsertLeave:%s:%s', bufnr, ns.name) end ----@private local function execute_scheduled_display(namespace, bufnr) local args = bufs_waiting_to_update[bufnr][namespace] if not args then @@ -348,7 +343,6 @@ end --- Table of autocmd events to fire the update for displaying new diagnostic information local insert_leave_auto_cmds = { 'InsertLeave', 'CursorHoldI' } ----@private local function schedule_display(namespace, bufnr, args) bufs_waiting_to_update[bufnr][namespace] = args @@ -367,7 +361,6 @@ local function schedule_display(namespace, bufnr, args) end end ----@private local function clear_scheduled_display(namespace, bufnr) local key = make_augroup_key(namespace, bufnr) @@ -377,7 +370,6 @@ local function clear_scheduled_display(namespace, bufnr) end end ----@private local function get_diagnostics(bufnr, opts, clamp) opts = opts or {} @@ -392,9 +384,9 @@ local function get_diagnostics(bufnr, opts, clamp) end, }) - ---@private local function add(b, d) if not opts.lnum or d.lnum == opts.lnum then + d = vim.deepcopy(d) if clamp and api.nvim_buf_is_loaded(b) then local line_count = buf_line_count[b] - 1 if @@ -405,7 +397,6 @@ local function get_diagnostics(bufnr, opts, clamp) or d.col < 0 or d.end_col < 0 then - d = vim.deepcopy(d) d.lnum = math.max(math.min(d.lnum, line_count), 0) d.end_lnum = math.max(math.min(d.end_lnum, line_count), 0) d.col = math.max(d.col, 0) @@ -416,7 +407,6 @@ local function get_diagnostics(bufnr, opts, clamp) end end - ---@private local function add_all_diags(buf, diags) for _, diagnostic in pairs(diags) do add(buf, diagnostic) @@ -450,7 +440,6 @@ local function get_diagnostics(bufnr, opts, clamp) return diagnostics end ----@private local function set_list(loclist, opts) opts = opts or {} local open = vim.F.if_nil(opts.open, true) @@ -474,7 +463,6 @@ local function set_list(loclist, opts) end end ----@private local function next_diagnostic(position, search_forward, bufnr, opts, namespace) position[1] = position[1] - 1 bufnr = get_bufnr(bufnr) @@ -483,6 +471,7 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) local diagnostics = get_diagnostics(bufnr, vim.tbl_extend('keep', opts, { namespace = namespace }), true) local line_diagnostics = diagnostic_lines(diagnostics) + for i = 0, line_count do local offset = i * (search_forward and 1 or -1) local lnum = position[1] + offset @@ -524,7 +513,6 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace) end end ----@private local function diagnostic_move_pos(opts, pos) opts = opts or {} @@ -565,14 +553,16 @@ end --- followed by namespace configuration, and finally global configuration. --- --- For example, if a user enables virtual text globally with ---- <pre>lua ---- vim.diagnostic.config({ virtual_text = true }) ---- </pre> +--- +--- ```lua +--- vim.diagnostic.config({ virtual_text = true }) +--- ``` --- --- and a diagnostic producer sets diagnostics with ---- <pre>lua ---- vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) ---- </pre> +--- +--- ```lua +--- vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) +--- ``` --- --- then virtual text will not be enabled for those diagnostics. --- @@ -585,11 +575,13 @@ end ---@param opts table|nil When omitted or "nil", retrieve the current configuration. Otherwise, a --- configuration table with the following keys: --- - underline: (default true) Use underline for diagnostics. Options: ---- * severity: Only underline diagnostics matching the given severity ---- |diagnostic-severity| +--- * severity: Only underline diagnostics matching the given +--- severity |diagnostic-severity| --- - virtual_text: (default true) Use virtual text for diagnostics. If multiple diagnostics --- are set for a namespace, one prefix per diagnostic + the last diagnostic ---- message are shown. +--- message are shown. In addition to the options listed below, the +--- "virt_text" options of |nvim_buf_set_extmark()| may also be used here +--- (e.g. "virt_text_pos" and "hl_mode"). --- Options: --- * severity: Only show virtual text for diagnostics matching the given --- severity |diagnostic-severity| @@ -599,7 +591,12 @@ end --- means to always show the diagnostic source. --- * spacing: (number) Amount of empty spaces inserted at the beginning --- of the virtual text. ---- * prefix: (string) Prepend diagnostic message with prefix. +--- * prefix: (string or function) prepend diagnostic message with prefix. +--- If a function, it must have the signature (diagnostic, i, total) +--- -> string, where {diagnostic} is of type |diagnostic-structure|, +--- {i} is the index of the diagnostic being evaluated, and {total} +--- is the total number of diagnostics for the line. This can be +--- used to render diagnostic symbols or error codes. --- * suffix: (string or function) Append diagnostic message with suffix. --- If a function, it must have the signature (diagnostic) -> --- string, where {diagnostic} is of type |diagnostic-structure|. @@ -616,8 +613,8 @@ end --- end --- </pre> --- - signs: (default true) Use signs for diagnostics. Options: ---- * severity: Only show signs for diagnostics matching the given severity ---- |diagnostic-severity| +--- * severity: Only show signs for diagnostics matching the given +--- severity |diagnostic-severity| --- * priority: (number, default 10) Base priority to use for signs. When --- {severity_sort} is used, the priority of a sign is adjusted based on --- its severity. Otherwise, all signs use the same priority. @@ -630,7 +627,7 @@ end --- Options: --- * reverse: (boolean) Reverse sort order --- ----@param namespace number|nil Update the options for the given namespace. When omitted, update the +---@param namespace integer|nil Update the options for the given namespace. When omitted, update the --- global diagnostic options. function M.config(opts, namespace) vim.validate({ @@ -657,16 +654,14 @@ function M.config(opts, namespace) if namespace then for bufnr, v in pairs(diagnostic_cache) do - if api.nvim_buf_is_loaded(bufnr) and v[namespace] then + if v[namespace] then M.show(namespace, bufnr) end end else for bufnr, v in pairs(diagnostic_cache) do - if api.nvim_buf_is_loaded(bufnr) then - for ns in pairs(v) do - M.show(ns, bufnr) - end + for ns in pairs(v) do + M.show(ns, bufnr) end end end @@ -674,8 +669,8 @@ end --- Set diagnostics for the given namespace and buffer. --- ----@param namespace number The diagnostic namespace ----@param bufnr number Buffer number +---@param namespace integer The diagnostic namespace +---@param bufnr integer Buffer number ---@param diagnostics table A list of diagnostic items |diagnostic-structure| ---@param opts table|nil Display options to pass to |vim.diagnostic.show()| function M.set(namespace, bufnr, diagnostics, opts) @@ -698,9 +693,7 @@ function M.set(namespace, bufnr, diagnostics, opts) set_diagnostic_cache(namespace, bufnr, diagnostics) end - if api.nvim_buf_is_loaded(bufnr) then - M.show(namespace, bufnr, nil, opts) - end + M.show(namespace, bufnr, nil, opts) api.nvim_exec_autocmds('DiagnosticChanged', { modeline = false, @@ -711,7 +704,7 @@ end --- Get namespace metadata. --- ----@param namespace number Diagnostic namespace +---@param namespace integer Diagnostic namespace ---@return table Namespace metadata function M.get_namespace(namespace) vim.validate({ namespace = { namespace, 'n' } }) @@ -743,26 +736,29 @@ function M.get_namespaces() end ---@class Diagnostic ----@field buffer number ----@field lnum number 0-indexed ----@field end_lnum nil|number 0-indexed ----@field col number 0-indexed ----@field end_col nil|number 0-indexed ----@field severity DiagnosticSeverity +---@field bufnr? integer +---@field lnum integer 0-indexed +---@field end_lnum? integer 0-indexed +---@field col integer 0-indexed +---@field end_col? integer 0-indexed +---@field severity? DiagnosticSeverity ---@field message string ----@field source nil|string ----@field code nil|string ----@field user_data nil|any arbitrary data plugins can add +---@field source? string +---@field code? string +---@field _tags? { deprecated: boolean, unnecessary: boolean} +---@field user_data? any arbitrary data plugins can add --- Get current diagnostics. --- ----@param bufnr number|nil Buffer number to get diagnostics from. Use 0 for +--- Modifying diagnostics in the returned table has no effect. To set diagnostics in a buffer, use |vim.diagnostic.set()|. +--- +---@param bufnr integer|nil Buffer number to get diagnostics from. Use 0 for --- current buffer or nil for all buffers. ---@param opts table|nil A table with the following keys: --- - namespace: (number) Limit diagnostics to the given namespace. --- - lnum: (number) Limit diagnostics to the given line number. --- - severity: See |diagnostic-severity|. ----@return Diagnostic[] table A list of diagnostic items |diagnostic-structure|. +---@return Diagnostic[] table A list of diagnostic items |diagnostic-structure|. Keys `bufnr`, `end_lnum`, `end_col`, and `severity` are guaranteed to be present. function M.get(bufnr, opts) vim.validate({ bufnr = { bufnr, 'n', true }, @@ -838,13 +834,13 @@ end --- ---@param opts table|nil Configuration table with the following keys: --- - namespace: (number) Only consider diagnostics from the given namespace. ---- - cursor_position: (cursor position) Cursor position as a (row, col) tuple. See ---- |nvim_win_get_cursor()|. Defaults to the current cursor position. +--- - cursor_position: (cursor position) Cursor position as a (row, col) tuple. +--- See |nvim_win_get_cursor()|. Defaults to the current cursor position. --- - wrap: (boolean, default true) Whether to loop around file or not. Similar to 'wrapscan'. --- - severity: See |diagnostic-severity|. --- - float: (boolean or table, default true) If "true", call |vim.diagnostic.open_float()| ---- after moving. If a table, pass the table as the {opts} parameter to ---- |vim.diagnostic.open_float()|. Unless overridden, the float will show +--- after moving. If a table, pass the table as the {opts} parameter +--- to |vim.diagnostic.open_float()|. Unless overridden, the float will show --- diagnostics at the new cursor position (as if "cursor" were passed to --- the "scope" option). --- - win_id: (number, default 0) Window ID @@ -930,6 +926,10 @@ M.handlers.underline = { bufnr = get_bufnr(bufnr) opts = opts or {} + if not vim.api.nvim_buf_is_loaded(bufnr) then + return + end + if opts.underline and opts.underline.severity then diagnostics = filter_by_severity(opts.underline.severity, diagnostics) end @@ -948,6 +948,16 @@ M.handlers.underline = { higroup = underline_highlight_map.Error end + if diagnostic._tags then + -- TODO(lewis6991): we should be able to stack these. + if diagnostic._tags.unnecessary then + higroup = 'DiagnosticUnnecessary' + end + if diagnostic._tags.deprecated then + higroup = 'DiagnosticDeprecated' + end + end + vim.highlight.range( bufnr, underline_ns, @@ -986,6 +996,10 @@ M.handlers.virtual_text = { bufnr = get_bufnr(bufnr) opts = opts or {} + if not vim.api.nvim_buf_is_loaded(bufnr) then + return + end + local severity if opts.virtual_text then if opts.virtual_text.format then @@ -1017,8 +1031,11 @@ M.handlers.virtual_text = { if virt_texts then api.nvim_buf_set_extmark(bufnr, virt_text_ns, line, 0, { - hl_mode = 'combine', + hl_mode = opts.virtual_text.hl_mode or 'combine', virt_text = virt_texts, + virt_text_pos = opts.virtual_text.virt_text_pos, + virt_text_hide = opts.virtual_text.virt_text_hide, + virt_text_win_col = opts.virtual_text.virt_text_win_col, }) end end @@ -1054,8 +1071,15 @@ function M._get_virt_text_chunks(line_diags, opts) -- Create a little more space between virtual text and contents local virt_texts = { { string.rep(' ', spacing) } } - for i = 1, #line_diags - 1 do - table.insert(virt_texts, { prefix, virtual_text_highlight_map[line_diags[i].severity] }) + for i = 1, #line_diags do + local resolved_prefix = prefix + if type(prefix) == 'function' then + resolved_prefix = prefix(line_diags[i], i, #line_diags) or '' + end + table.insert( + virt_texts, + { resolved_prefix, virtual_text_highlight_map[line_diags[i].severity] } + ) end local last = line_diags[#line_diags] @@ -1066,7 +1090,7 @@ function M._get_virt_text_chunks(line_diags, opts) suffix = suffix(last) or '' end table.insert(virt_texts, { - string.format('%s %s%s', prefix, last.message:gsub('\r', ''):gsub('\n', ' '), suffix), + string.format(' %s%s', last.message:gsub('\r', ''):gsub('\n', ' '), suffix), virtual_text_highlight_map[last.severity], }) @@ -1083,9 +1107,9 @@ end --- To hide diagnostics and prevent them from re-displaying, use --- |vim.diagnostic.disable()|. --- ----@param namespace number|nil Diagnostic namespace. When omitted, hide +---@param namespace integer|nil Diagnostic namespace. When omitted, hide --- diagnostics from all namespaces. ----@param bufnr number|nil Buffer number, or 0 for current buffer. When +---@param bufnr integer|nil Buffer number, or 0 for current buffer. When --- omitted, hide diagnostics in all buffers. function M.hide(namespace, bufnr) vim.validate({ @@ -1108,8 +1132,8 @@ end --- Check whether diagnostics are disabled in a given buffer. --- ----@param bufnr number|nil Buffer number, or 0 for current buffer. ----@param namespace number|nil Diagnostic namespace. When omitted, checks if +---@param bufnr integer|nil Buffer number, or 0 for current buffer. +---@param namespace integer|nil Diagnostic namespace. When omitted, checks if --- all diagnostics are disabled in {bufnr}. --- Otherwise, only checks if diagnostics from --- {namespace} are disabled. @@ -1129,9 +1153,9 @@ end --- Display diagnostics for the given namespace and buffer. --- ----@param namespace number|nil Diagnostic namespace. When omitted, show +---@param namespace integer|nil Diagnostic namespace. When omitted, show --- diagnostics from all namespaces. ----@param bufnr number|nil Buffer number, or 0 for current buffer. When omitted, show +---@param bufnr integer|nil Buffer number, or 0 for current buffer. When omitted, show --- diagnostics in all buffers. ---@param diagnostics table|nil The diagnostics to display. When omitted, use the --- saved diagnostics for the given namespace and @@ -1215,8 +1239,8 @@ end --- Show diagnostics in a floating window. --- ----@param opts table|nil Configuration table with the same keys as ---- |vim.lsp.util.open_floating_preview()| in addition to the following: +---@param opts table|nil Configuration table with the same keys +--- as |vim.lsp.util.open_floating_preview()| in addition to the following: --- - bufnr: (number) Buffer number to show diagnostics from. --- Defaults to the current buffer. --- - namespace: (number) Limit diagnostics to the given namespace @@ -1229,16 +1253,15 @@ end --- otherwise, a (row, col) tuple. --- - severity_sort: (default false) Sort diagnostics by severity. Overrides the setting --- from |vim.diagnostic.config()|. ---- - severity: See |diagnostic-severity|. Overrides the setting from ---- |vim.diagnostic.config()|. +--- - severity: See |diagnostic-severity|. Overrides the setting +--- from |vim.diagnostic.config()|. --- - header: (string or table) String to use as the header for the floating window. If a --- table, it is interpreted as a [text, hl_group] tuple. Overrides the setting --- from |vim.diagnostic.config()|. --- - source: (boolean or string) Include the diagnostic source in the message. --- Use "if_many" to only show sources if there is more than one source of --- diagnostics in the buffer. Otherwise, any truthy value means to always show ---- the diagnostic source. Overrides the setting from ---- |vim.diagnostic.config()|. +--- the diagnostic source. Overrides the setting from |vim.diagnostic.config()|. --- - format: (function) A function that takes a diagnostic as input and returns a --- string. The return value is the text used to display the diagnostic. --- Overrides the setting from |vim.diagnostic.config()|. @@ -1256,7 +1279,7 @@ end --- Overrides the setting from |vim.diagnostic.config()|. --- - suffix: Same as {prefix}, but appends the text to the diagnostic instead of --- prepending it. Overrides the setting from |vim.diagnostic.config()|. ----@return number|nil, number|nil: ({float_bufnr}, {win_id}) +---@return integer|nil, integer|nil: ({float_bufnr}, {win_id}) function M.open_float(opts, ...) -- Support old (bufnr, opts) signature local bufnr @@ -1463,9 +1486,9 @@ end --- simply remove diagnostic decorations in a way that they can be --- re-displayed, use |vim.diagnostic.hide()|. --- ----@param namespace number|nil Diagnostic namespace. When omitted, remove +---@param namespace integer|nil Diagnostic namespace. When omitted, remove --- diagnostics from all namespaces. ----@param bufnr number|nil Remove diagnostics for the given buffer. When omitted, +---@param bufnr integer|nil Remove diagnostics for the given buffer. When omitted, --- diagnostics are removed for all buffers. function M.reset(namespace, bufnr) vim.validate({ @@ -1518,9 +1541,9 @@ end --- Disable diagnostics in the given buffer. --- ----@param bufnr number|nil Buffer number, or 0 for current buffer. When +---@param bufnr integer|nil Buffer number, or 0 for current buffer. When --- omitted, disable diagnostics in all buffers. ----@param namespace number|nil Only disable diagnostics for the given namespace. +---@param namespace integer|nil Only disable diagnostics for the given namespace. function M.disable(bufnr, namespace) vim.validate({ bufnr = { bufnr, 'n', true }, namespace = { namespace, 'n', true } }) if bufnr == nil then @@ -1555,9 +1578,9 @@ end --- Enable diagnostics in the given buffer. --- ----@param bufnr number|nil Buffer number, or 0 for current buffer. When +---@param bufnr integer|nil Buffer number, or 0 for current buffer. When --- omitted, enable diagnostics in all buffers. ----@param namespace number|nil Only enable diagnostics for the given namespace. +---@param namespace integer|nil Only enable diagnostics for the given namespace. function M.enable(bufnr, namespace) vim.validate({ bufnr = { bufnr, 'n', true }, namespace = { namespace, 'n', true } }) if bufnr == nil then @@ -1586,18 +1609,20 @@ end --- Parse a diagnostic from a string. --- --- For example, consider a line of output from a linter: ---- <pre> +--- +--- ``` --- WARNING filename:27:3: Variable 'foo' does not exist ---- </pre> +--- ``` --- --- This can be parsed into a diagnostic |diagnostic-structure| --- with: ---- <pre>lua ---- local s = "WARNING filename:27:3: Variable 'foo' does not exist" ---- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" ---- local groups = { "severity", "lnum", "col", "message" } ---- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) ---- </pre> +--- +--- ```lua +--- local s = "WARNING filename:27:3: Variable 'foo' does not exist" +--- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" +--- local groups = { "severity", "lnum", "col", "message" } +--- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) +--- ``` --- ---@param str string String to parse diagnostics from. ---@param pat string Lua pattern with capture groups. @@ -1694,8 +1719,7 @@ end --- Convert a list of quickfix items to a list of diagnostics. --- ----@param list table A list of quickfix items from |getqflist()| or ---- |getloclist()|. +---@param list table[] List of quickfix items from |getqflist()| or |getloclist()|. ---@return Diagnostic[] array of |diagnostic-structure| function M.fromqflist(list) vim.validate({ diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 9293c828b8..c6200f16bb 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -1,8 +1,16 @@ local api = vim.api +local fn = vim.fn local M = {} ----@private +--- @alias vim.filetype.mapfn fun(path:string,bufnr:integer, ...):string?, fun(b:integer)? +--- @alias vim.filetype.maptbl {[1]:string|vim.filetype.mapfn, [2]:{priority:integer}} +--- @alias vim.filetype.mapping.value string|vim.filetype.mapfn|vim.filetype.maptbl +--- @alias vim.filetype.mapping table<string,vim.filetype.mapping.value> + +--- @param ft string|vim.filetype.mapfn +--- @param opts? {priority:integer} +--- @return vim.filetype.maptbl local function starsetf(ft, opts) return { function(path, bufnr) @@ -24,36 +32,38 @@ local function starsetf(ft, opts) end ---@private ---- Get a single line or line range from the buffer. ---- If only start_lnum is specified, return a single line as a string. ---- If both start_lnum and end_lnum are omitted, return all lines from the buffer. ---- ----@param bufnr number|nil The buffer to get the lines from ----@param start_lnum number|nil The line number of the first line (inclusive, 1-based) ----@param end_lnum number|nil The line number of the last line (inclusive, 1-based) ----@return table<string>|string Array of lines, or string when end_lnum is omitted -function M.getlines(bufnr, start_lnum, end_lnum) - if end_lnum then - -- Return a line range - return api.nvim_buf_get_lines(bufnr, start_lnum - 1, end_lnum, false) - end +--- Get a line range from the buffer. +---@param bufnr integer The buffer to get the lines from +---@param start_lnum integer|nil The line number of the first line (inclusive, 1-based) +---@param end_lnum integer|nil The line number of the last line (inclusive, 1-based) +---@return string[] # Array of lines +function M._getlines(bufnr, start_lnum, end_lnum) if start_lnum then - -- Return a single line - return api.nvim_buf_get_lines(bufnr, start_lnum - 1, start_lnum, false)[1] or '' - else - -- Return all lines - return api.nvim_buf_get_lines(bufnr, 0, -1, false) + return api.nvim_buf_get_lines(bufnr, start_lnum - 1, end_lnum or start_lnum, false) end + + -- Return all lines + return api.nvim_buf_get_lines(bufnr, 0, -1, false) +end + +---@private +--- Get a single line from the buffer. +---@param bufnr integer The buffer to get the lines from +---@param start_lnum integer The line number of the first line (inclusive, 1-based) +---@return string +function M._getline(bufnr, start_lnum) + -- Return a single line + return api.nvim_buf_get_lines(bufnr, start_lnum - 1, start_lnum, false)[1] or '' end ---@private --- Check whether a string matches any of the given Lua patterns. --- ----@param s string The string to check ----@param patterns table<string> A list of Lua patterns +---@param s string? The string to check +---@param patterns string[] A list of Lua patterns ---@return boolean `true` if s matched a pattern, else `false` -function M.findany(s, patterns) - if s == nil then +function M._findany(s, patterns) + if not s then return false end for _, v in ipairs(patterns) do @@ -67,11 +77,11 @@ end ---@private --- Get the next non-whitespace line in the buffer. --- ----@param bufnr number The buffer to get the line from ----@param start_lnum number The line number of the first line to start from (inclusive, 1-based) +---@param bufnr integer The buffer to get the line from +---@param start_lnum integer The line number of the first line to start from (inclusive, 1-based) ---@return string|nil The first non-blank line if found or `nil` otherwise -function M.nextnonblank(bufnr, start_lnum) - for _, line in ipairs(M.getlines(bufnr, start_lnum, -1)) do +function M._nextnonblank(bufnr, start_lnum) + for _, line in ipairs(M._getlines(bufnr, start_lnum, -1)) do if not line:find('^%s*$') then return line end @@ -79,30 +89,93 @@ function M.nextnonblank(bufnr, start_lnum) return nil end ----@private ---- Check whether the given string matches the Vim regex pattern. -M.matchregex = (function() - local cache = {} - return function(s, pattern) - if s == nil then - return nil +do + --- @type table<string,vim.regex> + local regex_cache = {} + + ---@private + --- Check whether the given string matches the Vim regex pattern. + --- @param s string? + --- @param pattern string + --- @return boolean + function M._matchregex(s, pattern) + if not s then + return false end - if not cache[pattern] then - cache[pattern] = vim.regex(pattern) + if not regex_cache[pattern] then + regex_cache[pattern] = vim.regex(pattern) end - return cache[pattern]:match_str(s) + return regex_cache[pattern]:match_str(s) ~= nil end -end)() +end + +--- @module 'vim.filetype.detect' +local detect = setmetatable({}, { + --- @param k string + --- @param t table<string,function> + --- @return function + __index = function(t, k) + t[k] = function(...) + return require('vim.filetype.detect')[k](...) + end + return t[k] + end, +}) + +--- @param ... string|vim.filetype.mapfn +--- @return vim.filetype.mapfn +local function detect_seq(...) + local candidates = { ... } + return function(...) + for _, c in ipairs(candidates) do + if type(c) == 'string' then + return c + end + if type(c) == 'function' then + local r = c(...) + if r then + return r + end + end + end + end +end + +local function detect_noext(path, bufnr) + local root = fn.fnamemodify(path, ':r') + return M.match({ buf = bufnr, filename = root }) +end + +--- @param pat string +--- @param a string? +--- @param b string? +--- @return vim.filetype.mapfn +local function detect_line1(pat, a, b) + return function(_path, bufnr) + if M._getline(bufnr, 1):find(pat) then + return a + end + return b + end +end + +--- @type vim.filetype.mapfn +local detect_rc = function(path, _bufnr) + if not path:find('/etc/Muttrc%.d/') then + return 'rc' + end +end -- luacheck: push no unused args -- luacheck: push ignore 122 -- Filetypes based on file extension ---@diagnostic disable: unused-local +--- @type vim.filetype.mapping local extension = { -- BEGIN EXTENSION ['8th'] = '8th', - ['a65'] = 'a65', + a65 = 'a65', aap = 'aap', abap = 'abap', abc = 'abc', @@ -128,51 +201,36 @@ local extension = { end return 'aspvbs' end, - asm = function(path, bufnr) - return require('vim.filetype.detect').asm(bufnr) - end, - lst = function(path, bufnr) - return require('vim.filetype.detect').asm(bufnr) - end, - mac = function(path, bufnr) - return require('vim.filetype.detect').asm(bufnr) - end, - ['asn1'] = 'asn', + asm = detect.asm, + lst = detect.asm, + mac = detect.asm, + asn1 = 'asn', asn = 'asn', - asp = function(path, bufnr) - return require('vim.filetype.detect').asp(bufnr) - end, + asp = detect.asp, astro = 'astro', atl = 'atlas', as = 'atlas', + zed = 'authzed', ahk = 'autohotkey', - ['au3'] = 'autoit', + au3 = 'autoit', ave = 'ave', gawk = 'awk', awk = 'awk', ref = 'b', imp = 'b', mch = 'b', - bas = function(path, bufnr) - return require('vim.filetype.detect').bas(bufnr) - end, - bi = function(path, bufnr) - return require('vim.filetype.detect').bas(bufnr) - end, - bm = function(path, bufnr) - return require('vim.filetype.detect').bas(bufnr) - end, + bas = detect.bas, + bass = 'bass', + bi = detect.bas, + bm = detect.bas, bc = 'bc', bdf = 'bdf', beancount = 'beancount', bib = 'bib', - com = function(path, bufnr) - return require('vim.filetype.detect').bindzone(bufnr, 'dcl') - end, - db = function(path, bufnr) - return require('vim.filetype.detect').bindzone(bufnr) - end, + com = detect_seq(detect.bindzone, 'dcl'), + db = detect.bindzone, bicep = 'bicep', + bicepparam = 'bicep', bb = 'bitbake', bbappend = 'bitbake', bbclass = 'bitbake', @@ -190,7 +248,9 @@ local extension = { BUILD = 'bzl', qc = 'c', cabal = 'cabal', + cairo = 'cairo', capnp = 'capnp', + cdc = 'cdc', cdl = 'cdl', toc = 'cdrtoc', cfc = 'cf', @@ -199,9 +259,7 @@ local extension = { hgrc = 'cfg', chf = 'ch', chai = 'chaiscript', - ch = function(path, bufnr) - return require('vim.filetype.detect').change(bufnr) - end, + ch = detect.change, chs = 'chaskell', chatito = 'chatito', chopro = 'chordpro', @@ -224,22 +282,19 @@ local extension = { atg = 'coco', recipe = 'conaryrecipe', hook = function(path, bufnr) - return M.getlines(bufnr, 1) == '[Trigger]' and 'conf' + return M._getline(bufnr, 1) == '[Trigger]' and 'confini' or nil end, + nmconnection = 'confini', mklx = 'context', mkiv = 'context', mkii = 'context', mkxl = 'context', mkvi = 'context', - control = function(path, bufnr) - return require('vim.filetype.detect').control(bufnr) - end, - copyright = function(path, bufnr) - return require('vim.filetype.detect').copyright(bufnr) - end, - csh = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, + control = detect.control, + copyright = detect.copyright, + corn = 'corn', + csh = detect.csh, + cpon = 'cpon', moc = 'cpp', hh = 'cpp', tlh = 'cpp', @@ -252,14 +307,15 @@ local extension = { tcc = 'cpp', hxx = 'cpp', hpp = 'cpp', - cpp = function(path, bufnr) - return vim.g.cynlib_syntax_for_cpp and 'cynlib' or 'cpp' - end, - cc = function(path, bufnr) - return vim.g.cynlib_syntax_for_cc and 'cynlib' or 'cpp' - end, + ccm = 'cpp', + cppm = 'cpp', + cxxm = 'cpp', + ['c++m'] = 'cpp', + cpp = detect.cpp, + cc = detect.cpp, cql = 'cqlang', crm = 'crm', + cr = 'crystal', csx = 'cs', cs = 'cs', csc = 'csc', @@ -273,26 +329,23 @@ local extension = { feature = 'cucumber', cuh = 'cuda', cu = 'cuda', + cue = 'cue', pld = 'cupl', si = 'cuplsim', cyn = 'cynpp', + cypher = 'cypher', dart = 'dart', drt = 'dart', ds = 'datascript', dcd = 'dcd', - decl = function(path, bufnr) - return require('vim.filetype.detect').decl(bufnr) - end, - dec = function(path, bufnr) - return require('vim.filetype.detect').decl(bufnr) - end, - dcl = function(path, bufnr) - return require('vim.filetype.detect').decl(bufnr) or 'clean' - end, + decl = detect.decl, + dec = detect.decl, + dcl = detect_seq(detect.decl, 'clean'), def = 'def', desc = 'desc', directory = 'desktop', desktop = 'desktop', + dhall = 'dhall', diff = 'diff', rej = 'diff', Dockerfile = 'dockerfile', @@ -300,125 +353,98 @@ local extension = { bat = 'dosbatch', wrap = 'dosini', ini = 'dosini', + INI = 'dosini', + vbp = 'dosini', dot = 'dot', gv = 'dot', drac = 'dracula', drc = 'dracula', dtd = 'dtd', - d = function(path, bufnr) - return require('vim.filetype.detect').dtrace(bufnr) - end, + d = detect.dtrace, dts = 'dts', dtsi = 'dts', dylan = 'dylan', intr = 'dylanintr', lid = 'dylanlid', - e = function(path, bufnr) - return require('vim.filetype.detect').e(bufnr) - end, - E = function(path, bufnr) - return require('vim.filetype.detect').e(bufnr) - end, + e = detect.e, + E = detect.e, ecd = 'ecd', edf = 'edif', edif = 'edif', edo = 'edif', - edn = function(path, bufnr) - return require('vim.filetype.detect').edn(bufnr) - end, + edn = detect.edn, eex = 'eelixir', leex = 'eelixir', am = 'elf', exs = 'elixir', elm = 'elm', + lc = 'elsa', elv = 'elvish', - ent = function(path, bufnr) - return require('vim.filetype.detect').ent(bufnr) - end, + ent = detect.ent, epp = 'epuppet', erl = 'erlang', hrl = 'erlang', yaws = 'erlang', erb = 'eruby', rhtml = 'eruby', + esdl = 'esdl', ec = 'esqlc', EC = 'esqlc', strl = 'esterel', - eu = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - EU = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - ew = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - EW = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - EX = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - exu = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - EXU = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - exw = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - EXW = function(path, bufnr) - return vim.g.filetype_euphoria or 'euphoria3' - end, - ex = function(path, bufnr) - return require('vim.filetype.detect').ex(bufnr) - end, + eu = detect.euphoria, + EU = detect.euphoria, + ew = detect.euphoria, + EW = detect.euphoria, + EX = detect.euphoria, + exu = detect.euphoria, + EXU = detect.euphoria, + exw = detect.euphoria, + EXW = detect.euphoria, + ex = detect.ex, exp = 'expect', + f = detect.f, factor = 'factor', fal = 'falcon', fan = 'fan', fwt = 'fan', fnl = 'fennel', - ['m4gl'] = 'fgl', + m4gl = 'fgl', ['4gl'] = 'fgl', ['4gh'] = 'fgl', + fir = 'firrtl', fish = 'fish', focexec = 'focexec', fex = 'focexec', - fth = 'forth', ft = 'forth', + fth = 'forth', + ['4th'] = 'forth', FOR = 'fortran', - ['f77'] = 'fortran', - ['f03'] = 'fortran', + f77 = 'fortran', + f03 = 'fortran', fortran = 'fortran', - ['F95'] = 'fortran', - ['f90'] = 'fortran', - ['F03'] = 'fortran', + F95 = 'fortran', + f90 = 'fortran', + F03 = 'fortran', fpp = 'fortran', FTN = 'fortran', ftn = 'fortran', ['for'] = 'fortran', - ['F90'] = 'fortran', - ['F77'] = 'fortran', - ['f95'] = 'fortran', + F90 = 'fortran', + F77 = 'fortran', + f95 = 'fortran', FPP = 'fortran', - f = 'fortran', F = 'fortran', - ['F08'] = 'fortran', - ['f08'] = 'fortran', + F08 = 'fortran', + f08 = 'fortran', fpc = 'fpcmake', fsl = 'framescript', - frm = function(path, bufnr) - return require('vim.filetype.detect').frm(bufnr) - end, + frm = detect.frm, fb = 'freebasic', - fs = function(path, bufnr) - return require('vim.filetype.detect').fs(bufnr) - end, + fs = detect.fs, fsh = 'fsh', fsi = 'fsharp', fsx = 'fsharp', + fc = 'func', fusion = 'fusion', gdb = 'gdb', gdmo = 'gdmo', @@ -434,6 +460,8 @@ local extension = { gift = 'gift', gleam = 'gleam', glsl = 'glsl', + gn = 'gn', + gni = 'gn', gpi = 'gnuplot', go = 'go', gp = 'gp', @@ -459,17 +487,16 @@ local extension = { hsig = 'haskell', hsc = 'haskell', hs = 'haskell', + persistentmodels = 'haskellpersistent', ht = 'haste', htpp = 'hastepreproc', + hcl = 'hcl', hb = 'hb', - h = function(path, bufnr) - return require('vim.filetype.detect').header(bufnr) - end, + h = detect.header, sum = 'hercules', errsum = 'hercules', ev = 'hercules', vc = 'hercules', - hcl = 'hcl', heex = 'heex', hex = 'hex', ['h32'] = 'hex', @@ -479,56 +506,29 @@ local extension = { hog = 'hog', hws = 'hollywood', hoon = 'hoon', - cpt = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, - dtml = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, - htm = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, - html = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, - pt = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, - shtml = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, - stm = function(path, bufnr) - return require('vim.filetype.detect').html(bufnr) - end, + cpt = detect.html, + dtml = detect.html, + htm = detect.html, + html = detect.html, + pt = detect.html, + shtml = detect.html, + stm = detect.html, htt = 'httest', htb = 'httest', - hw = function(path, bufnr) - return require('vim.filetype.detect').hw(bufnr) - end, - module = function(path, bufnr) - return require('vim.filetype.detect').hw(bufnr) - end, - pkg = function(path, bufnr) - return require('vim.filetype.detect').hw(bufnr) - end, + hurl = 'hurl', + hw = detect.hw, + module = detect.hw, + pkg = detect.hw, iba = 'ibasic', ibi = 'ibasic', icn = 'icon', - idl = function(path, bufnr) - return require('vim.filetype.detect').idl(bufnr) - end, - inc = function(path, bufnr) - return require('vim.filetype.detect').inc(bufnr) - end, + idl = detect.idl, + inc = detect.inc, inf = 'inform', INF = 'inform', ii = 'initng', - inp = function(path, bufnr) - return require('vim.filetype.detect').inp(bufnr) - end, - ms = function(path, bufnr) - return require('vim.filetype.detect').nroff(bufnr) or 'xmath' - end, + inp = detect.inp, + ms = detect_seq(detect.nroff, 'xmath'), iss = 'iss', mst = 'ist', ist = 'ist', @@ -537,6 +537,7 @@ local extension = { jal = 'jal', jpr = 'jam', jpl = 'jam', + janet = 'janet', jav = 'java', java = 'java', jj = 'javacc', @@ -550,7 +551,7 @@ local extension = { jsx = 'javascriptreact', clp = 'jess', jgr = 'jgraph', - ['j73'] = 'jovial', + j73 = 'jovial', jov = 'jovial', jovial = 'jovial', properties = 'jproperties', @@ -558,15 +559,19 @@ local extension = { slnf = 'json', json = 'json', jsonp = 'json', + geojson = 'json', webmanifest = 'json', ipynb = 'json', ['json-patch'] = 'json', json5 = 'json5', jsonc = 'jsonc', + jsonl = 'jsonl', jsonnet = 'jsonnet', libsonnet = 'jsonnet', jsp = 'jsp', jl = 'julia', + just = 'just', + kdl = 'kdl', kv = 'kivy', kix = 'kix', kts = 'kotlin', @@ -580,6 +585,7 @@ local extension = { lte = 'latte', ld = 'ld', ldif = 'ldif', + lean = 'lean', journal = 'ledger', ldg = 'ledger', ledger = 'ledger', @@ -593,6 +599,7 @@ local extension = { ly = 'lilypond', ily = 'lilypond', liquid = 'liquid', + liq = 'liquidsoap', cl = 'lisp', L = 'lisp', lisp = 'lisp', @@ -601,6 +608,7 @@ local extension = { asd = 'lisp', lt = 'lite', lite = 'lite', + livemd = 'livebook', lgt = 'logtalk', lotos = 'lotos', lot = 'lotos', @@ -608,28 +616,21 @@ local extension = { lou = 'lout', ulpc = 'lpc', lpc = 'lpc', - c = function(path, bufnr) - return require('vim.filetype.detect').lpc(bufnr) - end, - lsl = function(path, bufnr) - return require('vim.filetype.detect').lsl(bufnr) - end, + c = detect.lpc, + lsl = detect.lsl, lss = 'lss', nse = 'lua', rockspec = 'lua', lua = 'lua', + luau = 'luau', lrc = 'lyrics', - m = function(path, bufnr) - return require('vim.filetype.detect').m(bufnr) - end, + m = detect.m, at = 'm4', - mc = function(path, bufnr) - return require('vim.filetype.detect').mc(bufnr) - end, + mc = detect.mc, quake = 'm3quake', - ['m4'] = function(path, bufnr) + m4 = function(path, bufnr) path = path:lower() - return not (path:find('html%.m4$') or path:find('fvwm2rc')) and 'm4' + return not (path:find('html%.m4$') or path:find('fvwm2rc')) and 'm4' or nil end, eml = 'mail', mk = 'make', @@ -668,47 +669,34 @@ local extension = { mib = 'mib', mix = 'mix', mixal = 'mix', - mm = function(path, bufnr) - return require('vim.filetype.detect').mm(bufnr) - end, + mm = detect.mm, nb = 'mma', mmp = 'mmp', - mms = function(path, bufnr) - return require('vim.filetype.detect').mms(bufnr) - end, + mms = detect.mms, DEF = 'modula2', - ['m2'] = 'modula2', + m2 = 'modula2', mi = 'modula2', lm3 = 'modula3', + mojo = 'mojo', + ['🔥'] = 'mojo', -- 🙄 ssc = 'monk', monk = 'monk', tsc = 'monk', isc = 'monk', moo = 'moo', moon = 'moonscript', + move = 'move', mp = 'mp', - mpiv = function(path, bufnr) - return 'mp', function(b) - vim.b[b].mp_metafun = 1 - end - end, - mpvi = function(path, bufnr) - return 'mp', function(b) - vim.b[b].mp_metafun = 1 - end - end, - mpxl = function(path, bufnr) - return 'mp', function(b) - vim.b[b].mp_metafun = 1 - end - end, + mpiv = detect.mp, + mpvi = detect.mp, + mpxl = detect.mp, mof = 'msidl', odl = 'msidl', msql = 'msql', mu = 'mupad', mush = 'mush', mysql = 'mysql', - ['n1ql'] = 'n1ql', + n1ql = 'n1ql', nql = 'n1ql', nanorc = 'nanorc', ncf = 'ncf', @@ -718,6 +706,7 @@ local extension = { nimble = 'nim', ninja = 'ninja', nix = 'nix', + norg = 'norg', nqc = 'nqc', roff = 'nroff', tmac = 'nroff', @@ -727,7 +716,10 @@ local extension = { tr = 'nroff', nsi = 'nsis', nsh = 'nsis', + nu = 'nu', obj = 'obj', + objdump = 'objdump', + cppobjdump = 'objdump', obl = 'obse', obse = 'obse', oblivion = 'obse', @@ -740,6 +732,7 @@ local extension = { mli = 'ocaml', ml = 'ocaml', occ = 'occam', + odin = 'odin', xom = 'omnimark', xin = 'omnimark', opam = 'opam', @@ -759,6 +752,10 @@ local extension = { g = 'pccts', pcmk = 'pcmk', pdf = 'pdf', + pem = 'pem', + cer = 'pem', + crt = 'pem', + csr = 'pem', plx = 'perl', prisma = 'prisma', psgi = 'perl', @@ -771,12 +768,10 @@ local extension = { pike = 'pike', pmod = 'pike', rcp = 'pilrc', - PL = function(path, bufnr) - return require('vim.filetype.detect').pl(bufnr) - end, + PL = detect.pl, pli = 'pli', - ['pl1'] = 'pli', - ['p36'] = 'plm', + pl1 = 'pli', + p36 = 'plm', plm = 'plm', pac = 'plm', plp = 'plp', @@ -787,6 +782,7 @@ local extension = { pod = 'pod', filter = 'poefilter', pk = 'poke', + pony = 'pony', ps = 'postscr', epsi = 'postscr', afm = 'postscr', @@ -803,11 +799,12 @@ local extension = { pdb = 'prolog', pml = 'promela', proto = 'proto', - ['psd1'] = 'ps1', - ['psm1'] = 'ps1', - ['ps1'] = 'ps1', + prql = 'prql', + psd1 = 'ps1', + psm1 = 'ps1', + ps1 = 'ps1', pssc = 'ps1', - ['ps1xml'] = 'ps1xml', + ps1xml = 'ps1xml', psf = 'psf', psl = 'psl', pug = 'pug', @@ -820,25 +817,29 @@ local extension = { ptl = 'python', ql = 'ql', qll = 'ql', + qml = 'qml', + qbs = 'qml', qmd = 'quarto', - R = function(path, bufnr) - return require('vim.filetype.detect').r(bufnr) - end, + R = detect.r, + rkt = 'racket', + rktd = 'racket', + rktl = 'racket', rad = 'radiance', mat = 'radiance', - ['pod6'] = 'raku', + pod6 = 'raku', rakudoc = 'raku', rakutest = 'raku', rakumod = 'raku', - ['pm6'] = 'raku', + pm6 = 'raku', raku = 'raku', - ['t6'] = 'raku', - ['p6'] = 'raku', + t6 = 'raku', + p6 = 'raku', raml = 'raml', rbs = 'rbs', rego = 'rego', rem = 'remind', remind = 'remind', + pip = 'requirements', res = 'rescript', resi = 'rescript', frt = 'reva', @@ -866,8 +867,11 @@ local extension = { Snw = 'rnoweb', robot = 'robot', resource = 'robot', + ron = 'ron', rsc = 'routeros', x = 'rpcgen', + rpgle = 'rpgle', + rpgleinc = 'rpgle', rpl = 'rpl', Srst = 'rrst', srst = 'rrst', @@ -885,6 +889,7 @@ local extension = { builder = 'ruby', rake = 'ruby', rs = 'rust', + sage = 'sage', sas = 'sas', sass = 'sass', sa = 'sather', @@ -893,9 +898,6 @@ local extension = { ss = 'scheme', scm = 'scheme', sld = 'scheme', - rkt = 'scheme', - rktd = 'scheme', - rktl = 'scheme', sce = 'scilab', sci = 'scilab', scss = 'scss', @@ -905,34 +907,18 @@ local extension = { sdl = 'sdl', sed = 'sed', sexp = 'sexplib', - bash = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ebuild = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - eclass = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - env = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, - ksh = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'ksh') - end, - sh = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, + bash = detect.bash, + ebuild = detect.bash, + eclass = detect.bash, + env = detect.sh, + ksh = detect.ksh, + sh = detect.sh, sieve = 'sieve', siv = 'sieve', - sig = function(path, bufnr) - return require('vim.filetype.detect').sig(bufnr) - end, - sil = function(path, bufnr) - return require('vim.filetype.detect').sil(bufnr) - end, + sig = detect.sig, + sil = detect.sil, sim = 'simula', - ['s85'] = 'sinda', + s85 = 'sinda', sin = 'sinda', ssm = 'sisu', sst = 'sisu', @@ -969,7 +955,7 @@ local extension = { spi = 'spyce', spy = 'spyce', tyc = 'sql', - typ = 'sql', + typ = detect.typ, pkb = 'sql', tyb = 'sql', pks = 'sql', @@ -977,15 +963,18 @@ local extension = { sqi = 'sqr', sqr = 'sqr', nut = 'squirrel', - ['s28'] = 'srec', - ['s37'] = 'srec', + s28 = 'srec', + s37 = 'srec', srec = 'srec', mot = 'srec', - ['s19'] = 'srec', + s19 = 'srec', srt = 'srt', ssa = 'ssa', ass = 'ssa', st = 'st', + ipd = 'starlark', + star = 'starlark', + starlark = 'starlark', imata = 'stata', ['do'] = 'stata', mata = 'stata', @@ -996,9 +985,15 @@ local extension = { svelte = 'svelte', svg = 'svg', swift = 'swift', + swig = 'swig', + swg = 'swig', svh = 'systemverilog', sv = 'systemverilog', + cmm = 'trace32', + t32 = 'trace32', + td = 'tablegen', tak = 'tak', + tal = 'tal', task = 'taskedit', tm = 'tcl', tcl = 'tcl', @@ -1014,9 +1009,7 @@ local extension = { bbl = 'tex', latex = 'tex', sty = 'tex', - cls = function(path, bufnr) - return require('vim.filetype.detect').cls(bufnr) - end, + cls = detect.cls, texi = 'texinfo', txi = 'texinfo', texinfo = 'texinfo', @@ -1035,20 +1028,31 @@ local extension = { tsv = 'tsv', tutor = 'tutor', twig = 'twig', - ts = function(path, bufnr) - return M.getlines(bufnr, 1):find('<%?xml') and 'xml' or 'typescript' - end, + ts = detect_line1('<%?xml', 'xml', 'typescript'), mts = 'typescript', cts = 'typescript', tsx = 'typescriptreact', uc = 'uc', uit = 'uil', uil = 'uil', + ungram = 'ungrammar', + u = 'unison', + uu = 'unison', + url = 'urlshortcut', + usd = 'usd', + usda = 'usd', + v = detect.v, + vsh = 'v', + vv = 'v', + ctl = 'vb', + dob = 'vb', + dsm = 'vb', + dsr = 'vb', + pag = 'vb', sba = 'vb', vb = 'vb', - dsm = 'vb', - ctl = 'vb', vbs = 'vb', + vba = detect.vba, vdf = 'vdf', vdmpp = 'vdmpp', vpp = 'vdmpp', @@ -1058,7 +1062,6 @@ local extension = { vr = 'vera', vri = 'vera', vrh = 'vera', - v = 'verilog', va = 'verilogams', vams = 'verilogams', vhdl = 'vhdl', @@ -1069,17 +1072,18 @@ local extension = { vbe = 'vhdl', tape = 'vhs', vim = 'vim', - vba = 'vim', mar = 'vmasm', cm = 'voscm', wrl = 'vrml', vroom = 'vroom', vue = 'vue', - wat = 'wast', - wast = 'wast', + wast = 'wat', + wat = 'wat', wdl = 'wdl', wm = 'webmacro', + wgsl = 'wgsl', wbt = 'winbatch', + wit = 'wit', wml = 'wml', wsml = 'wsml', ad = 'xdefaults', @@ -1087,7 +1091,7 @@ local extension = { xht = 'xhtml', msc = 'xmath', msf = 'xmath', - ['psc1'] = 'xml', + psc1 = 'xml', tpm = 'xml', xliff = 'xml', atom = 'xml', @@ -1103,10 +1107,8 @@ local extension = { csproj = 'xml', wpl = 'xml', xmi = 'xml', - xpm = function(path, bufnr) - return M.getlines(bufnr, 1):find('XPM2') and 'xpm2' or 'xpm' - end, - ['xpm2'] = 'xpm2', + xpm = detect_line1('XPM2', 'xpm2', 'xpm'), + xpm2 = 'xpm2', xqy = 'xquery', xqm = 'xquery', xquery = 'xquery', @@ -1121,191 +1123,80 @@ local extension = { yxx = 'yacc', yml = 'yaml', yaml = 'yaml', + eyaml = 'yaml', yang = 'yang', - ['z8a'] = 'z8a', + yuck = 'yuck', + z8a = 'z8a', zig = 'zig', - zir = 'zir', + zon = 'zig', zu = 'zimbu', zut = 'zimbutempl', + zs = 'zserio', zsh = 'zsh', vala = 'vala', - web = function(path, bufnr) - return require('vim.filetype.detect').web(bufnr) - end, - pl = function(path, bufnr) - return require('vim.filetype.detect').pl(bufnr) - end, - pp = function(path, bufnr) - return require('vim.filetype.detect').pp(bufnr) - end, - i = function(path, bufnr) - return require('vim.filetype.detect').progress_asm(bufnr) - end, - w = function(path, bufnr) - return require('vim.filetype.detect').progress_cweb(bufnr) - end, - p = function(path, bufnr) - return require('vim.filetype.detect').progress_pascal(bufnr) - end, - pro = function(path, bufnr) - return require('vim.filetype.detect').proto(bufnr, 'idlang') - end, - patch = function(path, bufnr) - return require('vim.filetype.detect').patch(bufnr) - end, - r = function(path, bufnr) - return require('vim.filetype.detect').r(bufnr) - end, - rdf = function(path, bufnr) - return require('vim.filetype.detect').redif(bufnr) - end, - rules = function(path, bufnr) - return require('vim.filetype.detect').rules(path) - end, - sc = function(path, bufnr) - return require('vim.filetype.detect').sc(bufnr) - end, - scd = function(path, bufnr) - return require('vim.filetype.detect').scd(bufnr) - end, + web = detect.web, + pl = detect.pl, + pp = detect.pp, + i = detect.i, + w = detect.progress_cweb, + p = detect.progress_pascal, + pro = detect_seq(detect.proto, 'idlang'), + patch = detect.patch, + r = detect.r, + rdf = detect.redif, + rules = detect.rules, + sc = detect.sc, + scd = detect.scd, tcsh = function(path, bufnr) - return require('vim.filetype.detect').shell(path, M.getlines(bufnr), 'tcsh') - end, - sql = function(path, bufnr) - return vim.g.filetype_sql and vim.g.filetype_sql or 'sql' - end, - zsql = function(path, bufnr) - return vim.g.filetype_sql and vim.g.filetype_sql or 'sql' - end, - tex = function(path, bufnr) - return require('vim.filetype.detect').tex(path, bufnr) - end, - tf = function(path, bufnr) - return require('vim.filetype.detect').tf(bufnr) - end, - txt = function(path, bufnr) - return require('vim.filetype.detect').txt(bufnr) - end, - xml = function(path, bufnr) - return require('vim.filetype.detect').xml(bufnr) - end, - y = function(path, bufnr) - return require('vim.filetype.detect').y(bufnr) - end, - cmd = function(path, bufnr) - return M.getlines(bufnr, 1):find('^/%*') and 'rexx' or 'dosbatch' - end, - rul = function(path, bufnr) - return require('vim.filetype.detect').rul(bufnr) - end, - cpy = function(path, bufnr) - return M.getlines(bufnr, 1):find('^##') and 'python' or 'cobol' - end, - dsl = function(path, bufnr) - return M.getlines(bufnr, 1):find('^%s*<!') and 'dsl' or 'structurizr' - end, - smil = function(path, bufnr) - return M.getlines(bufnr, 1):find('<%?%s*xml.*%?>') and 'xml' or 'smil' - end, - smi = function(path, bufnr) - return require('vim.filetype.detect').smi(bufnr) - end, - install = function(path, bufnr) - return require('vim.filetype.detect').install(path, bufnr) - end, - pm = function(path, bufnr) - return require('vim.filetype.detect').pm(bufnr) - end, - me = function(path, bufnr) - return require('vim.filetype.detect').me(path) - end, - reg = function(path, bufnr) - return require('vim.filetype.detect').reg(bufnr) - end, - ttl = function(path, bufnr) - return require('vim.filetype.detect').ttl(bufnr) - end, - rc = function(path, bufnr) - if not path:find('/etc/Muttrc%.d/') then - return 'rc' - end - end, - rch = function(path, bufnr) - if not path:find('/etc/Muttrc%.d/') then - return 'rc' - end - end, - class = function(path, bufnr) - require('vim.filetype.detect').class(bufnr) - end, - sgml = function(path, bufnr) - return require('vim.filetype.detect').sgml(bufnr) - end, - sgm = function(path, bufnr) - return require('vim.filetype.detect').sgml(bufnr) - end, - t = function(path, bufnr) - local nroff = require('vim.filetype.detect').nroff(bufnr) - return nroff or require('vim.filetype.detect').perl(path, bufnr) or 'tads' - end, + return require('vim.filetype.detect').shell(path, M._getlines(bufnr), 'tcsh') + end, + sql = detect.sql, + zsql = detect.sql, + tex = detect.tex, + tf = detect.tf, + txt = detect.txt, + xml = detect.xml, + y = detect.y, + cmd = detect_line1('^/%*', 'rexx', 'dosbatch'), + rul = detect.rul, + cpy = detect_line1('^##', 'python', 'cobol'), + dsl = detect_line1('^%s*<!', 'dsl', 'structurizr'), + smil = detect_line1('<%?%s*xml.*%?>', 'xml', 'smil'), + smi = detect.smi, + install = detect.install, + pm = detect.pm, + me = detect.me, + reg = detect.reg, + ttl = detect.ttl, + rc = detect_rc, + rch = detect_rc, + class = detect.class, + sgml = detect.sgml, + sgm = detect.sgml, + t = detect_seq(detect.nroff, detect.perl, 'tads'), -- Ignored extensions - bak = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - ['dpkg-bak'] = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - ['dpkg-dist'] = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - ['dpkg-old'] = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - ['dpkg-new'] = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, + bak = detect_noext, + ['dpkg-bak'] = detect_noext, + ['dpkg-dist'] = detect_noext, + ['dpkg-old'] = detect_noext, + ['dpkg-new'] = detect_noext, ['in'] = function(path, bufnr) if vim.fs.basename(path) ~= 'configure.in' then - local root = vim.fn.fnamemodify(path, ':r') + local root = fn.fnamemodify(path, ':r') return M.match({ buf = bufnr, filename = root }) end end, - new = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - old = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - orig = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - pacsave = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - pacnew = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - rpmsave = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, - rmpnew = function(path, bufnr) - local root = vim.fn.fnamemodify(path, ':r') - return M.match({ buf = bufnr, filename = root }) - end, + new = detect_noext, + old = detect_noext, + orig = detect_noext, + pacsave = detect_noext, + pacnew = detect_noext, + rpmsave = detect_noext, + rmpnew = detect_noext, -- END EXTENSION } +--- @type vim.filetype.mapping local filename = { -- BEGIN FILENAME ['a2psrc'] = 'a2ps', @@ -1324,6 +1215,7 @@ local filename = { ['named.root'] = 'bindzone', WORKSPACE = 'bzl', ['WORKSPACE.bzlmod'] = 'bzl', + BUCK = 'bzl', BUILD = 'bzl', ['cabal.project'] = 'cabalproject', ['cabal.config'] = 'cabalconfig', @@ -1335,24 +1227,12 @@ local filename = { ['/etc/defaults/cdrdao'] = 'cdrdaoconf', ['cfengine.conf'] = 'cfengine', ['CMakeLists.txt'] = 'cmake', - ['.alias'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, - ['.cshrc'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, - ['.login'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, - ['csh.cshrc'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, - ['csh.login'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, - ['csh.logout'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, + ['.alias'] = detect.csh, + ['.cshrc'] = detect.csh, + ['.login'] = detect.csh, + ['csh.cshrc'] = detect.csh, + ['csh.login'] = detect.csh, + ['csh.logout'] = detect.csh, ['auto.master'] = 'conf', ['configure.in'] = 'config', ['configure.ac'] = 'config', @@ -1392,18 +1272,10 @@ local filename = { ['exim.conf'] = 'exim', exports = 'exports', ['.fetchmailrc'] = 'fetchmail', - fvSchemes = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - fvSolution = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - fvConstraints = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - fvModels = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, + fvSchemes = detect.foam, + fvSolution = detect.foam, + fvConstraints = detect.foam, + fvModels = detect.foam, fstab = 'fstab', mtab = 'fstab', ['.gdbinit'] = 'gdb', @@ -1411,11 +1283,11 @@ local filename = { ['.gdbearlyinit'] = 'gdb', gdbearlyinit = 'gdb', ['lltxxxxx.txt'] = 'gedcom', - ['TAG_EDITMSG'] = 'gitcommit', - ['MERGE_MSG'] = 'gitcommit', - ['COMMIT_EDITMSG'] = 'gitcommit', - ['NOTES_EDITMSG'] = 'gitcommit', - ['EDIT_DESCRIPTION'] = 'gitcommit', + TAG_EDITMSG = 'gitcommit', + MERGE_MSG = 'gitcommit', + COMMIT_EDITMSG = 'gitcommit', + NOTES_EDITMSG = 'gitcommit', + EDIT_DESCRIPTION = 'gitcommit', ['.gitconfig'] = 'gitconfig', ['.gitmodules'] = 'gitconfig', ['.gitattributes'] = 'gitattributes', @@ -1429,10 +1301,12 @@ local filename = { gnashrc = 'gnash', ['.gnuplot'] = 'gnuplot', ['go.sum'] = 'gosum', + ['go.work.sum'] = 'gosum', ['go.work'] = 'gowork', ['.gprc'] = 'gp', ['/.gnupg/gpg.conf'] = 'gpg', ['/.gnupg/options'] = 'gpg', + Jenkinsfile = 'groovy', ['/var/backups/gshadow.bak'] = 'group', ['/etc/gshadow'] = 'group', ['/etc/group-'] = 'group', @@ -1461,12 +1335,14 @@ local filename = { ['Pipfile.lock'] = 'json', ['.firebaserc'] = 'json', ['.prettierrc'] = 'json', + ['.stylelintrc'] = 'json', ['.babelrc'] = 'jsonc', ['.eslintrc'] = 'jsonc', ['.hintrc'] = 'jsonc', ['.jsfmtrc'] = 'jsonc', ['.jshintrc'] = 'jsonc', ['.swrc'] = 'jsonc', + ['.justfile'] = 'just', Kconfig = 'kconfig', ['Kconfig.debug'] = 'kconfig', ['lftp.conf'] = 'lftp', @@ -1481,9 +1357,8 @@ local filename = { ['.sawfishrc'] = 'lisp', ['/etc/login.access'] = 'loginaccess', ['/etc/login.defs'] = 'logindefs', - ['.lsl'] = function(path, bufnr) - return require('vim.filetype.detect').lsl(bufnr) - end, + ['.lsl'] = detect.lsl, + ['.busted'] = 'lua', ['.luacheckrc'] = 'lua', ['lynx.cfg'] = 'lynx', ['m3overrides'] = 'm3build', @@ -1500,6 +1375,7 @@ local filename = { ['man.config'] = 'manconf', ['maxima-init.mac'] = 'maxima', ['meson.build'] = 'meson', + ['meson.options'] = 'meson', ['meson_options.txt'] = 'meson', ['/etc/conf.modules'] = 'modconf', ['/etc/modules'] = 'modconf', @@ -1511,9 +1387,7 @@ local filename = { ['/etc/nanorc'] = 'nanorc', Neomuttrc = 'neomuttrc', ['.netrc'] = 'netrc', - NEWS = function(path, bufnr) - return require('vim.filetype.detect').news(bufnr) - end, + NEWS = detect.news, ['.ocamlinit'] = 'ocaml', ['.octaverc'] = 'octave', octaverc = 'octave', @@ -1542,39 +1416,36 @@ local filename = { ['/etc/pinforc'] = 'pinfo', ['/.pinforc'] = 'pinfo', ['.povrayrc'] = 'povini', - ['printcap'] = function(path, bufnr) + printcap = function(path, bufnr) return 'ptcap', function(b) vim.b[b].ptcap_type = 'print' end end, - ['termcap'] = function(path, bufnr) + termcap = function(path, bufnr) return 'ptcap', function(b) vim.b[b].ptcap_type = 'term' end end, ['.procmailrc'] = 'procmail', ['.procmail'] = 'procmail', - ['indent.pro'] = function(path, bufnr) - return require('vim.filetype.detect').proto(bufnr, 'indent') - end, + ['indent.pro'] = detect_seq(detect.proto, 'indent'), ['/etc/protocols'] = 'protocols', - ['INDEX'] = function(path, bufnr) - return require('vim.filetype.detect').psf(bufnr) - end, - ['INFO'] = function(path, bufnr) - return require('vim.filetype.detect').psf(bufnr) - end, + INDEX = detect.psf, + INFO = detect.psf, + ['MANIFEST.in'] = 'pymanifest', ['.pythonstartup'] = 'python', ['.pythonrc'] = 'python', SConstruct = 'python', + qmldir = 'qmldir', ['.Rprofile'] = 'r', - ['Rprofile'] = 'r', + Rprofile = 'r', ['Rprofile.site'] = 'r', ratpoisonrc = 'ratpoison', ['.ratpoisonrc'] = 'ratpoison', inputrc = 'readline', ['.inputrc'] = 'readline', ['.reminders'] = 'remind', + ['requirements.txt'] = 'requirements', ['resolv.conf'] = 'resolv', ['robots.txt'] = 'robots', Gemfile = 'ruby', @@ -1590,42 +1461,18 @@ local filename = { ['/etc/services'] = 'services', ['/etc/serial.conf'] = 'setserial', ['/etc/udev/cdsymlinks.conf'] = 'sh', - ['bash.bashrc'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - bashrc = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['.bashrc'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['.env'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, - ['.kshrc'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'ksh') - end, - ['.profile'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, - ['/etc/profile'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, - APKBUILD = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - PKGBUILD = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['.tcshrc'] = function(path, bufnr) - return require('vim.filetype.detect').shell(path, M.getlines(bufnr), 'tcsh') - end, - ['tcsh.login'] = function(path, bufnr) - return require('vim.filetype.detect').shell(path, M.getlines(bufnr), 'tcsh') - end, - ['tcsh.tcshrc'] = function(path, bufnr) - return require('vim.filetype.detect').shell(path, M.getlines(bufnr), 'tcsh') - end, + ['bash.bashrc'] = detect.bash, + bashrc = detect.bash, + ['.bashrc'] = detect.bash, + ['.env'] = detect.sh, + ['.kshrc'] = detect.ksh, + ['.profile'] = detect.sh, + ['/etc/profile'] = detect.sh, + APKBUILD = detect.bash, + PKGBUILD = detect.bash, + ['.tcshrc'] = detect.tcsh, + ['tcsh.login'] = detect.tcsh, + ['tcsh.tcshrc'] = detect.tcsh, ['/etc/slp.conf'] = 'slpconf', ['/etc/slp.reg'] = 'slpreg', ['/etc/slp.spi'] = 'slpspi', @@ -1675,27 +1522,20 @@ local filename = { wget2rc = 'wget2', ['.wvdialrc'] = 'wvdial', ['wvdial.conf'] = 'wvdial', + ['.XCompose'] = 'xcompose', + ['Compose'] = 'xcompose', ['.Xresources'] = 'xdefaults', ['.Xpdefaults'] = 'xdefaults', ['xdm-config'] = 'xdefaults', ['.Xdefaults'] = 'xdefaults', - ['xorg.conf'] = function(path, bufnr) - return 'xf86conf', function(b) - vim.b[b].xf86conf_xfree86_version = 4 - end - end, - ['xorg.conf-4'] = function(path, bufnr) - return 'xf86conf', function(b) - vim.b[b].xf86conf_xfree86_version = 4 - end - end, - ['XF86Config'] = function(path, bufnr) - return require('vim.filetype.detect').xfree86() - end, + ['xorg.conf'] = detect.xfree86_v4, + ['xorg.conf-4'] = detect.xfree86_v4, + ['XF86Config'] = detect.xfree86_v3, ['/etc/xinetd.conf'] = 'xinetd', fglrxrc = 'xml', ['/etc/blkid.tab'] = 'xml', ['/etc/blkid.tab.old'] = 'xml', + ['.clangd'] = 'yaml', ['.clang-format'] = 'yaml', ['.clang-tidy'] = 'yaml', ['/etc/zprofile'] = 'zsh', @@ -1709,6 +1549,12 @@ local filename = { -- END FILENAME } +-- Re-use closures as much as possible +local detect_apache = starsetf('apache') +local detect_muttrc = starsetf('muttrc') +local detect_neomuttrc = starsetf('neomuttrc') + +--- @type vim.filetype.mapping local pattern = { -- BEGIN PATTERN ['.*/etc/a2ps/.*%.cfg'] = 'a2ps', @@ -1717,40 +1563,39 @@ local pattern = { ['.*/etc/asound%.conf'] = 'alsaconf', ['.*/etc/apache2/sites%-.*/.*%.com'] = 'apache', ['.*/etc/httpd/.*%.conf'] = 'apache', - ['.*/etc/apache2/.*%.conf.*'] = starsetf('apache'), - ['.*/etc/apache2/conf%..*/.*'] = starsetf('apache'), - ['.*/etc/apache2/mods%-.*/.*'] = starsetf('apache'), - ['.*/etc/apache2/sites%-.*/.*'] = starsetf('apache'), - ['access%.conf.*'] = starsetf('apache'), - ['apache%.conf.*'] = starsetf('apache'), - ['apache2%.conf.*'] = starsetf('apache'), - ['httpd%.conf.*'] = starsetf('apache'), - ['srm%.conf.*'] = starsetf('apache'), - ['.*/etc/httpd/conf%..*/.*'] = starsetf('apache'), - ['.*/etc/httpd/conf%.d/.*%.conf.*'] = starsetf('apache'), - ['.*/etc/httpd/mods%-.*/.*'] = starsetf('apache'), - ['.*/etc/httpd/sites%-.*/.*'] = starsetf('apache'), + ['.*/etc/apache2/.*%.conf.*'] = detect_apache, + ['.*/etc/apache2/conf%..*/.*'] = detect_apache, + ['.*/etc/apache2/mods%-.*/.*'] = detect_apache, + ['.*/etc/apache2/sites%-.*/.*'] = detect_apache, + ['access%.conf.*'] = detect_apache, + ['apache%.conf.*'] = detect_apache, + ['apache2%.conf.*'] = detect_apache, + ['httpd%.conf.*'] = detect_apache, + ['srm%.conf.*'] = detect_apache, + ['.*/etc/httpd/conf%..*/.*'] = detect_apache, + ['.*/etc/httpd/conf%.d/.*%.conf.*'] = detect_apache, + ['.*/etc/httpd/mods%-.*/.*'] = detect_apache, + ['.*/etc/httpd/sites%-.*/.*'] = detect_apache, ['.*/etc/proftpd/.*%.conf.*'] = starsetf('apachestyle'), ['.*/etc/proftpd/conf%..*/.*'] = starsetf('apachestyle'), ['proftpd%.conf.*'] = starsetf('apachestyle'), ['.*asterisk/.*%.conf.*'] = starsetf('asterisk'), ['.*asterisk.*/.*voicemail%.conf.*'] = starsetf('asteriskvm'), ['.*/%.aptitude/config'] = 'aptconf', - ['.*%.[aA]'] = function(path, bufnr) - return require('vim.filetype.detect').asm(bufnr) - end, - ['.*%.[sS]'] = function(path, bufnr) - return require('vim.filetype.detect').asm(bufnr) - end, + ['.*%.[aA]'] = detect.asm, + ['.*%.[sS]'] = detect.asm, ['[mM]akefile%.am'] = 'automake', ['.*/bind/db%..*'] = starsetf('bindzone'), ['.*/named/db%..*'] = starsetf('bindzone'), ['.*/build/conf/.*%.conf'] = 'bitbake', ['.*/meta/conf/.*%.conf'] = 'bitbake', ['.*/meta%-.*/conf/.*%.conf'] = 'bitbake', + ['.*%.blade%.php'] = 'blade', ['bzr_log%..*'] = 'bzr', ['.*enlightenment/.*%.cfg'] = 'c', ['${HOME}/cabal%.config'] = 'cabalconfig', + ['${HOME}/%.config/cabal/config'] = 'cabalconfig', + ['${XDG_CONFIG_HOME}/cabal/config'] = 'cabalconfig', ['cabal%.project%..*'] = starsetf('cabalproject'), ['.*/%.calendar/.*'] = starsetf('calendar'), ['.*/share/calendar/.*/calendar%..*'] = starsetf('calendar'), @@ -1761,16 +1606,12 @@ local pattern = { ['.*/etc/default/cdrdao'] = 'cdrdaoconf', ['.*hgrc'] = 'cfg', ['.*%.[Cc][Ff][Gg]'] = { - function(path, bufnr) - return require('vim.filetype.detect').cfg(bufnr) - end, + detect.cfg, -- Decrease priority to avoid conflicts with more specific patterns -- such as '.*/etc/a2ps/.*%.cfg', '.*enlightenment/.*%.cfg', etc. { priority = -1 }, }, - ['[cC]hange[lL]og.*'] = starsetf(function(path, bufnr) - return require('vim.filetype.detect').changelog(bufnr) - end), + ['[cC]hange[lL]og.*'] = starsetf(detect.changelog), ['.*%.%.ch'] = 'chill', ['.*%.cmake%.in'] = 'cmake', -- */cmus/rc and */.cmus/rc @@ -1782,19 +1623,11 @@ local pattern = { ['.*/etc/hostname%..*'] = starsetf('config'), ['crontab%..*'] = starsetf('crontab'), ['.*/etc/cron%.d/.*'] = starsetf('crontab'), - ['%.cshrc.*'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, - ['%.login.*'] = function(path, bufnr) - return require('vim.filetype.detect').csh(path, bufnr) - end, + ['%.cshrc.*'] = detect.csh, + ['%.login.*'] = detect.csh, ['cvs%d+'] = 'cvs', - ['.*%.[Dd][Aa][Tt]'] = function(path, bufnr) - return require('vim.filetype.detect').dat(path, bufnr) - end, - ['.*/debian/patches/.*'] = function(path, bufnr) - return require('vim.filetype.detect').dep3patch(path, bufnr) - end, + ['.*%.[Dd][Aa][Tt]'] = detect.dat, + ['.*/debian/patches/.*'] = detect.dep3patch, ['.*/etc/dnsmasq%.d/.*'] = starsetf('dnsmasq'), ['Containerfile%..*'] = starsetf('dockerfile'), ['Dockerfile%..*'] = starsetf('dockerfile'), @@ -1805,6 +1638,7 @@ local pattern = { ['.*/debian/copyright'] = 'debcopyright', ['.*/etc/apt/sources%.list%.d/.*%.list'] = 'debsources', ['.*/etc/apt/sources%.list'] = 'debsources', + ['.*/etc/apt/sources%.list%.d/.*%.sources'] = 'deb822sources', ['.*%.directory'] = 'desktop', ['.*%.desktop'] = 'desktop', ['dictd.*%.conf'] = 'dictdconf', @@ -1820,53 +1654,25 @@ local pattern = { ['.*/dtrace/.*%.d'] = 'dtrace', ['.*esmtprc'] = 'esmtprc', ['.*Eterm/.*%.cfg'] = 'eterm', - ['[a-zA-Z0-9].*Dict'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['[a-zA-Z0-9].*Dict%..*'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['[a-zA-Z].*Properties'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['[a-zA-Z].*Properties%..*'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['.*Transport%..*'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['.*/constant/g'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['.*/0/.*'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, - ['.*/0%.orig/.*'] = function(path, bufnr) - return require('vim.filetype.detect').foam(bufnr) - end, + ['[a-zA-Z0-9].*Dict'] = detect.foam, + ['[a-zA-Z0-9].*Dict%..*'] = detect.foam, + ['[a-zA-Z].*Properties'] = detect.foam, + ['[a-zA-Z].*Properties%..*'] = detect.foam, + ['.*Transport%..*'] = detect.foam, + ['.*/constant/g'] = detect.foam, + ['.*/0/.*'] = detect.foam, + ['.*/0%.orig/.*'] = detect.foam, ['.*/%.fvwm/.*'] = starsetf('fvwm'), - ['.*fvwmrc.*'] = starsetf(function(path, bufnr) - return 'fvwm', function(b) - vim.b[b].fvwm_version = 1 - end - end), - ['.*fvwm95.*%.hook'] = starsetf(function(path, bufnr) - return 'fvwm', function(b) - vim.b[b].fvwm_version = 1 - end - end), - ['.*fvwm2rc.*'] = starsetf(function(path, bufnr) - return require('vim.filetype.detect').fvwm(path) - end), + ['.*fvwmrc.*'] = starsetf(detect.fvwm_v1), + ['.*fvwm95.*%.hook'] = starsetf(detect.fvwm_v1), + ['.*fvwm2rc.*'] = starsetf(detect.fvwm_v2), ['.*/tmp/lltmp.*'] = starsetf('gedcom'), ['.*/etc/gitconfig%.d/.*'] = starsetf('gitconfig'), ['.*/gitolite%-admin/conf/.*'] = starsetf('gitolite'), ['tmac%..*'] = starsetf('nroff'), ['.*/%.gitconfig%.d/.*'] = starsetf('gitconfig'), ['.*%.git/.*'] = { - function(path, bufnr) - return require('vim.filetype.detect').git(bufnr) - end, + detect.git, -- Decrease priority to run after simple pattern checks { priority = -1 }, }, @@ -1922,6 +1728,7 @@ local pattern = { ['org%.eclipse%..*%.prefs'] = 'jproperties', ['.*%.properties_.._.._.*'] = starsetf('jproperties'), ['[jt]sconfig.*%.json'] = 'jsonc', + ['[jJ]ustfile'] = 'just', ['Kconfig%..*'] = starsetf('kconfig'), ['.*%.[Ss][Uu][Bb]'] = 'krl', ['lilo%.conf.*'] = starsetf('lilo'), @@ -2029,15 +1836,13 @@ local pattern = { ['.*/log/news/news%.notice'] = 'messages', ['.*/log/syslog%.notice'] = 'messages', ['.*/log/user%.notice'] = 'messages', - ['.*%.[Mm][Oo][Dd]'] = function(path, bufnr) - return require('vim.filetype.detect').mod(path, bufnr) - end, + ['.*%.[Mm][Oo][Dd]'] = detect.mod, ['.*/etc/modules%.conf'] = 'modconf', ['.*/etc/conf%.modules'] = 'modconf', ['.*/etc/modules'] = 'modconf', ['.*/etc/modprobe%..*'] = starsetf('modconf'), ['.*/etc/modutils/.*'] = starsetf(function(path, bufnr) - if vim.fn.executable(vim.fn.expand(path)) ~= 1 then + if fn.executable(fn.expand(path)) ~= 1 then return 'modconf' end end), @@ -2046,32 +1851,30 @@ local pattern = { ['Muttngrc'] = 'muttrc', ['.*/etc/Muttrc%.d/.*'] = starsetf('muttrc'), ['.*/%.mplayer/config'] = 'mplayerconf', - ['Muttrc.*'] = starsetf('muttrc'), - ['Muttngrc.*'] = starsetf('muttrc'), + ['Muttrc.*'] = detect_muttrc, + ['Muttngrc.*'] = detect_muttrc, -- muttrc* and .muttrc* - ['%.?muttrc.*'] = starsetf('muttrc'), + ['%.?muttrc.*'] = detect_muttrc, -- muttngrc* and .muttngrc* - ['%.?muttngrc.*'] = starsetf('muttrc'), - ['.*/%.mutt/muttrc.*'] = starsetf('muttrc'), - ['.*/%.muttng/muttrc.*'] = starsetf('muttrc'), - ['.*/%.muttng/muttngrc.*'] = starsetf('muttrc'), + ['%.?muttngrc.*'] = detect_muttrc, + ['.*/%.mutt/muttrc.*'] = detect_muttrc, + ['.*/%.muttng/muttrc.*'] = detect_muttrc, + ['.*/%.muttng/muttngrc.*'] = detect_muttrc, ['rndc.*%.conf'] = 'named', ['rndc.*%.key'] = 'named', ['named.*%.conf'] = 'named', ['.*/etc/nanorc'] = 'nanorc', ['.*%.NS[ACGLMNPS]'] = 'natural', - ['Neomuttrc.*'] = starsetf('neomuttrc'), + ['Neomuttrc.*'] = detect_neomuttrc, -- neomuttrc* and .neomuttrc* - ['%.?neomuttrc.*'] = starsetf('neomuttrc'), - ['.*/%.neomutt/neomuttrc.*'] = starsetf('neomuttrc'), + ['%.?neomuttrc.*'] = detect_neomuttrc, + ['.*/%.neomutt/neomuttrc.*'] = detect_neomuttrc, ['nginx.*%.conf'] = 'nginx', ['.*/etc/nginx/.*'] = 'nginx', ['.*nginx%.conf'] = 'nginx', ['.*/nginx/.*%.conf'] = 'nginx', ['.*/usr/local/nginx/conf/.*'] = 'nginx', - ['.*%.[1-9]'] = function(path, bufnr) - return require('vim.filetype.detect').nroff(bufnr) - end, + ['.*%.[1-9]'] = detect.nroff, ['.*%.ml%.cppo'] = 'ocaml', ['.*%.mli%.cppo'] = 'ocaml', ['.*%.opam%.template'] = 'opam', @@ -2092,9 +1895,7 @@ local pattern = { ['.*%.php%d'] = 'php', ['.*/%.pinforc'] = 'pinfo', ['.*/etc/pinforc'] = 'pinfo', - ['.*%.[Pp][Rr][Gg]'] = function(path, bufnr) - return require('vim.filetype.detect').prg(bufnr) - end, + ['.*%.[Pp][Rr][Gg]'] = detect.prg, ['.*/etc/protocols'] = 'protocols', ['.*printcap.*'] = starsetf(function(path, bufnr) return require('vim.filetype.detect').printcap('print') @@ -2114,30 +1915,14 @@ local pattern = { ['.*/etc/services'] = 'services', ['.*/etc/serial%.conf'] = 'setserial', ['.*/etc/udev/cdsymlinks%.conf'] = 'sh', - ['%.bash[_%-]aliases'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['%.bash[_%-]logout'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['%.bash[_%-]profile'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['%.kshrc.*'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'ksh') - end, - ['%.profile.*'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, - ['.*/etc/profile'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr)) - end, - ['bash%-fc[%-%.]'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'bash') - end, - ['%.tcshrc.*'] = function(path, bufnr) - return require('vim.filetype.detect').sh(path, M.getlines(bufnr), 'tcsh') - end, + ['%.bash[_%-]aliases'] = detect.bash, + ['%.bash[_%-]logout'] = detect.bash, + ['%.bash[_%-]profile'] = detect.bash, + ['%.kshrc.*'] = detect.ksh, + ['%.profile.*'] = detect.sh, + ['.*/etc/profile'] = detect.sh, + ['bash%-fc[%-%.].*'] = detect.bash, + ['%.tcshrc.*'] = detect.tcsh, ['.*/etc/sudoers%.d/.*'] = starsetf('sudoers'), ['.*%._sst%.meta'] = 'sisu', ['.*%.%-sst%.meta'] = 'sisu', @@ -2149,17 +1934,13 @@ local pattern = { ['.*/%.ssh/config'] = 'sshconfig', ['.*/%.ssh/.*%.conf'] = 'sshconfig', ['.*/etc/ssh/sshd_config%.d/.*%.conf'] = 'sshdconfig', - ['.*%.[Ss][Rr][Cc]'] = function(path, bufnr) - return require('vim.filetype.detect').src(bufnr) - end, + ['.*%.[Ss][Rr][Cc]'] = detect.src, ['.*/etc/sudoers'] = 'sudoers', ['svn%-commit.*%.tmp'] = 'svn', ['.*/sway/config'] = 'swayconfig', ['.*/%.sway/config'] = 'swayconfig', ['.*%.swift%.gyb'] = 'swiftgyb', - ['.*%.[Ss][Yy][Ss]'] = function(path, bufnr) - return require('vim.filetype.detect').sys(bufnr) - end, + ['.*%.[Ss][Yy][Ss]'] = detect.sys, ['.*/etc/sysctl%.conf'] = 'sysctl', ['.*/etc/sysctl%.d/.*%.conf'] = 'sysctl', ['.*/systemd/.*%.automount'] = 'systemd', @@ -2202,14 +1983,17 @@ local pattern = { ['.*/%.config/upstart/.*%.conf'] = 'upstart', ['.*/%.init/.*%.conf'] = 'upstart', ['.*/usr/share/upstart/.*%.override'] = 'upstart', - ['.*%.[Ll][Oo][Gg]'] = function(path, bufnr) - return require('vim.filetype.detect').log(path) - end, + ['.*%.[Ll][Oo][Gg]'] = detect.log, ['.*%.vhdl_[0-9].*'] = starsetf('vhdl'), ['.*%.ws[fc]'] = 'wsh', ['.*/Xresources/.*'] = starsetf('xdefaults'), ['.*/app%-defaults/.*'] = starsetf('xdefaults'), ['.*/etc/xinetd%.conf'] = 'xinetd', + ['.*/usr/share/X11/xkb/compat/.*'] = starsetf('xkb'), + ['.*/usr/share/X11/xkb/geometry/.*'] = starsetf('xkb'), + ['.*/usr/share/X11/xkb/keycodes/.*'] = starsetf('xkb'), + ['.*/usr/share/X11/xkb/symbols/.*'] = starsetf('xkb'), + ['.*/usr/share/X11/xkb/types/.*'] = starsetf('xkb'), ['.*/etc/blkid%.tab'] = 'xml', ['.*/etc/blkid%.tab%.old'] = 'xml', ['.*%.vbproj%.user'] = 'xml', @@ -2222,20 +2006,10 @@ local pattern = { ['Xresources.*'] = starsetf('xdefaults'), ['.*/etc/xinetd%.d/.*'] = starsetf('xinetd'), ['.*xmodmap.*'] = starsetf('xmodmap'), - ['.*/xorg%.conf%.d/.*%.conf'] = function(path, bufnr) - return 'xf86config', function(b) - vim.b[b].xf86conf_xfree86_version = 4 - end - end, + ['.*/xorg%.conf%.d/.*%.conf'] = detect.xfree86_v4, -- Increase priority to run before the pattern below - ['XF86Config%-4.*'] = starsetf(function(path, bufnr) - return 'xf86conf', function(b) - vim.b[b].xf86conf_xfree86_version = 4 - end - end, { priority = -math.huge + 1 }), - ['XF86Config.*'] = starsetf(function(path, bufnr) - return require('vim.filetype.detect').xfree86() - end), + ['XF86Config%-4.*'] = starsetf(detect.xfree86_v4, { priority = -math.huge + 1 }), + ['XF86Config.*'] = starsetf(detect.xfree86_v3), ['%.zcompdump.*'] = starsetf('zsh'), -- .zlog* and zlog* ['%.?zlog.*'] = starsetf('zsh'), @@ -2245,7 +2019,7 @@ local pattern = { ['.*~'] = function(path, bufnr) local short = path:gsub('~$', '', 1) if path ~= short and short ~= '' then - return M.match({ buf = bufnr, filename = vim.fn.fnameescape(short) }) + return M.match({ buf = bufnr, filename = fn.fnameescape(short) }) end end, -- END PATTERN @@ -2253,9 +2027,10 @@ local pattern = { -- luacheck: pop -- luacheck: pop ----@private +--- @param t vim.filetype.mapping +--- @return vim.filetype.mapping[] local function sort_by_priority(t) - local sorted = {} + local sorted = {} --- @type vim.filetype.mapping[] for k, v in pairs(t) do local ft = type(v) == 'table' and v[1] or v assert( @@ -2277,7 +2052,9 @@ end local pattern_sorted = sort_by_priority(pattern) ----@private +--- @param path string +--- @param as_pattern? true +--- @return string local function normalize_path(path, as_pattern) local normal = path:gsub('\\', '/') if normal:find('^~') then @@ -2286,12 +2063,17 @@ local function normalize_path(path, as_pattern) -- The rest of path should already be properly escaped. normal = vim.pesc(vim.env.HOME) .. normal:sub(2) else - normal = vim.env.HOME .. normal:sub(2) + normal = vim.env.HOME .. normal:sub(2) --- @type string end end return normal end +--- @class vim.filetype.add.filetypes +--- @field pattern? vim.filetype.mapping +--- @field extension? vim.filetype.mapping +--- @field filename? vim.filetype.mapping + --- Add new filetype mappings. --- --- Filetype mappings can be added either by extension or by filename (either @@ -2307,7 +2089,8 @@ end --- pattern, if any) and should return a string that will be used as the --- buffer's filetype. Optionally, the function can return a second function --- value which, when called, modifies the state of the buffer. This can be used ---- to, for example, set filetype-specific buffer variables. +--- to, for example, set filetype-specific buffer variables. This function will +--- be called by Nvim before setting the buffer's filetype. --- --- Filename patterns can specify an optional priority to resolve cases when a --- file path matches multiple patterns. Higher priorities are matched first. @@ -2319,61 +2102,63 @@ end --- See $VIMRUNTIME/lua/vim/filetype.lua for more examples. --- --- Example: ---- <pre>lua ---- vim.filetype.add({ ---- extension = { ---- foo = 'fooscript', ---- bar = function(path, bufnr) ---- if some_condition() then ---- return 'barscript', function(bufnr) ---- -- Set a buffer variable ---- vim.b[bufnr].barscript_version = 2 ---- end ---- end ---- return 'bar' ---- end, ---- }, ---- filename = { ---- ['.foorc'] = 'toml', ---- ['/etc/foo/config'] = 'toml', ---- }, ---- pattern = { ---- ['.*/etc/foo/.*'] = 'fooscript', ---- -- Using an optional priority ---- ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, ---- -- A pattern containing an environment variable ---- ['${XDG_CONFIG_HOME}/foo/git'] = 'git', ---- ['README.(%a+)$'] = function(path, bufnr, ext) ---- if ext == 'md' then ---- return 'markdown' ---- elseif ext == 'rst' then ---- return 'rst' ---- end ---- end, ---- }, ---- }) ---- </pre> +--- +--- ```lua +--- vim.filetype.add({ +--- extension = { +--- foo = 'fooscript', +--- bar = function(path, bufnr) +--- if some_condition() then +--- return 'barscript', function(bufnr) +--- -- Set a buffer variable +--- vim.b[bufnr].barscript_version = 2 +--- end +--- end +--- return 'bar' +--- end, +--- }, +--- filename = { +--- ['.foorc'] = 'toml', +--- ['/etc/foo/config'] = 'toml', +--- }, +--- pattern = { +--- ['.*/etc/foo/.*'] = 'fooscript', +--- -- Using an optional priority +--- ['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, +--- -- A pattern containing an environment variable +--- ['${XDG_CONFIG_HOME}/foo/git'] = 'git', +--- ['README.(%a+)$'] = function(path, bufnr, ext) +--- if ext == 'md' then +--- return 'markdown' +--- elseif ext == 'rst' then +--- return 'rst' +--- end +--- end, +--- }, +--- }) +--- ``` --- --- To add a fallback match on contents, use ---- <pre>lua +--- +--- ```lua --- vim.filetype.add { --- pattern = { --- ['.*'] = { --- priority = -math.huge, --- function(path, bufnr) ---- local content = vim.filetype.getlines(bufnr, 1) ---- if vim.filetype.matchregex(content, [[^#!.*\\<mine\\>]]) then +--- local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or '' +--- if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then --- return 'mine' ---- elseif vim.filetype.matchregex(content, [[\\<drawing\\>]]) then +--- elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then --- return 'drawing' --- end --- end, --- }, --- }, --- } ---- </pre> +--- ``` --- ----@param filetypes table A table containing new filetype maps (see example). +---@param filetypes vim.filetype.add.filetypes A table containing new filetype maps (see example). function M.add(filetypes) for k, v in pairs(filetypes.extension or {}) do extension[k] = v @@ -2392,66 +2177,93 @@ function M.add(filetypes) end end ----@private +--- @param ft vim.filetype.mapping.value +--- @param path? string +--- @param bufnr? integer +--- @param ... any +--- @return string? +--- @return fun(b: integer)? local function dispatch(ft, path, bufnr, ...) - local on_detect - if type(ft) == 'function' then - if bufnr then - ft, on_detect = ft(path, bufnr, ...) - else - -- If bufnr is nil (meaning we are matching only against the filename), set it to an invalid - -- value (-1) and catch any errors from the filetype detection function. If the function tries - -- to use the buffer then it will fail, but this enables functions which do not need a buffer - -- to still work. - local ok - ok, ft, on_detect = pcall(ft, path, -1, ...) - if not ok then - return - end + if type(ft) == 'string' then + return ft + end + + if type(ft) ~= 'function' then + return + end + + assert(path) + + ---@type string|false?, fun(b: integer)? + local ft0, on_detect + if bufnr then + ft0, on_detect = ft(path, bufnr, ...) + else + -- If bufnr is nil (meaning we are matching only against the filename), set it to an invalid + -- value (-1) and catch any errors from the filetype detection function. If the function tries + -- to use the buffer then it will fail, but this enables functions which do not need a buffer + -- to still work. + local ok + ok, ft0, on_detect = pcall(ft, path, -1, ...) + if not ok then + return end end - if type(ft) == 'string' then - return ft, on_detect + if not ft0 then + return end + + return ft0, on_detect end --- Lookup table/cache for patterns that contain an environment variable pattern, e.g. ${SOME_VAR}. +--- Lookup table/cache for patterns that contain an environment variable pattern, e.g. ${SOME_VAR}. +--- @type table<string,boolean> local expand_env_lookup = {} ----@private +--- @param name string +--- @param path string +--- @param tail string +--- @param pat string +--- @return string|false? local function match_pattern(name, path, tail, pat) if expand_env_lookup[pat] == nil then expand_env_lookup[pat] = pat:find('%${') ~= nil end if expand_env_lookup[pat] then - local return_early + local return_early --- @type true? + --- @type string pat = pat:gsub('%${(%S-)}', function(env) -- If an environment variable is present in the pattern but not set, there is no match if not vim.env[env] then return_early = true return nil end - return vim.env[env] + return vim.pesc(vim.env[env]) end) if return_early then return false end end + -- If the pattern contains a / match against the full path, otherwise just the tail local fullpat = '^' .. pat .. '$' - local matches + if pat:find('/') then -- Similar to |autocmd-pattern|, if the pattern contains a '/' then check for a match against -- both the short file name (as typed) and the full file name (after expanding to full path -- and resolving symlinks) - matches = name:match(fullpat) or path:match(fullpat) - else - matches = tail:match(fullpat) + return (name:match(fullpat) or path:match(fullpat)) end - return matches + + return (tail:match(fullpat)) end +--- @class vim.filetype.match.args +--- @field buf? integer +--- @field filename? string +--- @field contents? string[] + --- Perform filetype detection. --- --- The filetype can be detected using one of three methods: @@ -2467,21 +2279,22 @@ end --- Each of the three options is specified using a key to the single argument of this function. --- Example: --- ---- <pre>lua ---- -- Using a buffer number ---- vim.filetype.match({ buf = 42 }) +--- ```lua +--- -- Using a buffer number +--- vim.filetype.match({ buf = 42 }) --- ---- -- Override the filename of the given buffer ---- vim.filetype.match({ buf = 42, filename = 'foo.c' }) +--- -- Override the filename of the given buffer +--- vim.filetype.match({ buf = 42, filename = 'foo.c' }) --- ---- -- Using a filename without a buffer ---- vim.filetype.match({ filename = 'main.lua' }) +--- -- Using a filename without a buffer +--- vim.filetype.match({ filename = 'main.lua' }) --- ---- -- Using file contents ---- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) ---- </pre> +--- -- Using file contents +--- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) +--- ``` --- ----@param args table Table specifying which matching strategy to use. Accepted keys are: +---@param args vim.filetype.match.args Table specifying which matching strategy to use. +--- Accepted keys are: --- * buf (number): Buffer number to use for matching. Mutually exclusive with --- {contents} --- * filename (string): Filename to use for matching. When {buf} is given, @@ -2494,8 +2307,8 @@ end --- * contents (table): An array of lines representing file contents to use for --- matching. Can be used with {filename}. Mutually exclusive --- with {buf}. ----@return string|nil If a match was found, the matched filetype. ----@return function|nil A function that modifies buffer state when called (for example, to set some +---@return string|nil # If a match was found, the matched filetype. +---@return function|nil # A function that modifies buffer state when called (for example, to set some --- filetype specific buffer variables). The function accepts a buffer number as --- its only argument. function M.match(args) @@ -2515,64 +2328,65 @@ function M.match(args) name = api.nvim_buf_get_name(bufnr) end - if name then - name = normalize_path(name) - end - + --- @type string?, fun(b: integer)? local ft, on_detect - -- First check for the simple case where the full path exists as a key - local path = vim.fn.fnamemodify(name, ':p') - ft, on_detect = dispatch(filename[path], path, bufnr) - if ft then - return ft, on_detect - end + if name then + name = normalize_path(name) - -- Next check against just the file name - local tail = vim.fn.fnamemodify(name, ':t') - ft, on_detect = dispatch(filename[tail], path, bufnr) - if ft then - return ft, on_detect - end + -- First check for the simple case where the full path exists as a key + local path = fn.fnamemodify(name, ':p') + ft, on_detect = dispatch(filename[path], path, bufnr) + if ft then + return ft, on_detect + end - -- Next, check the file path against available patterns with non-negative priority - local j = 1 - for i, v in ipairs(pattern_sorted) do - local k = next(v) - local opts = v[k][2] - if opts.priority < 0 then - j = i - break + -- Next check against just the file name + local tail = fn.fnamemodify(name, ':t') + ft, on_detect = dispatch(filename[tail], path, bufnr) + if ft then + return ft, on_detect end - local filetype = v[k][1] - local matches = match_pattern(name, path, tail, k) - if matches then - ft, on_detect = dispatch(filetype, path, bufnr, matches) - if ft then - return ft, on_detect + -- Next, check the file path against available patterns with non-negative priority + local j = 1 + for i, v in ipairs(pattern_sorted) do + local k = next(v) + local opts = v[k][2] + if opts.priority < 0 then + j = i + break + end + + local filetype = v[k][1] + local matches = match_pattern(name, path, tail, k) + if matches then + ft, on_detect = dispatch(filetype, path, bufnr, matches) + if ft then + return ft, on_detect + end end end - end - -- Next, check file extension - local ext = vim.fn.fnamemodify(name, ':e') - ft, on_detect = dispatch(extension[ext], path, bufnr) - if ft then - return ft, on_detect - end + -- Next, check file extension + local ext = fn.fnamemodify(name, ':e') + ft, on_detect = dispatch(extension[ext], path, bufnr) + if ft then + return ft, on_detect + end - -- Next, check patterns with negative priority - for i = j, #pattern_sorted do - local v = pattern_sorted[i] - local k = next(v) + -- Next, check patterns with negative priority + for i = j, #pattern_sorted do + local v = pattern_sorted[i] + local k = next(v) - local filetype = v[k][1] - local matches = match_pattern(name, path, tail, k) - if matches then - ft, on_detect = dispatch(filetype, path, bufnr, matches) - if ft then - return ft, on_detect + local filetype = v[k][1] + local matches = match_pattern(name, path, tail, k) + if matches then + ft, on_detect = dispatch(filetype, path, bufnr, matches) + if ft then + return ft, on_detect + end end end end @@ -2580,23 +2394,52 @@ function M.match(args) -- Finally, check file contents if contents or bufnr then if contents == nil then + assert(bufnr) if api.nvim_buf_line_count(bufnr) > 101 then -- only need first 100 and last line for current checks - contents = M.getlines(bufnr, 1, 100) - contents[#contents + 1] = M.getlines(bufnr, -1) + contents = M._getlines(bufnr, 1, 100) + contents[#contents + 1] = M._getline(bufnr, -1) else - contents = M.getlines(bufnr) + contents = M._getlines(bufnr) end end -- If name is nil, catch any errors from the contents filetype detection function. -- If the function tries to use the filename that is nil then it will fail, -- but this enables checks which do not need a filename to still work. local ok - ok, ft = pcall(require('vim.filetype.detect').match_contents, contents, name) - if ok and ft then - return ft + ok, ft, on_detect = pcall( + require('vim.filetype.detect').match_contents, + contents, + name, + function(ext) + return dispatch(extension[ext], name, bufnr) + end + ) + if ok then + return ft, on_detect end end end +--- Get the default option value for a {filetype}. +--- +--- The returned value is what would be set in a new buffer after 'filetype' +--- is set, meaning it should respect all FileType autocmds and ftplugin files. +--- +--- Example: +--- +--- ```lua +--- vim.filetype.get_option('vim', 'commentstring') +--- ``` +--- +--- Note: this uses |nvim_get_option_value()| but caches the result. +--- This means |ftplugin| and |FileType| autocommands are only +--- triggered once and may not reflect later changes. +--- @param filetype string Filetype +--- @param option string Option name +--- @return string|boolean|integer: Option value +function M.get_option(filetype, option) + return require('vim.filetype.options').get_option(filetype, option) +end + return M diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index edffdde9c7..9d0f1bd3ab 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -17,22 +17,26 @@ -- Example: -- `if line =~ '^\s*unwind_protect\>'` => `if matchregex(line, [[\c^\s*unwind_protect\>]])` +local fn = vim.fn + local M = {} -local getlines = vim.filetype.getlines -local findany = vim.filetype.findany -local nextnonblank = vim.filetype.nextnonblank -local matchregex = vim.filetype.matchregex +local getlines = vim.filetype._getlines +local getline = vim.filetype._getline +local findany = vim.filetype._findany +local nextnonblank = vim.filetype._nextnonblank +local matchregex = vim.filetype._matchregex -- luacheck: push no unused args -- luacheck: push ignore 122 -- This function checks for the kind of assembly that is wanted by the user, or -- can be detected from the first five lines of the file. -function M.asm(bufnr) +--- @type vim.filetype.mapfn +function M.asm(path, bufnr) local syntax = vim.b[bufnr].asmsyntax if not syntax or syntax == '' then - syntax = M.asm_syntax(bufnr) + syntax = M.asm_syntax(path, bufnr) end -- If b:asmsyntax still isn't set, default to asmsyntax or GNU @@ -48,20 +52,21 @@ function M.asm(bufnr) end end --- Active Server Pages (with Perl or Visual Basic Script) -function M.asp(bufnr) +--- Active Server Pages (with Perl or Visual Basic Script) +--- @type vim.filetype.mapfn +function M.asp(_, bufnr) if vim.g.filetype_asp then return vim.g.filetype_asp elseif table.concat(getlines(bufnr, 1, 3)):lower():find('perlscript') then return 'aspperl' - else - return 'aspvbs' end + return 'aspvbs' end -- Checks the first 5 lines for a asmsyntax=foo override. -- Only whitespace characters can be present immediately before or after this statement. -function M.asm_syntax(bufnr) +--- @type vim.filetype.mapfn +function M.asm_syntax(_, bufnr) local lines = ' ' .. table.concat(getlines(bufnr, 1, 5), ' '):lower() .. ' ' local match = lines:match('%sasmsyntax=([a-zA-Z0-9]+)%s') if match then @@ -72,10 +77,11 @@ function M.asm_syntax(bufnr) end local visual_basic_content = - { 'vb_name', 'begin vb%.form', 'begin vb%.mdiform', 'begin vb%.usercontrol' } + [[\c^\s*\%(Attribute\s\+VB_Name\|Begin\s\+\%(VB\.\|{\%(\x\+-\)\+\x\+}\)\)]] -- See frm() for Visual Basic form file detection -function M.bas(bufnr) +--- @type vim.filetype.mapfn +function M.bas(_, bufnr) if vim.g.filetype_bas then return vim.g.filetype_bas end @@ -91,7 +97,7 @@ function M.bas(bufnr) local qb64_preproc = [[\c^\s*\%($\a\+\|option\s\+\%(_explicit\|_\=explicitarray\)\>\)]] for _, line in ipairs(getlines(bufnr, 1, 100)) do - if findany(line:lower(), visual_basic_content) then + if matchregex(line, visual_basic_content) then return 'vb' elseif line:find(fb_comment) @@ -106,18 +112,21 @@ function M.bas(bufnr) return 'basic' end -function M.bindzone(bufnr, default) +--- @type vim.filetype.mapfn +function M.bindzone(_, bufnr) local lines = table.concat(getlines(bufnr, 1, 4)) if findany(lines, { '^; <<>> DiG [0-9%.]+.* <<>>', '%$ORIGIN', '%$TTL', 'IN%s+SOA' }) then return 'bindzone' end - return default end -- Returns true if file content looks like RAPID +--- @param bufnr integer +--- @param extension? string +--- @return string|boolean? local function is_rapid(bufnr, extension) if extension == 'cfg' then - local line = getlines(bufnr, 1):lower() + local line = getline(bufnr, 1):lower() return findany(line, { 'eio:cfg', 'mmc:cfg', 'moc:cfg', 'proc:cfg', 'sio:cfg', 'sys:cfg' }) end local line = nextnonblank(bufnr, 1) @@ -128,23 +137,24 @@ local function is_rapid(bufnr, extension) return false end -function M.cfg(bufnr) +--- @type vim.filetype.mapfn +function M.cfg(_, bufnr) if vim.g.filetype_cfg then - return vim.g.filetype_cfg + return vim.g.filetype_cfg --[[@as string]] elseif is_rapid(bufnr, 'cfg') then return 'rapid' - else - return 'cfg' end + return 'cfg' end --- This function checks if one of the first ten lines start with a '@'. In --- that case it is probably a change file. --- If the first line starts with # or ! it's probably a ch file. --- If a line has "main", "include", "//" or "/*" it's probably ch. --- Otherwise CHILL is assumed. -function M.change(bufnr) - local first_line = getlines(bufnr, 1) +--- This function checks if one of the first ten lines start with a '@'. In +--- that case it is probably a change file. +--- If the first line starts with # or ! it's probably a ch file. +--- If a line has "main", "include", "//" or "/*" it's probably ch. +--- Otherwise CHILL is assumed. +--- @type vim.filetype.mapfn +function M.change(_, bufnr) + local first_line = getline(bufnr, 1) if findany(first_line, { '^#', '^!' }) then return 'ch' end @@ -161,41 +171,52 @@ function M.change(bufnr) return 'chill' end -function M.changelog(bufnr) - local line = getlines(bufnr, 1):lower() +--- @type vim.filetype.mapfn +function M.changelog(_, bufnr) + local line = getline(bufnr, 1):lower() if line:find('; urgency=') then return 'debchangelog' end return 'changelog' end -function M.class(bufnr) +--- @type vim.filetype.mapfn +function M.class(_, bufnr) -- Check if not a Java class (starts with '\xca\xfe\xba\xbe') - if not getlines(bufnr, 1):find('^\202\254\186\190') then + if not getline(bufnr, 1):find('^\202\254\186\190') then return 'stata' end end -function M.cls(bufnr) +--- @type vim.filetype.mapfn +function M.cls(_, bufnr) if vim.g.filetype_cls then return vim.g.filetype_cls end - local line = getlines(bufnr, 1) - if line:find('^[%%\\]') then - return 'tex' - elseif line:find('^#') and line:lower():find('rexx') then + local line1 = getline(bufnr, 1) + if matchregex(line1, [[^#!.*\<\%(rexx\|regina\)\>]]) then return 'rexx' - elseif line == 'VERSION 1.0 CLASS' then + elseif line1 == 'VERSION 1.0 CLASS' then return 'vb' - else - return 'st' end + + local nonblank1 = nextnonblank(bufnr, 1) + if nonblank1 and nonblank1:find('^[%%\\]') then + return 'tex' + elseif nonblank1 and findany(nonblank1, { '^%s*/%*', '^%s*::%w' }) then + return 'rexx' + end + return 'st' end +--- @type vim.filetype.mapfn function M.conf(path, bufnr) - if vim.fn.did_filetype() ~= 0 or path:find(vim.g.ft_ignore_pat) then + if fn.did_filetype() ~= 0 or path:find(vim.g.ft_ignore_pat) then return end + if path:find('%.conf$') then + return 'conf' + end for _, line in ipairs(getlines(bufnr, 1, 5)) do if line:find('^#') then return 'conf' @@ -203,22 +224,30 @@ function M.conf(path, bufnr) end end --- Debian Control -function M.control(bufnr) - if getlines(bufnr, 1):find('^Source:') then +--- Debian Control +--- @type vim.filetype.mapfn +function M.control(_, bufnr) + if getline(bufnr, 1):find('^Source:') then return 'debcontrol' end end --- Debian Copyright -function M.copyright(bufnr) - if getlines(bufnr, 1):find('^Format:') then +--- Debian Copyright +--- @type vim.filetype.mapfn +function M.copyright(_, bufnr) + if getline(bufnr, 1):find('^Format:') then return 'debcopyright' end end +--- @type vim.filetype.mapfn +function M.cpp(_, _) + return vim.g.cynlib_syntax_for_cpp and 'cynlib' or 'cpp' +end + +--- @type vim.filetype.mapfn function M.csh(path, bufnr) - if vim.fn.did_filetype() ~= 0 then + if fn.did_filetype() ~= 0 then -- Filetype was already detected return end @@ -232,6 +261,9 @@ function M.csh(path, bufnr) end end +--- @param path string +--- @param contents string[] +--- @return string? local function cvs_diff(path, contents) for _, line in ipairs(contents) do if not line:find('^%? ') then @@ -277,8 +309,9 @@ local function cvs_diff(path, contents) end end +--- @type vim.filetype.mapfn function M.dat(path, bufnr) - local file_name = vim.fn.fnamemodify(path, ':t'):lower() + local file_name = fn.fnamemodify(path, ':t'):lower() -- Innovation data processing if findany(file_name, { '^upstream%.dat$', '^upstream%..*%.dat$', '^.*%.upstream%.dat$' }) then return 'upstreamdat' @@ -293,7 +326,8 @@ function M.dat(path, bufnr) end end -function M.decl(bufnr) +--- @type vim.filetype.mapfn +function M.decl(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 3)) do if line:lower():find('^<!sgml') then return 'sgmldecl' @@ -303,8 +337,9 @@ end -- This function is called for all files under */debian/patches/*, make sure not -- to non-dep3patch files, such as README and other text files. +--- @type vim.filetype.mapfn function M.dep3patch(path, bufnr) - local file_name = vim.fn.fnamemodify(path, ':t') + local file_name = fn.fnamemodify(path, ':t') if file_name == 'series' then return end @@ -349,7 +384,7 @@ local function diff(contents) end end -function M.dns_zone(contents) +local function dns_zone(contents) if findany( contents[1] .. contents[2] .. contents[3] .. contents[4], @@ -367,8 +402,9 @@ function M.dns_zone(contents) end end -function M.dtrace(bufnr) - if vim.fn.did_filetype() ~= 0 then +--- @type vim.filetype.mapfn +function M.dtrace(_, bufnr) + if fn.did_filetype() ~= 0 then -- Filetype was already detected return end @@ -383,7 +419,8 @@ function M.dtrace(bufnr) return 'd' end -function M.e(bufnr) +--- @type vim.filetype.mapfn +function M.e(_, bufnr) if vim.g.filetype_euphoria then return vim.g.filetype_euphoria end @@ -395,8 +432,9 @@ function M.e(bufnr) return 'eiffel' end -function M.edn(bufnr) - local line = getlines(bufnr, 1) +--- @type vim.filetype.mapfn +function M.edn(_, bufnr) + local line = getline(bufnr, 1) if matchregex(line, [[\c^\s*(\s*edif\>]]) then return 'edif' else @@ -407,7 +445,8 @@ end -- This function checks for valid cl syntax in the first five lines. -- Look for either an opening comment, '#', or a block start, '{'. -- If not found, assume SGML. -function M.ent(bufnr) +--- @type vim.filetype.mapfn +function M.ent(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 5)) do if line:find('^%s*[#{]') then return 'cl' @@ -420,7 +459,13 @@ function M.ent(bufnr) return 'dtd' end -function M.ex(bufnr) +--- @type vim.filetype.mapfn +function M.euphoria(_, _) + return vim.g.filetype_euphoria or 'euphoria3' +end + +--- @type vim.filetype.mapfn +function M.ex(_, bufnr) if vim.g.filetype_euphoria then return vim.g.filetype_euphoria else @@ -433,10 +478,43 @@ function M.ex(bufnr) end end +--- @param bufnr integer +--- @return boolean +local function is_forth(bufnr) + local first_line = nextnonblank(bufnr, 1) + + -- SwiftForth block comment (line is usually filled with '-' or '=') or + -- OPTIONAL (sometimes precedes the header comment) + if first_line and findany(first_line:lower(), { '^%{%s', '^%{$', '^optional%s' }) then + return true + end + + for _, line in ipairs(getlines(bufnr, 1, 100)) do + -- Forth comments and colon definitions + if line:find('^[:(\\] ') then + return true + end + end + return false +end + +-- Distinguish between Forth and Fortran +--- @type vim.filetype.mapfn +function M.f(_, bufnr) + if vim.g.filetype_f then + return vim.g.filetype_f + end + if is_forth(bufnr) then + return 'forth' + end + return 'fortran' +end + -- This function checks the first 15 lines for appearance of 'FoamFile' -- and then 'object' in a following line. -- In that case, it's probably an OpenFOAM file -function M.foam(bufnr) +--- @type vim.filetype.mapfn +function M.foam(_, bufnr) local foam_file = false for _, line in ipairs(getlines(bufnr, 1, 15)) do if line:find('^FoamFile') then @@ -447,20 +525,32 @@ function M.foam(bufnr) end end -function M.frm(bufnr) +--- @type vim.filetype.mapfn +function M.frm(_, bufnr) if vim.g.filetype_frm then return vim.g.filetype_frm end - local lines = table.concat(getlines(bufnr, 1, 5)):lower() - if findany(lines, visual_basic_content) then + if getline(bufnr, 1) == 'VERSION 5.00' then return 'vb' - else - return 'form' end + for _, line in ipairs(getlines(bufnr, 1, 5)) do + if matchregex(line, visual_basic_content) then + return 'vb' + end + end + return 'form' end -function M.fvwm(path) - if vim.fn.fnamemodify(path, ':e') == 'm4' then +--- @type vim.filetype.mapfn +function M.fvwm_1(_, _) + return 'fvwm', function(bufnr) + vim.b[bufnr].fvwm_version = 1 + end +end + +--- @type vim.filetype.mapfn +function M.fvwm_v2(path, _) + if fn.fnamemodify(path, ':e') == 'm4' then return 'fvwm2m4' end return 'fvwm', function(bufnr) @@ -468,27 +558,28 @@ function M.fvwm(path) end end --- Distinguish between Forth and F#. -function M.fs(bufnr) +-- Distinguish between Forth and F# +--- @type vim.filetype.mapfn +function M.fs(_, bufnr) if vim.g.filetype_fs then return vim.g.filetype_fs end - local line = nextnonblank(bufnr, 1) - if findany(line, { '^%s*%.?%( ', '^%s*\\G? ', '^\\$', '^%s*: %S' }) then + if is_forth(bufnr) then return 'forth' - else - return 'fsharp' end + return 'fsharp' end -function M.git(bufnr) - local line = getlines(bufnr, 1) +--- @type vim.filetype.mapfn +function M.git(_, bufnr) + local line = getline(bufnr, 1) if matchregex(line, [[^\x\{40,\}\>\|^ref: ]]) then return 'git' end end -function M.header(bufnr) +--- @type vim.filetype.mapfn +function M.header(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 200)) do if findany(line:lower(), { '^@interface', '^@end', '^@class' }) then if vim.g.c_syntax_for_h then @@ -507,7 +598,8 @@ function M.header(bufnr) end end -function M.html(bufnr) +--- @type vim.filetype.mapfn +function M.html(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 10)) do if matchregex(line, [[\<DTD\s\+XHTML\s]]) then return 'xhtml' @@ -519,14 +611,41 @@ function M.html(bufnr) end -- Virata Config Script File or Drupal module -function M.hw(bufnr) - if getlines(bufnr, 1):lower():find('<%?php') then +--- @type vim.filetype.mapfn +function M.hw(_, bufnr) + if getline(bufnr, 1):lower():find('<%?php') then return 'php' end return 'virata' end -function M.idl(bufnr) +-- This function checks for an assembly comment or a SWIG keyword or verbatim +-- block in the first 50 lines. +-- If not found, assume Progress. +--- @type vim.filetype.mapfn +function M.i(path, bufnr) + if vim.g.filetype_i then + return vim.g.filetype_i + end + + -- These include the leading '%' sign + local ft_swig_keywords = + [[^\s*%\%(addmethods\|apply\|beginfile\|clear\|constant\|define\|echo\|enddef\|endoffile\|extend\|feature\|fragment\|ignore\|import\|importfile\|include\|includefile\|inline\|insert\|keyword\|module\|name\|namewarn\|native\|newobject\|parms\|pragma\|rename\|template\|typedef\|typemap\|types\|varargs\|warn\)]] + -- This is the start/end of a block that is copied literally to the processor file (C/C++) + local ft_swig_verbatim_block_start = '^%s*%%{' + + for _, line in ipairs(getlines(bufnr, 1, 50)) do + if line:find('^%s*;') or line:find('^%*') then + return M.asm(path, bufnr) + elseif matchregex(line, ft_swig_keywords) or line:find(ft_swig_verbatim_block_start) then + return 'swig' + end + end + return 'progress' +end + +--- @type vim.filetype.mapfn +function M.idl(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 50)) do if findany(line:lower(), { '^%s*import%s+"unknwn"%.idl', '^%s*import%s+"objidl"%.idl' }) then return 'msidl' @@ -539,7 +658,8 @@ local pascal_comments = { '^%s*{', '^%s*%(%*', '^%s*//' } local pascal_keywords = [[\c^\s*\%(program\|unit\|library\|uses\|begin\|procedure\|function\|const\|type\|var\)\>]] -function M.inc(bufnr) +--- @type vim.filetype.mapfn +function M.inc(path, bufnr) if vim.g.filetype_inc then return vim.g.filetype_inc end @@ -557,7 +677,7 @@ function M.inc(bufnr) elseif findany(lines, { '^%s*inherit ', '^%s*require ', '^%s*%u[%w_:${}]*%s+%??[?:+]?= ' }) then return 'bitbake' else - local syntax = M.asm_syntax(bufnr) + local syntax = M.asm_syntax(path, bufnr) if not syntax or syntax == '' then return 'pov' end @@ -567,8 +687,9 @@ function M.inc(bufnr) end end -function M.inp(bufnr) - if getlines(bufnr, 1):find('^%*') then +--- @type vim.filetype.mapfn +function M.inp(_, bufnr) + if getline(bufnr, 1):find('^%*') then return 'abaqus' else for _, line in ipairs(getlines(bufnr, 1, 500)) do @@ -579,16 +700,18 @@ function M.inp(bufnr) end end +--- @type vim.filetype.mapfn function M.install(path, bufnr) - if getlines(bufnr, 1):lower():find('<%?php') then + if getline(bufnr, 1):lower():find('<%?php') then return 'php' end - return M.sh(path, getlines(bufnr), 'bash') + return M.bash(path, bufnr) end --- Innovation Data Processing --- (refactor of filetype.vim since the patterns are case-insensitive) -function M.log(path) +--- Innovation Data Processing +--- (refactor of filetype.vim since the patterns are case-insensitive) +--- @type vim.filetype.mapfn +function M.log(path, _) path = path:lower() if findany( @@ -611,7 +734,8 @@ function M.log(path) end end -function M.lpc(bufnr) +--- @type vim.filetype.mapfn +function M.lpc(_, bufnr) if vim.g.lpc_syntax_for_c then for _, line in ipairs(getlines(bufnr, 1, 12)) do if @@ -634,7 +758,8 @@ function M.lpc(bufnr) return 'c' end -function M.lsl(bufnr) +--- @type vim.filetype.mapfn +function M.lsl(_, bufnr) if vim.g.filetype_lsl then return vim.g.filetype_lsl end @@ -647,7 +772,8 @@ function M.lsl(bufnr) end end -function M.m(bufnr) +--- @type vim.filetype.mapfn +function M.m(_, bufnr) if vim.g.filetype_m then return vim.g.filetype_m end @@ -700,6 +826,8 @@ function M.m(bufnr) end end +--- @param contents string[] +--- @return string? local function m4(contents) for _, line in ipairs(contents) do if matchregex(line, [[^\s*dnl\>]]) then @@ -712,9 +840,10 @@ local function m4(contents) end end --- Rely on the file to start with a comment. --- MS message text files use ';', Sendmail files use '#' or 'dnl' -function M.mc(bufnr) +--- Rely on the file to start with a comment. +--- MS message text files use ';', Sendmail files use '#' or 'dnl' +--- @type vim.filetype.mapfn +function M.mc(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 20)) do if findany(line:lower(), { '^%s*#', '^%s*dnl' }) then -- Sendmail .mc file @@ -727,14 +856,17 @@ function M.mc(bufnr) return 'm4' end +--- @param path string +--- @return string? function M.me(path) - local filename = vim.fn.fnamemodify(path, ':t'):lower() + local filename = fn.fnamemodify(path, ':t'):lower() if filename ~= 'read.me' and filename ~= 'click.me' then return 'nroff' end end -function M.mm(bufnr) +--- @type vim.filetype.mapfn +function M.mm(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 20)) do if matchregex(line, [[\c^\s*\(#\s*\(include\|import\)\>\|@import\>\|/\*\)]]) then return 'objcpp' @@ -743,7 +875,8 @@ function M.mm(bufnr) return 'nroff' end -function M.mms(bufnr) +--- @type vim.filetype.mapfn +function M.mms(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 20)) do if findany(line, { '^%s*%%', '^%s*//', '^%*' }) then return 'mmix' @@ -754,7 +887,9 @@ function M.mms(bufnr) return 'mmix' end --- Returns true if file content looks like LambdaProlog +--- Returns true if file content looks like LambdaProlog +--- @param bufnr integer +--- @return boolean local function is_lprolog(bufnr) -- Skip apparent comments and blank lines, what looks like -- LambdaProlog comment may be RAPID header @@ -762,38 +897,49 @@ local function is_lprolog(bufnr) -- The second pattern matches a LambdaProlog comment if not findany(line, { '^%s*$', '^%s*%%' }) then -- The pattern must not catch a go.mod file - return matchregex(line, [[\c\<module\s\+\w\+\s*\.\s*\(%\|$\)]]) ~= nil + return matchregex(line, [[\c\<module\s\+\w\+\s*\.\s*\(%\|$\)]]) end end + return false end --- Determine if *.mod is ABB RAPID, LambdaProlog, Modula-2, Modsim III or go.mod +--- Determine if *.mod is ABB RAPID, LambdaProlog, Modula-2, Modsim III or go.mod +--- @type vim.filetype.mapfn function M.mod(path, bufnr) if vim.g.filetype_mod then return vim.g.filetype_mod + elseif matchregex(path, [[\c\<go\.mod$]]) then + return 'gomod' elseif is_lprolog(bufnr) then return 'lprolog' elseif matchregex(nextnonblank(bufnr, 1), [[\%(\<MODULE\s\+\w\+\s*;\|^\s*(\*\)]]) then return 'modula2' elseif is_rapid(bufnr) then return 'rapid' - elseif matchregex(path, [[\c\<go\.mod$]]) then - return 'gomod' - else - -- Nothing recognized, assume modsim3 - return 'modsim3' end + -- Nothing recognized, assume modsim3 + return 'modsim3' end -function M.news(bufnr) - if getlines(bufnr, 1):lower():find('; urgency=') then +--- Determine if *.mod is ABB RAPID, LambdaProlog, Modula-2, Modsim III or go.mod +--- @type vim.filetype.mapfn +function M.mp(_, _) + return 'mp', function(b) + vim.b[b].mp_metafun = 1 + end +end + +--- @type vim.filetype.mapfn +function M.news(_, bufnr) + if getline(bufnr, 1):lower():find('; urgency=') then return 'debchangelog' end end --- This function checks if one of the first five lines start with a dot. In --- that case it is probably an nroff file. -function M.nroff(bufnr) +--- This function checks if one of the first five lines start with a dot. In +--- that case it is probably an nroff file. +--- @type vim.filetype.mapfn +function M.nroff(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 5)) do if line:find('^%.') then return 'nroff' @@ -801,25 +947,26 @@ function M.nroff(bufnr) end end -function M.patch(bufnr) - local firstline = getlines(bufnr, 1) +--- @type vim.filetype.mapfn +function M.patch(_, bufnr) + local firstline = getline(bufnr, 1) if string.find(firstline, '^From ' .. string.rep('%x', 40) .. '+ Mon Sep 17 00:00:00 2001$') then return 'gitsendemail' - else - return 'diff' end + return 'diff' end --- If the file has an extension of 't' and is in a directory 't' or 'xt' then --- it is almost certainly a Perl test file. --- If the first line starts with '#' and contains 'perl' it's probably a Perl file. --- (Slow test) If a file contains a 'use' statement then it is almost certainly a Perl file. +--- If the file has an extension of 't' and is in a directory 't' or 'xt' then +--- it is almost certainly a Perl test file. +--- If the first line starts with '#' and contains 'perl' it's probably a Perl file. +--- (Slow test) If a file contains a 'use' statement then it is almost certainly a Perl file. +--- @type vim.filetype.mapfn function M.perl(path, bufnr) local dir_name = vim.fs.dirname(path) - if vim.fn.expand(path, '%:e') == 't' and (dir_name == 't' or dir_name == 'xt') then + if fn.expand(path, '%:e') == 't' and (dir_name == 't' or dir_name == 'xt') then return 'perl' end - local first_line = getlines(bufnr, 1) + local first_line = getline(bufnr, 1) if first_line:find('^#') and first_line:lower():find('perl') then return 'perl' end @@ -830,7 +977,8 @@ function M.perl(path, bufnr) end end -function M.pl(bufnr) +--- @type vim.filetype.mapfn +function M.pl(_, bufnr) if vim.g.filetype_pl then return vim.g.filetype_pl end @@ -848,8 +996,9 @@ function M.pl(bufnr) end end -function M.pm(bufnr) - local line = getlines(bufnr, 1) +--- @type vim.filetype.mapfn +function M.pm(_, bufnr) + local line = getline(bufnr, 1) if line:find('XPM2') then return 'xpm2' elseif line:find('XPM') then @@ -859,7 +1008,8 @@ function M.pm(bufnr) end end -function M.pp(bufnr) +--- @type vim.filetype.mapfn +function M.pp(_, bufnr) if vim.g.filetype_pp then return vim.g.filetype_pp end @@ -871,7 +1021,8 @@ function M.pp(bufnr) end end -function M.prg(bufnr) +--- @type vim.filetype.mapfn +function M.prg(_, bufnr) if vim.g.filetype_prg then return vim.g.filetype_prg elseif is_rapid(bufnr) then @@ -883,39 +1034,21 @@ function M.prg(bufnr) end function M.printcap(ptcap_type) - if vim.fn.did_filetype() == 0 then + if fn.did_filetype() == 0 then return 'ptcap', function(bufnr) vim.b[bufnr].ptcap_type = ptcap_type end end end --- This function checks for an assembly comment in the first ten lines. --- If not found, assume Progress. -function M.progress_asm(bufnr) - if vim.g.filetype_i then - return vim.g.filetype_i - end - - for _, line in ipairs(getlines(bufnr, 1, 10)) do - if line:find('^%s*;') or line:find('^/%*') then - return M.asm(bufnr) - elseif not line:find('^%s*$') or line:find('^/%*') then - -- Not an empty line: doesn't look like valid assembly code - -- or it looks like a Progress /* comment. - break - end - end - return 'progress' -end - -function M.progress_cweb(bufnr) +--- @type vim.filetype.mapfn +function M.progress_cweb(_, bufnr) if vim.g.filetype_w then return vim.g.filetype_w else if - getlines(bufnr, 1):lower():find('^&analyze') - or getlines(bufnr, 3):lower():find('^&global%-define') + getline(bufnr, 1):lower():find('^&analyze') + or getline(bufnr, 3):lower():find('^&global%-define') then return 'progress' else @@ -927,7 +1060,8 @@ end -- This function checks for valid Pascal syntax in the first 10 lines. -- Look for either an opening comment or a program start. -- If not found, assume Progress. -function M.progress_pascal(bufnr) +--- @type vim.filetype.mapfn +function M.progress_pascal(_, bufnr) if vim.g.filetype_p then return vim.g.filetype_p end @@ -943,34 +1077,33 @@ function M.progress_pascal(bufnr) return 'progress' end --- Distinguish between "default", Prolog and Cproto prototype file. -function M.proto(bufnr, default) +--- Distinguish between "default", Prolog and Cproto prototype file. +--- @type vim.filetype.mapfn +function M.proto(_, bufnr) -- Cproto files have a comment in the first line and a function prototype in -- the second line, it always ends in ";". Indent files may also have -- comments, thus we can't match comments to see the difference. -- IDL files can have a single ';' in the second line, require at least one -- character before the ';'. - if getlines(bufnr, 2):find('.;$') then + if getline(bufnr, 2):find('.;$') then return 'cpp' - else - -- Recognize Prolog by specific text in the first non-empty line; - -- require a blank after the '%' because Perl uses "%list" and "%translate" - local line = nextnonblank(bufnr, 1) - if - line and line:find(':%-') - or matchregex(line, [[\c\<prolog\>]]) - or findany(line, { '^%s*%%+%s', '^%s*%%+$', '^%s*/%*' }) - then - return 'prolog' - else - return default - end + end + -- Recognize Prolog by specific text in the first non-empty line; + -- require a blank after the '%' because Perl uses "%list" and "%translate" + local line = nextnonblank(bufnr, 1) + if + line and line:find(':%-') + or matchregex(line, [[\c\<prolog\>]]) + or findany(line, { '^%s*%%+%s', '^%s*%%+$', '^%s*/%*' }) + then + return 'prolog' end end -- Software Distributor Product Specification File (POSIX 1387.2-1995) -function M.psf(bufnr) - local line = getlines(bufnr, 1):lower() +--- @type vim.filetype.mapfn +function M.psf(_, bufnr) + local line = getline(bufnr, 1):lower() if findany(line, { '^%s*distribution%s*$', @@ -984,7 +1117,8 @@ function M.psf(bufnr) end end -function M.r(bufnr) +--- @type vim.filetype.mapfn +function M.r(_, bufnr) local lines = getlines(bufnr, 1, 50) -- Rebol is easy to recognize, check for that first if matchregex(table.concat(lines), [[\c\<rebol\>]]) then @@ -1005,13 +1139,13 @@ function M.r(bufnr) -- Nothing recognized, use user default or assume R if vim.g.filetype_r then return vim.g.filetype_r - else - -- Rexx used to be the default, but R appears to be much more popular. - return 'r' end + -- Rexx used to be the default, but R appears to be much more popular. + return 'r' end -function M.redif(bufnr) +--- @type vim.filetype.mapfn +function M.redif(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 5)) do if line:lower():find('^template%-type:') then return 'redif' @@ -1019,8 +1153,9 @@ function M.redif(bufnr) end end -function M.reg(bufnr) - local line = getlines(bufnr, 1):lower() +--- @type vim.filetype.mapfn +function M.reg(_, bufnr) + local line = getline(bufnr, 1):lower() if line:find('^regedit[0-9]*%s*$') or line:find('^windows registry editor version %d*%.%d*%s*$') then @@ -1029,7 +1164,8 @@ function M.reg(bufnr) end -- Diva (with Skill) or InstallShield -function M.rul(bufnr) +--- @type vim.filetype.mapfn +function M.rul(_, bufnr) if table.concat(getlines(bufnr, 1, 6)):lower():find('installshield') then return 'ishd' end @@ -1037,6 +1173,7 @@ function M.rul(bufnr) end local udev_rules_pattern = '^%s*udev_rules%s*=%s*"([%^"]+)/*".*' +--- @type vim.filetype.mapfn function M.rules(path) path = path:lower() if @@ -1056,11 +1193,12 @@ function M.rules(path) elseif findany(path, { '^/etc/polkit%-1/rules%.d', '/usr/share/polkit%-1/rules%.d' }) then return 'javascript' else - local ok, config_lines = pcall(vim.fn.readfile, '/etc/udev/udev.conf') + local ok, config_lines = pcall(fn.readfile, '/etc/udev/udev.conf') + --- @cast config_lines +string[] if not ok then return 'hog' end - local dir = vim.fn.expand(path, ':h') + local dir = fn.expand(path, ':h') for _, line in ipairs(config_lines) do local match = line:match(udev_rules_pattern) if match then @@ -1075,7 +1213,8 @@ function M.rules(path) end -- LambdaProlog and Standard ML signature files -function M.sig(bufnr) +--- @type vim.filetype.mapfn +function M.sig(_, bufnr) if vim.g.filetype_sig then return vim.g.filetype_sig end @@ -1093,7 +1232,8 @@ end -- This function checks the first 25 lines of file extension "sc" to resolve -- detection between scala and SuperCollider -function M.sc(bufnr) +--- @type vim.filetype.mapfn +function M.sc(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 25)) do if findany(line, { @@ -1113,18 +1253,19 @@ end -- This function checks the first line of file extension "scd" to resolve -- detection between scdoc and SuperCollider -function M.scd(bufnr) +--- @type vim.filetype.mapfn +function M.scd(_, bufnr) local first = '^%S+%(%d[0-9A-Za-z]*%)' local opt = [[%s+"[^"]*"]] - local line = getlines(bufnr, 1) + local line = getline(bufnr, 1) if findany(line, { first .. '$', first .. opt .. '$', first .. opt .. opt .. '$' }) then return 'scdoc' - else - return 'supercollider' end + return 'supercollider' end -function M.sgml(bufnr) +--- @type vim.filetype.mapfn +function M.sgml(_, bufnr) local lines = table.concat(getlines(bufnr, 1, 5)) if lines:find('linuxdoc') then return 'smgllnx' @@ -1139,15 +1280,17 @@ function M.sgml(bufnr) end end -function M.sh(path, contents, name) +--- @param path string +--- @param contents string[] +--- @param name? string +--- @return string?, fun(b: integer)? +local function sh(path, contents, name) -- Path may be nil, do not fail in that case - if vim.fn.did_filetype() ~= 0 or (path or ''):find(vim.g.ft_ignore_pat) then + if fn.did_filetype() ~= 0 or (path or ''):find(vim.g.ft_ignore_pat) then -- Filetype was already detected or detection should be skipped return end - local on_detect - -- Get the name from the first line if not specified name = name or contents[1] if matchregex(name, [[\<csh\>]]) then @@ -1159,7 +1302,11 @@ function M.sh(path, contents, name) -- Some .sh scripts contain #!/bin/zsh. elseif matchregex(name, [[\<zsh\>]]) then return M.shell(path, contents, 'zsh') - elseif matchregex(name, [[\<ksh\>]]) then + end + + local on_detect --- @type fun(b: integer)? + + if matchregex(name, [[\<ksh\>]]) then on_detect = function(b) vim.b[b].is_kornshell = 1 vim.b[b].is_bash = nil @@ -1182,9 +1329,26 @@ function M.sh(path, contents, name) return M.shell(path, contents, 'sh'), on_detect end --- For shell-like file types, check for an "exec" command hidden in a comment, as used for Tcl. +--- @param name? string +--- @return vim.filetype.mapfn +local function sh_with(name) + return function(path, bufnr) + return sh(path, getlines(bufnr), name) + end +end + +M.sh = sh_with() +M.bash = sh_with('bash') +M.ksh = sh_with('ksh') +M.tcsh = sh_with('tcsh') + +--- For shell-like file types, check for an "exec" command hidden in a comment, as used for Tcl. +--- @param path string +--- @param contents string[] +--- @param name? string +--- @return string? function M.shell(path, contents, name) - if vim.fn.did_filetype() ~= 0 or matchregex(path, vim.g.ft_ignore_pat) then + if fn.did_filetype() ~= 0 or matchregex(path, vim.g.ft_ignore_pat) then -- Filetype was already detected or detection should be skipped return end @@ -1193,6 +1357,7 @@ function M.shell(path, contents, name) for line_nr, line in ipairs(contents) do -- Skip the first line if line_nr ~= 1 then + --- @type string line = line:lower() if line:find('%s*exec%s') and not prev_line:find('^%s*#.*\\$') then -- Found an "exec" line after a comment with continuation @@ -1208,7 +1373,8 @@ function M.shell(path, contents, name) end -- Swift Intermediate Language or SILE -function M.sil(bufnr) +--- @type vim.filetype.mapfn +function M.sil(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 100)) do if line:find('^%s*[\\%%]') then return 'sile' @@ -1221,8 +1387,9 @@ function M.sil(bufnr) end -- SMIL or SNMP MIB file -function M.smi(bufnr) - local line = getlines(bufnr, 1) +--- @type vim.filetype.mapfn +function M.smi(_, bufnr) + local line = getline(bufnr, 1) if matchregex(line, [[\c\<smil\>]]) then return 'smil' else @@ -1230,8 +1397,14 @@ function M.smi(bufnr) end end +--- @type vim.filetype.mapfn +function M.sql(_, _) + return vim.g.filetype_sql and vim.g.filetype_sql or 'sql' +end + -- Determine if a *.src file is Kuka Robot Language -function M.src(bufnr) +--- @type vim.filetype.mapfn +function M.src(_, bufnr) if vim.g.filetype_src then return vim.g.filetype_src end @@ -1241,23 +1414,25 @@ function M.src(bufnr) end end -function M.sys(bufnr) +--- @type vim.filetype.mapfn +function M.sys(_, bufnr) if vim.g.filetype_sys then return vim.g.filetype_sys elseif is_rapid(bufnr) then return 'rapid' - else - return 'bat' end + return 'bat' end -- Choose context, plaintex, or tex (LaTeX) based on these rules: -- 1. Check the first line of the file for "%&<format>". -- 2. Check the first 1000 non-comment lines for LaTeX or ConTeXt keywords. -- 3. Default to "plain" or to g:tex_flavor, can be set in user's vimrc. +--- @type vim.filetype.mapfn function M.tex(path, bufnr) - local matched, _, format = getlines(bufnr, 1):find('^%%&%s*(%a+)') + local matched, _, format = getline(bufnr, 1):find('^%%&%s*(%a+)') if matched then + --- @type string format = format:lower():gsub('pdf', '', 1) elseif path:lower():find('tex/context/.*/.*%.tex') then return 'context' @@ -1296,7 +1471,8 @@ function M.tex(path, bufnr) end -- Determine if a *.tf file is TF mud client or terraform -function M.tf(bufnr) +--- @type vim.filetype.mapfn +function M.tf(_, bufnr) for _, line in ipairs(getlines(bufnr)) do -- Assume terraform file on a non-empty line (not whitespace-only) -- and when the first non-whitespace character is not a ; or / @@ -1307,24 +1483,77 @@ function M.tf(bufnr) return 'tf' end -function M.ttl(bufnr) - local line = getlines(bufnr, 1):lower() +--- @type vim.filetype.mapfn +function M.ttl(_, bufnr) + local line = getline(bufnr, 1):lower() if line:find('^@?prefix') or line:find('^@?base') then return 'turtle' end return 'teraterm' end -function M.txt(bufnr) +--- @type vim.filetype.mapfn +function M.txt(_, bufnr) -- helpfiles match *.txt, but should have a modeline as last line - if not getlines(bufnr, -1):find('vim:.*ft=help') then + if not getline(bufnr, -1):find('vim:.*ft=help') then return 'text' end end +--- @type vim.filetype.mapfn +function M.typ(_, bufnr) + if vim.g.filetype_typ then + return vim.g.filetype_typ + end + + for _, line in ipairs(getlines(bufnr, 1, 200)) do + if + findany(line, { + '^CASE[%s]?=[%s]?SAME$', + '^CASE[%s]?=[%s]?LOWER$', + '^CASE[%s]?=[%s]?UPPER$', + '^CASE[%s]?=[%s]?OPPOSITE$', + '^TYPE%s', + }) + then + return 'sql' + end + end + + return 'typst' +end + +-- Determine if a .v file is Verilog, V, or Coq +--- @type vim.filetype.mapfn +function M.v(_, bufnr) + if fn.did_filetype() ~= 0 then + -- Filetype was already detected + return + end + for _, line in ipairs(getlines(bufnr, 1, 200)) do + if not line:find('^%s*/') then + if findany(line, { ';%s*$', ';%s*/' }) then + return 'verilog' + elseif findany(line, { '%.%s*$', '%.%s*%(%*' }) then + return 'coq' + end + end + end + return 'v' +end + +--- @type vim.filetype.mapfn +function M.vba(_, bufnr) + if getline(bufnr, 1):find('^["#] Vimball Archiver') then + return 'vim' + end + return 'vb' +end + -- WEB (*.web is also used for Winbatch: Guess, based on expecting "%" comment -- lines in a WEB file). -function M.web(bufnr) +--- @type vim.filetype.mapfn +function M.web(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 5)) do if line:find('^%%') then return 'web' @@ -1334,17 +1563,27 @@ function M.web(bufnr) end -- XFree86 config -function M.xfree86() +--- @type vim.filetype.mapfn +function M.xfree86_v3(_, _) return 'xf86conf', function(bufnr) - local line = getlines(bufnr, 1) + local line = getline(bufnr, 1) if matchregex(line, [[\<XConfigurator\>]]) then vim.b[bufnr].xf86conf_xfree86_version = 3 end end end -function M.xml(bufnr) +-- XFree86 config +--- @type vim.filetype.mapfn +function M.xfree86_v4(_, _) + return 'xf86conf', function(b) + vim.b[b].xf86conf_xfree86_version = 4 + end +end + +--- @type vim.filetype.mapfn +function M.xml(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 100)) do local is_docbook4 = line:find('<!DOCTYPE.*DocBook') line = line:lower() @@ -1363,7 +1602,8 @@ function M.xml(bufnr) return 'xml' end -function M.y(bufnr) +--- @type vim.filetype.mapfn +function M.y(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 100)) do if line:find('^%s*%%') then return 'yacc' @@ -1416,11 +1656,21 @@ local patterns_hashbang = { ['gforth\\>'] = { 'forth', { vim_regex = true } }, ['icon\\>'] = { 'icon', { vim_regex = true } }, guile = 'scheme', + ['nix%-shell'] = 'nix', + ['^crystal\\>'] = { 'crystal', { vim_regex = true } }, + ['^\\%(rexx\\|regina\\)\\>'] = { 'rexx', { vim_regex = true } }, + ['^janet\\>'] = { 'janet', { vim_regex = true } }, + ['^dart\\>'] = { 'dart', { vim_regex = true } }, } ---@private --- File starts with "#!". -local function match_from_hashbang(contents, path) +--- File starts with "#!". +--- @param contents string[] +--- @param path string +--- @param dispatch_extension fun(name: string): string?, fun(b: integer)? +--- @return string? +--- @return fun(b: integer)? +local function match_from_hashbang(contents, path, dispatch_extension) local first_line = contents[1] -- Check for a line like "#!/usr/bin/env {options} bash". Turn it into -- "#!/usr/bin/bash" to make matching easier. @@ -1431,7 +1681,7 @@ local function match_from_hashbang(contents, path) :gsub('%-%-ignore%-environment', '', 1) :gsub('%-%-split%-string', '', 1) :gsub('%-[iS]', '', 1) - first_line = vim.fn.substitute(first_line, [[\<env\s\+]], '', '') + first_line = fn.substitute(first_line, [[\<env\s\+]], '', '') end -- Get the program name. @@ -1440,15 +1690,15 @@ local function match_from_hashbang(contents, path) -- "#!/usr/bin/env perl [path/args]" -- If there is no path use the first word: "#!perl [path/args]". -- Otherwise get the last word after a slash: "#!/usr/bin/perl [path/args]". - local name + local name --- @type string if first_line:find('^#!%s*%a:[/\\]') then - name = vim.fn.substitute(first_line, [[^#!.*[/\\]\(\i\+\).*]], '\\1', '') + name = fn.substitute(first_line, [[^#!.*[/\\]\(\i\+\).*]], '\\1', '') elseif matchregex(first_line, [[^#!.*\<env\>]]) then - name = vim.fn.substitute(first_line, [[^#!.*\<env\>\s\+\(\i\+\).*]], '\\1', '') + name = fn.substitute(first_line, [[^#!.*\<env\>\s\+\(\i\+\).*]], '\\1', '') elseif matchregex(first_line, [[^#!\s*[^/\\ ]*\>\([^/\\]\|$\)]]) then - name = vim.fn.substitute(first_line, [[^#!\s*\([^/\\ ]*\>\).*]], '\\1', '') + name = fn.substitute(first_line, [[^#!\s*\([^/\\ ]*\>\).*]], '\\1', '') else - name = vim.fn.substitute(first_line, [[^#!\s*\S*[/\\]\(\i\+\).*]], '\\1', '') + name = fn.substitute(first_line, [[^#!\s*\S*[/\\]\(\f\+\).*]], '\\1', '') end -- tcl scripts may have #!/bin/sh in the first line and "exec wish" in the @@ -1459,11 +1709,11 @@ local function match_from_hashbang(contents, path) if matchregex(name, [[^\(bash\d*\|dash\|ksh\d*\|sh\)\>]]) then -- Bourne-like shell scripts: bash bash2 dash ksh ksh93 sh - return require('vim.filetype.detect').sh(path, contents, first_line) + return sh(path, contents, first_line) elseif matchregex(name, [[^csh\>]]) then - return require('vim.filetype.detect').shell(path, contents, vim.g.filetype_csh or 'csh') + return M.shell(path, contents, vim.g.filetype_csh or 'csh') elseif matchregex(name, [[^tcsh\>]]) then - return require('vim.filetype.detect').shell(path, contents, 'tcsh') + return M.shell(path, contents, 'tcsh') end for k, v in pairs(patterns_hashbang) do @@ -1473,6 +1723,11 @@ local function match_from_hashbang(contents, path) return ft end end + + -- If nothing matched, check the extension table. For a hashbang like + -- '#!/bin/env foo', this will set the filetype to 'fooscript' assuming + -- the filetype for the 'foo' extension is 'fooscript' in the extension table. + return dispatch_extension(name) end local patterns_text = { @@ -1545,8 +1800,15 @@ local patterns_text = { ['^SNNS pattern definition file'] = 'snnspat', ['^SNNS result file'] = 'snnsres', ['^%%.-[Vv]irata'] = { 'virata', { start_lnum = 1, end_lnum = 5 } }, - ['[0-9:%.]* *execve%('] = 'strace', - ['^__libc_start_main'] = 'strace', + function(lines) + if + -- inaccurate fast match first, then use accurate slow match + (lines[1]:find('execve%(') and lines[1]:find('^[0-9:%. ]*execve%(')) + or lines[1]:find('^__libc_start_main') + then + return 'strace' + end + end, -- VSE JCL ['^\\* $$ JOB\\>'] = { 'vsejcl', { vim_regex = true } }, ['^// *JOB\\>'] = { 'vsejcl', { vim_regex = true } }, @@ -1556,9 +1818,7 @@ local patterns_text = { ['S Y S T E M S I M P R O V E D '] = { 'syndaout', { start_lnum = 3 } }, ['Run Date: '] = { 'takcmp', { start_lnum = 6 } }, ['Node File 1'] = { 'sindacmp', { start_lnum = 9 } }, - function(contents) - require('vim.filetype.detect').dns_zone(contents) - end, + dns_zone, -- Valgrind ['^==%d+== valgrind'] = 'valgrind', ['^==%d+== Using valgrind'] = { 'valgrind', { start_lnum = 3 } }, @@ -1597,11 +1857,15 @@ local patterns_text = { } ---@private --- File does not start with "#!". +--- File does not start with "#!". +--- @param contents string[] +--- @param path string +--- @return string? +--- @return fun(b: integer)? local function match_from_text(contents, path) if contents[1]:find('^:$') then -- Bourne-like shell scripts: sh ksh bash bash2 - return M.sh(path, contents) + return sh(path, contents) elseif matchregex( '\n' .. table.concat(contents, '\n'), @@ -1652,10 +1916,15 @@ local function match_from_text(contents, path) return cvs_diff(path, contents) end -M.match_contents = function(contents, path) +--- @param contents string[] +--- @param path string +--- @param dispatch_extension fun(name: string): string?, fun(b: integer)? +--- @return string? +--- @return fun(b: integer)? +function M.match_contents(contents, path, dispatch_extension) local first_line = contents[1] if first_line:find('^#!') then - return match_from_hashbang(contents, path) + return match_from_hashbang(contents, path, dispatch_extension) else return match_from_text(contents, path) end diff --git a/runtime/lua/vim/filetype/options.lua b/runtime/lua/vim/filetype/options.lua new file mode 100644 index 0000000000..2a28b5a8e3 --- /dev/null +++ b/runtime/lua/vim/filetype/options.lua @@ -0,0 +1,88 @@ +local api = vim.api + +local M = {} + +local function get_ftplugin_runtime(filetype) + local files = api.nvim__get_runtime({ + string.format('ftplugin/%s.vim', filetype), + string.format('ftplugin/%s_*.vim', filetype), + string.format('ftplugin/%s/*.vim', filetype), + string.format('ftplugin/%s.lua', filetype), + string.format('ftplugin/%s_*.lua', filetype), + string.format('ftplugin/%s/*.lua', filetype), + }, true, {}) --[[@as string[] ]] + + local r = {} ---@type string[] + for _, f in ipairs(files) do + -- VIMRUNTIME should be static so shouldn't need to worry about it changing + if not vim.startswith(f, vim.env.VIMRUNTIME) then + r[#r + 1] = f + end + end + return r +end + +-- Keep track of ftplugin files +local ftplugin_cache = {} ---@type table<string,table<string,integer>> + +-- Keep track of total number of FileType autocmds +local ft_autocmd_num ---@type integer? + +-- Keep track of filetype options +local ft_option_cache = {} ---@type table<string,table<string,any>> + +--- @param path string +--- @return integer +local function hash(path) + local mtime0 = vim.uv.fs_stat(path).mtime + return mtime0.sec * 1000000000 + mtime0.nsec +end + +--- Only update the cache on changes to the number of FileType autocmds +--- and changes to any ftplugin/ file. This isn't guaranteed to catch everything +--- but should be good enough. +--- @param filetype string +local function update_ft_option_cache(filetype) + local new_ftautos = #api.nvim_get_autocmds({ event = 'FileType' }) + if new_ftautos ~= ft_autocmd_num then + -- invalidate + ft_option_cache[filetype] = nil + ft_autocmd_num = new_ftautos + end + + local files = get_ftplugin_runtime(filetype) + + ftplugin_cache[filetype] = ftplugin_cache[filetype] or {} + + if #files ~= #vim.tbl_keys(ftplugin_cache[filetype]) then + -- invalidate + ft_option_cache[filetype] = nil + ftplugin_cache[filetype] = {} + end + + for _, f in ipairs(files) do + local mtime = hash(f) + if ftplugin_cache[filetype][f] ~= mtime then + -- invalidate + ft_option_cache[filetype] = nil + ftplugin_cache[filetype][f] = mtime + end + end +end + +--- @private +--- @param filetype string Filetype +--- @param option string Option name +--- @return string|integer|boolean +function M.get_option(filetype, option) + update_ft_option_cache(filetype) + + if not ft_option_cache[filetype] or not ft_option_cache[filetype][option] then + ft_option_cache[filetype] = ft_option_cache[filetype] or {} + ft_option_cache[filetype][option] = api.nvim_get_option_value(option, { filetype = filetype }) + end + + return ft_option_cache[filetype][option] +end + +return M diff --git a/runtime/lua/vim/fs.lua b/runtime/lua/vim/fs.lua index a0d2c4c339..22612a7255 100644 --- a/runtime/lua/vim/fs.lua +++ b/runtime/lua/vim/fs.lua @@ -1,11 +1,12 @@ local M = {} -local iswin = vim.loop.os_uname().sysname == 'Windows_NT' +local iswin = vim.uv.os_uname().sysname == 'Windows_NT' ---- Iterate over all the parents of the given file or directory. +--- Iterate over all the parents of the given path. --- --- Example: ---- <pre>lua +--- +--- ```lua --- local root_dir --- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do --- if vim.fn.isdirectory(dir .. "/.git") == 1 then @@ -17,10 +18,12 @@ local iswin = vim.loop.os_uname().sysname == 'Windows_NT' --- if root_dir then --- print("Found git repository at", root_dir) --- end ---- </pre> +--- ``` --- ----@param start (string) Initial file or directory. ----@return (function) Iterator +---@param start (string) Initial path. +---@return fun(_, dir: string): string? # Iterator +---@return nil +---@return string|nil function M.parents(start) return function(_, dir) local parent = M.dirname(dir) @@ -34,10 +37,10 @@ function M.parents(start) start end ---- Return the parent directory of the given file or directory +--- Return the parent directory of the given path --- ----@param file (string) File or directory ----@return (string) Parent directory of {file} +---@param file (string) Path +---@return string|nil Parent directory of {file} function M.dirname(file) if file == nil then return nil @@ -57,10 +60,10 @@ function M.dirname(file) return (dir:gsub('\\', '/')) end ---- Return the basename of the given file or directory +--- Return the basename of the given path --- ----@param file (string) File or directory ----@return (string) Basename of {file} +---@param file string Path +---@return string|nil Basename of {file} function M.basename(file) if file == nil then return nil @@ -72,12 +75,18 @@ function M.basename(file) return file:match('[/\\]$') and '' or (file:match('[^\\/]*$'):gsub('\\', '/')) end ----@private -local function join_paths(...) +--- Concatenate directories and/or file paths into a single path with normalization +--- (e.g., `"foo/"` and `"bar"` get joined to `"foo/bar"`) +--- +---@param ... string +---@return string +function M.joinpath(...) return (table.concat({ ... }, '/'):gsub('//+', '/')) end ---- Return an iterator over the files and directories located in {path} +---@alias Iterator fun(): string?, string? + +--- Return an iterator over the items located in {path} --- ---@param path (string) An absolute or relative path to the directory to iterate --- over. The path is first normalized |vim.fs.normalize()|. @@ -87,9 +96,10 @@ end --- to control traversal. Return false to stop searching the current directory. --- Only useful when depth > 1 --- ----@return Iterator over files and directories in {path}. Each iteration yields ---- two values: name and type. Each "name" is the basename of the file or ---- directory relative to {path}. Type is one of "file" or "directory". +---@return Iterator over items in {path}. Each iteration yields two values: "name" and "type". +--- "name" is the basename of the item relative to {path}. +--- "type" is one of the following: +--- "file", "directory", "link", "fifo", "socket", "char", "block", "unknown". function M.dir(path, opts) opts = opts or {} @@ -100,25 +110,29 @@ function M.dir(path, opts) }) if not opts.depth or opts.depth == 1 then - return function(fs) - return vim.loop.fs_scandir_next(fs) - end, - vim.loop.fs_scandir(M.normalize(path)) + local fs = vim.uv.fs_scandir(M.normalize(path)) + return function() + if not fs then + return + end + return vim.uv.fs_scandir_next(fs) + end end --- @async return coroutine.wrap(function() local dirs = { { path, 1 } } while #dirs > 0 do + --- @type string, integer local dir0, level = unpack(table.remove(dirs, 1)) - local dir = level == 1 and dir0 or join_paths(path, dir0) - local fs = vim.loop.fs_scandir(M.normalize(dir)) + local dir = level == 1 and dir0 or M.joinpath(path, dir0) + local fs = vim.uv.fs_scandir(M.normalize(dir)) while fs do - local name, t = vim.loop.fs_scandir_next(fs) + local name, t = vim.uv.fs_scandir_next(fs) if not name then break end - local f = level == 1 and name or join_paths(dir0, name) + local f = level == 1 and name or M.joinpath(dir0, name) coroutine.yield(f, t) if opts.depth @@ -133,22 +147,52 @@ function M.dir(path, opts) end) end ---- Find files or directories in the given path. +--- @class vim.fs.find.opts +--- @field path string +--- @field upward boolean +--- @field stop string +--- @field type string +--- @field limit number + +--- Find files or directories (or other items as specified by `opts.type`) in the given path. +--- +--- Finds items given in {names} starting from {path}. If {upward} is "true" +--- then the search traverses upward through parent directories; otherwise, +--- the search traverses downward. Note that downward searches are recursive +--- and may search through many directories! If {stop} is non-nil, then the +--- search stops when the directory given in {stop} is reached. The search +--- terminates when {limit} (default 1) matches are found. You can set {type} +--- to "file", "directory", "link", "socket", "char", "block", or "fifo" +--- to narrow the search to find only that type. --- ---- Finds any files or directories given in {names} starting from {path}. If ---- {upward} is "true" then the search traverses upward through parent ---- directories; otherwise, the search traverses downward. Note that downward ---- searches are recursive and may search through many directories! If {stop} ---- is non-nil, then the search stops when the directory given in {stop} is ---- reached. The search terminates when {limit} (default 1) matches are found. ---- The search can be narrowed to find only files or only directories by ---- specifying {type} to be "file" or "directory", respectively. +--- Examples: +--- +--- ```lua +--- -- location of Cargo.toml from the current buffer's path +--- local cargo = vim.fs.find('Cargo.toml', { +--- upward = true, +--- stop = vim.uv.os_homedir(), +--- path = vim.fs.dirname(vim.api.nvim_buf_get_name(0)), +--- }) +--- +--- -- list all test directories under the runtime directory +--- local test_dirs = vim.fs.find( +--- {'test', 'tst', 'testdir'}, +--- {limit = math.huge, type = 'directory', path = './runtime/'} +--- ) +--- +--- -- get all files ending with .cpp or .hpp inside lib/ +--- local cpp_hpp = vim.fs.find(function(name, path) +--- return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$') +--- end, {limit = math.huge, type = 'file'}) +--- ``` --- ----@param names (string|table|fun(name: string): boolean) Names of the files ---- and directories to find. ---- Must be base names, paths and globs are not supported. ---- The function is called per file and directory within the ---- traversed directories to test if they match {names}. +---@param names (string|string[]|fun(name: string, path: string): boolean) Names of the items to find. +--- Must be base names, paths and globs are not supported when {names} is a string or a table. +--- If {names} is a function, it is called for each traversed item with args: +--- - name: base name of the current item +--- - path: full path of the current item +--- The function should return `true` if the given item is considered a match. --- ---@param opts (table) Optional keyword arguments: --- - path (string): Path to begin searching from. If @@ -159,16 +203,14 @@ end --- (recursively). --- - stop (string): Stop searching when this directory is --- reached. The directory itself is not searched. ---- - type (string): Find only files ("file") or ---- directories ("directory"). If omitted, both ---- files and directories that match {names} are ---- included. +--- - type (string): Find only items of the given type. +--- If omitted, all items that match {names} are included. --- - limit (number, default 1): Stop the search after --- finding this many matches. Use `math.huge` to --- place no limit on the number of matches. ----@return (table) Normalized paths |vim.fs.normalize()| of all matching files or directories +---@return (string[]) # Normalized paths |vim.fs.normalize()| of all matching items function M.find(names, opts) - opts = opts or {} + opts = opts or {} --[[@as vim.fs.find.opts]] vim.validate({ names = { names, { 's', 't', 'f' } }, path = { opts.path, 's', true }, @@ -178,41 +220,42 @@ function M.find(names, opts) limit = { opts.limit, 'n', true }, }) - names = type(names) == 'string' and { names } or names + if type(names) == 'string' then + names = { names } + end - local path = opts.path or vim.loop.cwd() + local path = opts.path or vim.uv.cwd() local stop = opts.stop local limit = opts.limit or 1 - local matches = {} + local matches = {} --- @type string[] - ---@private local function add(match) - matches[#matches + 1] = match + matches[#matches + 1] = M.normalize(match) if #matches == limit then return true end end if opts.upward then - local test + local test --- @type fun(p: string): string[] if type(names) == 'function' then test = function(p) local t = {} for name, type in M.dir(p) do - if names(name) and (not opts.type or opts.type == type) then - table.insert(t, join_paths(p, name)) + if (not opts.type or opts.type == type) and names(name, p) then + table.insert(t, M.joinpath(p, name)) end end return t end else test = function(p) - local t = {} + local t = {} --- @type string[] for _, name in ipairs(names) do - local f = join_paths(p, name) - local stat = vim.loop.fs_stat(f) + local f = M.joinpath(p, name) + local stat = vim.uv.fs_stat(f) if stat and (not opts.type or opts.type == stat.type) then t[#t + 1] = f end @@ -248,9 +291,9 @@ function M.find(names, opts) end for other, type_ in M.dir(dir) do - local f = join_paths(dir, other) + local f = M.joinpath(dir, other) if type(names) == 'function' then - if names(other) and (not opts.type or opts.type == type_) then + if (not opts.type or opts.type == type_) and names(other, dir) then if add(f) then return matches end @@ -281,28 +324,47 @@ end --- variables are also expanded. --- --- Examples: ---- <pre>lua ---- vim.fs.normalize('C:\\\\Users\\\\jdoe') ---- --> 'C:/Users/jdoe' --- ---- vim.fs.normalize('~/src/neovim') ---- --> '/home/jdoe/src/neovim' +--- ```lua +--- vim.fs.normalize('C:\\\\Users\\\\jdoe') +--- -- 'C:/Users/jdoe' --- ---- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') ---- --> '/Users/jdoe/.config/nvim/init.vim' ---- </pre> +--- vim.fs.normalize('~/src/neovim') +--- -- '/home/jdoe/src/neovim' +--- +--- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') +--- -- '/Users/jdoe/.config/nvim/init.vim' +--- ``` --- ---@param path (string) Path to normalize +---@param opts table|nil Options: +--- - expand_env: boolean Expand environment variables (default: true) ---@return (string) Normalized path -function M.normalize(path) - vim.validate({ path = { path, 's' } }) - return ( - path - :gsub('^~$', vim.loop.os_homedir()) - :gsub('^~/', vim.loop.os_homedir() .. '/') - :gsub('%$([%w_]+)', vim.loop.os_getenv) - :gsub('\\', '/') - ) +function M.normalize(path, opts) + opts = opts or {} + + vim.validate({ + path = { path, { 'string' } }, + expand_env = { opts.expand_env, { 'boolean' }, true }, + }) + + if path:sub(1, 1) == '~' then + local home = vim.uv.os_homedir() or '~' + if home:sub(-1) == '\\' or home:sub(-1) == '/' then + home = home:sub(1, -2) + end + path = home .. path:sub(2) + end + + if opts.expand_env == nil or opts.expand_env then + path = path:gsub('%$([%w_]+)', vim.uv.os_getenv) + end + + path = path:gsub('\\', '/'):gsub('/+', '/') + if iswin and path:match('^%w:/$') then + return path + end + return (path:gsub('(.)/$', '%1')) end return M diff --git a/runtime/lua/vim/func.lua b/runtime/lua/vim/func.lua new file mode 100644 index 0000000000..206d1bae95 --- /dev/null +++ b/runtime/lua/vim/func.lua @@ -0,0 +1,41 @@ +local M = {} + +-- TODO(lewis6991): Private for now until: +-- - There are other places in the codebase that could benefit from this +-- (e.g. LSP), but might require other changes to accommodate. +-- - Invalidation of the cache needs to be controllable. Using weak tables +-- is an acceptable invalidation policy, but it shouldn't be the only +-- one. +-- - I don't think the story around `hash` is completely thought out. We +-- may be able to have a good default hash by hashing each argument, +-- so basically a better 'concat'. +-- - Need to support multi level caches. Can be done by allow `hash` to +-- return multiple values. +-- +--- Memoizes a function {fn} using {hash} to hash the arguments. +--- +--- Internally uses a |lua-weaktable| to cache the results of {fn} meaning the +--- cache will be invalidated whenever Lua does garbage collection. +--- +--- The memoized function returns shared references so be wary about +--- mutating return values. +--- +--- @generic F: function +--- @param hash integer|string|function Hash function to create a hash to use as a key to +--- store results. Possible values: +--- - When integer, refers to the index of an argument of {fn} to hash. +--- This argument can have any type. +--- - When function, is evaluated using the same arguments passed to {fn}. +--- - When `concat`, the hash is determined by string concatenating all the +--- arguments passed to {fn}. +--- - When `concat-n`, the hash is determined by string concatenating the +--- first n arguments passed to {fn}. +--- +--- @param fn F Function to memoize. +--- @return F # Memoized version of {fn} +--- @nodoc +function M._memoize(hash, fn) + return require('vim.func._memoize')(hash, fn) +end + +return M diff --git a/runtime/lua/vim/func/_memoize.lua b/runtime/lua/vim/func/_memoize.lua new file mode 100644 index 0000000000..835bf64c93 --- /dev/null +++ b/runtime/lua/vim/func/_memoize.lua @@ -0,0 +1,59 @@ +--- Module for private utility functions + +--- @param argc integer? +--- @return fun(...): any +local function concat_hash(argc) + return function(...) + return table.concat({ ... }, '%%', 1, argc) + end +end + +--- @param idx integer +--- @return fun(...): any +local function idx_hash(idx) + return function(...) + return select(idx, ...) + end +end + +--- @param hash integer|string|fun(...): any +--- @return fun(...): any +local function resolve_hash(hash) + if type(hash) == 'number' then + hash = idx_hash(hash) + elseif type(hash) == 'string' then + local c = hash == 'concat' or hash:match('^concat%-(%d+)') + if c then + hash = concat_hash(tonumber(c)) + else + error('invalid value for hash: ' .. hash) + end + end + --- @cast hash -integer + return hash +end + +--- @generic F: function +--- @param hash integer|string|fun(...): any +--- @param fn F +--- @return F +return function(hash, fn) + vim.validate({ + hash = { hash, { 'number', 'string', 'function' } }, + fn = { fn, 'function' }, + }) + + ---@type table<any,table<any,any>> + local cache = setmetatable({}, { __mode = 'kv' }) + + hash = resolve_hash(hash) + + return function(...) + local key = hash(...) + if cache[key] == nil then + cache[key] = vim.F.pack_len(fn(...)) + end + + return vim.F.unpack_len(cache[key]) + end +end diff --git a/runtime/lua/vim/health.lua b/runtime/lua/vim/health.lua index 044880e076..6e47a22d03 100644 --- a/runtime/lua/vim/health.lua +++ b/runtime/lua/vim/health.lua @@ -1,23 +1,230 @@ local M = {} -function M.report_start(msg) - vim.fn['health#report_start'](msg) +local s_output = {} + +-- Returns the fold text of the current healthcheck section +function M.foldtext() + local foldtext = vim.fn.foldtext() + + if vim.bo.filetype ~= 'checkhealth' then + return foldtext + end + + if vim.b.failedchecks == nil then + vim.b.failedchecks = vim.empty_dict() + end + + if vim.b.failedchecks[foldtext] == nil then + local warning = '- WARNING ' + local warninglen = string.len(warning) + local err = '- ERROR ' + local errlen = string.len(err) + local failedchecks = vim.b.failedchecks + failedchecks[foldtext] = false + + local foldcontent = vim.api.nvim_buf_get_lines(0, vim.v.foldstart - 1, vim.v.foldend, false) + for _, line in ipairs(foldcontent) do + if string.sub(line, 1, warninglen) == warning or string.sub(line, 1, errlen) == err then + failedchecks[foldtext] = true + break + end + end + + vim.b.failedchecks = failedchecks + end + + return vim.b.failedchecks[foldtext] and '+WE' .. foldtext:sub(4) or foldtext end -function M.report_info(msg) - vim.fn['health#report_info'](msg) +-- From a path return a list [{name}, {func}, {type}] representing a healthcheck +local function filepath_to_healthcheck(path) + path = vim.fs.normalize(path) + local name + local func + local filetype + if path:find('vim$') then + name = vim.fs.basename(path):gsub('%.vim$', '') + func = 'health#' .. name .. '#check' + filetype = 'v' + else + local subpath = path:gsub('.*lua/', '') + if vim.fs.basename(subpath) == 'health.lua' then + -- */health.lua + name = vim.fs.dirname(subpath) + else + -- */health/init.lua + name = vim.fs.dirname(vim.fs.dirname(subpath)) + end + name = name:gsub('/', '.') + + func = 'require("' .. name .. '.health").check()' + filetype = 'l' + end + return { name, func, filetype } end -function M.report_ok(msg) - vim.fn['health#report_ok'](msg) +-- Returns { {name, func, type}, ... } representing healthchecks +local function get_healthcheck_list(plugin_names) + local healthchecks = {} + plugin_names = vim.split(plugin_names, ' ') + for _, p in pairs(plugin_names) do + -- support vim/lsp/health{/init/}.lua as :checkhealth vim.lsp + + p = p:gsub('%.', '/') + p = p:gsub('*', '**') + + local paths = vim.api.nvim_get_runtime_file('autoload/health/' .. p .. '.vim', true) + vim.list_extend( + paths, + vim.api.nvim_get_runtime_file('lua/**/' .. p .. '/health/init.lua', true) + ) + vim.list_extend(paths, vim.api.nvim_get_runtime_file('lua/**/' .. p .. '/health.lua', true)) + + if vim.tbl_count(paths) == 0 then + healthchecks[#healthchecks + 1] = { p, '', '' } -- healthcheck not found + else + local unique_paths = {} + for _, v in pairs(paths) do + unique_paths[v] = true + end + paths = {} + for k, _ in pairs(unique_paths) do + paths[#paths + 1] = k + end + + for _, v in ipairs(paths) do + healthchecks[#healthchecks + 1] = filepath_to_healthcheck(v) + end + end + end + return healthchecks end -function M.report_warn(msg, ...) - vim.fn['health#report_warn'](msg, ...) +-- Returns {name: [func, type], ..} representing healthchecks +local function get_healthcheck(plugin_names) + local health_list = get_healthcheck_list(plugin_names) + local healthchecks = {} + for _, c in pairs(health_list) do + if c[1] ~= 'vim' then + healthchecks[c[1]] = { c[2], c[3] } + end + end + + return healthchecks +end + +-- Indents lines *except* line 1 of a string if it contains newlines. +local function indent_after_line1(s, columns) + local lines = vim.split(s, '\n') + local indent = string.rep(' ', columns) + for i = 2, #lines do + lines[i] = indent .. lines[i] + end + return table.concat(lines, '\n') +end + +-- Changes ':h clipboard' to ':help |clipboard|'. +local function help_to_link(s) + return vim.fn.substitute(s, [[\v:h%[elp] ([^|][^"\r\n ]+)]], [[:help |\1|]], [[g]]) end +-- Format a message for a specific report item. +-- Variable args: Optional advice (string or list) +local function format_report_message(status, msg, ...) + local output = '- ' .. status + if status ~= '' then + output = output .. ' ' + end + + output = output .. indent_after_line1(msg, 2) + + local varargs = ... + + -- Optional parameters + if varargs then + if type(varargs) == 'string' then + varargs = { varargs } + end + + output = output .. '\n - ADVICE:' + + -- Report each suggestion + for _, v in ipairs(varargs) do + if v then + output = output .. '\n - ' .. indent_after_line1(v, 6) + end + end + end + + return help_to_link(output) +end + +local function collect_output(output) + vim.list_extend(s_output, vim.split(output, '\n')) +end + +-- Starts a new report. +function M.start(name) + local input = string.format('\n%s ~', name) + collect_output(input) +end + +-- Reports a message in the current section. +function M.info(msg) + local input = format_report_message('', msg) + collect_output(input) +end + +-- Reports a successful healthcheck. +function M.ok(msg) + local input = format_report_message('OK', msg) + collect_output(input) +end + +-- Reports a health warning. +-- ...: Optional advice (string or table) +function M.warn(msg, ...) + local input = format_report_message('WARNING', msg, ...) + collect_output(input) +end + +-- Reports a failed healthcheck. +-- ...: Optional advice (string or table) +function M.error(msg, ...) + local input = format_report_message('ERROR', msg, ...) + collect_output(input) +end + +local function deprecate(type) + local before = string.format('vim.health.report_%s()', type) + local after = string.format('vim.health.%s()', type) + local message = vim.deprecate(before, after, '0.11') + if message then + M.warn(message) + end + vim.cmd.redraw() + vim.print('Running healthchecks...') +end + +function M.report_start(name) + deprecate('start') + M.start(name) +end +function M.report_info(msg) + deprecate('info') + M.info(msg) +end +function M.report_ok(msg) + deprecate('ok') + M.ok(msg) +end +function M.report_warn(msg, ...) + deprecate('warn') + M.warn(msg, ...) +end function M.report_error(msg, ...) - vim.fn['health#report_error'](msg, ...) + deprecate('error') + M.error(msg, ...) end local path2name = function(path) @@ -59,4 +266,77 @@ M._complete = function() return vim.tbl_keys(unique) end +-- Runs the specified healthchecks. +-- Runs all discovered healthchecks if plugin_names is empty. +function M._check(plugin_names) + local healthchecks = plugin_names == '' and get_healthcheck('*') or get_healthcheck(plugin_names) + + -- Create buffer and open in a tab, unless this is the default buffer when Nvim starts. + local emptybuf = vim.fn.bufnr('$') == 1 and vim.fn.getline(1) == '' and 1 == vim.fn.line('$') + local mod = emptybuf and 'buffer' or 'tab sbuffer' + local bufnr = vim.api.nvim_create_buf(true, true) + vim.cmd(mod .. ' ' .. bufnr) + + if vim.fn.bufexists('health://') == 1 then + vim.cmd.bwipe('health://') + end + vim.cmd.file('health://') + vim.cmd.setfiletype('checkhealth') + + if healthchecks == nil or next(healthchecks) == nil then + vim.fn.setline(1, 'ERROR: No healthchecks found.') + return + end + vim.cmd.redraw() + vim.print('Running healthchecks...') + + for name, value in vim.spairs(healthchecks) do + local func = value[1] + local type = value[2] + s_output = {} + + if func == '' then + s_output = {} + M.error('No healthcheck found for "' .. name .. '" plugin.') + end + if type == 'v' then + vim.fn.call(func, {}) + else + local f = assert(loadstring(func)) + local ok, output = pcall(f) + if not ok then + M.error( + string.format('Failed to run healthcheck for "%s" plugin. Exception:\n%s\n', name, output) + ) + end + end + -- in the event the healthcheck doesn't return anything + -- (the plugin author should avoid this possibility) + if next(s_output) == nil then + s_output = {} + M.error('The healthcheck report for "' .. name .. '" plugin is empty.') + end + local header = { string.rep('=', 78), name .. ': ' .. func, '' } + -- remove empty line after header from report_start + if s_output[1] == '' then + local tmp = {} + for i = 2, #s_output do + tmp[#tmp + 1] = s_output[i] + end + s_output = {} + for _, v in ipairs(tmp) do + s_output[#s_output + 1] = v + end + end + s_output[#s_output + 1] = '' + s_output = vim.list_extend(header, s_output) + vim.fn.append('$', s_output) + vim.cmd.redraw() + end + + -- Clear the 'Running healthchecks...' message. + vim.cmd.redraw() + vim.print('') +end + return M diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua index 20ad48dd27..fc2fd43c97 100644 --- a/runtime/lua/vim/highlight.lua +++ b/runtime/lua/vim/highlight.lua @@ -1,7 +1,36 @@ +---@defgroup vim.highlight +--- +--- Nvim includes a function for highlighting a selection on yank. +--- +--- To enable it, add the following to your `init.vim`: +--- +--- ```vim +--- au TextYankPost * silent! lua vim.highlight.on_yank() +--- ``` +--- +--- You can customize the highlight group and the duration of the highlight via: +--- +--- ```vim +--- au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} +--- ``` +--- +--- If you want to exclude visual selections from highlighting on yank, use: +--- +--- ```vim +--- au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} +--- ``` + local api = vim.api local M = {} +--- Table with default priorities used for highlighting: +--- - `syntax`: `50`, used for standard syntax highlighting +--- - `treesitter`: `100`, used for tree-sitter-based highlighting +--- - `semantic_tokens`: `125`, used for LSP semantic token highlighting +--- - `diagnostics`: `150`, used for code analysis such as diagnostics +--- - `user`: `200`, used for user-triggered highlights such as LSP document +--- symbols or `on_yank` autocommands M.priorities = { syntax = 50, treesitter = 100, @@ -10,52 +39,26 @@ M.priorities = { user = 200, } ----@private -function M.create(higroup, hi_info, default) - vim.deprecate('vim.highlight.create', 'vim.api.nvim_set_hl', '0.9') - local options = {} - -- TODO: Add validation - for k, v in pairs(hi_info) do - table.insert(options, string.format('%s=%s', k, v)) - end - vim.cmd( - string.format( - [[highlight %s %s %s]], - default and 'default' or '', - higroup, - table.concat(options, ' ') - ) - ) -end - ----@private -function M.link(higroup, link_to, force) - vim.deprecate('vim.highlight.link', 'vim.api.nvim_set_hl', '0.9') - vim.cmd(string.format([[highlight%s link %s %s]], force and '!' or ' default', higroup, link_to)) -end - ---- Highlight range between two positions +--- Apply highlight group to range of text. --- ----@param bufnr number of buffer to apply highlighting to ----@param ns namespace to add highlight to ----@param higroup highlight group to use for highlighting ----@param start first position (tuple {line,col}) ----@param finish second position (tuple {line,col}) ----@param opts table with options: --- - regtype type of range (see |setreg()|, default charwise) --- - inclusive boolean indicating whether the range is end-inclusive (default false) --- - priority number indicating priority of highlight (default priorities.user) +---@param bufnr integer Buffer number to apply highlighting to +---@param ns integer Namespace to add highlight to +---@param higroup string Highlight group to use for highlighting +---@param start integer[]|string Start of region as a (line, column) tuple or string accepted by |getpos()| +---@param finish integer[]|string End of region as a (line, column) tuple or string accepted by |getpos()| +---@param opts table|nil Optional parameters +--- - regtype type of range (see |setreg()|, default charwise) +--- - inclusive boolean indicating whether the range is end-inclusive (default false) +--- - priority number indicating priority of highlight (default priorities.user) function M.range(bufnr, ns, higroup, start, finish, opts) opts = opts or {} local regtype = opts.regtype or 'v' local inclusive = opts.inclusive or false local priority = opts.priority or M.priorities.user - -- sanity check - if start[2] < 0 or finish[1] < start[1] then - return - end - + -- TODO: in case of 'v', 'V' (not block), this should calculate equivalent + -- bounds (row, col, end_row, end_col) as multiline regions are natively + -- supported now local region = vim.region(bufnr, start, finish, regtype, inclusive) for linenr, cols in pairs(region) do local end_row @@ -75,21 +78,16 @@ end local yank_ns = api.nvim_create_namespace('hlyank') local yank_timer ---- Highlight the yanked region ---- ---- use from init.vim via ---- au TextYankPost * lua vim.highlight.on_yank() ---- customize highlight group and timeout via ---- au TextYankPost * lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} ---- customize conditions (here: do not highlight a visual selection) via ---- au TextYankPost * lua vim.highlight.on_yank {on_visual=false} + +--- Highlight the yanked text --- --- @param opts table with options controlling the highlight: --- - higroup highlight group for yanked region (default "IncSearch") --- - timeout time in ms before highlight is cleared (default 150) --- - on_macro highlight when executing macro (default false) --- - on_visual highlight when yanking visual selection (default true) --- - event event structure (default vim.v.event) +--- @param opts table|nil Optional parameters +--- - higroup highlight group for yanked region (default "IncSearch") +--- - timeout time in ms before highlight is cleared (default 150) +--- - on_macro highlight when executing macro (default false) +--- - on_visual highlight when yanking visual selection (default true) +--- - event event structure (default vim.v.event) +--- - priority integer priority (default |vim.highlight.priorities|`.user`) function M.on_yank(opts) vim.validate({ opts = { @@ -128,20 +126,11 @@ function M.on_yank(opts) yank_timer:close() end - local pos1 = vim.fn.getpos("'[") - local pos2 = vim.fn.getpos("']") - - pos1 = { pos1[2] - 1, pos1[3] - 1 + pos1[4] } - pos2 = { pos2[2] - 1, pos2[3] - 1 + pos2[4] } - - M.range( - bufnr, - yank_ns, - higroup, - pos1, - pos2, - { regtype = event.regtype, inclusive = event.inclusive, priority = M.priorities.user } - ) + M.range(bufnr, yank_ns, higroup, "'[", "']", { + regtype = event.regtype, + inclusive = event.inclusive, + priority = opts.priority or M.priorities.user, + }) yank_timer = vim.defer_fn(function() yank_timer = nil diff --git a/runtime/lua/vim/iter.lua b/runtime/lua/vim/iter.lua new file mode 100644 index 0000000000..874bdfb437 --- /dev/null +++ b/runtime/lua/vim/iter.lua @@ -0,0 +1,1013 @@ +---@defgroup vim.iter +--- +--- \*vim.iter()\* is an interface for |iterable|s: it wraps a table or function argument into an +--- \*Iter\* object with methods (such as |Iter:filter()| and |Iter:map()|) that transform the +--- underlying source data. These methods can be chained to create iterator "pipelines": the output +--- of each pipeline stage is input to the next stage. The first stage depends on the type passed to +--- `vim.iter()`: +--- +--- - List tables (arrays, |lua-list|) yield only the value of each element. +--- - Use |Iter:enumerate()| to also pass the index to the next stage. +--- - Or initialize with ipairs(): `vim.iter(ipairs(…))`. +--- - Non-list tables (|lua-dict|) yield both the key and value of each element. +--- - Function |iterator|s yield all values returned by the underlying function. +--- - Tables with a |__call()| metamethod are treated as function iterators. +--- +--- The iterator pipeline terminates when the underlying |iterable| is exhausted (for function +--- iterators this means it returned nil). +--- +--- Note: `vim.iter()` scans table input to decide if it is a list or a dict; to avoid this cost you +--- can wrap the table with an iterator e.g. `vim.iter(ipairs({…}))`, but that precludes the use of +--- |list-iterator| operations such as |Iter:rev()|). +--- +--- Examples: +--- +--- ```lua +--- local it = vim.iter({ 1, 2, 3, 4, 5 }) +--- it:map(function(v) +--- return v * 3 +--- end) +--- it:rev() +--- it:skip(2) +--- it:totable() +--- -- { 9, 6, 3 } +--- +--- -- ipairs() is a function iterator which returns both the index (i) and the value (v) +--- vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v) +--- if i > 2 then return v end +--- end):totable() +--- -- { 3, 4, 5 } +--- +--- local it = vim.iter(vim.gsplit('1,2,3,4,5', ',')) +--- it:map(function(s) return tonumber(s) end) +--- for i, d in it:enumerate() do +--- print(string.format("Column %d is %d", i, d)) +--- end +--- -- Column 1 is 1 +--- -- Column 2 is 2 +--- -- Column 3 is 3 +--- -- Column 4 is 4 +--- -- Column 5 is 5 +--- +--- vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v) +--- return k == 'z' +--- end) +--- -- true +--- +--- local rb = vim.ringbuf(3) +--- rb:push("a") +--- rb:push("b") +--- vim.iter(rb):totable() +--- -- { "a", "b" } +--- ``` +--- +--- In addition to the |vim.iter()| function, the |vim.iter| module provides +--- convenience functions like |vim.iter.filter()| and |vim.iter.totable()|. + +---@class IterMod +---@operator call:Iter +local M = {} + +---@class Iter +local Iter = {} +Iter.__index = Iter +Iter.__call = function(self) + return self:next() +end + +--- Special case implementations for iterators on list tables. +---@class ListIter : Iter +---@field _table table Underlying table data +---@field _head number Index to the front of a table iterator +---@field _tail number Index to the end of a table iterator (exclusive) +local ListIter = {} +ListIter.__index = setmetatable(ListIter, Iter) +ListIter.__call = function(self) + return self:next() +end + +--- Packed tables use this as their metatable +local packedmt = {} + +local function unpack(t) + if type(t) == 'table' and getmetatable(t) == packedmt then + return _G.unpack(t, 1, t.n) + end + return t +end + +local function pack(...) + local n = select('#', ...) + if n > 1 then + return setmetatable({ n = n, ... }, packedmt) + end + return ... +end + +local function sanitize(t) + if type(t) == 'table' and getmetatable(t) == packedmt then + -- Remove length tag + t.n = nil + end + return t +end + +--- Determine if the current iterator stage should continue. +--- +--- If any arguments are passed to this function, then return those arguments +--- and stop the current iterator stage. Otherwise, return true to signal that +--- the current stage should continue. +--- +---@param ... any Function arguments. +---@return boolean True if the iterator stage should continue, false otherwise +---@return any Function arguments. +local function continue(...) + if select(1, ...) ~= nil then + return false, ... + end + return true +end + +--- If no input arguments are given return false, indicating the current +--- iterator stage should stop. Otherwise, apply the arguments to the function +--- f. If that function returns no values, the current iterator stage continues. +--- Otherwise, those values are returned. +--- +---@param f function Function to call with the given arguments +---@param ... any Arguments to apply to f +---@return boolean True if the iterator pipeline should continue, false otherwise +---@return any Return values of f +local function apply(f, ...) + if select(1, ...) ~= nil then + return continue(f(...)) + end + return false +end + +--- Filters an iterator pipeline. +--- +--- Example: +--- +--- ```lua +--- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded) +--- ``` +--- +---@param f function(...):bool Takes all values returned from the previous stage +--- in the pipeline and returns false or nil if the +--- current iterator element should be removed. +---@return Iter +function Iter.filter(self, f) + return self:map(function(...) + if f(...) then + return ... + end + end) +end + +---@private +function ListIter.filter(self, f) + local inc = self._head < self._tail and 1 or -1 + local n = self._head + for i = self._head, self._tail - inc, inc do + local v = self._table[i] + if f(unpack(v)) then + self._table[n] = v + n = n + inc + end + end + self._tail = n + return self +end + +--- Maps the items of an iterator pipeline to the values returned by `f`. +--- +--- If the map function returns nil, the value is filtered from the iterator. +--- +--- Example: +--- +--- ```lua +--- local it = vim.iter({ 1, 2, 3, 4 }):map(function(v) +--- if v % 2 == 0 then +--- return v * 3 +--- end +--- end) +--- it:totable() +--- -- { 6, 12 } +--- ``` +--- +---@param f function(...):any Mapping function. Takes all values returned from +--- the previous stage in the pipeline as arguments +--- and returns one or more new values, which are used +--- in the next pipeline stage. Nil return values +--- are filtered from the output. +---@return Iter +function Iter.map(self, f) + -- Implementation note: the reader may be forgiven for observing that this + -- function appears excessively convoluted. The problem to solve is that each + -- stage of the iterator pipeline can return any number of values, and the + -- number of values could even change per iteration. And the return values + -- must be checked to determine if the pipeline has ended, so we cannot + -- naively forward them along to the next stage. + -- + -- A simple approach is to pack all of the return values into a table, check + -- for nil, then unpack the table for the next stage. However, packing and + -- unpacking tables is quite slow. There is no other way in Lua to handle an + -- unknown number of function return values than to simply forward those + -- values along to another function. Hence the intricate function passing you + -- see here. + + local next = self.next + + --- Drain values from the upstream iterator source until a value can be + --- returned. + --- + --- This is a recursive function. The base case is when the first argument is + --- false, which indicates that the rest of the arguments should be returned + --- as the values for the current iteration stage. + --- + ---@param cont boolean If true, the current iterator stage should continue to + --- pull values from its upstream pipeline stage. + --- Otherwise, this stage is complete and returns the + --- values passed. + ---@param ... any Values to return if cont is false. + ---@return any + local function fn(cont, ...) + if cont then + return fn(apply(f, next(self))) + end + return ... + end + + self.next = function() + return fn(apply(f, next(self))) + end + return self +end + +---@private +function ListIter.map(self, f) + local inc = self._head < self._tail and 1 or -1 + local n = self._head + for i = self._head, self._tail - inc, inc do + local v = pack(f(unpack(self._table[i]))) + if v ~= nil then + self._table[n] = v + n = n + inc + end + end + self._tail = n + return self +end + +--- Calls a function once for each item in the pipeline, draining the iterator. +--- +--- For functions with side effects. To modify the values in the iterator, use |Iter:map()|. +--- +---@param f function(...) Function to execute for each item in the pipeline. +--- Takes all of the values returned by the previous stage +--- in the pipeline as arguments. +function Iter.each(self, f) + local function fn(...) + if select(1, ...) ~= nil then + f(...) + return true + end + end + while fn(self:next()) do + end +end + +---@private +function ListIter.each(self, f) + local inc = self._head < self._tail and 1 or -1 + for i = self._head, self._tail - inc, inc do + f(unpack(self._table[i])) + end + self._head = self._tail +end + +--- Collect the iterator into a table. +--- +--- The resulting table depends on the initial source in the iterator pipeline. +--- List-like tables and function iterators will be collected into a list-like +--- table. If multiple values are returned from the final stage in the iterator +--- pipeline, each value will be included in a table. +--- +--- Examples: +--- +--- ```lua +--- vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable() +--- -- { 100, 20, 50 } +--- +--- vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable() +--- -- { { 1, 2 }, { 2, 4 }, { 3, 6 } } +--- +--- vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable() +--- -- { { 'a', 1 }, { 'c', 3 } } +--- ``` +--- +--- The generated table is a list-like table with consecutive, numeric indices. +--- To create a map-like table with arbitrary keys, use |Iter:fold()|. +--- +--- +---@return table +function Iter.totable(self) + local t = {} + + while true do + local args = pack(self:next()) + if args == nil then + break + end + + t[#t + 1] = sanitize(args) + end + return t +end + +---@private +function ListIter.totable(self) + if self.next ~= ListIter.next or self._head >= self._tail then + return Iter.totable(self) + end + + local needs_sanitize = getmetatable(self._table[1]) == packedmt + + -- Reindex and sanitize. + local len = self._tail - self._head + + if needs_sanitize then + for i = 1, len do + self._table[i] = sanitize(self._table[self._head - 1 + i]) + end + else + for i = 1, len do + self._table[i] = self._table[self._head - 1 + i] + end + end + + for i = len + 1, table.maxn(self._table) do + self._table[i] = nil + end + + self._head = 1 + self._tail = len + 1 + + return self._table +end + +--- Folds ("reduces") an iterator into a single value. +--- +--- Examples: +--- +--- ```lua +--- -- Create a new table with only even values +--- local t = { a = 1, b = 2, c = 3, d = 4 } +--- local it = vim.iter(t) +--- it:filter(function(k, v) return v % 2 == 0 end) +--- it:fold({}, function(t, k, v) +--- t[k] = v +--- return t +--- end) +--- -- { b = 2, d = 4 } +--- ``` +--- +---@generic A +--- +---@param init A Initial value of the accumulator. +---@param f function(acc:A, ...):A Accumulation function. +---@return A +function Iter.fold(self, init, f) + local acc = init + + --- Use a closure to handle var args returned from iterator + local function fn(...) + if select(1, ...) ~= nil then + acc = f(acc, ...) + return true + end + end + + while fn(self:next()) do + end + return acc +end + +---@private +function ListIter.fold(self, init, f) + local acc = init + local inc = self._head < self._tail and 1 or -1 + for i = self._head, self._tail - inc, inc do + acc = f(acc, unpack(self._table[i])) + end + return acc +end + +--- Gets the next value from the iterator. +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber) +--- it:next() +--- -- 1 +--- it:next() +--- -- 2 +--- it:next() +--- -- 3 +--- +--- ``` +--- +---@return any +function Iter.next(self) -- luacheck: no unused args + -- This function is provided by the source iterator in Iter.new. This definition exists only for + -- the docstring +end + +---@private +function ListIter.next(self) + if self._head ~= self._tail then + local v = self._table[self._head] + local inc = self._head < self._tail and 1 or -1 + self._head = self._head + inc + return unpack(v) + end +end + +--- Reverses a |list-iterator| pipeline. +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter({ 3, 6, 9, 12 }):rev() +--- it:totable() +--- -- { 12, 9, 6, 3 } +--- +--- ``` +--- +---@return Iter +function Iter.rev(self) + error('rev() requires a list-like table') + return self +end + +---@private +function ListIter.rev(self) + local inc = self._head < self._tail and 1 or -1 + self._head, self._tail = self._tail - inc, self._head - inc + return self +end + +--- Gets the next value in a |list-iterator| without consuming it. +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter({ 3, 6, 9, 12 }) +--- it:peek() +--- -- 3 +--- it:peek() +--- -- 3 +--- it:next() +--- -- 3 +--- +--- ``` +--- +---@return any +function Iter.peek(self) -- luacheck: no unused args + error('peek() requires a list-like table') +end + +---@private +function ListIter.peek(self) + if self._head ~= self._tail then + return self._table[self._head] + end +end + +--- Find the first value in the iterator that satisfies the given predicate. +--- +--- Advances the iterator. Returns nil and drains the iterator if no value is found. +--- +--- Examples: +--- +--- ```lua +--- +--- local it = vim.iter({ 3, 6, 9, 12 }) +--- it:find(12) +--- -- 12 +--- +--- local it = vim.iter({ 3, 6, 9, 12 }) +--- it:find(20) +--- -- nil +--- +--- local it = vim.iter({ 3, 6, 9, 12 }) +--- it:find(function(v) return v % 4 == 0 end) +--- -- 12 +--- +--- ``` +--- +---@return any +function Iter.find(self, f) + if type(f) ~= 'function' then + local val = f + f = function(v) + return v == val + end + end + + local result = nil + + --- Use a closure to handle var args returned from iterator + local function fn(...) + if select(1, ...) ~= nil then + if f(...) then + result = pack(...) + else + return true + end + end + end + + while fn(self:next()) do + end + return unpack(result) +end + +--- Gets the first value in a |list-iterator| that satisfies a predicate, starting from the end. +--- +--- Advances the iterator. Returns nil and drains the iterator if no value is found. +--- +--- Examples: +--- +--- ```lua +--- +--- local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate() +--- it:rfind(1) +--- -- 5 1 +--- it:rfind(1) +--- -- 1 1 +--- +--- ``` +--- +---@see Iter.find +--- +---@return any +function Iter.rfind(self, f) -- luacheck: no unused args + error('rfind() requires a list-like table') +end + +---@private +function ListIter.rfind(self, f) -- luacheck: no unused args + if type(f) ~= 'function' then + local val = f + f = function(v) + return v == val + end + end + + local inc = self._head < self._tail and 1 or -1 + for i = self._tail - inc, self._head, -inc do + local v = self._table[i] + if f(unpack(v)) then + self._tail = i + return unpack(v) + end + end + self._head = self._tail +end + +--- "Pops" a value from a |list-iterator| (gets the last value and decrements the tail). +--- +--- Example: +--- +--- ```lua +--- local it = vim.iter({1, 2, 3, 4}) +--- it:nextback() +--- -- 4 +--- it:nextback() +--- -- 3 +--- ``` +--- +---@return any +function Iter.nextback(self) -- luacheck: no unused args + error('nextback() requires a list-like table') +end + +function ListIter.nextback(self) + if self._head ~= self._tail then + local inc = self._head < self._tail and 1 or -1 + self._tail = self._tail - inc + return self._table[self._tail] + end +end + +--- Gets the last value of a |list-iterator| without consuming it. +--- +--- See also |Iter:last()|. +--- +--- Example: +--- +--- ```lua +--- local it = vim.iter({1, 2, 3, 4}) +--- it:peekback() +--- -- 4 +--- it:peekback() +--- -- 4 +--- it:nextback() +--- -- 4 +--- ``` +--- +---@return any +function Iter.peekback(self) -- luacheck: no unused args + error('peekback() requires a list-like table') +end + +function ListIter.peekback(self) + if self._head ~= self._tail then + local inc = self._head < self._tail and 1 or -1 + return self._table[self._tail - inc] + end +end + +--- Skips `n` values of an iterator pipeline. +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter({ 3, 6, 9, 12 }):skip(2) +--- it:next() +--- -- 9 +--- +--- ``` +--- +---@param n number Number of values to skip. +---@return Iter +function Iter.skip(self, n) + for _ = 1, n do + local _ = self:next() + end + return self +end + +---@private +function ListIter.skip(self, n) + local inc = self._head < self._tail and n or -n + self._head = self._head + inc + if (inc > 0 and self._head > self._tail) or (inc < 0 and self._head < self._tail) then + self._head = self._tail + end + return self +end + +--- Skips `n` values backwards from the end of a |list-iterator| pipeline. +--- +--- Example: +--- +--- ```lua +--- local it = vim.iter({ 1, 2, 3, 4, 5 }):skipback(2) +--- it:next() +--- -- 1 +--- it:nextback() +--- -- 3 +--- ``` +--- +---@param n number Number of values to skip. +---@return Iter +function Iter.skipback(self, n) -- luacheck: no unused args + error('skipback() requires a list-like table') + return self +end + +---@private +function ListIter.skipback(self, n) + local inc = self._head < self._tail and n or -n + self._tail = self._tail - inc + if (inc > 0 and self._head > self._tail) or (inc < 0 and self._head < self._tail) then + self._head = self._tail + end + return self +end + +--- Gets the nth value of an iterator (and advances to it). +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter({ 3, 6, 9, 12 }) +--- it:nth(2) +--- -- 6 +--- it:nth(2) +--- -- 12 +--- +--- ``` +--- +---@param n number The index of the value to return. +---@return any +function Iter.nth(self, n) + if n > 0 then + return self:skip(n - 1):next() + end +end + +--- Gets the nth value from the end of a |list-iterator| (and advances to it). +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter({ 3, 6, 9, 12 }) +--- it:nthback(2) +--- -- 9 +--- it:nthback(2) +--- -- 3 +--- +--- ``` +--- +---@param n number The index of the value to return. +---@return any +function Iter.nthback(self, n) + if n > 0 then + return self:skipback(n - 1):nextback() + end +end + +--- Sets the start and end of a |list-iterator| pipeline. +--- +--- Equivalent to `:skip(first - 1):skipback(len - last + 1)`. +--- +---@param first number +---@param last number +---@return Iter +function Iter.slice(self, first, last) -- luacheck: no unused args + error('slice() requires a list-like table') + return self +end + +---@private +function ListIter.slice(self, first, last) + return self:skip(math.max(0, first - 1)):skipback(math.max(0, self._tail - last - 1)) +end + +--- Returns true if any of the items in the iterator match the given predicate. +--- +---@param pred function(...):bool Predicate function. Takes all values returned from the previous +--- stage in the pipeline as arguments and returns true if the +--- predicate matches. +function Iter.any(self, pred) + local any = false + + --- Use a closure to handle var args returned from iterator + local function fn(...) + if select(1, ...) ~= nil then + if pred(...) then + any = true + else + return true + end + end + end + + while fn(self:next()) do + end + return any +end + +--- Returns true if all items in the iterator match the given predicate. +--- +---@param pred function(...):bool Predicate function. Takes all values returned from the previous +--- stage in the pipeline as arguments and returns true if the +--- predicate matches. +function Iter.all(self, pred) + local all = true + + local function fn(...) + if select(1, ...) ~= nil then + if not pred(...) then + all = false + else + return true + end + end + end + + while fn(self:next()) do + end + return all +end + +--- Drains the iterator and returns the last item. +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter(vim.gsplit('abcdefg', '')) +--- it:last() +--- -- 'g' +--- +--- local it = vim.iter({ 3, 6, 9, 12, 15 }) +--- it:last() +--- -- 15 +--- +--- ``` +--- +---@return any +function Iter.last(self) + local last = self:next() + local cur = self:next() + while cur do + last = cur + cur = self:next() + end + return last +end + +---@private +function ListIter.last(self) + local inc = self._head < self._tail and 1 or -1 + local v = self._table[self._tail - inc] + self._head = self._tail + return v +end + +--- Yields the item index (count) and value for each item of an iterator pipeline. +--- +--- For list tables, this is more efficient: +--- +--- ```lua +--- vim.iter(ipairs(t)) +--- ``` +--- +--- instead of: +--- +--- ```lua +--- vim.iter(t):enumerate() +--- ``` +--- +--- Example: +--- +--- ```lua +--- +--- local it = vim.iter(vim.gsplit('abc', '')):enumerate() +--- it:next() +--- -- 1 'a' +--- it:next() +--- -- 2 'b' +--- it:next() +--- -- 3 'c' +--- +--- ``` +--- +---@return Iter +function Iter.enumerate(self) + local i = 0 + return self:map(function(...) + i = i + 1 + return i, ... + end) +end + +---@private +function ListIter.enumerate(self) + local inc = self._head < self._tail and 1 or -1 + for i = self._head, self._tail - inc, inc do + local v = self._table[i] + self._table[i] = pack(i, v) + end + return self +end + +--- Creates a new Iter object from a table or other |iterable|. +--- +---@param src table|function Table or iterator to drain values from +---@return Iter +---@private +function Iter.new(src, ...) + local it = {} + if type(src) == 'table' then + local mt = getmetatable(src) + if mt and type(mt.__call) == 'function' then + ---@private + function it.next() + return src() + end + + setmetatable(it, Iter) + return it + end + + local t = {} + + -- O(n): scan the source table to decide if it is a list (consecutive integer indices 1…n). + local count = 0 + for _ in pairs(src) do + count = count + 1 + local v = src[count] + if v == nil then + return Iter.new(pairs(src)) + end + t[count] = v + end + return ListIter.new(t) + end + + if type(src) == 'function' then + local s, var = ... + + --- Use a closure to handle var args returned from iterator + local function fn(...) + -- Per the Lua 5.1 reference manual, an iterator is complete when the first returned value is + -- nil (even if there are other, non-nil return values). See |for-in|. + if select(1, ...) ~= nil then + var = select(1, ...) + return ... + end + end + + ---@private + function it.next() + return fn(src(s, var)) + end + + setmetatable(it, Iter) + else + error('src must be a table or function') + end + return it +end + +--- Create a new ListIter +--- +---@param t table List-like table. Caller guarantees that this table is a valid list. +---@return Iter +---@private +function ListIter.new(t) + local it = {} + it._table = t + it._head = 1 + it._tail = #t + 1 + setmetatable(it, ListIter) + return it +end + +--- Collects an |iterable| into a table. +--- +--- ```lua +--- -- Equivalent to: +--- vim.iter(f):totable() +--- ``` +--- +---@param f function Iterator function +---@return table +function M.totable(f, ...) + return Iter.new(f, ...):totable() +end + +--- Filters a table or other |iterable|. +--- +--- ```lua +--- -- Equivalent to: +--- vim.iter(src):filter(f):totable() +--- ``` +--- +---@see |Iter:filter()| +--- +---@param f function(...):bool Filter function. Accepts the current iterator or table values as +--- arguments and returns true if those values should be kept in the +--- final table +---@param src table|function Table or iterator function to filter +---@return table +function M.filter(f, src, ...) + return Iter.new(src, ...):filter(f):totable() +end + +--- Maps a table or other |iterable|. +--- +--- ```lua +--- -- Equivalent to: +--- vim.iter(src):map(f):totable() +--- ``` +--- +---@see |Iter:map()| +--- +---@param f function(...):?any Map function. Accepts the current iterator or table values as +--- arguments and returns one or more new values. Nil values are removed +--- from the final table. +---@param src table|function Table or iterator function to filter +---@return table +function M.map(f, src, ...) + return Iter.new(src, ...):map(f):totable() +end + +---@type IterMod +return setmetatable(M, { + __call = function(_, ...) + return Iter.new(...) + end, +}) diff --git a/runtime/lua/vim/keymap.lua b/runtime/lua/vim/keymap.lua index ef1c66ea20..bdea95f9ab 100644 --- a/runtime/lua/vim/keymap.lua +++ b/runtime/lua/vim/keymap.lua @@ -1,53 +1,41 @@ local keymap = {} ---- Add a new |mapping|. +--- Adds a new |mapping|. --- Examples: ---- <pre>lua ---- -- Can add mapping to Lua functions ---- vim.keymap.set('n', 'lhs', function() print("real lua function") end) --- ---- -- Can use it to map multiple modes ---- vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true }) +--- ```lua +--- -- Map to a Lua function: +--- vim.keymap.set('n', 'lhs', function() print("real lua function") end) +--- -- Map to multiple modes: +--- vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer = true }) +--- -- Buffer-local mapping: +--- vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 }) +--- -- Expr mapping: +--- vim.keymap.set('i', '<Tab>', function() +--- return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>" +--- end, { expr = true }) +--- -- <Plug> mapping: +--- vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)') +--- ``` --- ---- -- Can add mapping for specific buffer ---- vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 }) ---- ---- -- Expr mappings ---- vim.keymap.set('i', '<Tab>', function() ---- return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>" ---- end, { expr = true }) ---- -- <Plug> mappings ---- vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)') ---- </pre> ---- ---- Note that in a mapping like: ---- <pre>lua ---- vim.keymap.set('n', 'asdf', require('jkl').my_fun) ---- </pre> ---- ---- the ``require('jkl')`` gets evaluated during this call in order to access the function. ---- If you want to avoid this cost at startup you can wrap it in a function, for example: ---- <pre>lua ---- vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end) ---- </pre> ---- ----@param mode string|table Same mode short names as |nvim_set_keymap()|. +---@param mode string|table Mode short-name, see |nvim_set_keymap()|. --- Can also be list of modes to create mapping on multiple modes. ---@param lhs string Left-hand side |{lhs}| of the mapping. ----@param rhs string|function Right-hand side |{rhs}| of the mapping. Can also be a Lua function. --- ----@param opts table|nil A table of |:map-arguments|. ---- + Accepts options accepted by the {opts} parameter in |nvim_set_keymap()|, ---- with the following notable differences: ---- - replace_keycodes: Defaults to `true` if "expr" is `true`. ---- - noremap: Always overridden with the inverse of "remap" (see below). ---- + In addition to those options, the table accepts the following keys: ---- - buffer: (number or boolean) Add a mapping to the given buffer. ---- When `0` or `true`, use the current buffer. ---- - remap: (boolean) Make the mapping recursive. ---- This is the inverse of the "noremap" option from |nvim_set_keymap()|. +---@param rhs string|function Right-hand side |{rhs}| of the mapping, can be a Lua function. +--- +---@param opts table|nil Table of |:map-arguments|. +--- - Same as |nvim_set_keymap()| {opts}, except: +--- - "replace_keycodes" defaults to `true` if "expr" is `true`. +--- - "noremap": inverse of "remap" (see below). +--- - Also accepts: +--- - "buffer": (integer|boolean) Creates buffer-local mapping, `0` or `true` +--- for current buffer. +--- - "remap": (boolean) Make the mapping recursive. Inverse of "noremap". --- Defaults to `false`. ---@see |nvim_set_keymap()| +---@see |maparg()| +---@see |mapcheck()| +---@see |mapset()| function keymap.set(mode, lhs, rhs, opts) vim.validate({ mode = { mode, { 's', 't' } }, @@ -56,7 +44,9 @@ function keymap.set(mode, lhs, rhs, opts) opts = { opts, 't', true }, }) - opts = vim.deepcopy(opts) or {} + opts = vim.deepcopy(opts or {}) + + ---@cast mode string[] mode = type(mode) == 'string' and { mode } or mode if opts.expr and opts.replace_keycodes ~= false then @@ -69,7 +59,7 @@ function keymap.set(mode, lhs, rhs, opts) else -- remaps behavior is opposite of noremap option. opts.noremap = not opts.remap - opts.remap = nil + opts.remap = nil ---@type boolean? end if type(rhs) == 'function' then @@ -78,8 +68,8 @@ function keymap.set(mode, lhs, rhs, opts) end if opts.buffer then - local bufnr = opts.buffer == true and 0 or opts.buffer - opts.buffer = nil + local bufnr = opts.buffer == true and 0 or opts.buffer --[[@as integer]] + opts.buffer = nil ---@type integer? for _, m in ipairs(mode) do vim.api.nvim_buf_set_keymap(bufnr, m, lhs, rhs, opts) end @@ -93,14 +83,16 @@ end --- Remove an existing mapping. --- Examples: ---- <pre>lua ---- vim.keymap.del('n', 'lhs') --- ---- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) ---- </pre> +--- ```lua +--- vim.keymap.del('n', 'lhs') +--- +--- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) +--- ``` +--- ---@param opts table|nil A table of optional arguments: ---- - buffer: (number or boolean) Remove a mapping from the given buffer. ---- When "true" or 0, use the current buffer. +--- - "buffer": (integer|boolean) Remove a mapping from the given buffer. +--- When `0` or `true`, use the current buffer. ---@see |vim.keymap.set()| --- function keymap.del(modes, lhs, opts) @@ -113,9 +105,9 @@ function keymap.del(modes, lhs, opts) opts = opts or {} modes = type(modes) == 'string' and { modes } or modes - local buffer = false + local buffer = false ---@type false|integer if opts.buffer ~= nil then - buffer = opts.buffer == true and 0 or opts.buffer + buffer = opts.buffer == true and 0 or opts.buffer --[[@as integer]] end if buffer == false then diff --git a/runtime/lua/vim/loader.lua b/runtime/lua/vim/loader.lua new file mode 100644 index 0000000000..ee01111337 --- /dev/null +++ b/runtime/lua/vim/loader.lua @@ -0,0 +1,536 @@ +local uv = vim.uv +local uri_encode = vim.uri_encode + +--- @type (fun(modename: string): fun()|string)[] +local loaders = package.loaders + +local M = {} + +---@alias CacheHash {mtime: {nsec: integer, sec: integer}, size: integer, type?: uv.aliases.fs_stat_types} +---@alias CacheEntry {hash:CacheHash, chunk:string} + +---@class ModuleFindOpts +---@field all? boolean Search for all matches (defaults to `false`) +---@field rtp? boolean Search for modname in the runtime path (defaults to `true`) +---@field patterns? string[] Patterns to use (defaults to `{"/init.lua", ".lua"}`) +---@field paths? string[] Extra paths to search for modname + +---@class ModuleInfo +---@field modpath string Path of the module +---@field modname string Name of the module +---@field stat? uv.uv_fs_t File stat of the module path + +---@alias LoaderStats table<string, {total:number, time:number, [string]:number?}?> + +---@nodoc +M.path = vim.fn.stdpath('cache') .. '/luac' + +---@nodoc +M.enabled = false + +---@class Loader +---@field _rtp string[] +---@field _rtp_pure string[] +---@field _rtp_key string +---@field _hashes? table<string, CacheHash> +local Loader = { + VERSION = 4, + ---@type table<string, table<string,ModuleInfo>> + _indexed = {}, + ---@type table<string, string[]> + _topmods = {}, + _loadfile = loadfile, + ---@type LoaderStats + _stats = { + find = { total = 0, time = 0, not_found = 0 }, + }, +} + +--- @param path string +--- @return CacheHash +--- @private +function Loader.get_hash(path) + if not Loader._hashes then + return uv.fs_stat(path) --[[@as CacheHash]] + end + + if not Loader._hashes[path] then + -- Note we must never save a stat for a non-existent path. + -- For non-existent paths fs_stat() will return nil. + Loader._hashes[path] = uv.fs_stat(path) + end + return Loader._hashes[path] +end + +local function normalize(path) + return vim.fs.normalize(path, { expand_env = false }) +end + +--- Gets the rtp excluding after directories. +--- The result is cached, and will be updated if the runtime path changes. +--- When called from a fast event, the cached value will be returned. +--- @return string[] rtp, boolean updated +---@private +function Loader.get_rtp() + if vim.in_fast_event() then + return (Loader._rtp or {}), false + end + local updated = false + local key = vim.go.rtp + if key ~= Loader._rtp_key then + Loader._rtp = {} + for _, path in ipairs(vim.api.nvim_get_runtime_file('', true)) do + path = normalize(path) + -- skip after directories + if + path:sub(-6, -1) ~= '/after' + and not (Loader._indexed[path] and vim.tbl_isempty(Loader._indexed[path])) + then + Loader._rtp[#Loader._rtp + 1] = path + end + end + updated = true + Loader._rtp_key = key + end + return Loader._rtp, updated +end + +--- Returns the cache file name +---@param name string can be a module name, or a file name +---@return string file_name +---@private +function Loader.cache_file(name) + local ret = ('%s/%s'):format(M.path, uri_encode(name, 'rfc2396')) + return ret:sub(-4) == '.lua' and (ret .. 'c') or (ret .. '.luac') +end + +--- Saves the cache entry for a given module or file +---@param name string module name or filename +---@param entry CacheEntry +---@private +function Loader.write(name, entry) + local cname = Loader.cache_file(name) + local f = assert(uv.fs_open(cname, 'w', 438)) + local header = { + Loader.VERSION, + entry.hash.size, + entry.hash.mtime.sec, + entry.hash.mtime.nsec, + } + uv.fs_write(f, table.concat(header, ',') .. '\0') + uv.fs_write(f, entry.chunk) + uv.fs_close(f) +end + +--- @param path string +--- @param mode integer +--- @return string? data +local function readfile(path, mode) + local f = uv.fs_open(path, 'r', mode) + if f then + local hash = assert(uv.fs_fstat(f)) + local data = uv.fs_read(f, hash.size, 0) --[[@as string?]] + uv.fs_close(f) + return data + end +end + +--- Loads the cache entry for a given module or file +---@param name string module name or filename +---@return CacheEntry? +---@private +function Loader.read(name) + local cname = Loader.cache_file(name) + local data = readfile(cname, 438) + if data then + local zero = data:find('\0', 1, true) + if not zero then + return + end + + ---@type integer[]|{[0]:integer} + local header = vim.split(data:sub(1, zero - 1), ',') + if tonumber(header[1]) ~= Loader.VERSION then + return + end + return { + hash = { + size = tonumber(header[2]), + mtime = { sec = tonumber(header[3]), nsec = tonumber(header[4]) }, + }, + chunk = data:sub(zero + 1), + } + end +end + +--- The `package.loaders` loader for Lua files using the cache. +---@param modname string module name +---@return string|function +---@private +function Loader.loader(modname) + Loader._hashes = {} + local ret = M.find(modname)[1] + if ret then + -- Make sure to call the global loadfile so we respect any augmentations done elsewhere. + -- E.g. profiling + local chunk, err = loadfile(ret.modpath) + Loader._hashes = nil + return chunk or error(err) + end + Loader._hashes = nil + return '\ncache_loader: module ' .. modname .. ' not found' +end + +--- The `package.loaders` loader for libs +---@param modname string module name +---@return string|function +---@private +function Loader.loader_lib(modname) + local sysname = uv.os_uname().sysname:lower() or '' + local is_win = sysname:find('win', 1, true) and not sysname:find('darwin', 1, true) + local ret = M.find(modname, { patterns = is_win and { '.dll' } or { '.so' } })[1] + ---@type function?, string? + if ret then + -- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is + -- a) strip prefix up to and including the first dash, if any + -- b) replace all dots by underscores + -- c) prepend "luaopen_" + -- So "foo-bar.baz" should result in "luaopen_bar_baz" + local dash = modname:find('-', 1, true) + local funcname = dash and modname:sub(dash + 1) or modname + local chunk, err = package.loadlib(ret.modpath, 'luaopen_' .. funcname:gsub('%.', '_')) + return chunk or error(err) + end + return '\ncache_loader_lib: module ' .. modname .. ' not found' +end + +--- `loadfile` using the cache +--- Note this has the mode and env arguments which is supported by LuaJIT and is 5.1 compatible. +---@param filename? string +---@param mode? "b"|"t"|"bt" +---@param env? table +---@return function?, string? error_message +---@private +-- luacheck: ignore 312 +function Loader.loadfile(filename, mode, env) + -- ignore mode, since we byte-compile the Lua source files + mode = nil + return Loader.load(normalize(filename), { mode = mode, env = env }) +end + +--- Checks whether two cache hashes are the same based on: +--- * file size +--- * mtime in seconds +--- * mtime in nanoseconds +---@param h1 CacheHash +---@param h2 CacheHash +---@private +function Loader.eq(h1, h2) + return h1 + and h2 + and h1.size == h2.size + and h1.mtime.sec == h2.mtime.sec + and h1.mtime.nsec == h2.mtime.nsec +end + +--- Loads the given module path using the cache +---@param modpath string +---@param opts? {mode?: "b"|"t"|"bt", env?:table} (table|nil) Options for loading the module: +--- - mode: (string) the mode to load the module with. "b"|"t"|"bt" (defaults to `nil`) +--- - env: (table) the environment to load the module in. (defaults to `nil`) +---@see |luaL_loadfile()| +---@return function?, string? error_message +---@private +function Loader.load(modpath, opts) + opts = opts or {} + local hash = Loader.get_hash(modpath) + ---@type function?, string? + local chunk, err + + if not hash then + -- trigger correct error + return Loader._loadfile(modpath, opts.mode, opts.env) + end + + local entry = Loader.read(modpath) + if entry and Loader.eq(entry.hash, hash) then + -- found in cache and up to date + chunk, err = load(entry.chunk --[[@as string]], '@' .. modpath, opts.mode, opts.env) + if not (err and err:find('cannot load incompatible bytecode', 1, true)) then + return chunk, err + end + end + entry = { hash = hash, modpath = modpath } + + chunk, err = Loader._loadfile(modpath, opts.mode, opts.env) + if chunk then + entry.chunk = string.dump(chunk) + Loader.write(modpath, entry) + end + return chunk, err +end + +--- Finds Lua modules for the given module name. +---@param modname string Module name, or `"*"` to find the top-level modules instead +---@param opts? ModuleFindOpts (table|nil) Options for finding a module: +--- - rtp: (boolean) Search for modname in the runtime path (defaults to `true`) +--- - paths: (string[]) Extra paths to search for modname (defaults to `{}`) +--- - patterns: (string[]) List of patterns to use when searching for modules. +--- A pattern is a string added to the basename of the Lua module being searched. +--- (defaults to `{"/init.lua", ".lua"}`) +--- - all: (boolean) Return all matches instead of just the first one (defaults to `false`) +---@return ModuleInfo[] (list) A list of results with the following properties: +--- - modpath: (string) the path to the module +--- - modname: (string) the name of the module +--- - stat: (table|nil) the fs_stat of the module path. Won't be returned for `modname="*"` +function M.find(modname, opts) + opts = opts or {} + + modname = modname:gsub('/', '.') + local basename = modname:gsub('%.', '/') + local idx = modname:find('.', 1, true) + + -- HACK: fix incorrect require statements. Really not a fan of keeping this, + -- but apparently the regular Lua loader also allows this + if idx == 1 then + modname = modname:gsub('^%.+', '') + basename = modname:gsub('%.', '/') + idx = modname:find('.', 1, true) + end + + -- get the top-level module name + local topmod = idx and modname:sub(1, idx - 1) or modname + + -- OPTIM: search for a directory first when topmod == modname + local patterns = opts.patterns + or (topmod == modname and { '/init.lua', '.lua' } or { '.lua', '/init.lua' }) + for p, pattern in ipairs(patterns) do + patterns[p] = '/lua/' .. basename .. pattern + end + + ---@type ModuleInfo[] + local results = {} + + -- Only continue if we haven't found anything yet or we want to find all + local function continue() + return #results == 0 or opts.all + end + + -- Checks if the given paths contain the top-level module. + -- If so, it tries to find the module path for the given module name. + ---@param paths string[] + local function _find(paths) + for _, path in ipairs(paths) do + if topmod == '*' then + for _, r in pairs(Loader.lsmod(path)) do + results[#results + 1] = r + if not continue() then + return + end + end + elseif Loader.lsmod(path)[topmod] then + for _, pattern in ipairs(patterns) do + local modpath = path .. pattern + Loader._stats.find.stat = (Loader._stats.find.stat or 0) + 1 + local hash = Loader.get_hash(modpath) + if hash then + results[#results + 1] = { modpath = modpath, stat = hash, modname = modname } + if not continue() then + return + end + end + end + end + end + end + + -- always check the rtp first + if opts.rtp ~= false then + _find(Loader._rtp or {}) + if continue() then + local rtp, updated = Loader.get_rtp() + if updated then + _find(rtp) + end + end + end + + -- check any additional paths + if continue() and opts.paths then + _find(opts.paths) + end + + if #results == 0 then + -- module not found + Loader._stats.find.not_found = Loader._stats.find.not_found + 1 + end + + return results +end + +--- Resets the cache for the path, or all the paths +--- if path is nil. +---@param path string? path to reset +function M.reset(path) + if path then + Loader._indexed[normalize(path)] = nil + else + Loader._indexed = {} + end + + -- Path could be a directory so just clear all the hashes. + if Loader._hashes then + Loader._hashes = {} + end +end + +--- Enables the experimental Lua module loader: +--- * overrides loadfile +--- * adds the Lua loader using the byte-compilation cache +--- * adds the libs loader +--- * removes the default Nvim loader +function M.enable() + if M.enabled then + return + end + M.enabled = true + vim.fn.mkdir(vim.fn.fnamemodify(M.path, ':p'), 'p') + _G.loadfile = Loader.loadfile + -- add Lua loader + table.insert(loaders, 2, Loader.loader) + -- add libs loader + table.insert(loaders, 3, Loader.loader_lib) + -- remove Nvim loader + for l, loader in ipairs(loaders) do + if loader == vim._load_package then + table.remove(loaders, l) + break + end + end +end + +--- Disables the experimental Lua module loader: +--- * removes the loaders +--- * adds the default Nvim loader +function M.disable() + if not M.enabled then + return + end + M.enabled = false + _G.loadfile = Loader._loadfile + for l, loader in ipairs(loaders) do + if loader == Loader.loader or loader == Loader.loader_lib then + table.remove(loaders, l) + end + end + table.insert(loaders, 2, vim._load_package) +end + +--- Return the top-level \`/lua/*` modules for this path +---@param path string path to check for top-level Lua modules +---@private +function Loader.lsmod(path) + if not Loader._indexed[path] then + Loader._indexed[path] = {} + for name, t in vim.fs.dir(path .. '/lua') do + local modpath = path .. '/lua/' .. name + -- HACK: type is not always returned due to a bug in luv + t = t or Loader.get_hash(modpath).type + ---@type string + local topname + local ext = name:sub(-4) + if ext == '.lua' or ext == '.dll' then + topname = name:sub(1, -5) + elseif name:sub(-3) == '.so' then + topname = name:sub(1, -4) + elseif t == 'link' or t == 'directory' then + topname = name + end + if topname then + Loader._indexed[path][topname] = { modpath = modpath, modname = topname } + Loader._topmods[topname] = Loader._topmods[topname] or {} + if not vim.list_contains(Loader._topmods[topname], path) then + table.insert(Loader._topmods[topname], path) + end + end + end + end + return Loader._indexed[path] +end + +--- Tracks the time spent in a function +--- @generic F: function +--- @param f F +--- @return F +--- @private +function Loader.track(stat, f) + return function(...) + local start = vim.uv.hrtime() + local r = { f(...) } + Loader._stats[stat] = Loader._stats[stat] or { total = 0, time = 0 } + Loader._stats[stat].total = Loader._stats[stat].total + 1 + Loader._stats[stat].time = Loader._stats[stat].time + uv.hrtime() - start + return unpack(r, 1, table.maxn(r)) + end +end + +---@class ProfileOpts +---@field loaders? boolean Add profiling to the loaders + +--- Debug function that wraps all loaders and tracks stats +---@private +---@param opts ProfileOpts? +function M._profile(opts) + Loader.get_rtp = Loader.track('get_rtp', Loader.get_rtp) + Loader.read = Loader.track('read', Loader.read) + Loader.loader = Loader.track('loader', Loader.loader) + Loader.loader_lib = Loader.track('loader_lib', Loader.loader_lib) + Loader.loadfile = Loader.track('loadfile', Loader.loadfile) + Loader.load = Loader.track('load', Loader.load) + M.find = Loader.track('find', M.find) + Loader.lsmod = Loader.track('lsmod', Loader.lsmod) + + if opts and opts.loaders then + for l, loader in pairs(loaders) do + local loc = debug.getinfo(loader, 'Sn').source:sub(2) + loaders[l] = Loader.track('loader ' .. l .. ': ' .. loc, loader) + end + end +end + +--- Prints all cache stats +---@param opts? {print?:boolean} +---@return LoaderStats +---@private +function M._inspect(opts) + if opts and opts.print then + local function ms(nsec) + return math.floor(nsec / 1e6 * 1000 + 0.5) / 1000 .. 'ms' + end + local chunks = {} ---@type string[][] + ---@type string[] + local stats = vim.tbl_keys(Loader._stats) + table.sort(stats) + for _, stat in ipairs(stats) do + vim.list_extend(chunks, { + { '\n' .. stat .. '\n', 'Title' }, + { '* total: ' }, + { tostring(Loader._stats[stat].total) .. '\n', 'Number' }, + { '* time: ' }, + { ms(Loader._stats[stat].time) .. '\n', 'Bold' }, + { '* avg time: ' }, + { ms(Loader._stats[stat].time / Loader._stats[stat].total) .. '\n', 'Bold' }, + }) + for k, v in pairs(Loader._stats[stat]) do + if not vim.list_contains({ 'time', 'total' }, k) then + chunks[#chunks + 1] = { '* ' .. k .. ':' .. string.rep(' ', 9 - #k) } + chunks[#chunks + 1] = { tostring(v) .. '\n', 'Number' } + end + end + end + vim.api.nvim_echo(chunks, true, {}) + end + return Loader._stats +end + +return M diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index c5392ac154..261a3aa5de 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -1,19 +1,17 @@ +---@diagnostic disable: invisible local default_handlers = require('vim.lsp.handlers') local log = require('vim.lsp.log') local lsp_rpc = require('vim.lsp.rpc') local protocol = require('vim.lsp.protocol') +local ms = protocol.Methods local util = require('vim.lsp.util') local sync = require('vim.lsp.sync') local semantic_tokens = require('vim.lsp.semantic_tokens') local api = vim.api -local nvim_err_writeln, nvim_buf_get_lines, nvim_command, nvim_buf_get_option, nvim_exec_autocmds = - api.nvim_err_writeln, - api.nvim_buf_get_lines, - api.nvim_command, - api.nvim_buf_get_option, - api.nvim_exec_autocmds -local uv = vim.loop +local nvim_err_writeln, nvim_buf_get_lines, nvim_command, nvim_exec_autocmds = + api.nvim_err_writeln, api.nvim_buf_get_lines, api.nvim_command, api.nvim_exec_autocmds +local uv = vim.uv local tbl_isempty, tbl_extend = vim.tbl_isempty, vim.tbl_extend local validate = vim.validate local if_nil = vim.F.if_nil @@ -26,6 +24,7 @@ local lsp = { buf = require('vim.lsp.buf'), diagnostic = require('vim.lsp.diagnostic'), codelens = require('vim.lsp.codelens'), + inlay_hint = require('vim.lsp.inlay_hint'), semantic_tokens = semantic_tokens, util = util, @@ -38,47 +37,50 @@ local lsp = { -- maps request name to the required server_capability in the client. lsp._request_name_to_capability = { - ['textDocument/hover'] = { 'hoverProvider' }, - ['textDocument/signatureHelp'] = { 'signatureHelpProvider' }, - ['textDocument/definition'] = { 'definitionProvider' }, - ['textDocument/implementation'] = { 'implementationProvider' }, - ['textDocument/declaration'] = { 'declarationProvider' }, - ['textDocument/typeDefinition'] = { 'typeDefinitionProvider' }, - ['textDocument/documentSymbol'] = { 'documentSymbolProvider' }, - ['textDocument/prepareCallHierarchy'] = { 'callHierarchyProvider' }, - ['textDocument/rename'] = { 'renameProvider' }, - ['textDocument/prepareRename'] = { 'renameProvider', 'prepareProvider' }, - ['textDocument/codeAction'] = { 'codeActionProvider' }, - ['textDocument/codeLens'] = { 'codeLensProvider' }, - ['codeLens/resolve'] = { 'codeLensProvider', 'resolveProvider' }, - ['workspace/executeCommand'] = { 'executeCommandProvider' }, - ['workspace/symbol'] = { 'workspaceSymbolProvider' }, - ['textDocument/references'] = { 'referencesProvider' }, - ['textDocument/rangeFormatting'] = { 'documentRangeFormattingProvider' }, - ['textDocument/formatting'] = { 'documentFormattingProvider' }, - ['textDocument/completion'] = { 'completionProvider' }, - ['textDocument/documentHighlight'] = { 'documentHighlightProvider' }, - ['textDocument/semanticTokens/full'] = { 'semanticTokensProvider' }, - ['textDocument/semanticTokens/full/delta'] = { 'semanticTokensProvider' }, + [ms.textDocument_hover] = { 'hoverProvider' }, + [ms.textDocument_signatureHelp] = { 'signatureHelpProvider' }, + [ms.textDocument_definition] = { 'definitionProvider' }, + [ms.textDocument_implementation] = { 'implementationProvider' }, + [ms.textDocument_declaration] = { 'declarationProvider' }, + [ms.textDocument_typeDefinition] = { 'typeDefinitionProvider' }, + [ms.textDocument_documentSymbol] = { 'documentSymbolProvider' }, + [ms.textDocument_prepareCallHierarchy] = { 'callHierarchyProvider' }, + [ms.callHierarchy_incomingCalls] = { 'callHierarchyProvider' }, + [ms.callHierarchy_outgoingCalls] = { 'callHierarchyProvider' }, + [ms.textDocument_rename] = { 'renameProvider' }, + [ms.textDocument_prepareRename] = { 'renameProvider', 'prepareProvider' }, + [ms.textDocument_codeAction] = { 'codeActionProvider' }, + [ms.textDocument_codeLens] = { 'codeLensProvider' }, + [ms.codeLens_resolve] = { 'codeLensProvider', 'resolveProvider' }, + [ms.codeAction_resolve] = { 'codeActionProvider', 'resolveProvider' }, + [ms.workspace_executeCommand] = { 'executeCommandProvider' }, + [ms.workspace_symbol] = { 'workspaceSymbolProvider' }, + [ms.textDocument_references] = { 'referencesProvider' }, + [ms.textDocument_rangeFormatting] = { 'documentRangeFormattingProvider' }, + [ms.textDocument_formatting] = { 'documentFormattingProvider' }, + [ms.textDocument_completion] = { 'completionProvider' }, + [ms.textDocument_documentHighlight] = { 'documentHighlightProvider' }, + [ms.textDocument_semanticTokens_full] = { 'semanticTokensProvider' }, + [ms.textDocument_semanticTokens_full_delta] = { 'semanticTokensProvider' }, + [ms.textDocument_inlayHint] = { 'inlayHintProvider' }, + [ms.textDocument_diagnostic] = { 'diagnosticProvider' }, + [ms.inlayHint_resolve] = { 'inlayHintProvider', 'resolveProvider' }, } -- TODO improve handling of scratch buffers with LSP attached. ----@private --- Concatenates and writes a list of strings to the Vim error buffer. --- ----@param {...} table[] List to write to the buffer +---@param ... string List to write to the buffer local function err_message(...) nvim_err_writeln(table.concat(vim.tbl_flatten({ ... }))) nvim_command('redraw') end ----@private --- Returns the buffer number for the given {bufnr}. --- ----@param bufnr (number|nil) Buffer number to resolve. Defaults to the current ----buffer if not given. ----@returns bufnr (number) Number of requested buffer +---@param bufnr (integer|nil) Buffer number to resolve. Defaults to current buffer +---@return integer bufnr local function resolve_bufnr(bufnr) validate({ bufnr = { bufnr, 'n', true } }) if bufnr == nil or bufnr == 0 then @@ -100,11 +102,10 @@ function lsp._unsupported_method(method) return msg end ----@private --- Checks whether a given path is a directory. --- ---@param filename (string) path to check ----@returns true if {filename} exists and is a directory, false otherwise +---@return boolean # true if {filename} exists and is a directory, false otherwise local function is_dir(filename) validate({ filename = { filename, 's' } }) local stat = uv.fs_stat(filename) @@ -131,28 +132,27 @@ local format_line_ending = { ['mac'] = '\r', } ----@private ---@param bufnr (number) ----@returns (string) +---@return string local function buf_get_line_ending(bufnr) - return format_line_ending[nvim_buf_get_option(bufnr, 'fileformat')] or '\n' + return format_line_ending[vim.bo[bufnr].fileformat] or '\n' end local client_index = 0 ----@private --- Returns a new, unused client id. --- ----@returns (number) client id +---@return integer client_id local function next_client_id() client_index = client_index + 1 return client_index end -- Tracks all clients created via lsp.start_client -local active_clients = {} -local all_buffer_active_clients = {} -local uninitialized_clients = {} +local active_clients = {} --- @type table<integer,lsp.Client> +local all_buffer_active_clients = {} --- @type table<integer,table<integer,true>> +local uninitialized_clients = {} --- @type table<integer,lsp.Client> ----@private +---@param bufnr? integer +---@param fn fun(client: lsp.Client, client_id: integer, bufnr: integer) local function for_each_buffer_client(bufnr, fn, restrict_client_ids) validate({ fn = { fn, 'f' }, @@ -165,9 +165,9 @@ local function for_each_buffer_client(bufnr, fn, restrict_client_ids) end if restrict_client_ids and #restrict_client_ids > 0 then - local filtered_client_ids = {} + local filtered_client_ids = {} --- @type table<integer,true> for client_id in pairs(client_ids) do - if vim.tbl_contains(restrict_client_ids, client_id) then + if vim.list_contains(restrict_client_ids, client_id) then filtered_client_ids[client_id] = true end end @@ -182,22 +182,24 @@ local function for_each_buffer_client(bufnr, fn, restrict_client_ids) end end --- Error codes to be used with `on_error` from |vim.lsp.start_client|. --- Can be used to look up the string from a the number or the number --- from the string. +--- Error codes to be used with `on_error` from |vim.lsp.start_client|. +--- Can be used to look up the string from a the number or the number +--- from the string. +--- @nodoc lsp.client_errors = tbl_extend( 'error', lsp_rpc.client_errors, vim.tbl_add_reverse_lookup({ - ON_INIT_CALLBACK_ERROR = table.maxn(lsp_rpc.client_errors) + 1, + BEFORE_INIT_CALLBACK_ERROR = table.maxn(lsp_rpc.client_errors) + 1, + ON_INIT_CALLBACK_ERROR = table.maxn(lsp_rpc.client_errors) + 2, + ON_ATTACH_ERROR = table.maxn(lsp_rpc.client_errors) + 3, }) ) ----@private --- Normalizes {encoding} to valid LSP encoding names. --- ---@param encoding (string) Encoding to normalize ----@returns (string) normalized encoding name +---@return string # normalized encoding name local function validate_encoding(encoding) validate({ encoding = { encoding, 's' }, @@ -215,9 +217,8 @@ end --- Parses a command invocation into the command itself and its args. If there --- are no arguments, an empty table is returned as the second argument. --- ----@param input (List) ----@returns (string) the command ----@returns (list of strings) its arguments +---@param input string[] +---@return string command, string[] args #the command and arguments function lsp._cmd_parts(input) validate({ cmd = { @@ -241,12 +242,11 @@ function lsp._cmd_parts(input) return cmd, cmd_args end ----@private --- Augments a validator function with support for optional (nil) values. --- ----@param fn (fun(v)) The original validator function; should return a +---@param fn (fun(v): boolean) The original validator function; should return a ---bool. ----@returns (fun(v)) The augmented function. Also returns true if {v} is +---@return fun(v): boolean # The augmented function. Also returns true if {v} is ---`nil`. local function optional_validator(fn) return function(v) @@ -254,14 +254,12 @@ local function optional_validator(fn) end end ----@private --- Validates a client configuration as given to |vim.lsp.start_client()|. --- ----@param config (table) ----@returns (table) "Cleaned" config, containing only the command, its ----arguments, and a valid encoding. ---- ----@see |vim.lsp.start_client()| +---@param config (lsp.ClientConfig) +---@return (string|fun(dispatchers:table):table) Command +---@return string[] Arguments +---@return string Encoding. local function validate_client_config(config) validate({ config = { config, 't' }, @@ -292,48 +290,44 @@ local function validate_client_config(config) 'flags.debounce_text_changes must be a number with the debounce time in milliseconds' ) - local cmd, cmd_args - if type(config.cmd) == 'function' then - cmd = config.cmd + local cmd, cmd_args --- @type (string|fun(dispatchers:table):table), string[] + local config_cmd = config.cmd + if type(config_cmd) == 'function' then + cmd = config_cmd else - cmd, cmd_args = lsp._cmd_parts(config.cmd) + cmd, cmd_args = lsp._cmd_parts(config_cmd) end local offset_encoding = valid_encodings.UTF16 if config.offset_encoding then offset_encoding = validate_encoding(config.offset_encoding) end - return { - cmd = cmd, - cmd_args = cmd_args, - offset_encoding = offset_encoding, - } + return cmd, cmd_args, offset_encoding end ----@private --- Returns full text of buffer {bufnr} as a string. --- ---@param bufnr (number) Buffer handle, or 0 for current. ----@returns Buffer text as string. +---@return string # Buffer text as string. local function buf_get_full_text(bufnr) local line_ending = buf_get_line_ending(bufnr) local text = table.concat(nvim_buf_get_lines(bufnr, 0, -1, true), line_ending) - if nvim_buf_get_option(bufnr, 'eol') then + if vim.bo[bufnr].eol then text = text .. line_ending end return text end ----@private --- Memoizes a function. On first run, the function return value is saved and --- immediately returned on subsequent runs. If the function returns a multival, --- only the first returned value will be memoized and returned. The function will only be run once, --- even if it has side effects. --- ----@param fn (function) Function to run ----@returns (function) Memoized function +---@generic T: function +---@param fn (T) Function to run +---@return T local function once(fn) - local value + local value --- @type any local ran = false return function(...) if not ran then @@ -365,7 +359,7 @@ do --- smallest debounce interval is used and we don't group clients by different intervals. --- --- @class CTGroup - --- @field sync_kind number TextDocumentSyncKind, considers config.flags.allow_incremental_sync + --- @field sync_kind integer TextDocumentSyncKind, considers config.flags.allow_incremental_sync --- @field offset_encoding "utf-8"|"utf-16"|"utf-32" --- --- @class CTBufferState @@ -373,17 +367,16 @@ do --- @field lines string[] snapshot of buffer lines from last didChange --- @field lines_tmp string[] --- @field pending_changes table[] List of debounced changes in incremental sync mode - --- @field timer nil|userdata uv_timer + --- @field timer nil|uv.uv_timer_t uv_timer --- @field last_flush nil|number uv.hrtime of the last flush/didChange-notification --- @field needs_flush boolean true if buffer updates haven't been sent to clients/servers yet - --- @field refs number how many clients are using this group + --- @field refs integer how many clients are using this group --- --- @class CTGroupState - --- @field buffers table<number, CTBufferState> - --- @field debounce number debounce duration in ms - --- @field clients table<number, table> clients using this state. {client_id, client} + --- @field buffers table<integer, CTBufferState> + --- @field debounce integer debounce duration in ms + --- @field clients table<integer, table> clients using this state. {client_id, client} - ---@private ---@param group CTGroup ---@return string local function group_key(group) @@ -404,12 +397,10 @@ do end, }) - ---@private ---@return CTGroup local function get_group(client) local allow_inc_sync = if_nil(client.config.flags.allow_incremental_sync, true) - local change_capability = - vim.tbl_get(client.server_capabilities or {}, 'textDocumentSync', 'change') + local change_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change') local sync_kind = change_capability or protocol.TextDocumentSyncKind.None if not allow_inc_sync and change_capability == protocol.TextDocumentSyncKind.Incremental then sync_kind = protocol.TextDocumentSyncKind.Full @@ -420,7 +411,6 @@ do } end - ---@private ---@param state CTBufferState local function incremental_changes(state, encoding, bufnr, firstline, lastline, new_lastline) local prev_lines = state.lines @@ -544,15 +534,13 @@ do end end - ---@private - -- -- Adjust debounce time by taking time of last didChange notification into -- consideration. If the last didChange happened more than `debounce` time ago, -- debounce can be skipped and otherwise maybe reduced. -- -- This turns the debounce into a kind of client rate limiting -- - ---@param debounce number + ---@param debounce integer ---@param buf_state CTBufferState ---@return number local function next_debounce(debounce, buf_state) @@ -568,9 +556,8 @@ do return math.max(debounce - ms_since_last_flush, 0) end - ---@private - ---@param bufnr number - ---@param sync_kind number protocol.TextDocumentSyncKind + ---@param bufnr integer + ---@param sync_kind integer protocol.TextDocumentSyncKind ---@param state CTGroupState ---@param buf_state CTBufferState local function send_changes(bufnr, sync_kind, state, buf_state) @@ -599,7 +586,7 @@ do local uri = vim.uri_from_bufnr(bufnr) for _, client in pairs(state.clients) do if not client.is_stopped() and lsp.buf_is_attached(bufnr, client.id) then - client.notify('textDocument/didChange', { + client.notify(ms.textDocument_didChange, { textDocument = { uri = uri, version = util.buf_versions[bufnr], @@ -612,8 +599,8 @@ do ---@private function changetracking.send_changes(bufnr, firstline, lastline, new_lastline) - local groups = {} - for _, client in pairs(lsp.get_active_clients({ bufnr = bufnr })) do + local groups = {} ---@type table<string,CTGroup> + for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do local group = get_group(client) groups[group_key(group)] = group end @@ -648,7 +635,7 @@ do if debounce == 0 then send_changes(bufnr, group.sync_kind, state, buf_state) else - local timer = uv.new_timer() + local timer = assert(uv.new_timer(), 'Must be able to create timer') buf_state.timer = timer timer:start( debounce, @@ -695,10 +682,9 @@ do end end ----@private --- Default handler for the 'textDocument/didOpen' LSP notification. --- ----@param bufnr number Number of the buffer, or 0 for current +---@param bufnr integer Number of the buffer, or 0 for current ---@param client table Client object local function text_document_did_open_handler(bufnr, client) changetracking.init(client, bufnr) @@ -708,7 +694,7 @@ local function text_document_did_open_handler(bufnr, client) if not api.nvim_buf_is_loaded(bufnr) then return end - local filetype = nvim_buf_get_option(bufnr, 'filetype') + local filetype = vim.bo[bufnr].filetype local params = { textDocument = { @@ -718,7 +704,7 @@ local function text_document_did_open_handler(bufnr, client) text = buf_get_full_text(bufnr), }, } - client.notify('textDocument/didOpen', params) + client.notify(ms.textDocument_didOpen, params) util.buf_versions[bufnr] = params.textDocument.version -- Next chance we get, we should re-do the diagnostics @@ -735,7 +721,7 @@ end -- FIXME: DOC: Shouldn't need to use a dummy function -- --- LSP client object. You can get an active client object via ---- |vim.lsp.get_client_by_id()| or |vim.lsp.get_active_clients()|. +--- |vim.lsp.get_client_by_id()| or |vim.lsp.get_clients()|. --- --- - Methods: --- @@ -801,29 +787,39 @@ end --- to the server. Entries are key-value pairs with the key --- being the request ID while the value is a table with `type`, --- `bufnr`, and `method` key-value pairs. `type` is either "pending" ---- for an active request, or "cancel" for a cancel request. +--- for an active request, or "cancel" for a cancel request. It will +--- be "complete" ephemerally while executing |LspRequest| autocmds +--- when replies are received from the server. --- --- - {config} (table): copy of the table that was passed by the user --- to |vim.lsp.start_client()|. --- --- - {server_capabilities} (table): Response from the server sent on --- `initialize` describing the server's capabilities. +--- +--- - {progress} A ring buffer (|vim.ringbuf()|) containing progress messages +--- sent by the server. function lsp.client() error() end +--- @class lsp.StartOpts +--- @field reuse_client fun(client: lsp.Client, config: table): boolean +--- @field bufnr integer + --- Create a new LSP client and start a language server or reuses an already --- running client if one is found matching `name` and `root_dir`. --- Attaches the current buffer to the client. --- --- Example: ---- <pre>lua +--- +--- ```lua --- vim.lsp.start({ --- name = 'my-server-name', --- cmd = {'name-of-language-server-executable'}, --- root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]), --- }) ---- </pre> +--- ``` --- --- See |vim.lsp.start_client()| for all available options. The most important are: --- @@ -849,7 +845,7 @@ end --- `ftplugin/<filetype_name>.lua` (See |ftplugin-name|) --- ---@param config table Same configuration as documented in |vim.lsp.start_client()| ----@param opts nil|table Optional keyword arguments: +---@param opts (nil|lsp.StartOpts) Optional keyword arguments: --- - reuse_client (fun(client: client, config: table): boolean) --- Predicate used to decide if a client should be re-used. --- Used on all running clients. @@ -858,14 +854,13 @@ end --- - bufnr (number) --- Buffer handle to attach to if starting or re-using a --- client (0 for current). ----@return number|nil client_id +---@return integer|nil client_id function lsp.start(config, opts) opts = opts or {} local reuse_client = opts.reuse_client or function(client, conf) return client.config.root_dir == conf.root_dir and client.name == conf.name end - config.name = config.name if not config.name and type(config.cmd) == 'table' then config.name = config.cmd[1] and vim.fs.basename(config.cmd[1]) or nil end @@ -873,7 +868,7 @@ function lsp.start(config, opts) if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() end - for _, clients in ipairs({ uninitialized_clients, lsp.get_active_clients() }) do + for _, clients in ipairs({ uninitialized_clients, lsp.get_clients() }) do for _, client in pairs(clients) do if reuse_client(client, config) then lsp.buf_attach_client(bufnr, client.id) @@ -889,6 +884,109 @@ function lsp.start(config, opts) return client_id end +--- Consumes the latest progress messages from all clients and formats them as a string. +--- Empty if there are no clients or if no new messages +--- +---@return string +function lsp.status() + local percentage = nil + local messages = {} + for _, client in ipairs(vim.lsp.get_clients()) do + for progress in client.progress do + local value = progress.value + if type(value) == 'table' and value.kind then + local message = value.message and (value.title .. ': ' .. value.message) or value.title + messages[#messages + 1] = message + if value.percentage then + percentage = math.max(percentage or 0, value.percentage) + end + end + -- else: Doesn't look like work done progress and can be in any format + -- Just ignore it as there is no sensible way to display it + end + end + local message = table.concat(messages, ', ') + if percentage then + return string.format('%3d%%: %s', percentage, message) + end + return message +end + +-- Determines whether the given option can be set by `set_defaults`. +local function is_empty_or_default(bufnr, option) + if vim.bo[bufnr][option] == '' then + return true + end + + local info = vim.api.nvim_get_option_info2(option, { buf = bufnr }) + local scriptinfo = vim.tbl_filter(function(e) + return e.sid == info.last_set_sid + end, vim.fn.getscriptinfo()) + + if #scriptinfo ~= 1 then + return false + end + + return vim.startswith(scriptinfo[1].name, vim.fn.expand('$VIMRUNTIME')) +end + +---@private +---@param client lsp.Client +function lsp._set_defaults(client, bufnr) + if + client.supports_method(ms.textDocument_definition) and is_empty_or_default(bufnr, 'tagfunc') + then + vim.bo[bufnr].tagfunc = 'v:lua.vim.lsp.tagfunc' + end + if + client.supports_method(ms.textDocument_completion) and is_empty_or_default(bufnr, 'omnifunc') + then + vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc' + end + if + client.supports_method(ms.textDocument_rangeFormatting) + and is_empty_or_default(bufnr, 'formatprg') + and is_empty_or_default(bufnr, 'formatexpr') + then + vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr()' + end + api.nvim_buf_call(bufnr, function() + if + client.supports_method(ms.textDocument_hover) + and is_empty_or_default(bufnr, 'keywordprg') + and vim.fn.maparg('K', 'n', false, false) == '' + then + vim.keymap.set('n', 'K', vim.lsp.buf.hover, { buffer = bufnr }) + end + end) + if client.supports_method(ms.textDocument_diagnostic) then + lsp.diagnostic._enable(bufnr) + end +end + +--- @class lsp.ClientConfig +--- @field cmd (string[]|fun(dispatchers: table):table) +--- @field cmd_cwd string +--- @field cmd_env (table) +--- @field detached boolean +--- @field workspace_folders (table) +--- @field capabilities lsp.ClientCapabilities +--- @field handlers table<string,function> +--- @field settings table +--- @field commands table +--- @field init_options table +--- @field name string +--- @field get_language_id fun(bufnr: integer, filetype: string): string +--- @field offset_encoding string +--- @field on_error fun(code: integer) +--- @field before_init function +--- @field on_init function +--- @field on_exit fun(code: integer, signal: integer, client_id: integer) +--- @field on_attach fun(client: lsp.Client, bufnr: integer) +--- @field trace 'off'|'messages'|'verbose'|nil +--- @field flags table +--- @field root_dir string + -- FIXME: DOC: Currently all methods on the `vim.lsp.client` object are -- documented twice: Here, and on the methods themselves (e.g. -- `client.request()`). This is a workaround for the vimdoc generator script @@ -899,9 +997,9 @@ end --- --- Field `cmd` in {config} is required. --- ----@param config (table) Configuration for the server: ---- - cmd: (table|string|fun(dispatchers: table):table) command string or ---- list treated like |jobstart()|. The command must launch the language server +---@param config (lsp.ClientConfig) Configuration for the server: +--- - cmd: (string[]|fun(dispatchers: table):table) command a list of +--- strings treated like |jobstart()|. The command must launch the language server --- process. `cmd` can also be a function that creates an RPC client. --- The function receives a dispatchers table and must return a table with the --- functions `request`, `notify`, `is_closing` and `terminate` @@ -912,11 +1010,11 @@ end --- the `cmd` process. Not related to `root_dir`. --- --- - cmd_env: (table) Environment flags to pass to the LSP on ---- spawn. Can be specified using keys like a map or as a list with `k=v` ---- pairs or both. Non-string values are coerced to string. +--- spawn. Must be specified using a table. +--- Non-string values are coerced to string. --- Example: --- <pre> ---- { "PRODUCTION=true"; "TEST=123"; PORT = 8080; HOST = "0.0.0.0"; } +--- { PORT = 8080; HOST = "0.0.0.0"; } --- </pre> --- --- - detached: (boolean, default true) Daemonize the server process so that it runs in a @@ -929,11 +1027,10 @@ end --- the LSP spec. --- --- - capabilities: Map overriding the default capabilities defined by ---- |vim.lsp.protocol.make_client_capabilities()|, passed to the language +--- \|vim.lsp.protocol.make_client_capabilities()|, passed to the language --- server on initialization. Hint: use make_client_capabilities() and modify --- its result. ---- - Note: To send an empty dictionary use ---- `{[vim.type_idx]=vim.types.dictionary}`, else it will be encoded as an +--- - Note: To send an empty dictionary use |vim.empty_dict()|, else it will be encoded as an --- array. --- --- - handlers: Map of language server method names to |lsp-handler| @@ -977,7 +1074,7 @@ end --- `initialize_result.offsetEncoding` if `capabilities.offsetEncoding` was --- sent to it. You can only modify the `client.offset_encoding` here before --- any notifications are sent. Most language servers expect to be sent client specified settings after ---- initialization. Neovim does not make this assumption. A +--- initialization. Nvim does not make this assumption. A --- `workspace/didChangeConfiguration` notification should be sent --- to the server during on_init. --- @@ -1006,13 +1103,11 @@ end --- server will base its workspaceFolders, rootUri, and rootPath --- on initialization. --- ----@returns Client id. |vim.lsp.get_client_by_id()| Note: client may not be +---@return integer|nil client_id. |vim.lsp.get_client_by_id()| Note: client may not be --- fully initialized. Use `on_init` to do any actions once --- the client has been initialized. function lsp.start_client(config) - local cleaned_config = validate_client_config(config) - local cmd, cmd_args, offset_encoding = - cleaned_config.cmd, cleaned_config.cmd_args, cleaned_config.offset_encoding + local cmd, cmd_args, offset_encoding = validate_client_config(config) config.flags = config.flags or {} config.settings = config.settings or {} @@ -1032,12 +1127,11 @@ function lsp.start_client(config) local dispatch = {} - ---@private --- Returns the handler associated with an LSP method. --- Returns the default handler if the user hasn't set a custom one. --- ---@param method (string) LSP method name - ---@returns (fn) The handler for the given method, if defined, or the default from |vim.lsp.handlers| + ---@return lsp-handler|nil The handler for the given method, if defined, or the default from |vim.lsp.handlers| local function resolve_handler(method) return handlers[method] or default_handlers[method] end @@ -1049,7 +1143,9 @@ function lsp.start_client(config) ---@param method (string) LSP method name ---@param params (table) The parameters for that method. function dispatch.notification(method, params) - local _ = log.trace() and log.trace('notification', method, params) + if log.trace() then + log.trace('notification', method, params) + end local handler = resolve_handler(method) if handler then -- Method name is provided here for convenience. @@ -1063,27 +1159,41 @@ function lsp.start_client(config) ---@param method (string) LSP method name ---@param params (table) The parameters for that method function dispatch.server_request(method, params) - local _ = log.trace() and log.trace('server_request', method, params) + if log.trace() then + log.trace('server_request', method, params) + end local handler = resolve_handler(method) if handler then - local _ = log.trace() and log.trace('server_request: found handler for', method) + if log.trace() then + log.trace('server_request: found handler for', method) + end return handler(nil, params, { method = method, client_id = client_id }) end - local _ = log.warn() and log.warn('server_request: no handler found for', method) + if log.warn() then + log.warn('server_request: no handler found for', method) + end return nil, lsp.rpc_response_error(protocol.ErrorCodes.MethodNotFound) end + --- Logs the given error to the LSP log and to the error buffer. + --- @param code integer Error code + --- @param err any Error arguments + local function write_error(code, err) + if log.error() then + log.error(log_prefix, 'on_error', { code = lsp.client_errors[code], err = err }) + end + err_message(log_prefix, ': Error ', lsp.client_errors[code], ': ', vim.inspect(err)) + end + ---@private --- Invoked when the client operation throws an error. --- - ---@param code (number) Error code + ---@param code (integer) Error code ---@param err (...) Other arguments may be passed depending on the error kind - ---@see `vim.lsp.rpc.client_errors` for possible errors. Use + ---@see vim.lsp.rpc.client_errors for possible errors. Use ---`vim.lsp.rpc.client_errors[code]` to get a human-friendly name. function dispatch.on_error(code, err) - local _ = log.error() - and log.error(log_prefix, 'on_error', { code = lsp.client_errors[code], err = err }) - err_message(log_prefix, ': Error ', lsp.client_errors[code], ': ', vim.inspect(err)) + write_error(code, err) if config.on_error then local status, usererr = pcall(config.on_error, code, err) if not status then @@ -1093,28 +1203,9 @@ function lsp.start_client(config) end end - ---@private - local function set_defaults(client, bufnr) - local capabilities = client.server_capabilities - if capabilities.definitionProvider and vim.bo[bufnr].tagfunc == '' then - vim.bo[bufnr].tagfunc = 'v:lua.vim.lsp.tagfunc' - end - if capabilities.completionProvider and vim.bo[bufnr].omnifunc == '' then - vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc' - end - if - capabilities.documentRangeFormattingProvider - and vim.bo[bufnr].formatprg == '' - and vim.bo[bufnr].formatexpr == '' - then - vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr()' - end - end - - ---@private --- Reset defaults set by `set_defaults`. --- Must only be called if the last client attached to a buffer exits. - local function unset_defaults(bufnr) + local function reset_defaults(bufnr) if vim.bo[bufnr].tagfunc == 'v:lua.vim.lsp.tagfunc' then vim.bo[bufnr].tagfunc = nil end @@ -1124,33 +1215,44 @@ function lsp.start_client(config) if vim.bo[bufnr].formatexpr == 'v:lua.vim.lsp.formatexpr()' then vim.bo[bufnr].formatexpr = nil end + api.nvim_buf_call(bufnr, function() + local keymap = vim.fn.maparg('K', 'n', false, true) + if keymap and keymap.callback == vim.lsp.buf.hover then + vim.keymap.del('n', 'K', { buffer = bufnr }) + end + end) end ---@private --- Invoked on client exit. --- - ---@param code (number) exit code of the process - ---@param signal (number) the signal used to terminate (if any) + ---@param code (integer) exit code of the process + ---@param signal (integer) the signal used to terminate (if any) function dispatch.on_exit(code, signal) if config.on_exit then pcall(config.on_exit, code, signal, client_id) end + local client = active_clients[client_id] and active_clients[client_id] + or uninitialized_clients[client_id] + for bufnr, client_ids in pairs(all_buffer_active_clients) do if client_ids[client_id] then vim.schedule(function() - nvim_exec_autocmds('LspDetach', { - buffer = bufnr, - modeline = false, - data = { client_id = client_id }, - }) + if client and client.attached_buffers[bufnr] then + nvim_exec_autocmds('LspDetach', { + buffer = bufnr, + modeline = false, + data = { client_id = client_id }, + }) + end local namespace = vim.lsp.diagnostic.get_namespace(client_id) vim.diagnostic.reset(namespace, bufnr) client_ids[client_id] = nil if vim.tbl_isempty(client_ids) then - unset_defaults(bufnr) + reset_defaults(bufnr) end end) end @@ -1159,8 +1261,6 @@ function lsp.start_client(config) -- Schedule the deletion of the client object so that it exists in the execution of LspDetach -- autocommands vim.schedule(function() - local client = active_clients[client_id] and active_clients[client_id] - or uninitialized_clients[client_id] active_clients[client_id] = nil uninitialized_clients[client_id] = nil @@ -1170,8 +1270,13 @@ function lsp.start_client(config) changetracking.reset(client) end if code ~= 0 or (signal ~= 0 and signal ~= 15) then - local msg = - string.format('Client %s quit with exit code %s and signal %s', client_id, code, signal) + local msg = string.format( + 'Client %s quit with exit code %s and signal %s. Check log for errors: %s', + name, + code, + signal, + lsp.get_log_path() + ) vim.notify(msg, vim.log.levels.WARN) end end) @@ -1194,6 +1299,7 @@ function lsp.start_client(config) return end + ---@class lsp.Client local client = { id = client_id, name = name, @@ -1205,26 +1311,44 @@ function lsp.start_client(config) handlers = handlers, commands = config.commands or {}, + --- @type table<integer,{ type: string, bufnr: integer, method: string}> requests = {}, - -- for $/progress report + + --- Contains $/progress report messages. + --- They have the format {token: integer|string, value: any} + --- For "work done progress", value will be one of: + --- - lsp.WorkDoneProgressBegin, + --- - lsp.WorkDoneProgressReport (extended with title from Begin) + --- - lsp.WorkDoneProgressEnd (extended with title from Begin) + progress = vim.ringbuf(50), + + --- @type lsp.ServerCapabilities + server_capabilities = {}, + + ---@deprecated use client.progress instead messages = { name = name, messages = {}, progress = {}, status = {} }, + dynamic_capabilities = require('vim.lsp._dynamic').new(client_id), } + ---@type table<string|integer, string> title of unfinished progress sequences by token + client.progress.pending = {} + + --- @type lsp.ClientCapabilities + client.config.capabilities = config.capabilities or protocol.make_client_capabilities() + -- Store the uninitialized_clients for cleanup in case we exit before initialize finishes. uninitialized_clients[client_id] = client - ---@private local function initialize() local valid_traces = { off = 'off', messages = 'messages', verbose = 'verbose', } - local version = vim.version() - local workspace_folders - local root_uri - local root_path + local workspace_folders --- @type table[]? + local root_uri --- @type string? + local root_path --- @type string? if config.workspace_folders or config.root_dir then if config.root_dir and not config.workspace_folders then workspace_folders = { @@ -1249,12 +1373,12 @@ function lsp.start_client(config) -- the process has not been started by another process. If the parent -- process is not alive then the server should exit (see exit notification) -- its process. - processId = uv.getpid(), + processId = uv.os_getpid(), -- Information about the client -- since 3.15.0 clientInfo = { name = 'Neovim', - version = string.format('%s.%s.%s', version.major, version.minor, version.patch), + version = tostring(vim.version()), }, -- The rootPath of the workspace. Is null if no folder is open. -- @@ -1271,15 +1395,37 @@ function lsp.start_client(config) -- User provided initialization options. initializationOptions = config.init_options, -- The capabilities provided by the client (editor or tool) - capabilities = config.capabilities or protocol.make_client_capabilities(), + capabilities = config.capabilities, -- The initial trace setting. If omitted trace is disabled ("off"). -- trace = "off" | "messages" | "verbose"; trace = valid_traces[config.trace] or 'off', } if config.before_init then - -- TODO(ashkan) handle errors here. - pcall(config.before_init, initialize_params, config) + local status, err = pcall(config.before_init, initialize_params, config) + if not status then + write_error(lsp.client_errors.BEFORE_INIT_CALLBACK_ERROR, err) + end end + + --- @param method string + --- @param opts? {bufnr?: number} + client.supports_method = function(method, opts) + opts = opts or {} + local required_capability = lsp._request_name_to_capability[method] + -- if we don't know about the method, assume that the client supports it. + if not required_capability then + return true + end + if vim.tbl_get(client.server_capabilities, unpack(required_capability)) then + return true + else + if client.dynamic_capabilities:supports_registration(method) then + return client.dynamic_capabilities:supports(method, opts) + end + return false + end + end + local _ = log.trace() and log.trace(log_prefix, 'initialize_params', initialize_params) rpc.request('initialize', initialize_params, function(init_err, result) assert(not init_err, tostring(init_err)) @@ -1295,46 +1441,18 @@ function lsp.start_client(config) assert(result.capabilities, "initialize result doesn't contain capabilities") client.server_capabilities = protocol.resolve_capabilities(client.server_capabilities) - -- Deprecation wrapper: this will be removed in 0.8 - local mt = {} - mt.__index = function(table, key) - if key == 'resolved_capabilities' then - vim.notify_once( - '[LSP] Accessing client.resolved_capabilities is deprecated, ' - .. 'update your plugins or configuration to access client.server_capabilities instead.' - .. 'The new key/value pairs in server_capabilities directly match those ' - .. 'defined in the language server protocol', - vim.log.levels.WARN - ) - rawset(table, key, protocol._resolve_capabilities_compat(client.server_capabilities)) - return rawget(table, key) - else - return rawget(table, key) - end - end - setmetatable(client, mt) - - client.supports_method = function(method) - local required_capability = lsp._request_name_to_capability[method] - -- if we don't know about the method, assume that the client supports it. - if not required_capability then - return true - end - if vim.tbl_get(client.server_capabilities, unpack(required_capability)) then - return true - else - return false - end + if client.server_capabilities.positionEncoding then + client.offset_encoding = client.server_capabilities.positionEncoding end if next(config.settings) then - client.notify('workspace/didChangeConfiguration', { settings = config.settings }) + client.notify(ms.workspace_didChangeConfiguration, { settings = config.settings }) end if config.on_init then local status, err = pcall(config.on_init, client, result) if not status then - pcall(handlers.on_error, lsp.client_errors.ON_INIT_CALLBACK_ERROR, err) + write_error(lsp.client_errors.ON_INIT_CALLBACK_ERROR, err) end end local _ = log.info() @@ -1357,23 +1475,23 @@ function lsp.start_client(config) end) end - ---@private + ---@nodoc --- Sends a request to the server. --- --- This is a thin wrapper around {client.rpc.request} with some additional --- checks for capabilities and handler availability. --- - ---@param method (string) LSP method name. - ---@param params (table) LSP request params. - ---@param handler (function|nil) Response |lsp-handler| for this method. - ---@param bufnr (number) Buffer handle (0 for current). - ---@returns ({status}, [request_id]): {status} is a bool indicating + ---@param method string LSP method name. + ---@param params table|nil LSP request params. + ---@param handler lsp-handler|nil Response |lsp-handler| for this method. + ---@param bufnr integer Buffer handle (0 for current). + ---@return boolean status, integer|nil request_id {status} is a bool indicating ---whether the request was successful. If it is `false`, then it will ---always be `false` (the client has shutdown). If it was ---successful, then it will return {request_id} as the ---second result. You can use this with `client.cancel_request(request_id)` ---to cancel the-request. - ---@see |vim.lsp.buf_request()| + ---@see |vim.lsp.buf_request_all()| function client.request(method, params, handler, bufnr) if not handler then handler = assert( @@ -1383,23 +1501,39 @@ function lsp.start_client(config) end -- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state changetracking.flush(client, bufnr) + local version = util.buf_versions[bufnr] bufnr = resolve_bufnr(bufnr) - local _ = log.debug() - and log.debug(log_prefix, 'client.request', client_id, method, params, handler, bufnr) + if log.debug() then + log.debug(log_prefix, 'client.request', client_id, method, params, handler, bufnr) + end local success, request_id = rpc.request(method, params, function(err, result) - handler( - err, - result, - { method = method, client_id = client_id, bufnr = bufnr, params = params } - ) + local context = { + method = method, + client_id = client_id, + bufnr = bufnr, + params = params, + version = version, + } + handler(err, result, context) end, function(request_id) + local request = client.requests[request_id] + request.type = 'complete' + nvim_exec_autocmds('LspRequest', { + buffer = api.nvim_buf_is_valid(bufnr) and bufnr or nil, + modeline = false, + data = { client_id = client_id, request_id = request_id, request = request }, + }) client.requests[request_id] = nil - nvim_exec_autocmds('User', { pattern = 'LspRequest', modeline = false }) end) if success and request_id then - client.requests[request_id] = { type = 'pending', bufnr = bufnr, method = method } - nvim_exec_autocmds('User', { pattern = 'LspRequest', modeline = false }) + local request = { type = 'pending', bufnr = bufnr, method = method } + client.requests[request_id] = request + nvim_exec_autocmds('LspRequest', { + buffer = bufnr, + modeline = false, + data = { client_id = client_id, request_id = request_id, request = request }, + }) end return success, request_id @@ -1412,13 +1546,14 @@ function lsp.start_client(config) --- ---@param method (string) LSP method name. ---@param params (table) LSP request params. - ---@param timeout_ms (number|nil) Maximum time in milliseconds to wait for + ---@param timeout_ms (integer|nil) Maximum time in milliseconds to wait for --- a result. Defaults to 1000 - ---@param bufnr (number) Buffer handle (0 for current). - ---@returns { err=err, result=result }, a dictionary, where `err` and `result` come from the |lsp-handler|. - ---On timeout, cancel or error, returns `(nil, err)` where `err` is a - ---string describing the failure reason. If the request was unsuccessful - ---returns `nil`. + ---@param bufnr (integer) Buffer handle (0 for current). + ---@return {err: lsp.ResponseError|nil, result:any}|nil, string|nil err # a dictionary, where + --- `err` and `result` come from the |lsp-handler|. + --- On timeout, cancel or error, returns `(nil, err)` where `err` is a + --- string describing the failure reason. If the request was unsuccessful + --- returns `nil`. ---@see |vim.lsp.buf_request_sync()| function client.request_sync(method, params, timeout_ms, bufnr) local request_result = nil @@ -1444,41 +1579,62 @@ function lsp.start_client(config) return request_result end - ---@private + ---@nodoc --- Sends a notification to an LSP server. --- ---@param method string LSP method name. ---@param params table|nil LSP request params. - ---@returns {status} (bool) true if the notification was successful. + ---@return boolean status true if the notification was successful. ---If it is false, then it will always be false ---(the client has shutdown). function client.notify(method, params) - if method ~= 'textDocument/didChange' then + if method ~= ms.textDocument_didChange then changetracking.flush(client) end - return rpc.notify(method, params) + + local client_active = rpc.notify(method, params) + + if client_active then + vim.schedule(function() + nvim_exec_autocmds('LspNotify', { + modeline = false, + data = { + client_id = client.id, + method = method, + params = params, + }, + }) + end) + end + + return client_active end - ---@private + ---@nodoc --- Cancels a request with a given request id. --- - ---@param id (number) id of request to cancel - ---@returns true if any client returns true; false otherwise + ---@param id (integer) id of request to cancel + ---@return boolean status true if notification was successful. false otherwise ---@see |vim.lsp.client.notify()| function client.cancel_request(id) validate({ id = { id, 'n' } }) local request = client.requests[id] if request and request.type == 'pending' then request.type = 'cancel' - nvim_exec_autocmds('User', { pattern = 'LspRequest', modeline = false }) + nvim_exec_autocmds('LspRequest', { + buffer = request.bufnr, + modeline = false, + data = { client_id = client_id, request_id = id, request = request }, + }) end - return rpc.notify('$/cancelRequest', { id = id }) + return rpc.notify(ms.dollar_cancelRequest, { id = id }) end -- Track this so that we can escalate automatically if we've already tried a -- graceful shutdown local graceful_shutdown_failed = false - ---@private + + ---@nodoc --- Stops a client, optionally with force. --- ---By default, it will just ask the - server to shutdown without force. If @@ -1495,9 +1651,9 @@ function lsp.start_client(config) return end -- Sending a signal after a process has exited is acceptable. - rpc.request('shutdown', nil, function(err, _) + rpc.request(ms.shutdown, nil, function(err, _) if err == nil then - rpc.notify('exit') + rpc.notify(ms.exit) else -- If there was an error in the shutdown request, then term to be safe. rpc.terminate() @@ -1509,19 +1665,59 @@ function lsp.start_client(config) ---@private --- Checks whether a client is stopped. --- - ---@returns (bool) true if client is stopped or in the process of being + ---@return boolean # true if client is stopped or in the process of being ---stopped; false otherwise function client.is_stopped() return rpc.is_closing() end ---@private + --- Execute a lsp command, either via client command function (if available) + --- or via workspace/executeCommand (if supported by the server) + --- + ---@param command lsp.Command + ---@param context? {bufnr: integer} + ---@param handler? lsp-handler only called if a server command + function client._exec_cmd(command, context, handler) + context = vim.deepcopy(context or {}) + context.bufnr = context.bufnr or api.nvim_get_current_buf() + context.client_id = client.id + local cmdname = command.command + local fn = client.commands[cmdname] or lsp.commands[cmdname] + if fn then + fn(command, context) + return + end + + local command_provider = client.server_capabilities.executeCommandProvider + local commands = type(command_provider) == 'table' and command_provider.commands or {} + if not vim.list_contains(commands, cmdname) then + vim.notify_once( + string.format( + 'Language server `%s` does not support command `%s`. This command may require a client extension.', + client.name, + cmdname + ), + vim.log.levels.WARN + ) + return + end + -- Not using command directly to exclude extra properties, + -- see https://github.com/python-lsp/python-lsp-server/issues/146 + local params = { + command = command.command, + arguments = command.arguments, + } + client.request(ms.workspace_executeCommand, params, handler, context.bufnr) + end + + ---@private --- Runs the on_attach function from the client's config if it was defined. - ---@param bufnr (number) Buffer number + ---@param bufnr integer Buffer number function client._on_attach(bufnr) text_document_did_open_handler(bufnr, client) - set_defaults(client, bufnr) + lsp._set_defaults(client, bufnr) nvim_exec_autocmds('LspAttach', { buffer = bufnr, @@ -1530,8 +1726,10 @@ function lsp.start_client(config) }) if config.on_attach then - -- TODO(ashkan) handle errors. - pcall(config.on_attach, client, bufnr) + local status, err = pcall(config.on_attach, client, bufnr) + if not status then + write_error(lsp.client_errors.ON_ATTACH_ERROR, err) + end end -- schedule the initialization of semantic tokens to give the above @@ -1573,17 +1771,21 @@ do end end ----@private ---Buffer lifecycle handler for textDocument/didSave local function text_document_did_save_handler(bufnr) bufnr = resolve_bufnr(bufnr) local uri = vim.uri_from_bufnr(bufnr) local text = once(buf_get_full_text) - for_each_buffer_client(bufnr, function(client) + for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do local name = api.nvim_buf_get_name(bufnr) local old_name = changetracking._get_and_set_name(client, bufnr, name) if old_name and name ~= old_name then - client.notify('textDocument/didOpen', { + client.notify(ms.textDocument_didClose, { + textDocument = { + uri = vim.uri_from_fname(old_name), + }, + }) + client.notify(ms.textDocument_didOpen, { textDocument = { version = 0, uri = uri, @@ -1599,14 +1801,14 @@ local function text_document_did_save_handler(bufnr) if type(save_capability) == 'table' and save_capability.includeText then included_text = text(bufnr) end - client.notify('textDocument/didSave', { + client.notify(ms.textDocument_didSave, { textDocument = { uri = uri, }, text = included_text, }) end - end) + end end --- Implements the `textDocument/did…` notifications required to track a buffer @@ -1614,8 +1816,9 @@ end --- --- Without calling this, the server won't be notified of changes to a buffer. --- ----@param bufnr (number) Buffer handle, or 0 for current ----@param client_id (number) Client id +---@param bufnr (integer) Buffer handle, or 0 for current +---@param client_id (integer) Client id +---@return boolean success `true` if client was attached successfully; `false` otherwise function lsp.buf_attach_client(bufnr, client_id) validate({ bufnr = { bufnr, 'n', true }, @@ -1641,7 +1844,7 @@ function lsp.buf_attach_client(bufnr, client_id) buffer = bufnr, desc = 'vim.lsp: textDocument/willSave', callback = function(ctx) - for_each_buffer_client(ctx.buf, function(client) + for _, client in ipairs(lsp.get_clients({ bufnr = ctx.buf })) do local params = { textDocument = { uri = uri, @@ -1649,18 +1852,18 @@ function lsp.buf_attach_client(bufnr, client_id) reason = protocol.TextDocumentSaveReason.Manual, } if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'willSave') then - client.notify('textDocument/willSave', params) + client.notify(ms.textDocument_willSave, params) end if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'willSaveWaitUntil') then local result, err = - client.request_sync('textDocument/willSaveWaitUntil', params, 1000, ctx.buf) + client.request_sync(ms.textDocument_willSaveWaitUntil, params, 1000, ctx.buf) if result and result.result then util.apply_text_edits(result.result, ctx.buf, client.offset_encoding) elseif err then log.error(vim.inspect(err)) end end - end) + end end, }) api.nvim_create_autocmd('BufWritePost', { @@ -1676,23 +1879,23 @@ function lsp.buf_attach_client(bufnr, client_id) on_lines = text_document_did_change_handler, on_reload = function() local params = { textDocument = { uri = uri } } - for_each_buffer_client(bufnr, function(client, _) + for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do changetracking.reset_buf(client, bufnr) if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'openClose') then - client.notify('textDocument/didClose', params) + client.notify(ms.textDocument_didClose, params) end text_document_did_open_handler(bufnr, client) - end) + end end, on_detach = function() local params = { textDocument = { uri = uri } } - for_each_buffer_client(bufnr, function(client, _) + for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do changetracking.reset_buf(client, bufnr) if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'openClose') then - client.notify('textDocument/didClose', params) + client.notify(ms.textDocument_didClose, params) end client.attached_buffers[bufnr] = nil - end) + end util.buf_versions[bufnr] = nil all_buffer_active_clients[bufnr] = nil end, @@ -1704,7 +1907,7 @@ function lsp.buf_attach_client(bufnr, client_id) end if buffer_client_ids[client_id] then - return + return true end -- This is our first time attaching this client to this buffer. buffer_client_ids[client_id] = true @@ -1722,8 +1925,8 @@ end --- Note: While the server is notified that the text document (buffer) --- was closed, it is still able to send notifications should it ignore this notification. --- ----@param bufnr number Buffer handle, or 0 for current ----@param client_id number Client id +---@param bufnr integer Buffer handle, or 0 for current +---@param client_id integer Client id function lsp.buf_detach_client(bufnr, client_id) validate({ bufnr = { bufnr, 'n', true }, @@ -1736,8 +1939,8 @@ function lsp.buf_detach_client(bufnr, client_id) vim.notify( string.format( 'Buffer (id: %d) is not attached to client (id: %d). Cannot detach.', - client_id, - bufnr + bufnr, + client_id ) ) return @@ -1754,7 +1957,7 @@ function lsp.buf_detach_client(bufnr, client_id) if vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'openClose') then local uri = vim.uri_from_bufnr(bufnr) local params = { textDocument = { uri = uri } } - client.notify('textDocument/didClose', params) + client.notify(ms.textDocument_didClose, params) end client.attached_buffers[bufnr] = nil @@ -1765,16 +1968,14 @@ function lsp.buf_detach_client(bufnr, client_id) all_buffer_active_clients[bufnr] = nil end - local namespace = vim.lsp.diagnostic.get_namespace(client_id) + local namespace = lsp.diagnostic.get_namespace(client_id) vim.diagnostic.reset(namespace, bufnr) - - vim.notify(string.format('Detached buffer (id: %d) from client (id: %d)', bufnr, client_id)) end --- Checks if a buffer is attached for a particular client. --- ----@param bufnr (number) Buffer handle, or 0 for current ----@param client_id (number) the client id +---@param bufnr (integer) Buffer handle, or 0 for current +---@param client_id (integer) the client id function lsp.buf_is_attached(bufnr, client_id) return (all_buffer_active_clients[resolve_bufnr(bufnr)] or {})[client_id] == true end @@ -1782,17 +1983,17 @@ end --- Gets a client by id, or nil if the id is invalid. --- The returned client may not yet be fully initialized. --- ----@param client_id number client id +---@param client_id integer client id --- ----@returns |vim.lsp.client| object, or nil +---@return (nil|lsp.Client) client rpc object function lsp.get_client_by_id(client_id) return active_clients[client_id] or uninitialized_clients[client_id] end --- Returns list of buffers attached to client_id. --- ----@param client_id number client id ----@returns list of buffer ids +---@param client_id integer client id +---@return integer[] buffers list of buffer ids function lsp.get_buffers_by_client_id(client_id) local client = lsp.get_client_by_id(client_id) return client and vim.tbl_keys(client.attached_buffers) or {} @@ -1802,14 +2003,15 @@ end --- --- You can also use the `stop()` function on a |vim.lsp.client| object. --- To stop all clients: ---- <pre>lua ---- vim.lsp.stop_client(vim.lsp.get_active_clients()) ---- </pre> +--- +--- ```lua +--- vim.lsp.stop_client(vim.lsp.get_clients()) +--- ``` --- --- By default asks the server to shutdown, unless stop was requested --- already for this client, then force-shutdown is attempted. --- ----@param client_id number|table id or |vim.lsp.client| object, or list thereof +---@param client_id integer|table id or |vim.lsp.client| object, or list thereof ---@param force boolean|nil shutdown forcefully function lsp.stop_client(client_id, force) local ids = type(client_id) == 'table' and client_id or { client_id } @@ -1824,26 +2026,28 @@ function lsp.stop_client(client_id, force) end end ----@class vim.lsp.get_active_clients.filter ----@field id number|nil Match clients by id ----@field bufnr number|nil match clients attached to the given buffer +---@class vim.lsp.get_clients.filter +---@field id integer|nil Match clients by id +---@field bufnr integer|nil match clients attached to the given buffer ---@field name string|nil match clients by name +---@field method string|nil match client by supported method name --- Get active clients. --- ----@param filter vim.lsp.get_active_clients.filter|nil (table|nil) A table with +---@param filter vim.lsp.get_clients.filter|nil (table|nil) A table with --- key-value pairs used to filter the returned clients. --- The available keys are: --- - id (number): Only return clients with the given id --- - bufnr (number): Only return clients attached to this buffer --- - name (string): Only return clients with the given name ----@returns (table) List of |vim.lsp.client| objects -function lsp.get_active_clients(filter) +--- - method (string): Only return clients supporting the given method +---@return lsp.Client[]: List of |vim.lsp.client| objects +function lsp.get_clients(filter) validate({ filter = { filter, 't', true } }) filter = filter or {} - local clients = {} + local clients = {} --- @type lsp.Client[] local t = filter.bufnr and (all_buffer_active_clients[resolve_bufnr(filter.bufnr)] or {}) or active_clients @@ -1853,6 +2057,7 @@ function lsp.get_active_clients(filter) client and (filter.id == nil or client.id == filter.id) and (filter.name == nil or client.name == filter.name) + and (filter.method == nil or client.supports_method(filter.method, { bufnr = filter.bufnr })) then clients[#clients + 1] = client end @@ -1860,6 +2065,13 @@ function lsp.get_active_clients(filter) return clients end +---@private +---@deprecated +function lsp.get_active_clients(filter) + -- TODO: add vim.deprecate call after 0.10 is out for removal in 0.12 + return lsp.get_clients(filter) +end + api.nvim_create_autocmd('VimLeavePre', { desc = 'vim.lsp: exit handler', callback = function() @@ -1890,7 +2102,6 @@ api.nvim_create_autocmd('VimLeavePre', { local poll_time = 50 - ---@private local function check_clients_closed() for client_id, timeout in pairs(timeouts) do timeouts[client_id] = timeout - poll_time @@ -1920,16 +2131,17 @@ api.nvim_create_autocmd('VimLeavePre', { --- Sends an async request for all active clients attached to the --- buffer. --- ----@param bufnr (number) Buffer handle, or 0 for current. +---@param bufnr (integer) Buffer handle, or 0 for current. ---@param method (string) LSP method name ---@param params table|nil Parameters to send to the server ----@param handler function|nil See |lsp-handler| +---@param handler? lsp-handler See |lsp-handler| --- If nil, follows resolution strategy defined in |lsp-handler-configuration| --- ----@returns 2-tuple: ---- - Map of client-id:request-id pairs for all successful requests. ---- - Function which can be used to cancel all the requests. You could instead ---- iterate all clients and call their `cancel_request()` methods. +---@return table<integer, integer> client_request_ids Map of client-id:request-id pairs +---for all successful requests. +---@return function _cancel_all_requests Function which can be used to +---cancel all the requests. You could instead +---iterate all clients and call their `cancel_request()` methods. function lsp.buf_request(bufnr, method, params, handler) validate({ bufnr = { bufnr, 'n', true }, @@ -1937,34 +2149,30 @@ function lsp.buf_request(bufnr, method, params, handler) handler = { handler, 'f', true }, }) - local supported_clients = {} + bufnr = resolve_bufnr(bufnr) local method_supported = false - for_each_buffer_client(bufnr, function(client, client_id) - if client.supports_method(method) then + local clients = lsp.get_clients({ bufnr = bufnr }) + local client_request_ids = {} + for _, client in ipairs(clients) do + if client.supports_method(method, { bufnr = bufnr }) then method_supported = true - table.insert(supported_clients, client_id) + + local request_success, request_id = client.request(method, params, handler, bufnr) + -- This could only fail if the client shut down in the time since we looked + -- it up and we did the request, which should be rare. + if request_success then + client_request_ids[client.id] = request_id + end end - end) + end -- if has client but no clients support the given method, notify the user - if - not tbl_isempty(all_buffer_active_clients[resolve_bufnr(bufnr)] or {}) and not method_supported - then + if next(clients) and not method_supported then vim.notify(lsp._unsupported_method(method), vim.log.levels.ERROR) nvim_command('redraw') return {}, function() end end - local client_request_ids = {} - for_each_buffer_client(bufnr, function(client, client_id, resolved_bufnr) - local request_success, request_id = client.request(method, params, handler, resolved_bufnr) - -- This could only fail if the client shut down in the time since we looked - -- it up and we did the request, which should be rare. - if request_success then - client_request_ids[client_id] = request_id - end - end, supported_clients) - local function _cancel_all_requests() for client_id, request_id in pairs(client_request_ids) do local client = active_clients[client_id] @@ -1975,39 +2183,36 @@ function lsp.buf_request(bufnr, method, params, handler) return client_request_ids, _cancel_all_requests end ----Sends an async request for all active clients attached to the buffer. ----Executes the callback on the combined result. ----Parameters are the same as |vim.lsp.buf_request()| but the return result and callback are ----different. +--- Sends an async request for all active clients attached to the buffer and executes the `handler` +--- callback with the combined result. --- ----@param bufnr (number) Buffer handle, or 0 for current. +---@param bufnr (integer) Buffer handle, or 0 for current. ---@param method (string) LSP method name ---@param params (table|nil) Parameters to send to the server ----@param callback (function) The callback to call when all requests are finished. --- Unlike `buf_request`, this will collect all the responses from each server instead of handling them. --- A map of client_id:request_result will be provided to the callback --- ----@returns (function) A function that will cancel all requests which is the same as the one returned from `buf_request`. -function lsp.buf_request_all(bufnr, method, params, callback) - local request_results = {} +---@param handler fun(results: table<integer, {error: lsp.ResponseError, result: any}>) (function) +--- Handler called after all requests are completed. Server results are passed as +--- a `client_id:result` map. +---@return function cancel Function that cancels all requests. +function lsp.buf_request_all(bufnr, method, params, handler) + local results = {} local result_count = 0 local expected_result_count = 0 local set_expected_result_count = once(function() - for_each_buffer_client(bufnr, function(client) - if client.supports_method(method) then + for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do + if client.supports_method(method, { bufnr = bufnr }) then expected_result_count = expected_result_count + 1 end - end) + end end) local function _sync_handler(err, result, ctx) - request_results[ctx.client_id] = { error = err, result = result } + results[ctx.client_id] = { error = err, result = result } result_count = result_count + 1 set_expected_result_count() if result_count >= expected_result_count then - callback(request_results) + handler(results) end end @@ -2019,18 +2224,17 @@ end --- Sends a request to all server and waits for the response of all of them. --- --- Calls |vim.lsp.buf_request_all()| but blocks Nvim while awaiting the result. ---- Parameters are the same as |vim.lsp.buf_request()| but the return result is ---- different. Wait maximum of {timeout_ms} (default 1000) ms. +--- Parameters are the same as |vim.lsp.buf_request_all()| but the result is +--- different. Waits a maximum of {timeout_ms} (default 1000) ms. --- ----@param bufnr (number) Buffer handle, or 0 for current. +---@param bufnr (integer) Buffer handle, or 0 for current. ---@param method (string) LSP method name ---@param params (table|nil) Parameters to send to the server ----@param timeout_ms (number|nil) Maximum time in milliseconds to wait for a +---@param timeout_ms (integer|nil) Maximum time in milliseconds to wait for a --- result. Defaults to 1000 --- ----@returns Map of client_id:request_result. On timeout, cancel or error, ---- returns `(nil, err)` where `err` is a string describing the failure ---- reason. +---@return table<integer, {err: lsp.ResponseError, result: any}>|nil (table) result Map of client_id:request_result. +---@return string|nil err On timeout, cancel, or error, `err` is a string describing the failure reason, and `result` is nil. function lsp.buf_request_sync(bufnr, method, params, timeout_ms) local request_results @@ -2051,41 +2255,23 @@ function lsp.buf_request_sync(bufnr, method, params, timeout_ms) end --- Send a notification to a server ----@param bufnr (number|nil) The number of the buffer +---@param bufnr (integer|nil) The number of the buffer ---@param method (string) Name of the request method ---@param params (any) Arguments to send to the server --- ----@returns true if any client returns true; false otherwise +---@return boolean success true if any client returns true; false otherwise function lsp.buf_notify(bufnr, method, params) validate({ bufnr = { bufnr, 'n', true }, method = { method, 's' }, }) local resp = false - for_each_buffer_client(bufnr, function(client, _client_id, _resolved_bufnr) + for _, client in ipairs(lsp.get_clients({ bufnr = bufnr })) do if client.rpc.notify(method, params) then resp = true end - end) - return resp -end - ----@private -local function adjust_start_col(lnum, line, items, encoding) - local min_start_char = nil - for _, item in pairs(items) do - if item.filterText == nil and item.textEdit and item.textEdit.range.start.line == lnum - 1 then - if min_start_char and min_start_char ~= item.textEdit.range.start.character then - return nil - end - min_start_char = item.textEdit.range.start.character - end - end - if min_start_char then - return util._str_byteindex_enc(line, min_start_char, encoding) - else - return nil end + return resp end --- Implements 'omnifunc' compatible LSP completion. @@ -2094,80 +2280,24 @@ end ---@see |complete-items| ---@see |CompleteDone| --- ----@param findstart number 0 or 1, decides behavior ----@param base number findstart=0, text to match against +---@param findstart integer 0 or 1, decides behavior +---@param base integer findstart=0, text to match against --- ----@returns (number) Decided by {findstart}: +---@return integer|table Decided by {findstart}: --- - findstart=0: column where the completion starts, or -2 or -3 --- - findstart=1: list of matches (actually just calls |complete()|) function lsp.omnifunc(findstart, base) - local _ = log.debug() and log.debug('omnifunc.findstart', { findstart = findstart, base = base }) - - local bufnr = resolve_bufnr() - local has_buffer_clients = not tbl_isempty(all_buffer_active_clients[bufnr] or {}) - if not has_buffer_clients then - if findstart == 1 then - return -1 - else - return {} - end + if log.debug() then + log.debug('omnifunc.findstart', { findstart = findstart, base = base }) end - - -- Then, perform standard completion request - local _ = log.info() and log.info('base ', base) - - local pos = api.nvim_win_get_cursor(0) - local line = api.nvim_get_current_line() - local line_to_cursor = line:sub(1, pos[2]) - local _ = log.trace() and log.trace('omnifunc.line', pos, line) - - -- Get the start position of the current keyword - local textMatch = vim.fn.match(line_to_cursor, '\\k*$') - - local params = util.make_position_params() - - local items = {} - lsp.buf_request(bufnr, 'textDocument/completion', params, function(err, result, ctx) - if err or not result or vim.fn.mode() ~= 'i' then - return - end - - -- Completion response items may be relative to a position different than `textMatch`. - -- Concrete example, with sumneko/lua-language-server: - -- - -- require('plenary.asy| - -- ▲ ▲ ▲ - -- │ │ └── cursor_pos: 20 - -- │ └────── textMatch: 17 - -- └────────────── textEdit.range.start.character: 9 - -- .newText = 'plenary.async' - -- ^^^ - -- prefix (We'd remove everything not starting with `asy`, - -- so we'd eliminate the `plenary.async` result - -- - -- `adjust_start_col` is used to prefer the language server boundary. - -- - local client = lsp.get_client_by_id(ctx.client_id) - local encoding = client and client.offset_encoding or 'utf-16' - local candidates = util.extract_completion_items(result) - local startbyte = adjust_start_col(pos[1], line, candidates, encoding) or textMatch - local prefix = line:sub(startbyte + 1, pos[2]) - local matches = util.text_document_completion_list_to_complete_items(result, prefix) - -- TODO(ashkan): is this the best way to do this? - vim.list_extend(items, matches) - vim.fn.complete(startbyte + 1, items) - end) - - -- Return -2 to signal that we should continue completion so that we can - -- async complete. - return -2 + return require('vim.lsp._completion').omnifunc(findstart, base) end --- Provides an interface between the built-in client and a `formatexpr` function. --- --- Currently only supports a single client. This can be set via --- `setlocal formatexpr=v:lua.vim.lsp.formatexpr()` but will typically or in `on_attach` ---- via ``vim.api.nvim_buf_set_option(bufnr, 'formatexpr', 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')``. +--- via ``vim.bo[bufnr].formatexpr = 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})'``. --- ---@param opts table options for customizing the formatting expression which takes the --- following optional keys: @@ -2176,7 +2306,7 @@ function lsp.formatexpr(opts) opts = opts or {} local timeout_ms = opts.timeout_ms or 500 - if vim.tbl_contains({ 'i', 'R', 'ic', 'ix' }, vim.fn.mode()) then + if vim.list_contains({ 'i', 'R', 'ic', 'ix' }, vim.fn.mode()) then -- `formatexpr` is also called when exceeding `textwidth` in insert mode -- fall back to internal formatting return 1 @@ -2189,10 +2319,10 @@ function lsp.formatexpr(opts) return 0 end local bufnr = api.nvim_get_current_buf() - for _, client in pairs(lsp.get_active_clients({ bufnr = bufnr })) do - if client.supports_method('textDocument/rangeFormatting') then + for _, client in pairs(lsp.get_clients({ bufnr = bufnr })) do + if client.supports_method(ms.textDocument_rangeFormatting) then local params = util.make_formatting_params() - local end_line = vim.fn.getline(end_lnum) + local end_line = vim.fn.getline(end_lnum) --[[@as string]] local end_col = util._str_utfindex_enc(end_line, nil, client.offset_encoding) params.range = { start = { @@ -2205,9 +2335,9 @@ function lsp.formatexpr(opts) }, } local response = - client.request_sync('textDocument/rangeFormatting', params, timeout_ms, bufnr) - if response.result then - vim.lsp.util.apply_text_edits(response.result, 0, client.offset_encoding) + client.request_sync(ms.textDocument_rangeFormatting, params, timeout_ms, bufnr) + if response and response.result then + lsp.util.apply_text_edits(response.result, 0, client.offset_encoding) return 0 end end @@ -2227,39 +2357,41 @@ end ---@param pattern string Pattern used to find a workspace symbol ---@param flags string See |tag-function| --- ----@returns A list of matching tags -function lsp.tagfunc(...) - return require('vim.lsp.tagfunc')(...) +---@return table[] tags A list of matching tags +function lsp.tagfunc(pattern, flags) + return require('vim.lsp.tagfunc')(pattern, flags) end ---Checks whether a client is stopped. --- ----@param client_id (number) ----@returns true if client is stopped, false otherwise. +---@param client_id (integer) +---@return boolean stopped true if client is stopped, false otherwise. function lsp.client_is_stopped(client_id) - return active_clients[client_id] == nil + assert(client_id, 'missing client_id param') + return active_clients[client_id] == nil and not uninitialized_clients[client_id] end --- Gets a map of client_id:client pairs for the given buffer, where each value --- is a |vim.lsp.client| object. --- ----@param bufnr (number|nil): Buffer handle, or 0 for current ----@returns (table) Table of (client_id, client) pairs ----@deprecated Use |vim.lsp.get_active_clients()| instead. +---@param bufnr (integer|nil): Buffer handle, or 0 for current +---@return table result is table of (client_id, client) pairs +---@deprecated Use |vim.lsp.get_clients()| instead. function lsp.buf_get_clients(bufnr) local result = {} - for _, client in ipairs(lsp.get_active_clients({ bufnr = resolve_bufnr(bufnr) })) do + for _, client in ipairs(lsp.get_clients({ bufnr = resolve_bufnr(bufnr) })) do result[client.id] = client end return result end --- Log level dictionary with reverse lookup as well. --- --- Can be used to lookup the number from the name or the --- name from the number. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" --- Level numbers begin with "TRACE" at 0 +--- Log level dictionary with reverse lookup as well. +--- +--- Can be used to lookup the number from the name or the +--- name from the number. +--- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" +--- Level numbers begin with "TRACE" at 0 +--- @nodoc lsp.log_levels = log.levels --- Sets the global log level for LSP logging. @@ -2272,7 +2404,7 @@ lsp.log_levels = log.levels --- ---@see |vim.lsp.log_levels| --- ----@param level (number|string) the case insensitive level name or number +---@param level (integer|string) the case insensitive level name or number function lsp.set_log_level(level) if type(level) == 'string' or type(level) == 'number' then log.set_level(level) @@ -2282,22 +2414,19 @@ function lsp.set_log_level(level) end --- Gets the path of the logfile used by the LSP client. ----@returns (String) Path to logfile. +---@return string path to log file function lsp.get_log_path() return log.get_filename() end +---@private --- Invokes a function for each LSP client attached to a buffer. --- ----@param bufnr number Buffer number +---@param bufnr integer Buffer number ---@param fn function Function to run on each client attached to buffer --- {bufnr}. The function takes the client, client ID, and ---- buffer number as arguments. Example: ---- <pre>lua ---- vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr) ---- print(vim.inspect(client)) ---- end) ---- </pre> +--- buffer number as arguments. +---@deprecated use lsp.get_clients({ bufnr = bufnr }) with regular loop function lsp.for_each_buffer_client(bufnr, fn) return for_each_buffer_client(bufnr, fn) end @@ -2316,10 +2445,13 @@ end --- are valid keys and make sense to include for this handler. --- --- Will error on invalid keys (i.e. keys that do not exist in the options) +--- @param name string +--- @param options table<string,any> +--- @param user_config table<string,any> function lsp._with_extend(name, options, user_config) user_config = user_config or {} - local resulting_config = {} + local resulting_config = {} --- @type table<string,any> for k, v in pairs(user_config) do if options[k] == nil then error( @@ -2374,4 +2506,3 @@ lsp.commands = setmetatable({}, { }) return lsp --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/_completion.lua b/runtime/lua/vim/lsp/_completion.lua new file mode 100644 index 0000000000..7a607d6c13 --- /dev/null +++ b/runtime/lua/vim/lsp/_completion.lua @@ -0,0 +1,236 @@ +local M = {} +local api = vim.api +local lsp = vim.lsp +local protocol = lsp.protocol +local ms = protocol.Methods + +---@param input string unparsed snippet +---@return string parsed snippet +local function parse_snippet(input) + local ok, parsed = pcall(function() + return require('vim.lsp._snippet_grammar').parse(input) + end) + return ok and tostring(parsed) or input +end + +--- Returns text that should be inserted when selecting completion item. The +--- precedence is as follows: textEdit.newText > insertText > label +--- +--- See https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion +--- +---@param item lsp.CompletionItem +---@return string +local function get_completion_word(item) + if item.textEdit ~= nil and item.textEdit.newText ~= nil and item.textEdit.newText ~= '' then + if item.insertTextFormat == protocol.InsertTextFormat.PlainText then + return item.textEdit.newText + else + return parse_snippet(item.textEdit.newText) + end + elseif item.insertText ~= nil and item.insertText ~= '' then + if item.insertTextFormat == protocol.InsertTextFormat.PlainText then + return item.insertText + else + return parse_snippet(item.insertText) + end + end + return item.label +end + +---@param result lsp.CompletionList|lsp.CompletionItem[] +---@return lsp.CompletionItem[] +local function get_items(result) + if result.items then + return result.items + end + return result +end + +--- Turns the result of a `textDocument/completion` request into vim-compatible +--- |complete-items|. +--- +---@param result lsp.CompletionList|lsp.CompletionItem[] Result of `textDocument/completion` +---@param prefix string prefix to filter the completion items +---@return table[] +---@see complete-items +function M._lsp_to_complete_items(result, prefix) + local items = get_items(result) + if vim.tbl_isempty(items) then + return {} + end + + local function matches_prefix(item) + return vim.startswith(get_completion_word(item), prefix) + end + + items = vim.tbl_filter(matches_prefix, items) --[[@as lsp.CompletionItem[]|]] + table.sort(items, function(a, b) + return (a.sortText or a.label) < (b.sortText or b.label) + end) + + local matches = {} + for _, item in ipairs(items) do + local info = '' + local documentation = item.documentation + if documentation then + if type(documentation) == 'string' and documentation ~= '' then + info = documentation + elseif type(documentation) == 'table' and type(documentation.value) == 'string' then + info = documentation.value + else + vim.notify( + ('invalid documentation value %s'):format(vim.inspect(documentation)), + vim.log.levels.WARN + ) + end + end + local word = get_completion_word(item) + table.insert(matches, { + word = word, + abbr = item.label, + kind = protocol.CompletionItemKind[item.kind] or 'Unknown', + menu = item.detail or '', + info = #info > 0 and info or nil, + icase = 1, + dup = 1, + empty = 1, + user_data = { + nvim = { + lsp = { + completion_item = item, + }, + }, + }, + }) + end + return matches +end + +---@param lnum integer 0-indexed +---@param items lsp.CompletionItem[] +local function adjust_start_col(lnum, line, items, encoding) + local min_start_char = nil + for _, item in pairs(items) do + if item.textEdit and item.textEdit.range.start.line == lnum then + if min_start_char and min_start_char ~= item.textEdit.range.start.character then + return nil + end + min_start_char = item.textEdit.range.start.character + end + end + if min_start_char then + return vim.lsp.util._str_byteindex_enc(line, min_start_char, encoding) + else + return nil + end +end + +---@private +---@param line string line content +---@param lnum integer 0-indexed line number +---@param client_start_boundary integer 0-indexed word boundary +---@param server_start_boundary? integer 0-indexed word boundary, based on textEdit.range.start.character +---@param result lsp.CompletionList|lsp.CompletionItem[] +---@param encoding string +---@return table[] matches +---@return integer? server_start_boundary +function M._convert_results( + line, + lnum, + cursor_col, + client_start_boundary, + server_start_boundary, + result, + encoding +) + -- Completion response items may be relative to a position different than `client_start_boundary`. + -- Concrete example, with lua-language-server: + -- + -- require('plenary.asy| + -- ▲ ▲ ▲ + -- │ │ └── cursor_pos: 20 + -- │ └────── client_start_boundary: 17 + -- └────────────── textEdit.range.start.character: 9 + -- .newText = 'plenary.async' + -- ^^^ + -- prefix (We'd remove everything not starting with `asy`, + -- so we'd eliminate the `plenary.async` result + -- + -- `adjust_start_col` is used to prefer the language server boundary. + -- + local candidates = get_items(result) + local curstartbyte = adjust_start_col(lnum, line, candidates, encoding) + if server_start_boundary == nil then + server_start_boundary = curstartbyte + elseif curstartbyte ~= nil and curstartbyte ~= server_start_boundary then + server_start_boundary = client_start_boundary + end + local prefix = line:sub((server_start_boundary or client_start_boundary) + 1, cursor_col) + local matches = M._lsp_to_complete_items(result, prefix) + return matches, server_start_boundary +end + +---@param findstart integer 0 or 1, decides behavior +---@param base integer findstart=0, text to match against +---@return integer|table Decided by {findstart}: +--- - findstart=0: column where the completion starts, or -2 or -3 +--- - findstart=1: list of matches (actually just calls |complete()|) +function M.omnifunc(findstart, base) + assert(base) -- silence luals + local bufnr = api.nvim_get_current_buf() + local clients = lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_completion }) + local remaining = #clients + if remaining == 0 then + return findstart == 1 and -1 or {} + end + + local win = api.nvim_get_current_win() + local cursor = api.nvim_win_get_cursor(win) + local lnum = cursor[1] - 1 + local cursor_col = cursor[2] + local line = api.nvim_get_current_line() + local line_to_cursor = line:sub(1, cursor_col) + local client_start_boundary = vim.fn.match(line_to_cursor, '\\k*$') --[[@as integer]] + local server_start_boundary = nil + local items = {} + + local function on_done() + local mode = api.nvim_get_mode()['mode'] + if mode == 'i' or mode == 'ic' then + vim.fn.complete((server_start_boundary or client_start_boundary) + 1, items) + end + end + + local util = vim.lsp.util + for _, client in ipairs(clients) do + local params = util.make_position_params(win, client.offset_encoding) + client.request(ms.textDocument_completion, params, function(err, result) + if err then + require('vim.lsp.log').warn(err.message) + end + if result and vim.fn.mode() == 'i' then + local matches + matches, server_start_boundary = M._convert_results( + line, + lnum, + cursor_col, + client_start_boundary, + server_start_boundary, + result, + client.offset_encoding + ) + vim.list_extend(items, matches) + end + remaining = remaining - 1 + if remaining == 0 then + vim.schedule(on_done) + end + end, bufnr) + end + + -- Return -2 to signal that we should continue completion so that we can + -- async complete. + return -2 +end + +return M diff --git a/runtime/lua/vim/lsp/_dynamic.lua b/runtime/lua/vim/lsp/_dynamic.lua new file mode 100644 index 0000000000..04040e8e28 --- /dev/null +++ b/runtime/lua/vim/lsp/_dynamic.lua @@ -0,0 +1,109 @@ +local wf = require('vim.lsp._watchfiles') + +--- @class lsp.DynamicCapabilities +--- @field capabilities table<string, lsp.Registration[]> +--- @field client_id number +local M = {} + +--- @param client_id number +function M.new(client_id) + return setmetatable({ + capabilities = {}, + client_id = client_id, + }, { __index = M }) +end + +function M:supports_registration(method) + local client = vim.lsp.get_client_by_id(self.client_id) + if not client then + return false + end + local capability = vim.tbl_get(client.config.capabilities, unpack(vim.split(method, '/'))) + return type(capability) == 'table' and capability.dynamicRegistration +end + +--- @param registrations lsp.Registration[] +--- @private +function M:register(registrations) + -- remove duplicates + self:unregister(registrations) + for _, reg in ipairs(registrations) do + local method = reg.method + if not self.capabilities[method] then + self.capabilities[method] = {} + end + table.insert(self.capabilities[method], reg) + end +end + +--- @param unregisterations lsp.Unregistration[] +--- @private +function M:unregister(unregisterations) + for _, unreg in ipairs(unregisterations) do + local method = unreg.method + if not self.capabilities[method] then + return + end + local id = unreg.id + for i, reg in ipairs(self.capabilities[method]) do + if reg.id == id then + table.remove(self.capabilities[method], i) + break + end + end + end +end + +--- @param method string +--- @param opts? {bufnr?: number} +--- @return lsp.Registration? (table|nil) the registration if found +--- @private +function M:get(method, opts) + opts = opts or {} + opts.bufnr = opts.bufnr or vim.api.nvim_get_current_buf() + for _, reg in ipairs(self.capabilities[method] or {}) do + if not reg.registerOptions then + return reg + end + local documentSelector = reg.registerOptions.documentSelector + if not documentSelector then + return reg + end + if M.match(opts.bufnr, documentSelector) then + return reg + end + end +end + +--- @param method string +--- @param opts? {bufnr?: number} +--- @private +function M:supports(method, opts) + return self:get(method, opts) ~= nil +end + +--- @param bufnr number +--- @param documentSelector lsp.DocumentSelector +--- @private +function M.match(bufnr, documentSelector) + local ft = vim.bo[bufnr].filetype + local uri = vim.uri_from_bufnr(bufnr) + local fname = vim.uri_to_fname(uri) + for _, filter in ipairs(documentSelector) do + local matches = true + if filter.language and ft ~= filter.language then + matches = false + end + if matches and filter.scheme and not vim.startswith(uri, filter.scheme .. ':') then + matches = false + end + if matches and filter.pattern and not wf._match(filter.pattern, fname) then + matches = false + end + if matches then + return true + end + end +end + +return M diff --git a/runtime/lua/vim/lsp/_meta.lua b/runtime/lua/vim/lsp/_meta.lua new file mode 100644 index 0000000000..acf799264e --- /dev/null +++ b/runtime/lua/vim/lsp/_meta.lua @@ -0,0 +1,22 @@ +---@meta +error('Cannot require a meta file') + +---@alias lsp-handler fun(err: lsp.ResponseError|nil, result: any, context: lsp.HandlerContext, config: table|nil): any? + +---@class lsp.HandlerContext +---@field method string +---@field client_id integer +---@field bufnr? integer +---@field params? any + +---@class lsp.ResponseError +---@field code integer +---@field message string +---@field data string|number|boolean|table[]|table|nil + +--- @class lsp.DocumentFilter +--- @field language? string +--- @field scheme? string +--- @field pattern? string + +--- @alias lsp.RegisterOptions any | lsp.StaticRegistrationOptions | lsp.TextDocumentRegistrationOptions diff --git a/runtime/lua/vim/lsp/_meta/protocol.lua b/runtime/lua/vim/lsp/_meta/protocol.lua new file mode 100644 index 0000000000..72b0f00f65 --- /dev/null +++ b/runtime/lua/vim/lsp/_meta/protocol.lua @@ -0,0 +1,4396 @@ +--[[ +This file is autogenerated from scripts/gen_lsp.lua +Regenerate: +nvim -l scripts/gen_lsp.lua gen --version 3.18 --runtime/lua/vim/lsp/_meta/protocol.lua +--]] + +---@meta +error('Cannot require a meta file') + +---@alias lsp.null nil +---@alias uinteger integer +---@alias lsp.decimal number +---@alias lsp.DocumentUri string +---@alias lsp.URI string +---@alias lsp.LSPObject table<string, lsp.LSPAny> +---@alias lsp.LSPArray lsp.LSPAny[] +---@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|number|boolean|nil + +---@class lsp.ImplementationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Represents a location inside a resource, such as a line +---inside a text file. +---@class lsp.Location +---@field uri lsp.DocumentUri +---@field range lsp.Range + +---@class lsp.ImplementationRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@class lsp.TypeDefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---@class lsp.TypeDefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---A workspace folder inside a client. +---@class lsp.WorkspaceFolder +---The associated URI for this workspace folder. +---@field uri lsp.URI +---The name of the workspace folder. Used to refer to this +---workspace folder in the user interface. +---@field name string + +---The parameters of a `workspace/didChangeWorkspaceFolders` notification. +---@class lsp.DidChangeWorkspaceFoldersParams +---The actual workspace folder change event. +---@field event lsp.WorkspaceFoldersChangeEvent + +---The parameters of a configuration request. +---@class lsp.ConfigurationParams +---@field items lsp.ConfigurationItem[] + +---Parameters for a {@link DocumentColorRequest}. +---@class lsp.DocumentColorParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents a color range from a document. +---@class lsp.ColorInformation +---The range in the document where this color appears. +---@field range lsp.Range +---The actual color value for this color range. +---@field color lsp.Color + +---@class lsp.DocumentColorRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---Parameters for a {@link ColorPresentationRequest}. +---@class lsp.ColorPresentationParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The color to request presentations for. +---@field color lsp.Color +---The range where the color would be inserted. Serves as a context. +---@field range lsp.Range + +---@class lsp.ColorPresentation +---The label of this color presentation. It will be shown on the color +---picker header. By default this is also the text that is inserted when selecting +---this color presentation. +---@field label string +---An {@link TextEdit edit} which is applied to a document when selecting +---this presentation for the color. When `falsy` the {@link ColorPresentation.label label} +---is used. +---@field textEdit? lsp.TextEdit +---An optional array of additional {@link TextEdit text edits} that are applied when +---selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves. +---@field additionalTextEdits? lsp.TextEdit[] + +---@class lsp.WorkDoneProgressOptions +---@field workDoneProgress? boolean + +---General text document registration options. +---@class lsp.TextDocumentRegistrationOptions +---A document selector to identify the scope of the registration. If set to null +---the document selector provided on the client side will be used. +---@field documentSelector lsp.DocumentSelector|lsp.null + +---Parameters for a {@link FoldingRangeRequest}. +---@class lsp.FoldingRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents a folding range. To be valid, start and end line must be bigger than zero and smaller +---than the number of lines in the document. Clients are free to ignore invalid ranges. +---@class lsp.FoldingRange +---The zero-based start line of the range to fold. The folded area starts after the line's last character. +---To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field startLine uinteger +---The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. +---@field startCharacter? uinteger +---The zero-based end line of the range to fold. The folded area ends with the line's last character. +---To be valid, the end must be zero or larger and smaller than the number of lines in the document. +---@field endLine uinteger +---The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. +---@field endCharacter? uinteger +---Describes the kind of the folding range such as `comment' or 'region'. The kind +---is used to categorize folding ranges and used by commands like 'Fold all comments'. +---See {@link FoldingRangeKind} for an enumeration of standardized kinds. +---@field kind? lsp.FoldingRangeKind +---The text that the client should show when the specified range is +---collapsed. If not defined or not supported by the client, a default +---will be chosen by the client. +--- +---@since 3.17.0 +---@field collapsedText? string + +---@class lsp.FoldingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@class lsp.DeclarationParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---@class lsp.DeclarationRegistrationOptions: lsp.DeclarationOptions, lsp.StaticRegistrationOptions + +---A parameter literal used in selection range requests. +---@class lsp.SelectionRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The positions inside the text document. +---@field positions lsp.Position[] + +---A selection range represents a part of a selection hierarchy. A selection range +---may have a parent selection range that contains it. +---@class lsp.SelectionRange +---The {@link Range range} of this selection range. +---@field range lsp.Range +---The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. +---@field parent? lsp.SelectionRange + +---@class lsp.SelectionRangeRegistrationOptions: lsp.SelectionRangeOptions, lsp.StaticRegistrationOptions + +---@class lsp.WorkDoneProgressCreateParams +---The token to be used to report progress. +---@field token lsp.ProgressToken + +---@class lsp.WorkDoneProgressCancelParams +---The token to be used to report progress. +---@field token lsp.ProgressToken + +---The parameter of a `textDocument/prepareCallHierarchy` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---Represents programming constructs like functions or constructors in the context +---of call hierarchy. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyItem +---The name of this item. +---@field name string +---The kind of this item. +---@field kind lsp.SymbolKind +---Tags for this item. +---@field tags? lsp.SymbolTag[] +---More detail for this item, e.g. the signature of a function. +---@field detail? string +---The resource identifier of this item. +---@field uri lsp.DocumentUri +---The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. +---Must be contained by the {@link CallHierarchyItem.range `range`}. +---@field selectionRange lsp.Range +---A data entry field that is preserved between a call hierarchy prepare and +---incoming calls or outgoing calls requests. +---@field data? lsp.LSPAny + +---Call hierarchy options used during static or dynamic registration. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameter of a `callHierarchy/incomingCalls` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyIncomingCallsParams +---@field item lsp.CallHierarchyItem + +---Represents an incoming call, e.g. a caller of a method or constructor. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyIncomingCall +---The item that makes the call. +---@field from lsp.CallHierarchyItem +---The ranges at which the calls appear. This is relative to the caller +---denoted by {@link CallHierarchyIncomingCall.from `this.from`}. +---@field fromRanges lsp.Range[] + +---The parameter of a `callHierarchy/outgoingCalls` request. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOutgoingCallsParams +---@field item lsp.CallHierarchyItem + +---Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOutgoingCall +---The item that is called. +---@field to lsp.CallHierarchyItem +---The range at which this item is called. This is the range relative to the caller, e.g the item +---passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`} +---and not {@link CallHierarchyOutgoingCall.to `this.to`}. +---@field fromRanges lsp.Range[] + +---@since 3.16.0 +---@class lsp.SemanticTokensParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---@since 3.16.0 +---@class lsp.SemanticTokens +---An optional result id. If provided and clients support delta updating +---the client will include the result id in the next semantic token request. +---A server can then instead of computing all semantic tokens again simply +---send a delta. +---@field resultId? string +---The actual tokens. +---@field data uinteger[] + +---@since 3.16.0 +---@class lsp.SemanticTokensPartialResult +---@field data uinteger[] + +---@since 3.16.0 +---@class lsp.SemanticTokensRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---@since 3.16.0 +---@class lsp.SemanticTokensDeltaParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The result id of a previous response. The result Id can either point to a full response +---or a delta response depending on what was received last. +---@field previousResultId string + +---@since 3.16.0 +---@class lsp.SemanticTokensDelta +---@field resultId? string +---The semantic token edits to transform a previous result into a new result. +---@field edits lsp.SemanticTokensEdit[] + +---@since 3.16.0 +---@class lsp.SemanticTokensDeltaPartialResult +---@field edits lsp.SemanticTokensEdit[] + +---@since 3.16.0 +---@class lsp.SemanticTokensRangeParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The range the semantic tokens are requested for. +---@field range lsp.Range + +---Params to show a resource in the UI. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentParams +---The uri to show. +---@field uri lsp.URI +---Indicates to show the resource in an external program. +---To show, for example, `https://code.visualstudio.com/` +---in the default WEB browser set `external` to `true`. +---@field external? boolean +---An optional property to indicate whether the editor +---showing the document should take focus or not. +---Clients might ignore this property if an external +---program is started. +---@field takeFocus? boolean +---An optional selection range if the document is a text +---document. Clients might ignore the property if an +---external program is started or the file is not a text +---file. +---@field selection? lsp.Range + +---The result of a showDocument request. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentResult +---A boolean indicating if the show was successful. +---@field success boolean + +---@class lsp.LinkedEditingRangeParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The result of a linked editing range request. +--- +---@since 3.16.0 +---@class lsp.LinkedEditingRanges +---A list of ranges that can be edited together. The ranges must have +---identical length and contain identical text content. The ranges cannot overlap. +---@field ranges lsp.Range[] +---An optional word pattern (regular expression) that describes valid contents for +---the given ranges. If no pattern is provided, the client configuration's word +---pattern will be used. +---@field wordPattern? string + +---@class lsp.LinkedEditingRangeRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameters sent in notifications/requests for user-initiated creation of +---files. +--- +---@since 3.16.0 +---@class lsp.CreateFilesParams +---An array of all files/folders created in this operation. +---@field files lsp.FileCreate[] + +---A workspace edit represents changes to many resources managed in the workspace. The edit +---should either provide `changes` or `documentChanges`. If documentChanges are present +---they are preferred over `changes` if the client can handle versioned document edits. +--- +---Since version 3.13.0 a workspace edit can contain resource operations as well. If resource +---operations are present clients need to execute the operations in the order in which they +---are provided. So a workspace edit for example can consist of the following two changes: +---(1) a create file a.txt and (2) a text document edit which insert text into file a.txt. +--- +---An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will +---cause failure of the operation. How the client recovers from the failure is described by +---the client capability: `workspace.workspaceEdit.failureHandling` +---@class lsp.WorkspaceEdit +---Holds changes to existing resources. +---@field changes? table<lsp.DocumentUri, lsp.TextEdit[]> +---Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes +---are either an array of `TextDocumentEdit`s to express changes to n different text documents +---where each text document edit addresses a specific version of a text document. Or it can contain +---above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. +--- +---Whether a client supports versioned document edits is expressed via +---`workspace.workspaceEdit.documentChanges` client capability. +--- +---If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then +---only plain `TextEdit`s using the `changes` property are supported. +---@field documentChanges? lsp.TextDocumentEdit|lsp.CreateFile|lsp.RenameFile|lsp.DeleteFile[] +---A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and +---delete file / folder operations. +--- +---Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`. +--- +---@since 3.16.0 +---@field changeAnnotations? table<lsp.ChangeAnnotationIdentifier, lsp.ChangeAnnotation> + +---The options to register for file operations. +--- +---@since 3.16.0 +---@class lsp.FileOperationRegistrationOptions +---The actual filters. +---@field filters lsp.FileOperationFilter[] + +---The parameters sent in notifications/requests for user-initiated renames of +---files. +--- +---@since 3.16.0 +---@class lsp.RenameFilesParams +---An array of all files/folders renamed in this operation. When a folder is renamed, only +---the folder will be included, and not its children. +---@field files lsp.FileRename[] + +---The parameters sent in notifications/requests for user-initiated deletes of +---files. +--- +---@since 3.16.0 +---@class lsp.DeleteFilesParams +---An array of all files/folders deleted in this operation. +---@field files lsp.FileDelete[] + +---@class lsp.MonikerParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Moniker definition to match LSIF 0.5 moniker definition. +--- +---@since 3.16.0 +---@class lsp.Moniker +---The scheme of the moniker. For example tsc or .Net +---@field scheme string +---The identifier of the moniker. The value is opaque in LSIF however +---schema owners are allowed to define the structure if they want. +---@field identifier string +---The scope in which the moniker is unique +---@field unique lsp.UniquenessLevel +---The moniker kind if known. +---@field kind? lsp.MonikerKind + +---@class lsp.MonikerRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameter of a `textDocument/prepareTypeHierarchy` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyPrepareParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---@since 3.17.0 +---@class lsp.TypeHierarchyItem +---The name of this item. +---@field name string +---The kind of this item. +---@field kind lsp.SymbolKind +---Tags for this item. +---@field tags? lsp.SymbolTag[] +---More detail for this item, e.g. the signature of a function. +---@field detail? string +---The resource identifier of this item. +---@field uri lsp.DocumentUri +---The range enclosing this symbol not including leading/trailing whitespace +---but everything else, e.g. comments and code. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being +---picked, e.g. the name of a function. Must be contained by the +---{@link TypeHierarchyItem.range `range`}. +---@field selectionRange lsp.Range +---A data entry field that is preserved between a type hierarchy prepare and +---supertypes or subtypes requests. It could also be used to identify the +---type hierarchy in the server, helping improve the performance on +---resolving supertypes and subtypes. +---@field data? lsp.LSPAny + +---Type hierarchy options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---The parameter of a `typeHierarchy/supertypes` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchySupertypesParams +---@field item lsp.TypeHierarchyItem + +---The parameter of a `typeHierarchy/subtypes` request. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchySubtypesParams +---@field item lsp.TypeHierarchyItem + +---A parameter literal used in inline value requests. +--- +---@since 3.17.0 +---@class lsp.InlineValueParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The document range for which inline values should be computed. +---@field range lsp.Range +---Additional information about the context in which inline values were +---requested. +---@field context lsp.InlineValueContext + +---Inline value options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.InlineValueRegistrationOptions: lsp.InlineValueOptions, lsp.StaticRegistrationOptions + +---A parameter literal used in inlay hint requests. +--- +---@since 3.17.0 +---@class lsp.InlayHintParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The document range for which inlay hints should be computed. +---@field range lsp.Range + +---Inlay hint information. +--- +---@since 3.17.0 +---@class lsp.InlayHint +---The position of this hint. +---@field position lsp.Position +---The label of this hint. A human readable string or an array of +---InlayHintLabelPart label parts. +--- +---*Note* that neither the string nor the label part can be empty. +---@field label string|lsp.InlayHintLabelPart[] +---The kind of this hint. Can be omitted in which case the client +---should fall back to a reasonable default. +---@field kind? lsp.InlayHintKind +---Optional text edits that are performed when accepting this inlay hint. +--- +---*Note* that edits are expected to change the document so that the inlay +---hint (or its nearest variant) is now part of the document and the inlay +---hint itself is now obsolete. +---@field textEdits? lsp.TextEdit[] +---The tooltip text when you hover over this item. +---@field tooltip? string|lsp.MarkupContent +---Render padding before the hint. +--- +---Note: Padding should use the editor's background color, not the +---background color of the hint itself. That means padding can be used +---to visually align/separate an inlay hint. +---@field paddingLeft? boolean +---Render padding after the hint. +--- +---Note: Padding should use the editor's background color, not the +---background color of the hint itself. That means padding can be used +---to visually align/separate an inlay hint. +---@field paddingRight? boolean +---A data entry field that is preserved on an inlay hint between +---a `textDocument/inlayHint` and a `inlayHint/resolve` request. +---@field data? lsp.LSPAny + +---Inlay hint options used during static or dynamic registration. +--- +---@since 3.17.0 +---@class lsp.InlayHintRegistrationOptions: lsp.InlayHintOptions, lsp.StaticRegistrationOptions + +---Parameters of the document diagnostic request. +--- +---@since 3.17.0 +---@class lsp.DocumentDiagnosticParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The additional identifier provided during registration. +---@field identifier? string +---The result id of a previous response if provided. +---@field previousResultId? string + +---A partial result for a document diagnostic report. +--- +---@since 3.17.0 +---@class lsp.DocumentDiagnosticReportPartialResult +---@field relatedDocuments table<lsp.DocumentUri, lsp.FullDocumentDiagnosticReport|lsp.UnchangedDocumentDiagnosticReport> + +---Cancellation data returned from a diagnostic request. +--- +---@since 3.17.0 +---@class lsp.DiagnosticServerCancellationData +---@field retriggerRequest boolean + +---Diagnostic registration options. +--- +---@since 3.17.0 +---@class lsp.DiagnosticRegistrationOptions: lsp.TextDocumentRegistrationOptions, lsp.StaticRegistrationOptions + +---Parameters of the workspace diagnostic request. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticParams +---The additional identifier provided during registration. +---@field identifier? string +---The currently known diagnostic reports with their +---previous result ids. +---@field previousResultIds lsp.PreviousResultId[] + +---A workspace diagnostic report. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticReport +---@field items lsp.WorkspaceDocumentDiagnosticReport[] + +---A partial result for a workspace diagnostic report. +--- +---@since 3.17.0 +---@class lsp.WorkspaceDiagnosticReportPartialResult +---@field items lsp.WorkspaceDocumentDiagnosticReport[] + +---The params sent in an open notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidOpenNotebookDocumentParams +---The notebook document that got opened. +---@field notebookDocument lsp.NotebookDocument +---The text documents that represent the content +---of a notebook cell. +---@field cellTextDocuments lsp.TextDocumentItem[] + +---The params sent in a change notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidChangeNotebookDocumentParams +---The notebook document that did change. The version number points +---to the version after all provided changes have been applied. If +---only the text document content of a cell changes the notebook version +---doesn't necessarily have to change. +---@field notebookDocument lsp.VersionedNotebookDocumentIdentifier +---The actual changes to the notebook document. +--- +---The changes describe single state changes to the notebook document. +---So if there are two changes c1 (at array index 0) and c2 (at array +---index 1) for a notebook in state S then c1 moves the notebook from +---S to S' and c2 from S' to S''. So c1 is computed on the state S and +---c2 is computed on the state S'. +--- +---To mirror the content of a notebook using change events use the following approach: +---- start with the same initial content +---- apply the 'notebookDocument/didChange' notifications in the order you receive them. +---- apply the `NotebookChangeEvent`s in a single notification in the order +--- you receive them. +---@field change lsp.NotebookDocumentChangeEvent + +---The params sent in a save notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidSaveNotebookDocumentParams +---The notebook document that got saved. +---@field notebookDocument lsp.NotebookDocumentIdentifier + +---The params sent in a close notebook document notification. +--- +---@since 3.17.0 +---@class lsp.DidCloseNotebookDocumentParams +---The notebook document that got closed. +---@field notebookDocument lsp.NotebookDocumentIdentifier +---The text documents that represent the content +---of a notebook cell that got closed. +---@field cellTextDocuments lsp.TextDocumentIdentifier[] + +---A parameter literal used in inline completion requests. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams +---Additional information about the context in which inline completions were +---requested. +---@field context lsp.InlineCompletionContext + +---Represents a collection of {@link InlineCompletionItem inline completion items} to be presented in the editor. +---@class lsp.InlineCompletionList +---The inline completion items +---@field items lsp.InlineCompletionItem[] + +---An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionItem +---The text to replace the range with. Must be set. +---@field insertText string +---The format of the insert text. The format applies to the `insertText`. If omitted defaults to `InsertTextFormat.PlainText`. +---@field insertTextFormat? lsp.InsertTextFormat +---A text that is used to decide if this inline completion should be shown. When `falsy` the {@link InlineCompletionItem.insertText} is used. +---@field filterText? string +---The range to replace. Must begin and end on the same line. +---@field range? lsp.Range +---An optional {@link Command} that is executed *after* inserting this completion. +---@field command? lsp.Command + +---Inline completion options used during static or dynamic registration. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionRegistrationOptions: lsp.InlineCompletionOptions, lsp.StaticRegistrationOptions + +---@class lsp.RegistrationParams +---@field registrations lsp.Registration[] + +---@class lsp.UnregistrationParams +---@field unregisterations lsp.Unregistration[] + +---@class lsp.InitializeParams: lsp._InitializeParams + +---The result returned from an initialize request. +---@class lsp.InitializeResult +---The capabilities the language server provides. +---@field capabilities lsp.ServerCapabilities +---Information about the server. +--- +---@since 3.15.0 +---@field serverInfo? anonym1 + +---The data type of the ResponseError if the +---initialize request fails. +---@class lsp.InitializeError +---Indicates whether the client execute the following retry logic: +---(1) show the message provided by the ResponseError to the user +---(2) user selects retry or cancel +---(3) if user selected retry the initialize method is sent again. +---@field retry boolean + +---@class lsp.InitializedParams + +---The parameters of a change configuration notification. +---@class lsp.DidChangeConfigurationParams +---The actual changed settings +---@field settings lsp.LSPAny + +---@class lsp.DidChangeConfigurationRegistrationOptions +---@field section? string|string[] + +---The parameters of a notification message. +---@class lsp.ShowMessageParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string + +---@class lsp.ShowMessageRequestParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string +---The message action items to present. +---@field actions? lsp.MessageActionItem[] + +---@class lsp.MessageActionItem +---A short title like 'Retry', 'Open Log' etc. +---@field title string + +---The log message parameters. +---@class lsp.LogMessageParams +---The message type. See {@link MessageType} +---@field type lsp.MessageType +---The actual message. +---@field message string + +---The parameters sent in an open text document notification +---@class lsp.DidOpenTextDocumentParams +---The document that was opened. +---@field textDocument lsp.TextDocumentItem + +---The change text document notification's parameters. +---@class lsp.DidChangeTextDocumentParams +---The document that did change. The version number points +---to the version after all provided content changes have +---been applied. +---@field textDocument lsp.VersionedTextDocumentIdentifier +---The actual content changes. The content changes describe single state changes +---to the document. So if there are two content changes c1 (at array index 0) and +---c2 (at array index 1) for a document in state S then c1 moves the document from +---S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed +---on the state S'. +--- +---To mirror the content of a document using change events use the following approach: +---- start with the same initial content +---- apply the 'textDocument/didChange' notifications in the order you receive them. +---- apply the `TextDocumentContentChangeEvent`s in a single notification in the order +--- you receive them. +---@field contentChanges lsp.TextDocumentContentChangeEvent[] + +---Describe options to be used when registered for text document change events. +---@class lsp.TextDocumentChangeRegistrationOptions: lsp.TextDocumentRegistrationOptions +---How documents are synced to the server. +---@field syncKind lsp.TextDocumentSyncKind + +---The parameters sent in a close text document notification +---@class lsp.DidCloseTextDocumentParams +---The document that was closed. +---@field textDocument lsp.TextDocumentIdentifier + +---The parameters sent in a save text document notification +---@class lsp.DidSaveTextDocumentParams +---The document that was saved. +---@field textDocument lsp.TextDocumentIdentifier +---Optional the content when saved. Depends on the includeText value +---when the save notification was requested. +---@field text? string + +---Save registration options. +---@class lsp.TextDocumentSaveRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters sent in a will save text document notification. +---@class lsp.WillSaveTextDocumentParams +---The document that will be saved. +---@field textDocument lsp.TextDocumentIdentifier +---The 'TextDocumentSaveReason'. +---@field reason lsp.TextDocumentSaveReason + +---A text edit applicable to a text document. +---@class lsp.TextEdit +---The range of the text document to be manipulated. To insert +---text into a document create a range where start === end. +---@field range lsp.Range +---The string to be inserted. For delete operations use an +---empty string. +---@field newText string + +---The watched files change notification's parameters. +---@class lsp.DidChangeWatchedFilesParams +---The actual file events. +---@field changes lsp.FileEvent[] + +---Describe options to be used when registered for text document change events. +---@class lsp.DidChangeWatchedFilesRegistrationOptions +---The watchers to register. +---@field watchers lsp.FileSystemWatcher[] + +---The publish diagnostic notification's parameters. +---@class lsp.PublishDiagnosticsParams +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---Optional the version number of the document the diagnostics are published for. +--- +---@since 3.15.0 +---@field version? integer +---An array of diagnostic information items. +---@field diagnostics lsp.Diagnostic[] + +---Completion parameters +---@class lsp.CompletionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams +---The completion context. This is only available it the client specifies +---to send this using the client capability `textDocument.completion.contextSupport === true` +---@field context? lsp.CompletionContext + +---A completion item represents a text snippet that is +---proposed to complete text that is being typed. +---@class lsp.CompletionItem +---The label of this completion item. +--- +---The label property is also by default the text that +---is inserted when selecting this completion. +--- +---If label details are provided the label itself should +---be an unqualified name of the completion item. +---@field label string +---Additional details for the label +--- +---@since 3.17.0 +---@field labelDetails? lsp.CompletionItemLabelDetails +---The kind of this completion item. Based of the kind +---an icon is chosen by the editor. +---@field kind? lsp.CompletionItemKind +---Tags for this completion item. +--- +---@since 3.15.0 +---@field tags? lsp.CompletionItemTag[] +---A human-readable string with additional information +---about this item, like type or symbol information. +---@field detail? string +---A human-readable string that represents a doc-comment. +---@field documentation? string|lsp.MarkupContent +---Indicates if this item is deprecated. +---@deprecated Use `tags` instead. +---@field deprecated? boolean +---Select this item when showing. +--- +---*Note* that only one completion item can be selected and that the +---tool / client decides which item that is. The rule is that the *first* +---item of those that match best is selected. +---@field preselect? boolean +---A string that should be used when comparing this item +---with other items. When `falsy` the {@link CompletionItem.label label} +---is used. +---@field sortText? string +---A string that should be used when filtering a set of +---completion items. When `falsy` the {@link CompletionItem.label label} +---is used. +---@field filterText? string +---A string that should be inserted into a document when selecting +---this completion. When `falsy` the {@link CompletionItem.label label} +---is used. +--- +---The `insertText` is subject to interpretation by the client side. +---Some tools might not take the string literally. For example +---VS Code when code complete is requested in this example +---`con<cursor position>` and a completion item with an `insertText` of +---`console` is provided it will only insert `sole`. Therefore it is +---recommended to use `textEdit` instead since it avoids additional client +---side interpretation. +---@field insertText? string +---The format of the insert text. The format applies to both the +---`insertText` property and the `newText` property of a provided +---`textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. +--- +---Please note that the insertTextFormat doesn't apply to +---`additionalTextEdits`. +---@field insertTextFormat? lsp.InsertTextFormat +---How whitespace and indentation is handled during completion +---item insertion. If not provided the clients default value depends on +---the `textDocument.completion.insertTextMode` client capability. +--- +---@since 3.16.0 +---@field insertTextMode? lsp.InsertTextMode +---An {@link TextEdit edit} which is applied to a document when selecting +---this completion. When an edit is provided the value of +---{@link CompletionItem.insertText insertText} is ignored. +--- +---Most editors support two different operations when accepting a completion +---item. One is to insert a completion text and the other is to replace an +---existing text with a completion text. Since this can usually not be +---predetermined by a server it can report both ranges. Clients need to +---signal support for `InsertReplaceEdits` via the +---`textDocument.completion.insertReplaceSupport` client capability +---property. +--- +---*Note 1:* The text edit's range as well as both ranges from an insert +---replace edit must be a [single line] and they must contain the position +---at which completion has been requested. +---*Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range +---must be a prefix of the edit's replace range, that means it must be +---contained and starting at the same position. +--- +---@since 3.16.0 additional type `InsertReplaceEdit` +---@field textEdit? lsp.TextEdit|lsp.InsertReplaceEdit +---The edit text used if the completion item is part of a CompletionList and +---CompletionList defines an item default for the text edit range. +--- +---Clients will only honor this property if they opt into completion list +---item defaults using the capability `completionList.itemDefaults`. +--- +---If not provided and a list's default range is provided the label +---property is used as a text. +--- +---@since 3.17.0 +---@field textEditText? string +---An optional array of additional {@link TextEdit text edits} that are applied when +---selecting this completion. Edits must not overlap (including the same insert position) +---with the main {@link CompletionItem.textEdit edit} nor with themselves. +--- +---Additional text edits should be used to change text unrelated to the current cursor position +---(for example adding an import statement at the top of the file if the completion item will +---insert an unqualified type). +---@field additionalTextEdits? lsp.TextEdit[] +---An optional set of characters that when pressed while this completion is active will accept it first and +---then type that character. *Note* that all commit characters should have `length=1` and that superfluous +---characters will be ignored. +---@field commitCharacters? string[] +---An optional {@link Command command} that is executed *after* inserting this completion. *Note* that +---additional modifications to the current document should be described with the +---{@link CompletionItem.additionalTextEdits additionalTextEdits}-property. +---@field command? lsp.Command +---A data entry field that is preserved on a completion item between a +---{@link CompletionRequest} and a {@link CompletionResolveRequest}. +---@field data? lsp.LSPAny + +---Represents a collection of {@link CompletionItem completion items} to be presented +---in the editor. +---@class lsp.CompletionList +---This list it not complete. Further typing results in recomputing this list. +--- +---Recomputed lists have all their items replaced (not appended) in the +---incomplete completion sessions. +---@field isIncomplete boolean +---In many cases the items of an actual completion result share the same +---value for properties like `commitCharacters` or the range of a text +---edit. A completion list can therefore define item defaults which will +---be used if a completion item itself doesn't specify the value. +--- +---If a completion list specifies a default value and a completion item +---also specifies a corresponding value the one from the item is used. +--- +---Servers are only allowed to return default values if the client +---signals support for this via the `completionList.itemDefaults` +---capability. +--- +---@since 3.17.0 +---@field itemDefaults? anonym3 +---The completion items. +---@field items lsp.CompletionItem[] + +---Registration options for a {@link CompletionRequest}. +---@class lsp.CompletionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link HoverRequest}. +---@class lsp.HoverParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The result of a hover request. +---@class lsp.Hover +---The hover's content +---@field contents lsp.MarkupContent|lsp.MarkedString|lsp.MarkedString[] +---An optional range inside the text document that is used to +---visualize the hover, e.g. by changing the background color. +---@field range? lsp.Range + +---Registration options for a {@link HoverRequest}. +---@class lsp.HoverRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams +---The signature help context. This is only available if the client specifies +---to send this using the client capability `textDocument.signatureHelp.contextSupport === true` +--- +---@since 3.15.0 +---@field context? lsp.SignatureHelpContext + +---Signature help represents the signature of something +---callable. There can be multiple signature but only one +---active and only one active parameter. +---@class lsp.SignatureHelp +---One or more signatures. +---@field signatures lsp.SignatureInformation[] +---The active signature. If omitted or the value lies outside the +---range of `signatures` the value defaults to zero or is ignored if +---the `SignatureHelp` has no signatures. +--- +---Whenever possible implementors should make an active decision about +---the active signature and shouldn't rely on a default value. +--- +---In future version of the protocol this property might become +---mandatory to better express this. +---@field activeSignature? uinteger +---The active parameter of the active signature. If omitted or the value +---lies outside the range of `signatures[activeSignature].parameters` +---defaults to 0 if the active signature has parameters. If +---the active signature has no parameters it is ignored. +---In future version of the protocol this property might become +---mandatory to better express the active parameter if the +---active signature does have any. +---@field activeParameter? uinteger + +---Registration options for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DefinitionRequest}. +---@class lsp.DefinitionParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---Registration options for a {@link DefinitionRequest}. +---@class lsp.DefinitionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link ReferencesRequest}. +---@class lsp.ReferenceParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams +---@field context lsp.ReferenceContext + +---Registration options for a {@link ReferencesRequest}. +---@class lsp.ReferenceRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams, lsp.PartialResultParams + +---A document highlight is a range inside a text document which deserves +---special attention. Usually a document highlight is visualized by changing +---the background color of its range. +---@class lsp.DocumentHighlight +---The range this highlight applies to. +---@field range lsp.Range +---The highlight kind, default is {@link DocumentHighlightKind.Text text}. +---@field kind? lsp.DocumentHighlightKind + +---Registration options for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---Parameters for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier + +---Represents information about programming constructs like variables, classes, +---interfaces etc. +---@class lsp.SymbolInformation: lsp.BaseSymbolInformation +---Indicates if this symbol is deprecated. +--- +---@deprecated Use tags instead +---@field deprecated? boolean +---The location of this symbol. The location's range is used by a tool +---to reveal the location in the editor. If the symbol is selected in the +---tool the range's start information is used to position the cursor. So +---the range usually spans more than the actual symbol's name and does +---normally include things like visibility modifiers. +--- +---The range doesn't have to denote a node range in the sense of an abstract +---syntax tree. It can therefore not be used to re-construct a hierarchy of +---the symbols. +---@field location lsp.Location + +---Represents programming constructs like variables, classes, interfaces etc. +---that appear in a document. Document symbols can be hierarchical and they +---have two ranges: one that encloses its definition and one that points to +---its most interesting range, e.g. the range of an identifier. +---@class lsp.DocumentSymbol +---The name of this symbol. Will be displayed in the user interface and therefore must not be +---an empty string or a string only consisting of white spaces. +---@field name string +---More detail for this symbol, e.g the signature of a function. +---@field detail? string +---The kind of this symbol. +---@field kind lsp.SymbolKind +---Tags for this document symbol. +--- +---@since 3.16.0 +---@field tags? lsp.SymbolTag[] +---Indicates if this symbol is deprecated. +--- +---@deprecated Use tags instead +---@field deprecated? boolean +---The range enclosing this symbol not including leading/trailing whitespace but everything else +---like comments. This information is typically used to determine if the clients cursor is +---inside the symbol to reveal in the symbol in the UI. +---@field range lsp.Range +---The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. +---Must be contained by the `range`. +---@field selectionRange lsp.Range +---Children of this symbol, e.g. properties of a class. +---@field children? lsp.DocumentSymbol[] + +---Registration options for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link CodeActionRequest}. +---@class lsp.CodeActionParams +---The document in which the command was invoked. +---@field textDocument lsp.TextDocumentIdentifier +---The range for which the command was invoked. +---@field range lsp.Range +---Context carrying additional information. +---@field context lsp.CodeActionContext + +---Represents a reference to a command. Provides a title which +---will be used to represent a command in the UI and, optionally, +---an array of arguments which will be passed to the command handler +---function when invoked. +---@class lsp.Command +---Title of the command, like `save`. +---@field title string +---The identifier of the actual command handler. +---@field command string +---Arguments that the command handler should be +---invoked with. +---@field arguments? lsp.LSPAny[] + +---A code action represents a change that can be performed in code, e.g. to fix a problem or +---to refactor code. +--- +---A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. +---@class lsp.CodeAction +---A short, human-readable, title for this code action. +---@field title string +---The kind of the code action. +--- +---Used to filter code actions. +---@field kind? lsp.CodeActionKind +---The diagnostics that this code action resolves. +---@field diagnostics? lsp.Diagnostic[] +---Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted +---by keybindings. +--- +---A quick fix should be marked preferred if it properly addresses the underlying error. +---A refactoring should be marked preferred if it is the most reasonable choice of actions to take. +--- +---@since 3.15.0 +---@field isPreferred? boolean +---Marks that the code action cannot currently be applied. +--- +---Clients should follow the following guidelines regarding disabled code actions: +--- +--- - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) +--- code action menus. +--- +--- - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type +--- of code action, such as refactorings. +--- +--- - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) +--- that auto applies a code action and only disabled code actions are returned, the client should show the user an +--- error message with `reason` in the editor. +--- +---@since 3.16.0 +---@field disabled? anonym4 +---The workspace edit this code action performs. +---@field edit? lsp.WorkspaceEdit +---A command this code action executes. If a code action +---provides an edit and a command, first the edit is +---executed and then the command. +---@field command? lsp.Command +---A data entry field that is preserved on a code action between +---a `textDocument/codeAction` and a `codeAction/resolve` request. +--- +---@since 3.16.0 +---@field data? lsp.LSPAny + +---Registration options for a {@link CodeActionRequest}. +---@class lsp.CodeActionRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolParams +---A query string to filter symbols by. Clients may send an empty +---string here to request all symbols. +---@field query string + +---A special workspace symbol that supports locations without a range. +--- +---See also SymbolInformation. +--- +---@since 3.17.0 +---@class lsp.WorkspaceSymbol: lsp.BaseSymbolInformation +---The location of the symbol. Whether a server is allowed to +---return a location without a range depends on the client +---capability `workspace.symbol.resolveSupport`. +--- +---See SymbolInformation#location for more details. +---@field location lsp.Location|anonym5 +---A data entry field that is preserved on a workspace symbol between a +---workspace symbol request and a workspace symbol resolve request. +---@field data? lsp.LSPAny + +---Registration options for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolRegistrationOptions: lsp.WorkspaceSymbolOptions + +---The parameters of a {@link CodeLensRequest}. +---@class lsp.CodeLensParams +---The document to request code lens for. +---@field textDocument lsp.TextDocumentIdentifier + +---A code lens represents a {@link Command command} that should be shown along with +---source text, like the number of references, a way to run tests, etc. +--- +---A code lens is _unresolved_ when no command is associated to it. For performance +---reasons the creation of a code lens and resolving should be done in two stages. +---@class lsp.CodeLens +---The range in which this code lens is valid. Should only span a single line. +---@field range lsp.Range +---The command this code lens represents. +---@field command? lsp.Command +---A data entry field that is preserved on a code lens item between +---a {@link CodeLensRequest} and a [CodeLensResolveRequest] +---(#CodeLensResolveRequest) +---@field data? lsp.LSPAny + +---Registration options for a {@link CodeLensRequest}. +---@class lsp.CodeLensRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkParams +---The document to provide document links for. +---@field textDocument lsp.TextDocumentIdentifier + +---A document link is a range in a text document that links to an internal or external resource, like another +---text document or a web site. +---@class lsp.DocumentLink +---The range this link applies to. +---@field range lsp.Range +---The uri this link points to. If missing a resolve request is sent later. +---@field target? lsp.URI +---The tooltip text when you hover over this link. +--- +---If a tooltip is provided, is will be displayed in a string that includes instructions on how to +---trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, +---user settings, and localization. +--- +---@since 3.15.0 +---@field tooltip? string +---A data entry field that is preserved on a document link between a +---DocumentLinkRequest and a DocumentLinkResolveRequest. +---@field data? lsp.LSPAny + +---Registration options for a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The format options. +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The range to format +---@field range lsp.Range +---The format options +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link DocumentRangesFormattingRequest}. +--- +---@since 3.18.0 +---@proposed +---@class lsp.DocumentRangesFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The ranges to format +---@field ranges lsp.Range[] +---The format options +---@field options lsp.FormattingOptions + +---The parameters of a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingParams +---The document to format. +---@field textDocument lsp.TextDocumentIdentifier +---The position around which the on type formatting should happen. +---This is not necessarily the exact position where the character denoted +---by the property `ch` got typed. +---@field position lsp.Position +---The character that has been typed that triggered the formatting +---on type request. That is not necessarily the last character that +---got inserted into the document since the client could auto insert +---characters as well (e.g. like automatic brace completion). +---@field ch string +---The formatting options. +---@field options lsp.FormattingOptions + +---Registration options for a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---The parameters of a {@link RenameRequest}. +---@class lsp.RenameParams +---The document to rename. +---@field textDocument lsp.TextDocumentIdentifier +---The position at which this request was sent. +---@field position lsp.Position +---The new name of the symbol. If the given name is not valid the +---request must return a {@link ResponseError} with an +---appropriate message set. +---@field newName string + +---Registration options for a {@link RenameRequest}. +---@class lsp.RenameRegistrationOptions: lsp.TextDocumentRegistrationOptions + +---@class lsp.PrepareRenameParams: lsp.TextDocumentPositionParams, lsp.WorkDoneProgressParams + +---The parameters of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandParams +---The identifier of the actual command handler. +---@field command string +---Arguments that the command should be invoked with. +---@field arguments? lsp.LSPAny[] + +---Registration options for a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandRegistrationOptions: lsp.ExecuteCommandOptions + +---The parameters passed via an apply workspace edit request. +---@class lsp.ApplyWorkspaceEditParams +---An optional label of the workspace edit. This label is +---presented in the user interface for example on an undo +---stack to undo the workspace edit. +---@field label? string +---The edits to apply. +---@field edit lsp.WorkspaceEdit + +---The result returned from the apply workspace edit request. +--- +---@since 3.17 renamed from ApplyWorkspaceEditResponse +---@class lsp.ApplyWorkspaceEditResult +---Indicates whether the edit was applied or not. +---@field applied boolean +---An optional textual description for why the edit was not applied. +---This may be used by the server for diagnostic logging or to provide +---a suitable error for a request that triggered the edit. +---@field failureReason? string +---Depending on the client's failure handling strategy `failedChange` might +---contain the index of the change that failed. This property is only available +---if the client signals a `failureHandlingStrategy` in its client capabilities. +---@field failedChange? uinteger + +---@class lsp.WorkDoneProgressBegin +---@field kind "begin" +---Mandatory title of the progress operation. Used to briefly inform about +---the kind of operation being performed. +--- +---Examples: "Indexing" or "Linking dependencies". +---@field title string +---Controls if a cancel button should show to allow the user to cancel the +---long running operation. Clients that don't support cancellation are allowed +---to ignore the setting. +---@field cancellable? boolean +---Optional, more detailed associated progress message. Contains +---complementary information to the `title`. +--- +---Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". +---If unset, the previous progress message (if any) is still valid. +---@field message? string +---Optional progress percentage to display (value 100 is considered 100%). +---If not provided infinite progress is assumed and clients are allowed +---to ignore the `percentage` value in subsequent in report notifications. +--- +---The value should be steadily rising. Clients are free to ignore values +---that are not following this rule. The value range is [0, 100]. +---@field percentage? uinteger + +---@class lsp.WorkDoneProgressReport +---@field kind "report" +---Controls enablement state of a cancel button. +--- +---Clients that don't support cancellation or don't support controlling the button's +---enablement state are allowed to ignore the property. +---@field cancellable? boolean +---Optional, more detailed associated progress message. Contains +---complementary information to the `title`. +--- +---Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". +---If unset, the previous progress message (if any) is still valid. +---@field message? string +---Optional progress percentage to display (value 100 is considered 100%). +---If not provided infinite progress is assumed and clients are allowed +---to ignore the `percentage` value in subsequent in report notifications. +--- +---The value should be steadily rising. Clients are free to ignore values +---that are not following this rule. The value range is [0, 100] +---@field percentage? uinteger + +---@class lsp.WorkDoneProgressEnd +---@field kind "end" +---Optional, a final message indicating to for example indicate the outcome +---of the operation. +---@field message? string + +---@class lsp.SetTraceParams +---@field value lsp.TraceValues + +---@class lsp.LogTraceParams +---@field message string +---@field verbose? string + +---@class lsp.CancelParams +---The request id to cancel. +---@field id integer|string + +---@class lsp.ProgressParams +---The progress token provided by the client or server. +---@field token lsp.ProgressToken +---The progress data. +---@field value lsp.LSPAny + +---A parameter literal used in requests to pass a text document and a position inside that +---document. +---@class lsp.TextDocumentPositionParams +---The text document. +---@field textDocument lsp.TextDocumentIdentifier +---The position inside the text document. +---@field position lsp.Position + +---@class lsp.WorkDoneProgressParams +---An optional token that a server can use to report work done progress. +---@field workDoneToken? lsp.ProgressToken + +---@class lsp.PartialResultParams +---An optional token that a server can use to report partial results (e.g. streaming) to +---the client. +---@field partialResultToken? lsp.ProgressToken + +---Represents the connection of two locations. Provides additional metadata over normal {@link Location locations}, +---including an origin range. +---@class lsp.LocationLink +---Span of the origin of this link. +--- +---Used as the underlined span for mouse interaction. Defaults to the word range at +---the definition position. +---@field originSelectionRange? lsp.Range +---The target resource identifier of this link. +---@field targetUri lsp.DocumentUri +---The full target range of this link. If the target for example is a symbol then target range is the +---range enclosing this symbol not including leading/trailing whitespace but everything else +---like comments. This information is typically used to highlight the range in the editor. +---@field targetRange lsp.Range +---The range that should be selected and revealed when this link is being followed, e.g the name of a function. +---Must be contained by the `targetRange`. See also `DocumentSymbol#range` +---@field targetSelectionRange lsp.Range + +---A range in a text document expressed as (zero-based) start and end positions. +--- +---If you want to specify a range that contains a line including the line ending +---character(s) then use an end position denoting the start of the next line. +---For example: +---```ts +---{ +--- start: { line: 5, character: 23 } +--- end : { line 6, character : 0 } +---} +---``` +---@class lsp.Range +---The range's start position. +---@field start lsp.Position +---The range's end position. +---@field end lsp.Position + +---@class lsp.ImplementationOptions + +---Static registration options to be returned in the initialize +---request. +---@class lsp.StaticRegistrationOptions +---The id used to register the request. The id can be used to deregister +---the request again. See also Registration#id. +---@field id? string + +---@class lsp.TypeDefinitionOptions + +---The workspace folder change event. +---@class lsp.WorkspaceFoldersChangeEvent +---The array of added workspace folders +---@field added lsp.WorkspaceFolder[] +---The array of the removed workspace folders +---@field removed lsp.WorkspaceFolder[] + +---@class lsp.ConfigurationItem +---The scope to get the configuration section for. +---@field scopeUri? string +---The configuration section asked for. +---@field section? string + +---A literal to identify a text document in the client. +---@class lsp.TextDocumentIdentifier +---The text document's uri. +---@field uri lsp.DocumentUri + +---Represents a color in RGBA space. +---@class lsp.Color +---The red component of this color in the range [0-1]. +---@field red decimal +---The green component of this color in the range [0-1]. +---@field green decimal +---The blue component of this color in the range [0-1]. +---@field blue decimal +---The alpha component of this color in the range [0-1]. +---@field alpha decimal + +---@class lsp.DocumentColorOptions + +---@class lsp.FoldingRangeOptions + +---@class lsp.DeclarationOptions + +---Position in a text document expressed as zero-based line and character +---offset. Prior to 3.17 the offsets were always based on a UTF-16 string +---representation. So a string of the form `a𐐀b` the character offset of the +---character `a` is 0, the character offset of `𐐀` is 1 and the character +---offset of b is 3 since `𐐀` is represented using two code units in UTF-16. +---Since 3.17 clients and servers can agree on a different string encoding +---representation (e.g. UTF-8). The client announces it's supported encoding +---via the client capability [`general.positionEncodings`](#clientCapabilities). +---The value is an array of position encodings the client supports, with +---decreasing preference (e.g. the encoding at index `0` is the most preferred +---one). To stay backwards compatible the only mandatory encoding is UTF-16 +---represented via the string `utf-16`. The server can pick one of the +---encodings offered by the client and signals that encoding back to the +---client via the initialize result's property +---[`capabilities.positionEncoding`](#serverCapabilities). If the string value +---`utf-16` is missing from the client's capability `general.positionEncodings` +---servers can safely assume that the client supports UTF-16. If the server +---omits the position encoding in its initialize result the encoding defaults +---to the string value `utf-16`. Implementation considerations: since the +---conversion from one encoding into another requires the content of the +---file / line the conversion is best done where the file is read which is +---usually on the server side. +--- +---Positions are line end character agnostic. So you can not specify a position +---that denotes `\r|\n` or `\n|` where `|` represents the character offset. +--- +---@since 3.17.0 - support for negotiated position encoding. +---@class lsp.Position +---Line position in a document (zero-based). +--- +---If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. +---If a line number is negative, it defaults to 0. +---@field line uinteger +---Character offset on a line in a document (zero-based). +--- +---The meaning of this offset is determined by the negotiated +---`PositionEncodingKind`. +--- +---If the character value is greater than the line length it defaults back to the +---line length. +---@field character uinteger + +---@class lsp.SelectionRangeOptions + +---Call hierarchy options used during static registration. +--- +---@since 3.16.0 +---@class lsp.CallHierarchyOptions + +---@since 3.16.0 +---@class lsp.SemanticTokensOptions +---The legend used by the server +---@field legend lsp.SemanticTokensLegend +---Server supports providing semantic tokens for a specific range +---of a document. +---@field range? boolean|anonym6 +---Server supports providing semantic tokens for a full document. +---@field full? boolean|anonym7 + +---@since 3.16.0 +---@class lsp.SemanticTokensEdit +---The start offset of the edit. +---@field start uinteger +---The count of elements to remove. +---@field deleteCount uinteger +---The elements to insert. +---@field data? uinteger[] + +---@class lsp.LinkedEditingRangeOptions + +---Represents information on a file/folder create. +--- +---@since 3.16.0 +---@class lsp.FileCreate +---A file:// URI for the location of the file/folder being created. +---@field uri string + +---Describes textual changes on a text document. A TextDocumentEdit describes all changes +---on a document version Si and after they are applied move the document to version Si+1. +---So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any +---kind of ordering. However the edits must be non overlapping. +---@class lsp.TextDocumentEdit +---The text document to change. +---@field textDocument lsp.OptionalVersionedTextDocumentIdentifier +---The edits to be applied. +--- +---@since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a +---client capability. +---@field edits lsp.TextEdit|lsp.AnnotatedTextEdit[] + +---Create file operation. +---@class lsp.CreateFile: lsp.ResourceOperation +---A create +---@field kind "create" +---The resource to create. +---@field uri lsp.DocumentUri +---Additional options +---@field options? lsp.CreateFileOptions + +---Rename file operation +---@class lsp.RenameFile: lsp.ResourceOperation +---A rename +---@field kind "rename" +---The old (existing) location. +---@field oldUri lsp.DocumentUri +---The new location. +---@field newUri lsp.DocumentUri +---Rename options. +---@field options? lsp.RenameFileOptions + +---Delete file operation +---@class lsp.DeleteFile: lsp.ResourceOperation +---A delete +---@field kind "delete" +---The file to delete. +---@field uri lsp.DocumentUri +---Delete options. +---@field options? lsp.DeleteFileOptions + +---Additional information that describes document changes. +--- +---@since 3.16.0 +---@class lsp.ChangeAnnotation +---A human-readable string describing the actual change. The string +---is rendered prominent in the user interface. +---@field label string +---A flag which indicates that user confirmation is needed +---before applying the change. +---@field needsConfirmation? boolean +---A human-readable string which is rendered less prominent in +---the user interface. +---@field description? string + +---A filter to describe in which file operation requests or notifications +---the server is interested in receiving. +--- +---@since 3.16.0 +---@class lsp.FileOperationFilter +---A Uri scheme like `file` or `untitled`. +---@field scheme? string +---The actual file operation pattern. +---@field pattern lsp.FileOperationPattern + +---Represents information on a file/folder rename. +--- +---@since 3.16.0 +---@class lsp.FileRename +---A file:// URI for the original location of the file/folder being renamed. +---@field oldUri string +---A file:// URI for the new location of the file/folder being renamed. +---@field newUri string + +---Represents information on a file/folder delete. +--- +---@since 3.16.0 +---@class lsp.FileDelete +---A file:// URI for the location of the file/folder being deleted. +---@field uri string + +---@class lsp.MonikerOptions + +---Type hierarchy options used during static registration. +--- +---@since 3.17.0 +---@class lsp.TypeHierarchyOptions + +---@since 3.17.0 +---@class lsp.InlineValueContext +---The stack frame (as a DAP Id) where the execution has stopped. +---@field frameId integer +---The document range where execution has stopped. +---Typically the end position of the range denotes the line where the inline values are shown. +---@field stoppedLocation lsp.Range + +---Provide inline value as text. +--- +---@since 3.17.0 +---@class lsp.InlineValueText +---The document range for which the inline value applies. +---@field range lsp.Range +---The text of the inline value. +---@field text string + +---Provide inline value through a variable lookup. +---If only a range is specified, the variable name will be extracted from the underlying document. +---An optional variable name can be used to override the extracted name. +--- +---@since 3.17.0 +---@class lsp.InlineValueVariableLookup +---The document range for which the inline value applies. +---The range is used to extract the variable name from the underlying document. +---@field range lsp.Range +---If specified the name of the variable to look up. +---@field variableName? string +---How to perform the lookup. +---@field caseSensitiveLookup boolean + +---Provide an inline value through an expression evaluation. +---If only a range is specified, the expression will be extracted from the underlying document. +---An optional expression can be used to override the extracted expression. +--- +---@since 3.17.0 +---@class lsp.InlineValueEvaluatableExpression +---The document range for which the inline value applies. +---The range is used to extract the evaluatable expression from the underlying document. +---@field range lsp.Range +---If specified the expression overrides the extracted expression. +---@field expression? string + +---Inline value options used during static registration. +--- +---@since 3.17.0 +---@class lsp.InlineValueOptions + +---An inlay hint label part allows for interactive and composite labels +---of inlay hints. +--- +---@since 3.17.0 +---@class lsp.InlayHintLabelPart +---The value of this label part. +---@field value string +---The tooltip text when you hover over this label part. Depending on +---the client capability `inlayHint.resolveSupport` clients might resolve +---this property late using the resolve request. +---@field tooltip? string|lsp.MarkupContent +---An optional source code location that represents this +---label part. +--- +---The editor will use this location for the hover and for code navigation +---features: This part will become a clickable link that resolves to the +---definition of the symbol at the given location (not necessarily the +---location itself), it shows the hover that shows at the given location, +---and it shows a context menu with further code navigation commands. +--- +---Depending on the client capability `inlayHint.resolveSupport` clients +---might resolve this property late using the resolve request. +---@field location? lsp.Location +---An optional command for this label part. +--- +---Depending on the client capability `inlayHint.resolveSupport` clients +---might resolve this property late using the resolve request. +---@field command? lsp.Command + +---A `MarkupContent` literal represents a string value which content is interpreted base on its +---kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. +--- +---If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. +---See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +---Here is an example how such a string can be constructed using JavaScript / TypeScript: +---```ts +---let markdown: MarkdownContent = { +--- kind: MarkupKind.Markdown, +--- value: [ +--- '# Header', +--- 'Some text', +--- '```typescript', +--- 'someCode();', +--- '```' +--- ].join('\n') +---}; +---``` +--- +---*Please Note* that clients might sanitize the return markdown. A client could decide to +---remove HTML from the markdown to avoid script execution. +---@class lsp.MarkupContent +---The type of the Markup +---@field kind lsp.MarkupKind +---The content itself +---@field value string + +---Inlay hint options used during static registration. +--- +---@since 3.17.0 +---@class lsp.InlayHintOptions +---The server provides support to resolve additional +---information for an inlay hint item. +---@field resolveProvider? boolean + +---A full diagnostic report with a set of related documents. +--- +---@since 3.17.0 +---@class lsp.RelatedFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport +---Diagnostics of related documents. This information is useful +---in programming languages where code in a file A can generate +---diagnostics in a file B which A depends on. An example of +---such a language is C/C++ where marco definitions in a file +---a.cpp and result in errors in a header file b.hpp. +--- +---@since 3.17.0 +---@field relatedDocuments? table<lsp.DocumentUri, lsp.FullDocumentDiagnosticReport|lsp.UnchangedDocumentDiagnosticReport> + +---An unchanged diagnostic report with a set of related documents. +--- +---@since 3.17.0 +---@class lsp.RelatedUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport +---Diagnostics of related documents. This information is useful +---in programming languages where code in a file A can generate +---diagnostics in a file B which A depends on. An example of +---such a language is C/C++ where marco definitions in a file +---a.cpp and result in errors in a header file b.hpp. +--- +---@since 3.17.0 +---@field relatedDocuments? table<lsp.DocumentUri, lsp.FullDocumentDiagnosticReport|lsp.UnchangedDocumentDiagnosticReport> + +---A diagnostic report with a full set of problems. +--- +---@since 3.17.0 +---@class lsp.FullDocumentDiagnosticReport +---A full document diagnostic report. +---@field kind "full" +---An optional result id. If provided it will +---be sent on the next diagnostic request for the +---same document. +---@field resultId? string +---The actual items. +---@field items lsp.Diagnostic[] + +---A diagnostic report indicating that the last returned +---report is still accurate. +--- +---@since 3.17.0 +---@class lsp.UnchangedDocumentDiagnosticReport +---A document diagnostic report indicating +---no changes to the last result. A server can +---only return `unchanged` if result ids are +---provided. +---@field kind "unchanged" +---A result id which will be sent on the next +---diagnostic request for the same document. +---@field resultId string + +---Diagnostic options. +--- +---@since 3.17.0 +---@class lsp.DiagnosticOptions +---An optional identifier under which the diagnostics are +---managed by the client. +---@field identifier? string +---Whether the language has inter file dependencies meaning that +---editing code in one file can result in a different diagnostic +---set in another file. Inter file dependencies are common for +---most programming languages and typically uncommon for linters. +---@field interFileDependencies boolean +---The server provides support for workspace diagnostics as well. +---@field workspaceDiagnostics boolean + +---A previous result id in a workspace pull request. +--- +---@since 3.17.0 +---@class lsp.PreviousResultId +---The URI for which the client knowns a +---result id. +---@field uri lsp.DocumentUri +---The value of the previous result id. +---@field value string + +---A notebook document. +--- +---@since 3.17.0 +---@class lsp.NotebookDocument +---The notebook document's uri. +---@field uri lsp.URI +---The type of the notebook. +---@field notebookType string +---The version number of this document (it will increase after each +---change, including undo/redo). +---@field version integer +---Additional metadata stored with the notebook +---document. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---The cells of a notebook. +---@field cells lsp.NotebookCell[] + +---An item to transfer a text document from the client to the +---server. +---@class lsp.TextDocumentItem +---The text document's uri. +---@field uri lsp.DocumentUri +---The text document's language identifier. +---@field languageId string +---The version number of this document (it will increase after each +---change, including undo/redo). +---@field version integer +---The content of the opened text document. +---@field text string + +---A versioned notebook document identifier. +--- +---@since 3.17.0 +---@class lsp.VersionedNotebookDocumentIdentifier +---The version number of this notebook document. +---@field version integer +---The notebook document's uri. +---@field uri lsp.URI + +---A change event for a notebook document. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentChangeEvent +---The changed meta data if any. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---Changes to cells +---@field cells? anonym10 + +---A literal to identify a notebook document in the client. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentIdentifier +---The notebook document's uri. +---@field uri lsp.URI + +---Provides information about the context in which an inline completion was requested. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionContext +---Describes how the inline completion was triggered. +---@field triggerKind lsp.InlineCompletionTriggerKind +---Provides information about the currently selected item in the autocomplete widget if it is visible. +---@field selectedCompletionInfo? lsp.SelectedCompletionInfo + +---Inline completion options used during static registration. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionOptions + +---General parameters to to register for an notification or to register a provider. +---@class lsp.Registration +---The id used to register the request. The id can be used to deregister +---the request again. +---@field id string +---The method / capability to register for. +---@field method string +---Options necessary for the registration. +---@field registerOptions? lsp.LSPAny + +---General parameters to unregister a request or notification. +---@class lsp.Unregistration +---The id used to unregister the request or notification. Usually an id +---provided during the register request. +---@field id string +---The method to unregister for. +---@field method string + +---The initialize parameters +---@class lsp._InitializeParams +---The process Id of the parent process that started +---the server. +--- +---Is `null` if the process has not been started by another process. +---If the parent process is not alive then the server should exit. +---@field processId integer|lsp.null +---Information about the client +--- +---@since 3.15.0 +---@field clientInfo? anonym11 +---The locale the client is currently showing the user interface +---in. This must not necessarily be the locale of the operating +---system. +--- +---Uses IETF language tags as the value's syntax +---(See https://en.wikipedia.org/wiki/IETF_language_tag) +--- +---@since 3.16.0 +---@field locale? string +---The rootPath of the workspace. Is null +---if no folder is open. +--- +---@deprecated in favour of rootUri. +---@field rootPath? string|lsp.null +---The rootUri of the workspace. Is null if no +---folder is open. If both `rootPath` and `rootUri` are set +---`rootUri` wins. +--- +---@deprecated in favour of workspaceFolders. +---@field rootUri lsp.DocumentUri|lsp.null +---The capabilities provided by the client (editor or tool) +---@field capabilities lsp.ClientCapabilities +---User provided initialization options. +---@field initializationOptions? lsp.LSPAny +---The initial trace setting. If omitted trace is disabled ('off'). +---@field trace? lsp.TraceValues + +---@class lsp.WorkspaceFoldersInitializeParams +---The workspace folders configured in the client when the server starts. +--- +---This property is only available if the client supports workspace folders. +---It can be `null` if the client supports workspace folders but none are +---configured. +--- +---@since 3.6.0 +---@field workspaceFolders? lsp.WorkspaceFolder[]|lsp.null + +---Defines the capabilities provided by a language +---server. +---@class lsp.ServerCapabilities +---The position encoding the server picked from the encodings offered +---by the client via the client capability `general.positionEncodings`. +--- +---If the client didn't provide any position encodings the only valid +---value that a server can return is 'utf-16'. +--- +---If omitted it defaults to 'utf-16'. +--- +---@since 3.17.0 +---@field positionEncoding? lsp.PositionEncodingKind +---Defines how text documents are synced. Is either a detailed structure +---defining each notification or for backwards compatibility the +---TextDocumentSyncKind number. +---@field textDocumentSync? lsp.TextDocumentSyncOptions|lsp.TextDocumentSyncKind +---Defines how notebook documents are synced. +--- +---@since 3.17.0 +---@field notebookDocumentSync? lsp.NotebookDocumentSyncOptions|lsp.NotebookDocumentSyncRegistrationOptions +---The server provides completion support. +---@field completionProvider? lsp.CompletionOptions +---The server provides hover support. +---@field hoverProvider? boolean|lsp.HoverOptions +---The server provides signature help support. +---@field signatureHelpProvider? lsp.SignatureHelpOptions +---The server provides Goto Declaration support. +---@field declarationProvider? boolean|lsp.DeclarationOptions|lsp.DeclarationRegistrationOptions +---The server provides goto definition support. +---@field definitionProvider? boolean|lsp.DefinitionOptions +---The server provides Goto Type Definition support. +---@field typeDefinitionProvider? boolean|lsp.TypeDefinitionOptions|lsp.TypeDefinitionRegistrationOptions +---The server provides Goto Implementation support. +---@field implementationProvider? boolean|lsp.ImplementationOptions|lsp.ImplementationRegistrationOptions +---The server provides find references support. +---@field referencesProvider? boolean|lsp.ReferenceOptions +---The server provides document highlight support. +---@field documentHighlightProvider? boolean|lsp.DocumentHighlightOptions +---The server provides document symbol support. +---@field documentSymbolProvider? boolean|lsp.DocumentSymbolOptions +---The server provides code actions. CodeActionOptions may only be +---specified if the client states that it supports +---`codeActionLiteralSupport` in its initial `initialize` request. +---@field codeActionProvider? boolean|lsp.CodeActionOptions +---The server provides code lens. +---@field codeLensProvider? lsp.CodeLensOptions +---The server provides document link support. +---@field documentLinkProvider? lsp.DocumentLinkOptions +---The server provides color provider support. +---@field colorProvider? boolean|lsp.DocumentColorOptions|lsp.DocumentColorRegistrationOptions +---The server provides workspace symbol support. +---@field workspaceSymbolProvider? boolean|lsp.WorkspaceSymbolOptions +---The server provides document formatting. +---@field documentFormattingProvider? boolean|lsp.DocumentFormattingOptions +---The server provides document range formatting. +---@field documentRangeFormattingProvider? boolean|lsp.DocumentRangeFormattingOptions +---The server provides document formatting on typing. +---@field documentOnTypeFormattingProvider? lsp.DocumentOnTypeFormattingOptions +---The server provides rename support. RenameOptions may only be +---specified if the client states that it supports +---`prepareSupport` in its initial `initialize` request. +---@field renameProvider? boolean|lsp.RenameOptions +---The server provides folding provider support. +---@field foldingRangeProvider? boolean|lsp.FoldingRangeOptions|lsp.FoldingRangeRegistrationOptions +---The server provides selection range support. +---@field selectionRangeProvider? boolean|lsp.SelectionRangeOptions|lsp.SelectionRangeRegistrationOptions +---The server provides execute command support. +---@field executeCommandProvider? lsp.ExecuteCommandOptions +---The server provides call hierarchy support. +--- +---@since 3.16.0 +---@field callHierarchyProvider? boolean|lsp.CallHierarchyOptions|lsp.CallHierarchyRegistrationOptions +---The server provides linked editing range support. +--- +---@since 3.16.0 +---@field linkedEditingRangeProvider? boolean|lsp.LinkedEditingRangeOptions|lsp.LinkedEditingRangeRegistrationOptions +---The server provides semantic tokens support. +--- +---@since 3.16.0 +---@field semanticTokensProvider? lsp.SemanticTokensOptions|lsp.SemanticTokensRegistrationOptions +---The server provides moniker support. +--- +---@since 3.16.0 +---@field monikerProvider? boolean|lsp.MonikerOptions|lsp.MonikerRegistrationOptions +---The server provides type hierarchy support. +--- +---@since 3.17.0 +---@field typeHierarchyProvider? boolean|lsp.TypeHierarchyOptions|lsp.TypeHierarchyRegistrationOptions +---The server provides inline values. +--- +---@since 3.17.0 +---@field inlineValueProvider? boolean|lsp.InlineValueOptions|lsp.InlineValueRegistrationOptions +---The server provides inlay hints. +--- +---@since 3.17.0 +---@field inlayHintProvider? boolean|lsp.InlayHintOptions|lsp.InlayHintRegistrationOptions +---The server has support for pull model diagnostics. +--- +---@since 3.17.0 +---@field diagnosticProvider? lsp.DiagnosticOptions|lsp.DiagnosticRegistrationOptions +---Inline completion options used during static registration. +--- +---@since 3.18.0 +---@field inlineCompletionProvider? boolean|lsp.InlineCompletionOptions +---Workspace specific server capabilities. +---@field workspace? anonym12 +---Experimental server capabilities. +---@field experimental? lsp.LSPAny + +---A text document identifier to denote a specific version of a text document. +---@class lsp.VersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier +---The version number of this document. +---@field version integer + +---Save options. +---@class lsp.SaveOptions +---The client is supposed to include the content on save. +---@field includeText? boolean + +---An event describing a file change. +---@class lsp.FileEvent +---The file's uri. +---@field uri lsp.DocumentUri +---The change type. +---@field type lsp.FileChangeType + +---@class lsp.FileSystemWatcher +---The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail. +--- +---@since 3.17.0 support for relative patterns. +---@field globPattern lsp.GlobPattern +---The kind of events of interest. If omitted it defaults +---to WatchKind.Create | WatchKind.Change | WatchKind.Delete +---which is 7. +---@field kind? lsp.WatchKind + +---Represents a diagnostic, such as a compiler error or warning. Diagnostic objects +---are only valid in the scope of a resource. +---@class lsp.Diagnostic +---The range at which the message applies +---@field range lsp.Range +---The diagnostic's severity. Can be omitted. If omitted it is up to the +---client to interpret diagnostics as error, warning, info or hint. +---@field severity? lsp.DiagnosticSeverity +---The diagnostic's code, which usually appear in the user interface. +---@field code? integer|string +---An optional property to describe the error code. +---Requires the code field (above) to be present/not null. +--- +---@since 3.16.0 +---@field codeDescription? lsp.CodeDescription +---A human-readable string describing the source of this +---diagnostic, e.g. 'typescript' or 'super lint'. It usually +---appears in the user interface. +---@field source? string +---The diagnostic's message. It usually appears in the user interface +---@field message string +---Additional metadata about the diagnostic. +--- +---@since 3.15.0 +---@field tags? lsp.DiagnosticTag[] +---An array of related diagnostic information, e.g. when symbol-names within +---a scope collide all definitions can be marked via this property. +---@field relatedInformation? lsp.DiagnosticRelatedInformation[] +---A data entry field that is preserved between a `textDocument/publishDiagnostics` +---notification and `textDocument/codeAction` request. +--- +---@since 3.16.0 +---@field data? lsp.LSPAny + +---Contains additional information about the context in which a completion request is triggered. +---@class lsp.CompletionContext +---How the completion was triggered. +---@field triggerKind lsp.CompletionTriggerKind +---The trigger character (a single character) that has trigger code complete. +---Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` +---@field triggerCharacter? string + +---Additional details for a completion item label. +--- +---@since 3.17.0 +---@class lsp.CompletionItemLabelDetails +---An optional string which is rendered less prominently directly after {@link CompletionItem.label label}, +---without any spacing. Should be used for function signatures and type annotations. +---@field detail? string +---An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used +---for fully qualified names and file paths. +---@field description? string + +---A special text edit to provide an insert and a replace operation. +--- +---@since 3.16.0 +---@class lsp.InsertReplaceEdit +---The string to be inserted. +---@field newText string +---The range if the insert is requested +---@field insert lsp.Range +---The range if the replace is requested. +---@field replace lsp.Range + +---Completion options. +---@class lsp.CompletionOptions +---Most tools trigger completion request automatically without explicitly requesting +---it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user +---starts to type an identifier. For example if the user types `c` in a JavaScript file +---code complete will automatically pop up present `console` besides others as a +---completion item. Characters that make up identifiers don't need to be listed here. +--- +---If code complete should automatically be trigger on characters not being valid inside +---an identifier (for example `.` in JavaScript) list them in `triggerCharacters`. +---@field triggerCharacters? string[] +---The list of all possible characters that commit a completion. This field can be used +---if clients don't support individual commit characters per completion item. See +---`ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` +--- +---If a server provides both `allCommitCharacters` and commit characters on an individual +---completion item the ones on the completion item win. +--- +---@since 3.2.0 +---@field allCommitCharacters? string[] +---The server provides support to resolve additional +---information for a completion item. +---@field resolveProvider? boolean +---The server supports the following `CompletionItem` specific +---capabilities. +--- +---@since 3.17.0 +---@field completionItem? anonym13 + +---Hover options. +---@class lsp.HoverOptions + +---Additional information about the context in which a signature help request was triggered. +--- +---@since 3.15.0 +---@class lsp.SignatureHelpContext +---Action that caused signature help to be triggered. +---@field triggerKind lsp.SignatureHelpTriggerKind +---Character that caused signature help to be triggered. +--- +---This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` +---@field triggerCharacter? string +---`true` if signature help was already showing when it was triggered. +--- +---Retriggers occurs when the signature help is already active and can be caused by actions such as +---typing a trigger character, a cursor move, or document content changes. +---@field isRetrigger boolean +---The currently active `SignatureHelp`. +--- +---The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on +---the user navigating through available signatures. +---@field activeSignatureHelp? lsp.SignatureHelp + +---Represents the signature of something callable. A signature +---can have a label, like a function-name, a doc-comment, and +---a set of parameters. +---@class lsp.SignatureInformation +---The label of this signature. Will be shown in +---the UI. +---@field label string +---The human-readable doc-comment of this signature. Will be shown +---in the UI but can be omitted. +---@field documentation? string|lsp.MarkupContent +---The parameters of this signature. +---@field parameters? lsp.ParameterInformation[] +---The index of the active parameter. +--- +---If provided, this is used in place of `SignatureHelp.activeParameter`. +--- +---@since 3.16.0 +---@field activeParameter? uinteger + +---Server Capabilities for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpOptions +---List of characters that trigger signature help automatically. +---@field triggerCharacters? string[] +---List of characters that re-trigger signature help. +--- +---These trigger characters are only active when signature help is already showing. All trigger characters +---are also counted as re-trigger characters. +--- +---@since 3.15.0 +---@field retriggerCharacters? string[] + +---Server Capabilities for a {@link DefinitionRequest}. +---@class lsp.DefinitionOptions + +---Value-object that contains additional information when +---requesting references. +---@class lsp.ReferenceContext +---Include the declaration of the current symbol. +---@field includeDeclaration boolean + +---Reference options. +---@class lsp.ReferenceOptions + +---Provider options for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightOptions + +---A base for all symbol information. +---@class lsp.BaseSymbolInformation +---The name of this symbol. +---@field name string +---The kind of this symbol. +---@field kind lsp.SymbolKind +---Tags for this symbol. +--- +---@since 3.16.0 +---@field tags? lsp.SymbolTag[] +---The name of the symbol containing this symbol. This information is for +---user interface purposes (e.g. to render a qualifier in the user interface +---if necessary). It can't be used to re-infer a hierarchy for the document +---symbols. +---@field containerName? string + +---Provider options for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolOptions +---A human-readable string that is shown when multiple outlines trees +---are shown for the same document. +--- +---@since 3.16.0 +---@field label? string + +---Contains additional diagnostic information about the context in which +---a {@link CodeActionProvider.provideCodeActions code action} is run. +---@class lsp.CodeActionContext +---An array of diagnostics known on the client side overlapping the range provided to the +---`textDocument/codeAction` request. They are provided so that the server knows which +---errors are currently presented to the user for the given range. There is no guarantee +---that these accurately reflect the error state of the resource. The primary parameter +---to compute code actions is the provided range. +---@field diagnostics lsp.Diagnostic[] +---Requested kind of actions to return. +--- +---Actions not of this kind are filtered out by the client before being shown. So servers +---can omit computing them. +---@field only? lsp.CodeActionKind[] +---The reason why code actions were requested. +--- +---@since 3.17.0 +---@field triggerKind? lsp.CodeActionTriggerKind + +---Provider options for a {@link CodeActionRequest}. +---@class lsp.CodeActionOptions +---CodeActionKinds that this server may return. +--- +---The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server +---may list out every specific kind they provide. +---@field codeActionKinds? lsp.CodeActionKind[] +---The server provides support to resolve additional +---information for a code action. +--- +---@since 3.16.0 +---@field resolveProvider? boolean + +---Server capabilities for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolOptions +---The server provides support to resolve additional +---information for a workspace symbol. +--- +---@since 3.17.0 +---@field resolveProvider? boolean + +---Code Lens provider options of a {@link CodeLensRequest}. +---@class lsp.CodeLensOptions +---Code lens has a resolve provider as well. +---@field resolveProvider? boolean + +---Provider options for a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkOptions +---Document links have a resolve provider as well. +---@field resolveProvider? boolean + +---Value-object describing what options formatting should use. +---@class lsp.FormattingOptions +---Size of a tab in spaces. +---@field tabSize uinteger +---Prefer spaces over tabs. +---@field insertSpaces boolean +---Trim trailing whitespace on a line. +--- +---@since 3.15.0 +---@field trimTrailingWhitespace? boolean +---Insert a newline character at the end of the file if one does not exist. +--- +---@since 3.15.0 +---@field insertFinalNewline? boolean +---Trim all newlines after the final newline at the end of the file. +--- +---@since 3.15.0 +---@field trimFinalNewlines? boolean + +---Provider options for a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingOptions + +---Provider options for a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingOptions +---Whether the server supports formatting multiple ranges at once. +--- +---@since 3.18.0 +---@proposed +---@field rangesSupport? boolean + +---Provider options for a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingOptions +---A character on which formatting should be triggered, like `{`. +---@field firstTriggerCharacter string +---More trigger characters. +---@field moreTriggerCharacter? string[] + +---Provider options for a {@link RenameRequest}. +---@class lsp.RenameOptions +---Renames should be checked and tested before being executed. +--- +---@since version 3.12.0 +---@field prepareProvider? boolean + +---The server capabilities of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandOptions +---The commands to be executed on the server +---@field commands string[] + +---@since 3.16.0 +---@class lsp.SemanticTokensLegend +---The token types a server uses. +---@field tokenTypes string[] +---The token modifiers a server uses. +---@field tokenModifiers string[] + +---A text document identifier to optionally denote a specific version of a text document. +---@class lsp.OptionalVersionedTextDocumentIdentifier: lsp.TextDocumentIdentifier +---The version number of this document. If a versioned text document identifier +---is sent from the server to the client and the file is not open in the editor +---(the server has not received an open notification before) the server can send +---`null` to indicate that the version is unknown and the content on disk is the +---truth (as specified with document content ownership). +---@field version integer|lsp.null + +---A special text edit with an additional change annotation. +--- +---@since 3.16.0. +---@class lsp.AnnotatedTextEdit: lsp.TextEdit +---The actual identifier of the change annotation +---@field annotationId lsp.ChangeAnnotationIdentifier + +---A generic resource operation. +---@class lsp.ResourceOperation +---The resource operation kind. +---@field kind string +---An optional annotation identifier describing the operation. +--- +---@since 3.16.0 +---@field annotationId? lsp.ChangeAnnotationIdentifier + +---Options to create a file. +---@class lsp.CreateFileOptions +---Overwrite existing file. Overwrite wins over `ignoreIfExists` +---@field overwrite? boolean +---Ignore if exists. +---@field ignoreIfExists? boolean + +---Rename file options +---@class lsp.RenameFileOptions +---Overwrite target if existing. Overwrite wins over `ignoreIfExists` +---@field overwrite? boolean +---Ignores if target exists. +---@field ignoreIfExists? boolean + +---Delete file options +---@class lsp.DeleteFileOptions +---Delete the content recursively if a folder is denoted. +---@field recursive? boolean +---Ignore the operation if the file doesn't exist. +---@field ignoreIfNotExists? boolean + +---A pattern to describe in which file operation requests or notifications +---the server is interested in receiving. +--- +---@since 3.16.0 +---@class lsp.FileOperationPattern +---The glob pattern to match. Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +---@field glob string +---Whether to match files or folders with this pattern. +--- +---Matches both if undefined. +---@field matches? lsp.FileOperationPatternKind +---Additional options used during matching. +---@field options? lsp.FileOperationPatternOptions + +---A full document diagnostic report for a workspace diagnostic result. +--- +---@since 3.17.0 +---@class lsp.WorkspaceFullDocumentDiagnosticReport: lsp.FullDocumentDiagnosticReport +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---The version number for which the diagnostics are reported. +---If the document is not marked as open `null` can be provided. +---@field version integer|lsp.null + +---An unchanged document diagnostic report for a workspace diagnostic result. +--- +---@since 3.17.0 +---@class lsp.WorkspaceUnchangedDocumentDiagnosticReport: lsp.UnchangedDocumentDiagnosticReport +---The URI for which diagnostic information is reported. +---@field uri lsp.DocumentUri +---The version number for which the diagnostics are reported. +---If the document is not marked as open `null` can be provided. +---@field version integer|lsp.null + +---A notebook cell. +--- +---A cell's document URI must be unique across ALL notebook +---cells and can therefore be used to uniquely identify a +---notebook cell or the cell's text document. +--- +---@since 3.17.0 +---@class lsp.NotebookCell +---The cell's kind +---@field kind lsp.NotebookCellKind +---The URI of the cell's text document +---content. +---@field document lsp.DocumentUri +---Additional metadata stored with the cell. +--- +---Note: should always be an object literal (e.g. LSPObject) +---@field metadata? lsp.LSPObject +---Additional execution summary information +---if supported by the client. +---@field executionSummary? lsp.ExecutionSummary + +---A change describing how to move a `NotebookCell` +---array from state S to S'. +--- +---@since 3.17.0 +---@class lsp.NotebookCellArrayChange +---The start oftest of the cell that changed. +---@field start uinteger +---The deleted cells +---@field deleteCount uinteger +---The new cells, if any +---@field cells? lsp.NotebookCell[] + +---Describes the currently selected completion item. +--- +---@since 3.18.0 +---@class lsp.SelectedCompletionInfo +---The range that will be replaced if this completion item is accepted. +---@field range lsp.Range +---The text the range will be replaced with if this completion is accepted. +---@field text string + +---Defines the capabilities provided by the client. +---@class lsp.ClientCapabilities +---Workspace specific client capabilities. +---@field workspace? lsp.WorkspaceClientCapabilities +---Text document specific client capabilities. +---@field textDocument? lsp.TextDocumentClientCapabilities +---Capabilities specific to the notebook document support. +--- +---@since 3.17.0 +---@field notebookDocument? lsp.NotebookDocumentClientCapabilities +---Window specific client capabilities. +---@field window? lsp.WindowClientCapabilities +---General client capabilities. +--- +---@since 3.16.0 +---@field general? lsp.GeneralClientCapabilities +---Experimental client capabilities. +---@field experimental? lsp.LSPAny + +---@class lsp.TextDocumentSyncOptions +---Open and close notifications are sent to the server. If omitted open close notification should not +---be sent. +---@field openClose? boolean +---Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full +---and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None. +---@field change? lsp.TextDocumentSyncKind +---If present will save notifications are sent to the server. If omitted the notification should not be +---sent. +---@field willSave? boolean +---If present will save wait until requests are sent to the server. If omitted the request should not be +---sent. +---@field willSaveWaitUntil? boolean +---If present save notifications are sent to the server. If omitted the notification should not be +---sent. +---@field save? boolean|lsp.SaveOptions + +---Options specific to a notebook plus its cells +---to be synced to the server. +--- +---If a selector provides a notebook document +---filter but no cell selector all cells of a +---matching notebook document will be synced. +--- +---If a selector provides no notebook document +---filter but only a cell selector all notebook +---document that contain at least one matching +---cell will be synced. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncOptions +---The notebooks to be synced +---@field notebookSelector anonym15|anonym17[] +---Whether save notification should be forwarded to +---the server. Will only be honored if mode === `notebook`. +---@field save? boolean + +---Registration options specific to a notebook. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncRegistrationOptions: lsp.NotebookDocumentSyncOptions, lsp.StaticRegistrationOptions + +---@class lsp.WorkspaceFoldersServerCapabilities +---The server has support for workspace folders +---@field supported? boolean +---Whether the server wants to receive workspace folder +---change notifications. +--- +---If a string is provided the string is treated as an ID +---under which the notification is registered on the client +---side. The ID can be used to unregister for these events +---using the `client/unregisterCapability` request. +---@field changeNotifications? string|boolean + +---Options for notifications/requests for user operations on files. +--- +---@since 3.16.0 +---@class lsp.FileOperationOptions +---The server is interested in receiving didCreateFiles notifications. +---@field didCreate? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willCreateFiles requests. +---@field willCreate? lsp.FileOperationRegistrationOptions +---The server is interested in receiving didRenameFiles notifications. +---@field didRename? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willRenameFiles requests. +---@field willRename? lsp.FileOperationRegistrationOptions +---The server is interested in receiving didDeleteFiles file notifications. +---@field didDelete? lsp.FileOperationRegistrationOptions +---The server is interested in receiving willDeleteFiles file requests. +---@field willDelete? lsp.FileOperationRegistrationOptions + +---Structure to capture a description for an error code. +--- +---@since 3.16.0 +---@class lsp.CodeDescription +---An URI to open with more information about the diagnostic error. +---@field href lsp.URI + +---Represents a related message and source code location for a diagnostic. This should be +---used to point to code locations that cause or related to a diagnostics, e.g when duplicating +---a symbol in a scope. +---@class lsp.DiagnosticRelatedInformation +---The location of this related diagnostic information. +---@field location lsp.Location +---The message of this related diagnostic information. +---@field message string + +---Represents a parameter of a callable-signature. A parameter can +---have a label and a doc-comment. +---@class lsp.ParameterInformation +---The label of this parameter information. +--- +---Either a string or an inclusive start and exclusive end offsets within its containing +---signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 +---string representation as `Position` and `Range` does. +--- +---*Note*: a label of type string should be a substring of its containing signature label. +---Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. +---@field label string|{ [1]: uinteger, [2]: uinteger } +---The human-readable doc-comment of this parameter. Will be shown +---in the UI but can be omitted. +---@field documentation? string|lsp.MarkupContent + +---A notebook cell text document filter denotes a cell text +---document by different properties. +--- +---@since 3.17.0 +---@class lsp.NotebookCellTextDocumentFilter +---A filter that matches against the notebook +---containing the notebook cell. If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook string|lsp.NotebookDocumentFilter +---A language id like `python`. +--- +---Will be matched against the language id of the +---notebook cell document. '*' matches every language. +---@field language? string + +---Matching options for the file operation pattern. +--- +---@since 3.16.0 +---@class lsp.FileOperationPatternOptions +---The pattern should be matched ignoring casing. +---@field ignoreCase? boolean + +---@class lsp.ExecutionSummary +---A strict monotonically increasing value +---indicating the execution order of a cell +---inside a notebook. +---@field executionOrder uinteger +---Whether the execution was successful or +---not if known by the client. +---@field success? boolean + +---Workspace specific client capabilities. +---@class lsp.WorkspaceClientCapabilities +---The client supports applying batch edits +---to the workspace by supporting the request +---'workspace/applyEdit' +---@field applyEdit? boolean +---Capabilities specific to `WorkspaceEdit`s. +---@field workspaceEdit? lsp.WorkspaceEditClientCapabilities +---Capabilities specific to the `workspace/didChangeConfiguration` notification. +---@field didChangeConfiguration? lsp.DidChangeConfigurationClientCapabilities +---Capabilities specific to the `workspace/didChangeWatchedFiles` notification. +---@field didChangeWatchedFiles? lsp.DidChangeWatchedFilesClientCapabilities +---Capabilities specific to the `workspace/symbol` request. +---@field symbol? lsp.WorkspaceSymbolClientCapabilities +---Capabilities specific to the `workspace/executeCommand` request. +---@field executeCommand? lsp.ExecuteCommandClientCapabilities +---The client has support for workspace folders. +--- +---@since 3.6.0 +---@field workspaceFolders? boolean +---The client supports `workspace/configuration` requests. +--- +---@since 3.6.0 +---@field configuration? boolean +---Capabilities specific to the semantic token requests scoped to the +---workspace. +--- +---@since 3.16.0. +---@field semanticTokens? lsp.SemanticTokensWorkspaceClientCapabilities +---Capabilities specific to the code lens requests scoped to the +---workspace. +--- +---@since 3.16.0. +---@field codeLens? lsp.CodeLensWorkspaceClientCapabilities +---The client has support for file notifications/requests for user operations on files. +--- +---Since 3.16.0 +---@field fileOperations? lsp.FileOperationClientCapabilities +---Capabilities specific to the inline values requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field inlineValue? lsp.InlineValueWorkspaceClientCapabilities +---Capabilities specific to the inlay hint requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field inlayHint? lsp.InlayHintWorkspaceClientCapabilities +---Capabilities specific to the diagnostic requests scoped to the +---workspace. +--- +---@since 3.17.0. +---@field diagnostics? lsp.DiagnosticWorkspaceClientCapabilities + +---Text document specific client capabilities. +---@class lsp.TextDocumentClientCapabilities +---Defines which synchronization capabilities the client supports. +---@field synchronization? lsp.TextDocumentSyncClientCapabilities +---Capabilities specific to the `textDocument/completion` request. +---@field completion? lsp.CompletionClientCapabilities +---Capabilities specific to the `textDocument/hover` request. +---@field hover? lsp.HoverClientCapabilities +---Capabilities specific to the `textDocument/signatureHelp` request. +---@field signatureHelp? lsp.SignatureHelpClientCapabilities +---Capabilities specific to the `textDocument/declaration` request. +--- +---@since 3.14.0 +---@field declaration? lsp.DeclarationClientCapabilities +---Capabilities specific to the `textDocument/definition` request. +---@field definition? lsp.DefinitionClientCapabilities +---Capabilities specific to the `textDocument/typeDefinition` request. +--- +---@since 3.6.0 +---@field typeDefinition? lsp.TypeDefinitionClientCapabilities +---Capabilities specific to the `textDocument/implementation` request. +--- +---@since 3.6.0 +---@field implementation? lsp.ImplementationClientCapabilities +---Capabilities specific to the `textDocument/references` request. +---@field references? lsp.ReferenceClientCapabilities +---Capabilities specific to the `textDocument/documentHighlight` request. +---@field documentHighlight? lsp.DocumentHighlightClientCapabilities +---Capabilities specific to the `textDocument/documentSymbol` request. +---@field documentSymbol? lsp.DocumentSymbolClientCapabilities +---Capabilities specific to the `textDocument/codeAction` request. +---@field codeAction? lsp.CodeActionClientCapabilities +---Capabilities specific to the `textDocument/codeLens` request. +---@field codeLens? lsp.CodeLensClientCapabilities +---Capabilities specific to the `textDocument/documentLink` request. +---@field documentLink? lsp.DocumentLinkClientCapabilities +---Capabilities specific to the `textDocument/documentColor` and the +---`textDocument/colorPresentation` request. +--- +---@since 3.6.0 +---@field colorProvider? lsp.DocumentColorClientCapabilities +---Capabilities specific to the `textDocument/formatting` request. +---@field formatting? lsp.DocumentFormattingClientCapabilities +---Capabilities specific to the `textDocument/rangeFormatting` request. +---@field rangeFormatting? lsp.DocumentRangeFormattingClientCapabilities +---Capabilities specific to the `textDocument/onTypeFormatting` request. +---@field onTypeFormatting? lsp.DocumentOnTypeFormattingClientCapabilities +---Capabilities specific to the `textDocument/rename` request. +---@field rename? lsp.RenameClientCapabilities +---Capabilities specific to the `textDocument/foldingRange` request. +--- +---@since 3.10.0 +---@field foldingRange? lsp.FoldingRangeClientCapabilities +---Capabilities specific to the `textDocument/selectionRange` request. +--- +---@since 3.15.0 +---@field selectionRange? lsp.SelectionRangeClientCapabilities +---Capabilities specific to the `textDocument/publishDiagnostics` notification. +---@field publishDiagnostics? lsp.PublishDiagnosticsClientCapabilities +---Capabilities specific to the various call hierarchy requests. +--- +---@since 3.16.0 +---@field callHierarchy? lsp.CallHierarchyClientCapabilities +---Capabilities specific to the various semantic token request. +--- +---@since 3.16.0 +---@field semanticTokens? lsp.SemanticTokensClientCapabilities +---Capabilities specific to the `textDocument/linkedEditingRange` request. +--- +---@since 3.16.0 +---@field linkedEditingRange? lsp.LinkedEditingRangeClientCapabilities +---Client capabilities specific to the `textDocument/moniker` request. +--- +---@since 3.16.0 +---@field moniker? lsp.MonikerClientCapabilities +---Capabilities specific to the various type hierarchy requests. +--- +---@since 3.17.0 +---@field typeHierarchy? lsp.TypeHierarchyClientCapabilities +---Capabilities specific to the `textDocument/inlineValue` request. +--- +---@since 3.17.0 +---@field inlineValue? lsp.InlineValueClientCapabilities +---Capabilities specific to the `textDocument/inlayHint` request. +--- +---@since 3.17.0 +---@field inlayHint? lsp.InlayHintClientCapabilities +---Capabilities specific to the diagnostic pull model. +--- +---@since 3.17.0 +---@field diagnostic? lsp.DiagnosticClientCapabilities +---Client capabilities specific to inline completions. +--- +---@since 3.18.0 +---@field inlineCompletion? lsp.InlineCompletionClientCapabilities + +---Capabilities specific to the notebook document support. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentClientCapabilities +---Capabilities specific to notebook document synchronization +--- +---@since 3.17.0 +---@field synchronization lsp.NotebookDocumentSyncClientCapabilities + +---@class lsp.WindowClientCapabilities +---It indicates whether the client supports server initiated +---progress using the `window/workDoneProgress/create` request. +--- +---The capability also controls Whether client supports handling +---of progress notifications. If set servers are allowed to report a +---`workDoneProgress` property in the request specific server +---capabilities. +--- +---@since 3.15.0 +---@field workDoneProgress? boolean +---Capabilities specific to the showMessage request. +--- +---@since 3.16.0 +---@field showMessage? lsp.ShowMessageRequestClientCapabilities +---Capabilities specific to the showDocument request. +--- +---@since 3.16.0 +---@field showDocument? lsp.ShowDocumentClientCapabilities + +---General client capabilities. +--- +---@since 3.16.0 +---@class lsp.GeneralClientCapabilities +---Client capability that signals how the client +---handles stale requests (e.g. a request +---for which the client will not process the response +---anymore since the information is outdated). +--- +---@since 3.17.0 +---@field staleRequestSupport? anonym18 +---Client capabilities specific to regular expressions. +--- +---@since 3.16.0 +---@field regularExpressions? lsp.RegularExpressionsClientCapabilities +---Client capabilities specific to the client's markdown parser. +--- +---@since 3.16.0 +---@field markdown? lsp.MarkdownClientCapabilities +---The position encodings supported by the client. Client and server +---have to agree on the same position encoding to ensure that offsets +---(e.g. character position in a line) are interpreted the same on both +---sides. +--- +---To keep the protocol backwards compatible the following applies: if +---the value 'utf-16' is missing from the array of position encodings +---servers can assume that the client supports UTF-16. UTF-16 is +---therefore a mandatory encoding. +--- +---If omitted it defaults to ['utf-16']. +--- +---Implementation considerations: since the conversion from one encoding +---into another requires the content of the file / line the conversion +---is best done where the file is read which is usually on the server +---side. +--- +---@since 3.17.0 +---@field positionEncodings? lsp.PositionEncodingKind[] + +---A relative pattern is a helper to construct glob patterns that are matched +---relatively to a base URI. The common value for a `baseUri` is a workspace +---folder root, but it can be another absolute URI as well. +--- +---@since 3.17.0 +---@class lsp.RelativePattern +---A workspace folder or a base URI to which this pattern will be matched +---against relatively. +---@field baseUri lsp.WorkspaceFolder|lsp.URI +---The actual glob pattern; +---@field pattern lsp.Pattern + +---@class lsp.WorkspaceEditClientCapabilities +---The client supports versioned document changes in `WorkspaceEdit`s +---@field documentChanges? boolean +---The resource operations the client supports. Clients should at least +---support 'create', 'rename' and 'delete' files and folders. +--- +---@since 3.13.0 +---@field resourceOperations? lsp.ResourceOperationKind[] +---The failure handling strategy of a client if applying the workspace edit +---fails. +--- +---@since 3.13.0 +---@field failureHandling? lsp.FailureHandlingKind +---Whether the client normalizes line endings to the client specific +---setting. +---If set to `true` the client will normalize line ending characters +---in a workspace edit to the client-specified new line +---character. +--- +---@since 3.16.0 +---@field normalizesLineEndings? boolean +---Whether the client in general supports change annotations on text edits, +---create file, rename file and delete file changes. +--- +---@since 3.16.0 +---@field changeAnnotationSupport? anonym19 + +---@class lsp.DidChangeConfigurationClientCapabilities +---Did change configuration notification supports dynamic registration. +---@field dynamicRegistration? boolean + +---@class lsp.DidChangeWatchedFilesClientCapabilities +---Did change watched files notification supports dynamic registration. Please note +---that the current protocol doesn't support static configuration for file changes +---from the server side. +---@field dynamicRegistration? boolean +---Whether the client has support for {@link RelativePattern relative pattern} +---or not. +--- +---@since 3.17.0 +---@field relativePatternSupport? boolean + +---Client capabilities for a {@link WorkspaceSymbolRequest}. +---@class lsp.WorkspaceSymbolClientCapabilities +---Symbol request supports dynamic registration. +---@field dynamicRegistration? boolean +---Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. +---@field symbolKind? anonym20 +---The client supports tags on `SymbolInformation`. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.16.0 +---@field tagSupport? anonym21 +---The client support partial workspace symbols. The client will send the +---request `workspaceSymbol/resolve` to the server to resolve additional +---properties. +--- +---@since 3.17.0 +---@field resolveSupport? anonym22 + +---The client capabilities of a {@link ExecuteCommandRequest}. +---@class lsp.ExecuteCommandClientCapabilities +---Execute command supports dynamic registration. +---@field dynamicRegistration? boolean + +---@since 3.16.0 +---@class lsp.SemanticTokensWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---semantic tokens currently shown. It should be used with absolute care +---and is useful for situation where a server for example detects a project +---wide change that requires such a calculation. +---@field refreshSupport? boolean + +---@since 3.16.0 +---@class lsp.CodeLensWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from the +---server to the client. +--- +---Note that this event is global and will force the client to refresh all +---code lenses currently shown. It should be used with absolute care and is +---useful for situation where a server for example detect a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Capabilities relating to events from file operations by the user in the client. +--- +---These events do not come from the file system, they come from user operations +---like renaming a file in the UI. +--- +---@since 3.16.0 +---@class lsp.FileOperationClientCapabilities +---Whether the client supports dynamic registration for file requests/notifications. +---@field dynamicRegistration? boolean +---The client has support for sending didCreateFiles notifications. +---@field didCreate? boolean +---The client has support for sending willCreateFiles requests. +---@field willCreate? boolean +---The client has support for sending didRenameFiles notifications. +---@field didRename? boolean +---The client has support for sending willRenameFiles requests. +---@field willRename? boolean +---The client has support for sending didDeleteFiles notifications. +---@field didDelete? boolean +---The client has support for sending willDeleteFiles requests. +---@field willDelete? boolean + +---Client workspace capabilities specific to inline values. +--- +---@since 3.17.0 +---@class lsp.InlineValueWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from the +---server to the client. +--- +---Note that this event is global and will force the client to refresh all +---inline values currently shown. It should be used with absolute care and is +---useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Client workspace capabilities specific to inlay hints. +--- +---@since 3.17.0 +---@class lsp.InlayHintWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---inlay hints currently shown. It should be used with absolute care and +---is useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---Workspace client capabilities specific to diagnostic pull requests. +--- +---@since 3.17.0 +---@class lsp.DiagnosticWorkspaceClientCapabilities +---Whether the client implementation supports a refresh request sent from +---the server to the client. +--- +---Note that this event is global and will force the client to refresh all +---pulled diagnostics currently shown. It should be used with absolute care and +---is useful for situation where a server for example detects a project wide +---change that requires such a calculation. +---@field refreshSupport? boolean + +---@class lsp.TextDocumentSyncClientCapabilities +---Whether text document synchronization supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports sending will save notifications. +---@field willSave? boolean +---The client supports sending a will save request and +---waits for a response providing text edits which will +---be applied to the document before it is saved. +---@field willSaveWaitUntil? boolean +---The client supports did save notifications. +---@field didSave? boolean + +---Completion client capabilities +---@class lsp.CompletionClientCapabilities +---Whether completion supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports the following `CompletionItem` specific +---capabilities. +---@field completionItem? anonym26 +---@field completionItemKind? anonym27 +---Defines how the client handles whitespace and indentation +---when accepting a completion item that uses multi line +---text in either `insertText` or `textEdit`. +--- +---@since 3.17.0 +---@field insertTextMode? lsp.InsertTextMode +---The client supports to send additional context information for a +---`textDocument/completion` request. +---@field contextSupport? boolean +---The client supports the following `CompletionList` specific +---capabilities. +--- +---@since 3.17.0 +---@field completionList? anonym28 + +---@class lsp.HoverClientCapabilities +---Whether hover supports dynamic registration. +---@field dynamicRegistration? boolean +---Client supports the following content formats for the content +---property. The order describes the preferred format of the client. +---@field contentFormat? lsp.MarkupKind[] + +---Client Capabilities for a {@link SignatureHelpRequest}. +---@class lsp.SignatureHelpClientCapabilities +---Whether signature help supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports the following `SignatureInformation` +---specific properties. +---@field signatureInformation? anonym30 +---The client supports to send additional context information for a +---`textDocument/signatureHelp` request. A client that opts into +---contextSupport will also support the `retriggerCharacters` on +---`SignatureHelpOptions`. +--- +---@since 3.15.0 +---@field contextSupport? boolean + +---@since 3.14.0 +---@class lsp.DeclarationClientCapabilities +---Whether declaration supports dynamic registration. If this is set to `true` +---the client supports the new `DeclarationRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of declaration links. +---@field linkSupport? boolean + +---Client Capabilities for a {@link DefinitionRequest}. +---@class lsp.DefinitionClientCapabilities +---Whether definition supports dynamic registration. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---@since 3.14.0 +---@field linkSupport? boolean + +---Since 3.6.0 +---@class lsp.TypeDefinitionClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `TypeDefinitionRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---Since 3.14.0 +---@field linkSupport? boolean + +---@since 3.6.0 +---@class lsp.ImplementationClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `ImplementationRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports additional metadata in the form of definition links. +--- +---@since 3.14.0 +---@field linkSupport? boolean + +---Client Capabilities for a {@link ReferencesRequest}. +---@class lsp.ReferenceClientCapabilities +---Whether references supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client Capabilities for a {@link DocumentHighlightRequest}. +---@class lsp.DocumentHighlightClientCapabilities +---Whether document highlight supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client Capabilities for a {@link DocumentSymbolRequest}. +---@class lsp.DocumentSymbolClientCapabilities +---Whether document symbol supports dynamic registration. +---@field dynamicRegistration? boolean +---Specific capabilities for the `SymbolKind` in the +---`textDocument/documentSymbol` request. +---@field symbolKind? anonym31 +---The client supports hierarchical document symbols. +---@field hierarchicalDocumentSymbolSupport? boolean +---The client supports tags on `SymbolInformation`. Tags are supported on +---`DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.16.0 +---@field tagSupport? anonym32 +---The client supports an additional label presented in the UI when +---registering a document symbol provider. +--- +---@since 3.16.0 +---@field labelSupport? boolean + +---The Client Capabilities of a {@link CodeActionRequest}. +---@class lsp.CodeActionClientCapabilities +---Whether code action supports dynamic registration. +---@field dynamicRegistration? boolean +---The client support code action literals of type `CodeAction` as a valid +---response of the `textDocument/codeAction` request. If the property is not +---set the request can only return `Command` literals. +--- +---@since 3.8.0 +---@field codeActionLiteralSupport? anonym34 +---Whether code action supports the `isPreferred` property. +--- +---@since 3.15.0 +---@field isPreferredSupport? boolean +---Whether code action supports the `disabled` property. +--- +---@since 3.16.0 +---@field disabledSupport? boolean +---Whether code action supports the `data` property which is +---preserved between a `textDocument/codeAction` and a +---`codeAction/resolve` request. +--- +---@since 3.16.0 +---@field dataSupport? boolean +---Whether the client supports resolving additional code action +---properties via a separate `codeAction/resolve` request. +--- +---@since 3.16.0 +---@field resolveSupport? anonym35 +---Whether the client honors the change annotations in +---text edits and resource operations returned via the +---`CodeAction#edit` property by for example presenting +---the workspace edit in the user interface and asking +---for confirmation. +--- +---@since 3.16.0 +---@field honorsChangeAnnotations? boolean + +---The client capabilities of a {@link CodeLensRequest}. +---@class lsp.CodeLensClientCapabilities +---Whether code lens supports dynamic registration. +---@field dynamicRegistration? boolean + +---The client capabilities of a {@link DocumentLinkRequest}. +---@class lsp.DocumentLinkClientCapabilities +---Whether document link supports dynamic registration. +---@field dynamicRegistration? boolean +---Whether the client supports the `tooltip` property on `DocumentLink`. +--- +---@since 3.15.0 +---@field tooltipSupport? boolean + +---@class lsp.DocumentColorClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `DocumentColorRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentFormattingRequest}. +---@class lsp.DocumentFormattingClientCapabilities +---Whether formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---Client capabilities of a {@link DocumentRangeFormattingRequest}. +---@class lsp.DocumentRangeFormattingClientCapabilities +---Whether range formatting supports dynamic registration. +---@field dynamicRegistration? boolean +---Whether the client supports formatting multiple ranges at once. +--- +---@since 3.18.0 +---@proposed +---@field rangesSupport? boolean + +---Client capabilities of a {@link DocumentOnTypeFormattingRequest}. +---@class lsp.DocumentOnTypeFormattingClientCapabilities +---Whether on type formatting supports dynamic registration. +---@field dynamicRegistration? boolean + +---@class lsp.RenameClientCapabilities +---Whether rename supports dynamic registration. +---@field dynamicRegistration? boolean +---Client supports testing for validity of rename operations +---before execution. +--- +---@since 3.12.0 +---@field prepareSupport? boolean +---Client supports the default behavior result. +--- +---The value indicates the default behavior used by the +---client. +--- +---@since 3.16.0 +---@field prepareSupportDefaultBehavior? lsp.PrepareSupportDefaultBehavior +---Whether the client honors the change annotations in +---text edits and resource operations returned via the +---rename request's workspace edit by for example presenting +---the workspace edit in the user interface and asking +---for confirmation. +--- +---@since 3.16.0 +---@field honorsChangeAnnotations? boolean + +---@class lsp.FoldingRangeClientCapabilities +---Whether implementation supports dynamic registration for folding range +---providers. If this is set to `true` the client supports the new +---`FoldingRangeRegistrationOptions` return value for the corresponding +---server capability as well. +---@field dynamicRegistration? boolean +---The maximum number of folding ranges that the client prefers to receive +---per document. The value serves as a hint, servers are free to follow the +---limit. +---@field rangeLimit? uinteger +---If set, the client signals that it only supports folding complete lines. +---If set, client will ignore specified `startCharacter` and `endCharacter` +---properties in a FoldingRange. +---@field lineFoldingOnly? boolean +---Specific options for the folding range kind. +--- +---@since 3.17.0 +---@field foldingRangeKind? anonym36 +---Specific options for the folding range. +--- +---@since 3.17.0 +---@field foldingRange? anonym37 + +---@class lsp.SelectionRangeClientCapabilities +---Whether implementation supports dynamic registration for selection range providers. If this is set to `true` +---the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server +---capability as well. +---@field dynamicRegistration? boolean + +---The publish diagnostic client capabilities. +---@class lsp.PublishDiagnosticsClientCapabilities +---Whether the clients accepts diagnostics with related information. +---@field relatedInformation? boolean +---Client supports the tag property to provide meta data about a diagnostic. +---Clients supporting tags have to handle unknown tags gracefully. +--- +---@since 3.15.0 +---@field tagSupport? anonym38 +---Whether the client interprets the version property of the +---`textDocument/publishDiagnostics` notification's parameter. +--- +---@since 3.15.0 +---@field versionSupport? boolean +---Client supports a codeDescription property +--- +---@since 3.16.0 +---@field codeDescriptionSupport? boolean +---Whether code action supports the `data` property which is +---preserved between a `textDocument/publishDiagnostics` and +---`textDocument/codeAction` request. +--- +---@since 3.16.0 +---@field dataSupport? boolean + +---@since 3.16.0 +---@class lsp.CallHierarchyClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---@since 3.16.0 +---@class lsp.SemanticTokensClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---Which requests the client supports and might send to the server +---depending on the server's capability. Please note that clients might not +---show semantic tokens or degrade some of the user experience if a range +---or full request is advertised by the client but not provided by the +---server. If for example the client capability `requests.full` and +---`request.range` are both set to true but the server only provides a +---range provider the client might not render a minimap correctly or might +---even decide to not show any semantic tokens at all. +---@field requests anonym41 +---The token types that the client supports. +---@field tokenTypes string[] +---The token modifiers that the client supports. +---@field tokenModifiers string[] +---The token formats the clients supports. +---@field formats lsp.TokenFormat[] +---Whether the client supports tokens that can overlap each other. +---@field overlappingTokenSupport? boolean +---Whether the client supports tokens that can span multiple lines. +---@field multilineTokenSupport? boolean +---Whether the client allows the server to actively cancel a +---semantic token request, e.g. supports returning +---LSPErrorCodes.ServerCancelled. If a server does the client +---needs to retrigger the request. +--- +---@since 3.17.0 +---@field serverCancelSupport? boolean +---Whether the client uses semantic tokens to augment existing +---syntax tokens. If set to `true` client side created syntax +---tokens and semantic tokens are both used for colorization. If +---set to `false` the client only uses the returned semantic tokens +---for colorization. +--- +---If the value is `undefined` then the client behavior is not +---specified. +--- +---@since 3.17.0 +---@field augmentsSyntaxTokens? boolean + +---Client capabilities for the linked editing range request. +--- +---@since 3.16.0 +---@class lsp.LinkedEditingRangeClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities specific to the moniker request. +--- +---@since 3.16.0 +---@class lsp.MonikerClientCapabilities +---Whether moniker supports dynamic registration. If this is set to `true` +---the client supports the new `MonikerRegistrationOptions` return value +---for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---@since 3.17.0 +---@class lsp.TypeHierarchyClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean + +---Client capabilities specific to inline values. +--- +---@since 3.17.0 +---@class lsp.InlineValueClientCapabilities +---Whether implementation supports dynamic registration for inline value providers. +---@field dynamicRegistration? boolean + +---Inlay hint client capabilities. +--- +---@since 3.17.0 +---@class lsp.InlayHintClientCapabilities +---Whether inlay hints support dynamic registration. +---@field dynamicRegistration? boolean +---Indicates which properties a client can resolve lazily on an inlay +---hint. +---@field resolveSupport? anonym42 + +---Client capabilities specific to diagnostic pull requests. +--- +---@since 3.17.0 +---@class lsp.DiagnosticClientCapabilities +---Whether implementation supports dynamic registration. If this is set to `true` +---the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---Whether the clients supports related documents for document diagnostic pulls. +---@field relatedDocumentSupport? boolean + +---Client capabilities specific to inline completions. +--- +---@since 3.18.0 +---@class lsp.InlineCompletionClientCapabilities +---Whether implementation supports dynamic registration for inline completion providers. +---@field dynamicRegistration? boolean + +---Notebook specific client capabilities. +--- +---@since 3.17.0 +---@class lsp.NotebookDocumentSyncClientCapabilities +---Whether implementation supports dynamic registration. If this is +---set to `true` the client supports the new +---`(TextDocumentRegistrationOptions & StaticRegistrationOptions)` +---return value for the corresponding server capability as well. +---@field dynamicRegistration? boolean +---The client supports sending execution summary data per cell. +---@field executionSummarySupport? boolean + +---Show message request client capabilities +---@class lsp.ShowMessageRequestClientCapabilities +---Capabilities specific to the `MessageActionItem` type. +---@field messageActionItem? anonym43 + +---Client capabilities for the showDocument request. +--- +---@since 3.16.0 +---@class lsp.ShowDocumentClientCapabilities +---The client has support for the showDocument +---request. +---@field support boolean + +---Client capabilities specific to regular expressions. +--- +---@since 3.16.0 +---@class lsp.RegularExpressionsClientCapabilities +---The engine's name. +---@field engine string +---The engine's version. +---@field version? string + +---Client capabilities specific to the used markdown parser. +--- +---@since 3.16.0 +---@class lsp.MarkdownClientCapabilities +---The name of the parser. +---@field parser string +---The version of the parser. +---@field version? string +---A list of HTML tags that the client allows / supports in +---Markdown. +--- +---@since 3.17.0 +---@field allowedTags? string[] + +---A set of predefined token types. This set is not fixed +---an clients can specify additional token types via the +---corresponding client capabilities. +--- +---@since 3.16.0 +---@alias lsp.SemanticTokenTypes +---| "namespace" # namespace +---| "type" # type +---| "class" # class +---| "enum" # enum +---| "interface" # interface +---| "struct" # struct +---| "typeParameter" # typeParameter +---| "parameter" # parameter +---| "variable" # variable +---| "property" # property +---| "enumMember" # enumMember +---| "event" # event +---| "function" # function +---| "method" # method +---| "macro" # macro +---| "keyword" # keyword +---| "modifier" # modifier +---| "comment" # comment +---| "string" # string +---| "number" # number +---| "regexp" # regexp +---| "operator" # operator +---| "decorator" # decorator + +---A set of predefined token modifiers. This set is not fixed +---an clients can specify additional token types via the +---corresponding client capabilities. +--- +---@since 3.16.0 +---@alias lsp.SemanticTokenModifiers +---| "declaration" # declaration +---| "definition" # definition +---| "readonly" # readonly +---| "static" # static +---| "deprecated" # deprecated +---| "abstract" # abstract +---| "async" # async +---| "modification" # modification +---| "documentation" # documentation +---| "defaultLibrary" # defaultLibrary + +---The document diagnostic report kinds. +--- +---@since 3.17.0 +---@alias lsp.DocumentDiagnosticReportKind +---| "full" # Full +---| "unchanged" # Unchanged + +---Predefined error codes. +---@alias lsp.ErrorCodes +---| -32700 # ParseError +---| -32600 # InvalidRequest +---| -32601 # MethodNotFound +---| -32602 # InvalidParams +---| -32603 # InternalError +---| -32002 # ServerNotInitialized +---| -32001 # UnknownErrorCode + +---@alias lsp.LSPErrorCodes +---| -32803 # RequestFailed +---| -32802 # ServerCancelled +---| -32801 # ContentModified +---| -32800 # RequestCancelled + +---A set of predefined range kinds. +---@alias lsp.FoldingRangeKind +---| "comment" # Comment +---| "imports" # Imports +---| "region" # Region + +---A symbol kind. +---@alias lsp.SymbolKind +---| 1 # File +---| 2 # Module +---| 3 # Namespace +---| 4 # Package +---| 5 # Class +---| 6 # Method +---| 7 # Property +---| 8 # Field +---| 9 # Constructor +---| 10 # Enum +---| 11 # Interface +---| 12 # Function +---| 13 # Variable +---| 14 # Constant +---| 15 # String +---| 16 # Number +---| 17 # Boolean +---| 18 # Array +---| 19 # Object +---| 20 # Key +---| 21 # Null +---| 22 # EnumMember +---| 23 # Struct +---| 24 # Event +---| 25 # Operator +---| 26 # TypeParameter + +---Symbol tags are extra annotations that tweak the rendering of a symbol. +--- +---@since 3.16 +---@alias lsp.SymbolTag +---| 1 # Deprecated + +---Moniker uniqueness level to define scope of the moniker. +--- +---@since 3.16.0 +---@alias lsp.UniquenessLevel +---| "document" # document +---| "project" # project +---| "group" # group +---| "scheme" # scheme +---| "global" # global + +---The moniker kind. +--- +---@since 3.16.0 +---@alias lsp.MonikerKind +---| "import" # import +---| "export" # export +---| "local" # local + +---Inlay hint kinds. +--- +---@since 3.17.0 +---@alias lsp.InlayHintKind +---| 1 # Type +---| 2 # Parameter + +---Defines whether the insert text in a completion item should be interpreted as +---plain text or a snippet. +---@alias lsp.InsertTextFormat +---| 1 # PlainText +---| 2 # Snippet + +---The message type +---@alias lsp.MessageType +---| 1 # Error +---| 2 # Warning +---| 3 # Info +---| 4 # Log + +---Defines how the host (editor) should sync +---document changes to the language server. +---@alias lsp.TextDocumentSyncKind +---| 0 # None +---| 1 # Full +---| 2 # Incremental + +---Represents reasons why a text document is saved. +---@alias lsp.TextDocumentSaveReason +---| 1 # Manual +---| 2 # AfterDelay +---| 3 # FocusOut + +---The kind of a completion entry. +---@alias lsp.CompletionItemKind +---| 1 # Text +---| 2 # Method +---| 3 # Function +---| 4 # Constructor +---| 5 # Field +---| 6 # Variable +---| 7 # Class +---| 8 # Interface +---| 9 # Module +---| 10 # Property +---| 11 # Unit +---| 12 # Value +---| 13 # Enum +---| 14 # Keyword +---| 15 # Snippet +---| 16 # Color +---| 17 # File +---| 18 # Reference +---| 19 # Folder +---| 20 # EnumMember +---| 21 # Constant +---| 22 # Struct +---| 23 # Event +---| 24 # Operator +---| 25 # TypeParameter + +---Completion item tags are extra annotations that tweak the rendering of a completion +---item. +--- +---@since 3.15.0 +---@alias lsp.CompletionItemTag +---| 1 # Deprecated + +---How whitespace and indentation is handled during completion +---item insertion. +--- +---@since 3.16.0 +---@alias lsp.InsertTextMode +---| 1 # asIs +---| 2 # adjustIndentation + +---A document highlight kind. +---@alias lsp.DocumentHighlightKind +---| 1 # Text +---| 2 # Read +---| 3 # Write + +---A set of predefined code action kinds +---@alias lsp.CodeActionKind +---| "" # Empty +---| "quickfix" # QuickFix +---| "refactor" # Refactor +---| "refactor.extract" # RefactorExtract +---| "refactor.inline" # RefactorInline +---| "refactor.rewrite" # RefactorRewrite +---| "source" # Source +---| "source.organizeImports" # SourceOrganizeImports +---| "source.fixAll" # SourceFixAll + +---@alias lsp.TraceValues +---| "off" # Off +---| "messages" # Messages +---| "verbose" # Verbose + +---Describes the content type that a client supports in various +---result literals like `Hover`, `ParameterInfo` or `CompletionItem`. +--- +---Please note that `MarkupKinds` must not start with a `$`. This kinds +---are reserved for internal usage. +---@alias lsp.MarkupKind +---| "plaintext" # PlainText +---| "markdown" # Markdown + +---Describes how an {@link InlineCompletionItemProvider inline completion provider} was triggered. +--- +---@since 3.18.0 +---@alias lsp.InlineCompletionTriggerKind +---| 0 # Invoked +---| 1 # Automatic + +---A set of predefined position encoding kinds. +--- +---@since 3.17.0 +---@alias lsp.PositionEncodingKind +---| "utf-8" # UTF8 +---| "utf-16" # UTF16 +---| "utf-32" # UTF32 + +---The file event type +---@alias lsp.FileChangeType +---| 1 # Created +---| 2 # Changed +---| 3 # Deleted + +---@alias lsp.WatchKind +---| 1 # Create +---| 2 # Change +---| 4 # Delete + +---The diagnostic's severity. +---@alias lsp.DiagnosticSeverity +---| 1 # Error +---| 2 # Warning +---| 3 # Information +---| 4 # Hint + +---The diagnostic tags. +--- +---@since 3.15.0 +---@alias lsp.DiagnosticTag +---| 1 # Unnecessary +---| 2 # Deprecated + +---How a completion was triggered +---@alias lsp.CompletionTriggerKind +---| 1 # Invoked +---| 2 # TriggerCharacter +---| 3 # TriggerForIncompleteCompletions + +---How a signature help was triggered. +--- +---@since 3.15.0 +---@alias lsp.SignatureHelpTriggerKind +---| 1 # Invoked +---| 2 # TriggerCharacter +---| 3 # ContentChange + +---The reason why code actions were requested. +--- +---@since 3.17.0 +---@alias lsp.CodeActionTriggerKind +---| 1 # Invoked +---| 2 # Automatic + +---A pattern kind describing if a glob pattern matches a file a folder or +---both. +--- +---@since 3.16.0 +---@alias lsp.FileOperationPatternKind +---| "file" # file +---| "folder" # folder + +---A notebook cell kind. +--- +---@since 3.17.0 +---@alias lsp.NotebookCellKind +---| 1 # Markup +---| 2 # Code + +---@alias lsp.ResourceOperationKind +---| "create" # Create +---| "rename" # Rename +---| "delete" # Delete + +---@alias lsp.FailureHandlingKind +---| "abort" # Abort +---| "transactional" # Transactional +---| "textOnlyTransactional" # TextOnlyTransactional +---| "undo" # Undo + +---@alias lsp.PrepareSupportDefaultBehavior +---| 1 # Identifier + +---@alias lsp.TokenFormat +---| "relative" # Relative + +---The definition of a symbol represented as one or many {@link Location locations}. +---For most programming languages there is only one location at which a symbol is +---defined. +--- +---Servers should prefer returning `DefinitionLink` over `Definition` if supported +---by the client. +---@alias lsp.Definition lsp.Location|lsp.Location[] + +---Information about where a symbol is defined. +--- +---Provides additional metadata over normal {@link Location location} definitions, including the range of +---the defining symbol +---@alias lsp.DefinitionLink lsp.LocationLink + +---LSP arrays. +---@since 3.17.0 +---@alias lsp.LSPArray lsp.LSPAny[] + +---The LSP any type. +---Please note that strictly speaking a property with the value `undefined` +---can't be converted into JSON preserving the property name. However for +---convenience it is allowed and assumed that all these properties are +---optional as well. +---@since 3.17.0 +---@alias lsp.LSPAny lsp.LSPObject|lsp.LSPArray|string|integer|uinteger|decimal|boolean|lsp.null + +---The declaration of a symbol representation as one or many {@link Location locations}. +---@alias lsp.Declaration lsp.Location|lsp.Location[] + +---Information about where a symbol is declared. +--- +---Provides additional metadata over normal {@link Location location} declarations, including the range of +---the declaring symbol. +--- +---Servers should prefer returning `DeclarationLink` over `Declaration` if supported +---by the client. +---@alias lsp.DeclarationLink lsp.LocationLink + +---Inline value information can be provided by different means: +---- directly as a text value (class InlineValueText). +---- as a name to use for a variable lookup (class InlineValueVariableLookup) +---- as an evaluatable expression (class InlineValueEvaluatableExpression) +---The InlineValue types combines all inline value types into one type. +--- +---@since 3.17.0 +---@alias lsp.InlineValue lsp.InlineValueText|lsp.InlineValueVariableLookup|lsp.InlineValueEvaluatableExpression + +---The result of a document diagnostic pull request. A report can +---either be a full report containing all diagnostics for the +---requested document or an unchanged report indicating that nothing +---has changed in terms of diagnostics in comparison to the last +---pull request. +--- +---@since 3.17.0 +---@alias lsp.DocumentDiagnosticReport lsp.RelatedFullDocumentDiagnosticReport|lsp.RelatedUnchangedDocumentDiagnosticReport + +---@alias lsp.PrepareRenameResult lsp.Range|anonym44|anonym45 + +---A document selector is the combination of one or many document filters. +--- +---@sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`; +--- +---The use of a string as a document filter is deprecated @since 3.16.0. +---@alias lsp.DocumentSelector lsp.DocumentFilter[] + +---@alias lsp.ProgressToken integer|string + +---An identifier to refer to a change annotation stored with a workspace edit. +---@alias lsp.ChangeAnnotationIdentifier string + +---A workspace diagnostic document report. +--- +---@since 3.17.0 +---@alias lsp.WorkspaceDocumentDiagnosticReport lsp.WorkspaceFullDocumentDiagnosticReport|lsp.WorkspaceUnchangedDocumentDiagnosticReport + +---An event describing a change to a text document. If only a text is provided +---it is considered to be the full content of the document. +---@alias lsp.TextDocumentContentChangeEvent anonym46|anonym47 + +---MarkedString can be used to render human readable text. It is either a markdown string +---or a code-block that provides a language and a code snippet. The language identifier +---is semantically equal to the optional language identifier in fenced code blocks in GitHub +---issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting +--- +---The pair of a language and a value is an equivalent to markdown: +---```${language} +---${value} +---``` +--- +---Note that markdown strings will be sanitized - that means html will be escaped. +---@deprecated use MarkupContent instead. +---@alias lsp.MarkedString string|anonym48 + +---A document filter describes a top level text document or +---a notebook cell document. +--- +---@since 3.17.0 - proposed support for NotebookCellTextDocumentFilter. +---@alias lsp.DocumentFilter lsp.TextDocumentFilter|lsp.NotebookCellTextDocumentFilter + +---LSP object definition. +---@since 3.17.0 +---@alias lsp.LSPObject table<string, lsp.LSPAny> + +---The glob pattern. Either a string pattern or a relative pattern. +--- +---@since 3.17.0 +---@alias lsp.GlobPattern lsp.Pattern|lsp.RelativePattern + +---A document filter denotes a document by different properties like +---the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of +---its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}. +--- +---Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +--- +---@sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` +---@sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }` +--- +---@since 3.17.0 +---@alias lsp.TextDocumentFilter anonym49|anonym50|anonym51 + +---A notebook document filter denotes a notebook document by +---different properties. The properties will be match +---against the notebook's URI (same as with documents) +--- +---@since 3.17.0 +---@alias lsp.NotebookDocumentFilter anonym52|anonym53|anonym54 + +---The glob pattern to watch relative to the base path. Glob patterns can have the following syntax: +---- `*` to match one or more characters in a path segment +---- `?` to match on one character in a path segment +---- `**` to match any number of path segments, including none +---- `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files) +---- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +---- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) +--- +---@since 3.17.0 +---@alias lsp.Pattern string + +---@class anonym1 +---The name of the server as defined by the server. +---@field name string +---The server's version as defined by the server. +---@field version? string + +---@class anonym3 +---@field insert lsp.Range +---@field replace lsp.Range + +---@class anonym2 +---A default commit character set. +--- +---@since 3.17.0 +---@field commitCharacters? string[] +---A default edit range. +--- +---@since 3.17.0 +---@field editRange? lsp.Range|anonym3 +---A default insert text format. +--- +---@since 3.17.0 +---@field insertTextFormat? lsp.InsertTextFormat +---A default insert text mode. +--- +---@since 3.17.0 +---@field insertTextMode? lsp.InsertTextMode +---A default data value. +--- +---@since 3.17.0 +---@field data? lsp.LSPAny + +---@class anonym4 +---Human readable description of why the code action is currently disabled. +--- +---This is displayed in the code actions UI. +---@field reason string + +---@class anonym5 +---@field uri lsp.DocumentUri + +---@class anonym6 + +---@class anonym7 +---The server supports deltas for full documents. +---@field delta? boolean + +---@class anonym9 +---The change to the cell array. +---@field array lsp.NotebookCellArrayChange +---Additional opened cell text documents. +---@field didOpen? lsp.TextDocumentItem[] +---Additional closed cell text documents. +---@field didClose? lsp.TextDocumentIdentifier[] + +---@class anonym10 +---@field document lsp.VersionedTextDocumentIdentifier +---@field changes lsp.TextDocumentContentChangeEvent[] + +---@class anonym8 +---Changes to the cell structure to add or +---remove cells. +---@field structure? anonym9 +---Changes to notebook cells properties like its +---kind, execution summary or metadata. +---@field data? lsp.NotebookCell[] +---Changes to the text content of notebook cells. +---@field textContent? anonym10[] + +---@class anonym11 +---The name of the client as defined by the client. +---@field name string +---The client's version as defined by the client. +---@field version? string + +---@class anonym12 +---The server supports workspace folder. +--- +---@since 3.6.0 +---@field workspaceFolders? lsp.WorkspaceFoldersServerCapabilities +---The server is interested in notifications/requests for operations on files. +--- +---@since 3.16.0 +---@field fileOperations? lsp.FileOperationOptions + +---@class anonym13 +---The server has support for completion item label +---details (see also `CompletionItemLabelDetails`) when +---receiving a completion item in a resolve call. +--- +---@since 3.17.0 +---@field labelDetailsSupport? boolean + +---@class anonym15 +---@field language string + +---@class anonym14 +---The notebook to be synced If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook string|lsp.NotebookDocumentFilter +---The cells of the matching notebook to be synced. +---@field cells? anonym15[] + +---@class anonym17 +---@field language string + +---@class anonym16 +---The notebook to be synced If a string +---value is provided it matches against the +---notebook type. '*' matches every notebook. +---@field notebook? string|lsp.NotebookDocumentFilter +---The cells of the matching notebook to be synced. +---@field cells anonym17[] + +---@class anonym18 +---The client will actively cancel the request. +---@field cancel boolean +---The list of requests for which the client +---will retry the request if it receives a +---response with error code `ContentModified` +---@field retryOnContentModified string[] + +---@class anonym19 +---Whether the client groups edits with equal labels into tree nodes, +---for instance all edits labelled with "Changes in Strings" would +---be a tree node. +---@field groupsOnLabel? boolean + +---@class anonym20 +---The symbol kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the symbol kinds from `File` to `Array` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.SymbolKind[] + +---@class anonym21 +---The tags supported by the client. +---@field valueSet lsp.SymbolTag[] + +---@class anonym22 +---The properties that a client can resolve lazily. Usually +---`location.range` +---@field properties string[] + +---@class anonym24 +---The tags supported by the client. +---@field valueSet lsp.CompletionItemTag[] + +---@class anonym25 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym26 +---@field valueSet lsp.InsertTextMode[] + +---@class anonym23 +---Client supports snippets as insert text. +--- +---A snippet can define tab stops and placeholders with `$1`, `$2` +---and `${3:foo}`. `$0` defines the final tab stop, it defaults to +---the end of the snippet. Placeholders with equal identifiers are linked, +---that is typing in one will update others too. +---@field snippetSupport? boolean +---Client supports commit characters on a completion item. +---@field commitCharactersSupport? boolean +---Client supports the following content formats for the documentation +---property. The order describes the preferred format of the client. +---@field documentationFormat? lsp.MarkupKind[] +---Client supports the deprecated property on a completion item. +---@field deprecatedSupport? boolean +---Client supports the preselect property on a completion item. +---@field preselectSupport? boolean +---Client supports the tag property on a completion item. Clients supporting +---tags have to handle unknown tags gracefully. Clients especially need to +---preserve unknown tags when sending a completion item back to the server in +---a resolve call. +--- +---@since 3.15.0 +---@field tagSupport? anonym24 +---Client support insert replace edit to control different behavior if a +---completion item is inserted in the text or should replace text. +--- +---@since 3.16.0 +---@field insertReplaceSupport? boolean +---Indicates which properties a client can resolve lazily on a completion +---item. Before version 3.16.0 only the predefined properties `documentation` +---and `details` could be resolved lazily. +--- +---@since 3.16.0 +---@field resolveSupport? anonym25 +---The client supports the `insertTextMode` property on +---a completion item to override the whitespace handling mode +---as defined by the client (see `insertTextMode`). +--- +---@since 3.16.0 +---@field insertTextModeSupport? anonym26 +---The client has support for completion item label +---details (see also `CompletionItemLabelDetails`). +--- +---@since 3.17.0 +---@field labelDetailsSupport? boolean + +---@class anonym27 +---The completion item kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the completion items kinds from `Text` to `Reference` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.CompletionItemKind[] + +---@class anonym28 +---The client supports the following itemDefaults on +---a completion list. +--- +---The value lists the supported property names of the +---`CompletionList.itemDefaults` object. If omitted +---no properties are supported. +--- +---@since 3.17.0 +---@field itemDefaults? string[] + +---@class anonym30 +---The client supports processing label offsets instead of a +---simple label string. +--- +---@since 3.14.0 +---@field labelOffsetSupport? boolean + +---@class anonym29 +---Client supports the following content formats for the documentation +---property. The order describes the preferred format of the client. +---@field documentationFormat? lsp.MarkupKind[] +---Client capabilities specific to parameter information. +---@field parameterInformation? anonym30 +---The client supports the `activeParameter` property on `SignatureInformation` +---literal. +--- +---@since 3.16.0 +---@field activeParameterSupport? boolean + +---@class anonym31 +---The symbol kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +--- +---If this property is not present the client only supports +---the symbol kinds from `File` to `Array` as defined in +---the initial version of the protocol. +---@field valueSet? lsp.SymbolKind[] + +---@class anonym32 +---The tags supported by the client. +---@field valueSet lsp.SymbolTag[] + +---@class anonym34 +---The code action kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +---@field valueSet lsp.CodeActionKind[] + +---@class anonym33 +---The code action kind is support with the following value +---set. +---@field codeActionKind anonym34 + +---@class anonym35 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym36 +---The folding range kind values the client supports. When this +---property exists the client also guarantees that it will +---handle values outside its set gracefully and falls back +---to a default value when unknown. +---@field valueSet? lsp.FoldingRangeKind[] + +---@class anonym37 +---If set, the client signals that it supports setting collapsedText on +---folding ranges to display custom labels instead of the default text. +--- +---@since 3.17.0 +---@field collapsedText? boolean + +---@class anonym38 +---The tags supported by the client. +---@field valueSet lsp.DiagnosticTag[] + +---@class anonym40 + +---@class anonym41 +---The client will send the `textDocument/semanticTokens/full/delta` request if +---the server provides a corresponding handler. +---@field delta? boolean + +---@class anonym39 +---The client will send the `textDocument/semanticTokens/range` request if +---the server provides a corresponding handler. +---@field range? boolean|anonym40 +---The client will send the `textDocument/semanticTokens/full` request if +---the server provides a corresponding handler. +---@field full? boolean|anonym41 + +---@class anonym42 +---The properties that a client can resolve lazily. +---@field properties string[] + +---@class anonym43 +---Whether the client supports additional attributes which +---are preserved and send back to the server in the +---request's response. +---@field additionalPropertiesSupport? boolean + +---@class anonym44 +---@field range lsp.Range +---@field placeholder string + +---@class anonym45 +---@field defaultBehavior boolean + +---@class anonym46 +---The range of the document that changed. +---@field range lsp.Range +---The optional length of the range that got replaced. +--- +---@deprecated use range instead. +---@field rangeLength? uinteger +---The new text for the provided range. +---@field text string + +---@class anonym47 +---The new text of the whole document. +---@field text string + +---@class anonym48 +---@field language string +---@field value string + +---@class anonym49 +---A language id, like `typescript`. +---@field language string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern, like `*.{ts,js}`. +---@field pattern? string + +---@class anonym50 +---A language id, like `typescript`. +---@field language? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme string +---A glob pattern, like `*.{ts,js}`. +---@field pattern? string + +---@class anonym51 +---A language id, like `typescript`. +---@field language? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern, like `*.{ts,js}`. +---@field pattern string + +---@class anonym52 +---The type of the enclosing notebook. +---@field notebookType string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern. +---@field pattern? string + +---@class anonym53 +---The type of the enclosing notebook. +---@field notebookType? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme string +---A glob pattern. +---@field pattern? string + +---@class anonym54 +---The type of the enclosing notebook. +---@field notebookType? string +---A Uri {@link Uri.scheme scheme}, like `file` or `untitled`. +---@field scheme? string +---A glob pattern. +---@field pattern string diff --git a/runtime/lua/vim/lsp/_snippet.lua b/runtime/lua/vim/lsp/_snippet.lua deleted file mode 100644 index 3488639fb4..0000000000 --- a/runtime/lua/vim/lsp/_snippet.lua +++ /dev/null @@ -1,500 +0,0 @@ -local P = {} - ----Take characters until the target characters (The escape sequence is '\' + char) ----@param targets string[] The character list for stop consuming text. ----@param specials string[] If the character isn't contained in targets/specials, '\' will be left. -P.take_until = function(targets, specials) - targets = targets or {} - specials = specials or {} - - return function(input, pos) - local new_pos = pos - local raw = {} - local esc = {} - while new_pos <= #input do - local c = string.sub(input, new_pos, new_pos) - if c == '\\' then - table.insert(raw, '\\') - new_pos = new_pos + 1 - c = string.sub(input, new_pos, new_pos) - if not vim.tbl_contains(targets, c) and not vim.tbl_contains(specials, c) then - table.insert(esc, '\\') - end - table.insert(raw, c) - table.insert(esc, c) - new_pos = new_pos + 1 - else - if vim.tbl_contains(targets, c) then - break - end - table.insert(raw, c) - table.insert(esc, c) - new_pos = new_pos + 1 - end - end - - if new_pos == pos then - return P.unmatch(pos) - end - - return { - parsed = true, - value = { - raw = table.concat(raw, ''), - esc = table.concat(esc, ''), - }, - pos = new_pos, - } - end -end - -P.unmatch = function(pos) - return { - parsed = false, - value = nil, - pos = pos, - } -end - -P.map = function(parser, map) - return function(input, pos) - local result = parser(input, pos) - if result.parsed then - return { - parsed = true, - value = map(result.value), - pos = result.pos, - } - end - return P.unmatch(pos) - end -end - -P.lazy = function(factory) - return function(input, pos) - return factory()(input, pos) - end -end - -P.token = function(token) - return function(input, pos) - local maybe_token = string.sub(input, pos, pos + #token - 1) - if token == maybe_token then - return { - parsed = true, - value = maybe_token, - pos = pos + #token, - } - end - return P.unmatch(pos) - end -end - -P.pattern = function(p) - return function(input, pos) - local maybe_match = string.match(string.sub(input, pos), '^' .. p) - if maybe_match then - return { - parsed = true, - value = maybe_match, - pos = pos + #maybe_match, - } - end - return P.unmatch(pos) - end -end - -P.many = function(parser) - return function(input, pos) - local values = {} - local new_pos = pos - while new_pos <= #input do - local result = parser(input, new_pos) - if not result.parsed then - break - end - table.insert(values, result.value) - new_pos = result.pos - end - if #values > 0 then - return { - parsed = true, - value = values, - pos = new_pos, - } - end - return P.unmatch(pos) - end -end - -P.any = function(...) - local parsers = { ... } - return function(input, pos) - for _, parser in ipairs(parsers) do - local result = parser(input, pos) - if result.parsed then - return result - end - end - return P.unmatch(pos) - end -end - -P.opt = function(parser) - return function(input, pos) - local result = parser(input, pos) - return { - parsed = true, - value = result.value, - pos = result.pos, - } - end -end - -P.seq = function(...) - local parsers = { ... } - return function(input, pos) - local values = {} - local new_pos = pos - for i, parser in ipairs(parsers) do - local result = parser(input, new_pos) - if result.parsed then - values[i] = result.value - new_pos = result.pos - else - return P.unmatch(pos) - end - end - return { - parsed = true, - value = values, - pos = new_pos, - } - end -end - -local Node = {} - -Node.Type = { - SNIPPET = 0, - TABSTOP = 1, - PLACEHOLDER = 2, - VARIABLE = 3, - CHOICE = 4, - TRANSFORM = 5, - FORMAT = 6, - TEXT = 7, -} - -function Node:__tostring() - local insert_text = {} - if self.type == Node.Type.SNIPPET then - for _, c in ipairs(self.children) do - table.insert(insert_text, tostring(c)) - end - elseif self.type == Node.Type.CHOICE then - table.insert(insert_text, self.items[1]) - elseif self.type == Node.Type.PLACEHOLDER then - for _, c in ipairs(self.children or {}) do - table.insert(insert_text, tostring(c)) - end - elseif self.type == Node.Type.TEXT then - table.insert(insert_text, self.esc) - end - return table.concat(insert_text, '') -end - ---@see https://code.visualstudio.com/docs/editor/userdefinedsnippets#_grammar - -local S = {} -S.dollar = P.token('$') -S.open = P.token('{') -S.close = P.token('}') -S.colon = P.token(':') -S.slash = P.token('/') -S.comma = P.token(',') -S.pipe = P.token('|') -S.plus = P.token('+') -S.minus = P.token('-') -S.question = P.token('?') -S.int = P.map(P.pattern('[0-9]+'), function(value) - return tonumber(value, 10) -end) -S.var = P.pattern('[%a_][%w_]+') -S.text = function(targets, specials) - return P.map(P.take_until(targets, specials), function(value) - return setmetatable({ - type = Node.Type.TEXT, - raw = value.raw, - esc = value.esc, - }, Node) - end) -end - -S.toplevel = P.lazy(function() - return P.any(S.placeholder, S.tabstop, S.variable, S.choice) -end) - -S.format = P.any( - P.map(P.seq(S.dollar, S.int), function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[2], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.int, S.close), function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - }, Node) - end), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - S.slash, - P.any( - P.token('upcase'), - P.token('downcase'), - P.token('capitalize'), - P.token('camelcase'), - P.token('pascalcase') - ), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - modifier = values[6], - }, Node) - end - ), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - P.seq( - S.question, - P.opt(P.take_until({ ':' }, { '\\' })), - S.colon, - P.opt(P.take_until({ '}' }, { '\\' })) - ), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = values[5][2] and values[5][2].esc or '', - else_text = values[5][4] and values[5][4].esc or '', - }, Node) - end - ), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - P.seq(S.plus, P.opt(P.take_until({ '}' }, { '\\' }))), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = values[5][2] and values[5][2].esc or '', - else_text = '', - }, Node) - end - ), - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - S.minus, - P.opt(P.take_until({ '}' }, { '\\' })), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = '', - else_text = values[6] and values[6].esc or '', - }, Node) - end - ), - P.map( - P.seq(S.dollar, S.open, S.int, S.colon, P.opt(P.take_until({ '}' }, { '\\' })), S.close), - function(values) - return setmetatable({ - type = Node.Type.FORMAT, - capture_index = values[3], - if_text = '', - else_text = values[5] and values[5].esc or '', - }, Node) - end - ) -) - -S.transform = P.map( - P.seq( - S.slash, - P.take_until({ '/' }, { '\\' }), - S.slash, - P.many(P.any(S.format, S.text({ '$', '/' }, { '\\' }))), - S.slash, - P.opt(P.pattern('[ig]+')) - ), - function(values) - return setmetatable({ - type = Node.Type.TRANSFORM, - pattern = values[2].raw, - format = values[4], - option = values[6], - }, Node) - end -) - -S.tabstop = P.any( - P.map(P.seq(S.dollar, S.int), function(values) - return setmetatable({ - type = Node.Type.TABSTOP, - tabstop = values[2], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.int, S.close), function(values) - return setmetatable({ - type = Node.Type.TABSTOP, - tabstop = values[3], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.int, S.transform, S.close), function(values) - return setmetatable({ - type = Node.Type.TABSTOP, - tabstop = values[3], - transform = values[4], - }, Node) - end) -) - -S.placeholder = P.any( - P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.colon, - P.opt(P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' })))), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.PLACEHOLDER, - tabstop = values[3], - -- insert empty text if opt did not match. - children = values[5] or { - setmetatable({ - type = Node.Type.TEXT, - raw = '', - esc = '', - }, Node), - }, - }, Node) - end - ) -) - -S.choice = P.map( - P.seq( - S.dollar, - S.open, - S.int, - S.pipe, - P.many(P.map(P.seq(S.text({ ',', '|' }), P.opt(S.comma)), function(values) - return values[1].esc - end)), - S.pipe, - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.CHOICE, - tabstop = values[3], - items = values[5], - }, Node) - end -) - -S.variable = P.any( - P.map(P.seq(S.dollar, S.var), function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[2], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.var, S.close), function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[3], - }, Node) - end), - P.map(P.seq(S.dollar, S.open, S.var, S.transform, S.close), function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[3], - transform = values[4], - }, Node) - end), - P.map( - P.seq( - S.dollar, - S.open, - S.var, - S.colon, - P.many(P.any(S.toplevel, S.text({ '$', '}' }, { '\\' }))), - S.close - ), - function(values) - return setmetatable({ - type = Node.Type.VARIABLE, - name = values[3], - children = values[5], - }, Node) - end - ) -) - -S.snippet = P.map(P.many(P.any(S.toplevel, S.text({ '$' }, { '}', '\\' }))), function(values) - return setmetatable({ - type = Node.Type.SNIPPET, - children = values, - }, Node) -end) - -local M = {} - ----The snippet node type enum ----@types table<string, number> -M.NodeType = Node.Type - ----Parse snippet string and returns the AST ----@param input string ----@return table -function M.parse(input) - local result = S.snippet(input, 1) - if not result.parsed then - error('snippet parsing failed.') - end - return result.value -end - -return M diff --git a/runtime/lua/vim/lsp/_snippet_grammar.lua b/runtime/lua/vim/lsp/_snippet_grammar.lua new file mode 100644 index 0000000000..9318fefcbc --- /dev/null +++ b/runtime/lua/vim/lsp/_snippet_grammar.lua @@ -0,0 +1,181 @@ +--- Grammar for LSP snippets, based on https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax + +local lpeg = vim.lpeg +local P, S, R, V = lpeg.P, lpeg.S, lpeg.R, lpeg.V +local C, Cg, Ct = lpeg.C, lpeg.Cg, lpeg.Ct + +local M = {} + +local alpha = R('az', 'AZ') +local backslash = P('\\') +local colon = P(':') +local dollar = P('$') +local int = R('09') ^ 1 +local l_brace, r_brace = P('{'), P('}') +local pipe = P('|') +local slash = P('/') +local underscore = P('_') +local var = Cg((underscore + alpha) * ((underscore + alpha + int) ^ 0), 'name') +local format_capture = Cg(int / tonumber, 'capture') +local format_modifier = Cg(P('upcase') + P('downcase') + P('capitalize'), 'modifier') +local tabstop = Cg(int / tonumber, 'tabstop') + +-- These characters are always escapable in text nodes no matter the context. +local escapable = '$}\\' + +--- Returns a function that unescapes occurrences of "special" characters. +--- +--- @param special? string +--- @return fun(match: string): string +local function escape_text(special) + special = special or escapable + return function(match) + local escaped = match:gsub('\\(.)', function(c) + return special:find(c) and c or '\\' .. c + end) + return escaped + end +end + +--- Returns a pattern for text nodes. Will match characters in `escape` when preceded by a backslash, +--- and will stop with characters in `stop_with`. +--- +--- @param escape string +--- @param stop_with? string +--- @return vim.lpeg.Pattern +local function text(escape, stop_with) + stop_with = stop_with or escape + return (backslash * S(escape)) + (P(1) - S(stop_with)) +end + +-- For text nodes inside curly braces. It stops parsing when reaching an escapable character. +local braced_text = (text(escapable) ^ 0) / escape_text() + +-- Within choice nodes, \ also escapes comma and pipe characters. +local choice_text = C(text(escapable .. ',|') ^ 1) / escape_text(escapable .. ',|') + +-- Within format nodes, make sure we stop at / +local format_text = C(text(escapable, escapable .. '/') ^ 1) / escape_text() + +local if_text, else_text = Cg(braced_text, 'if_text'), Cg(braced_text, 'else_text') + +-- Within ternary condition format nodes, make sure we stop at : +local if_till_colon_text = Cg(C(text(escapable, escapable .. ':') ^ 1) / escape_text(), 'if_text') + +-- Matches the string inside //, allowing escaping of the closing slash. +local regex = Cg(text('/') ^ 1, 'regex') + +-- Regex constructor flags (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#parameters). +local options = Cg(S('dgimsuvy') ^ 0, 'options') + +--- @enum vim.snippet.Type +local Type = { + Tabstop = 1, + Placeholder = 2, + Choice = 3, + Variable = 4, + Format = 5, + Text = 6, + Snippet = 7, +} +M.NodeType = Type + +--- @class vim.snippet.Node<T>: { type: vim.snippet.Type, data: T } +--- @class vim.snippet.TabstopData: { tabstop: integer } +--- @class vim.snippet.TextData: { text: string } +--- @class vim.snippet.PlaceholderData: { tabstop: integer, value: vim.snippet.Node<any> } +--- @class vim.snippet.ChoiceData: { tabstop: integer, values: string[] } +--- @class vim.snippet.VariableData: { name: string, default?: vim.snippet.Node<any>, regex?: string, format?: vim.snippet.Node<vim.snippet.FormatData|vim.snippet.TextData>[], options?: string } +--- @class vim.snippet.FormatData: { capture: number, modifier?: string, if_text?: string, else_text?: string } +--- @class vim.snippet.SnippetData: { children: vim.snippet.Node<any>[] } + +--- @type vim.snippet.Node<any> +local Node = {} + +--- @return string +--- @diagnostic disable-next-line: inject-field +function Node:__tostring() + local node_text = {} + local type, data = self.type, self.data + if type == Type.Snippet then + --- @cast data vim.snippet.SnippetData + for _, child in ipairs(data.children) do + table.insert(node_text, tostring(child)) + end + elseif type == Type.Choice then + --- @cast data vim.snippet.ChoiceData + table.insert(node_text, data.values[1]) + elseif type == Type.Placeholder then + --- @cast data vim.snippet.PlaceholderData + table.insert(node_text, tostring(data.value)) + elseif type == Type.Text then + --- @cast data vim.snippet.TextData + table.insert(node_text, data.text) + end + return table.concat(node_text) +end + +--- Returns a function that constructs a snippet node of the given type. +--- +--- @generic T +--- @param type vim.snippet.Type +--- @return fun(data: T): vim.snippet.Node<T> +local function node(type) + return function(data) + return setmetatable({ type = type, data = data }, Node) + end +end + +-- stylua: ignore +local G = P({ + 'snippet'; + snippet = Ct(Cg( + Ct(( + V('any') + + (Ct(Cg((text(escapable, '$') ^ 1) / escape_text(), 'text')) / node(Type.Text)) + ) ^ 1), 'children' + ) * -P(1)) / node(Type.Snippet), + any = V('placeholder') + V('tabstop') + V('choice') + V('variable'), + any_or_text = V('any') + (Ct(Cg(braced_text, 'text')) / node(Type.Text)), + tabstop = Ct(dollar * (tabstop + (l_brace * tabstop * r_brace))) / node(Type.Tabstop), + placeholder = Ct(dollar * l_brace * tabstop * colon * Cg(V('any_or_text'), 'value') * r_brace) / node(Type.Placeholder), + choice = Ct(dollar * + l_brace * + tabstop * + pipe * + Cg(Ct(choice_text * (P(',') * choice_text) ^ 0), 'values') * + pipe * + r_brace) / node(Type.Choice), + variable = Ct(dollar * ( + var + ( + l_brace * var * ( + r_brace + + (colon * Cg(V('any_or_text'), 'default') * r_brace) + + (slash * regex * slash * Cg(Ct((V('format') + (C(format_text) / node(Type.Text))) ^ 1), 'format') * slash * options * r_brace) + )) + )) / node(Type.Variable), + format = Ct(dollar * ( + format_capture + ( + l_brace * format_capture * ( + r_brace + + (colon * ( + (slash * format_modifier * r_brace) + + (P('+') * if_text * r_brace) + + (P('?') * if_till_colon_text * colon * else_text * r_brace) + + (P('-') * else_text * r_brace) + + (else_text * r_brace) + )) + )) + )) / node(Type.Format), +}) + +--- Parses the given input into a snippet tree. +--- @param input string +--- @return vim.snippet.Node<vim.snippet.SnippetData> +function M.parse(input) + local snippet = G:match(input) + assert(snippet, 'snippet parsing failed') + return snippet --- @type vim.snippet.Node<vim.snippet.SnippetData> +end + +return M diff --git a/runtime/lua/vim/lsp/_watchfiles.lua b/runtime/lua/vim/lsp/_watchfiles.lua new file mode 100644 index 0000000000..1fd112631d --- /dev/null +++ b/runtime/lua/vim/lsp/_watchfiles.lua @@ -0,0 +1,251 @@ +local bit = require('bit') +local watch = require('vim._watch') +local protocol = require('vim.lsp.protocol') +local ms = protocol.Methods +local lpeg = vim.lpeg + +local M = {} + +--- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that" +--- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern. +--- +---@param pattern string The raw glob pattern +---@return vim.lpeg.Pattern? pattern An |lpeg| representation of the pattern, or nil if the pattern is invalid. +local function parse(pattern) + local l = lpeg + + local P, S, V = lpeg.P, lpeg.S, lpeg.V + local C, Cc, Ct, Cf = lpeg.C, lpeg.Cc, lpeg.Ct, lpeg.Cf + + local pathsep = '/' + + local function class(inv, ranges) + for i, r in ipairs(ranges) do + ranges[i] = r[1] .. r[2] + end + local patt = l.R(unpack(ranges)) + if inv == '!' then + patt = P(1) - patt + end + return patt + end + + local function add(acc, a) + return acc + a + end + + local function mul(acc, m) + return acc * m + end + + local function star(stars, after) + return (-after * (l.P(1) - pathsep)) ^ #stars * after + end + + local function dstar(after) + return (-after * l.P(1)) ^ 0 * after + end + + local p = P({ + 'Pattern', + Pattern = V('Elem') ^ -1 * V('End'), + Elem = Cf( + (V('DStar') + V('Star') + V('Ques') + V('Class') + V('CondList') + V('Literal')) + * (V('Elem') + V('End')), + mul + ), + DStar = P('**') * (P(pathsep) * (V('Elem') + V('End')) + V('End')) / dstar, + Star = C(P('*') ^ 1) * (V('Elem') + V('End')) / star, + Ques = P('?') * Cc(l.P(1) - pathsep), + Class = P('[') * C(P('!') ^ -1) * Ct(Ct(C(1) * '-' * C(P(1) - ']')) ^ 1 * ']') / class, + CondList = P('{') * Cf(V('Cond') * (P(',') * V('Cond')) ^ 0, add) * '}', + -- TODO: '*' inside a {} condition is interpreted literally but should probably have the same + -- wildcard semantics it usually has. + -- Fixing this is non-trivial because '*' should match non-greedily up to "the rest of the + -- pattern" which in all other cases is the entire succeeding part of the pattern, but at the end of a {} + -- condition means "everything after the {}" where several other options separated by ',' may + -- exist in between that should not be matched by '*'. + Cond = Cf((V('Ques') + V('Class') + V('CondList') + (V('Literal') - S(',}'))) ^ 1, mul) + + Cc(l.P(0)), + Literal = P(1) / l.P, + End = P(-1) * Cc(l.P(-1)), + }) + + return p:match(pattern) --[[@as vim.lpeg.Pattern?]] +end + +---@private +--- Implementation of LSP 3.17.0's pattern matching: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern +--- +---@param pattern string|vim.lpeg.Pattern The glob pattern (raw or parsed) to match. +---@param s string The string to match against pattern. +---@return boolean Whether or not pattern matches s. +function M._match(pattern, s) + if type(pattern) == 'string' then + local p = assert(parse(pattern)) + return p:match(s) ~= nil + end + return pattern:match(s) ~= nil +end + +M._watchfunc = (vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1) and watch.watch or watch.poll + +---@type table<integer, table<string, function[]>> client id -> registration id -> cancel function +local cancels = vim.defaulttable() + +local queue_timeout_ms = 100 +---@type table<integer, uv.uv_timer_t> client id -> libuv timer which will send queued changes at its timeout +local queue_timers = {} +---@type table<integer, lsp.FileEvent[]> client id -> set of queued changes to send in a single LSP notification +local change_queues = {} +---@type table<integer, table<string, lsp.FileChangeType>> client id -> URI -> last type of change processed +--- Used to prune consecutive events of the same type for the same file +local change_cache = vim.defaulttable() + +---@type table<vim._watch.FileChangeType, lsp.FileChangeType> +local to_lsp_change_type = { + [watch.FileChangeType.Created] = protocol.FileChangeType.Created, + [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed, + [watch.FileChangeType.Deleted] = protocol.FileChangeType.Deleted, +} + +--- Default excludes the same as VSCode's `files.watcherExclude` setting. +--- https://github.com/microsoft/vscode/blob/eef30e7165e19b33daa1e15e92fa34ff4a5df0d3/src/vs/workbench/contrib/files/browser/files.contribution.ts#L261 +---@type vim.lpeg.Pattern parsed Lpeg pattern +M._poll_exclude_pattern = parse('**/.git/{objects,subtree-cache}/**') + + parse('**/node_modules/*/**') + + parse('**/.hg/store/**') + +--- Registers the workspace/didChangeWatchedFiles capability dynamically. +--- +---@param reg lsp.Registration LSP Registration object. +---@param ctx lsp.HandlerContext Context from the |lsp-handler|. +function M.register(reg, ctx) + local client_id = ctx.client_id + local client = assert(vim.lsp.get_client_by_id(client_id), 'Client must be running') + -- Ill-behaved servers may not honor the client capability and try to register + -- anyway, so ignore requests when the user has opted out of the feature. + local has_capability = vim.tbl_get( + client.config.capabilities or {}, + 'workspace', + 'didChangeWatchedFiles', + 'dynamicRegistration' + ) + if not has_capability or not client.workspace_folders then + return + end + local register_options = reg.registerOptions --[[@as lsp.DidChangeWatchedFilesRegistrationOptions]] + ---@type table<string, {pattern: vim.lpeg.Pattern, kind: lsp.WatchKind}[]> by base_dir + local watch_regs = vim.defaulttable() + for _, w in ipairs(register_options.watchers) do + local kind = w.kind + or (protocol.WatchKind.Create + protocol.WatchKind.Change + protocol.WatchKind.Delete) + local glob_pattern = w.globPattern + + if type(glob_pattern) == 'string' then + local pattern = parse(glob_pattern) + if not pattern then + error('Cannot parse pattern: ' .. glob_pattern) + end + for _, folder in ipairs(client.workspace_folders) do + local base_dir = vim.uri_to_fname(folder.uri) + table.insert(watch_regs[base_dir], { pattern = pattern, kind = kind }) + end + else + local base_uri = glob_pattern.baseUri + local uri = type(base_uri) == 'string' and base_uri or base_uri.uri + local base_dir = vim.uri_to_fname(uri) + local pattern = parse(glob_pattern.pattern) + if not pattern then + error('Cannot parse pattern: ' .. glob_pattern.pattern) + end + pattern = lpeg.P(base_dir .. '/') * pattern + table.insert(watch_regs[base_dir], { pattern = pattern, kind = kind }) + end + end + + ---@param base_dir string + local callback = function(base_dir) + return function(fullpath, change_type) + local registrations = watch_regs[base_dir] + for _, w in ipairs(registrations) do + local lsp_change_type = assert( + to_lsp_change_type[change_type], + 'Must receive change type Created, Changed or Deleted' + ) + -- e.g. match kind with Delete bit (0b0100) to Delete change_type (3) + local kind_mask = bit.lshift(1, lsp_change_type - 1) + local change_type_match = bit.band(w.kind, kind_mask) == kind_mask + if w.pattern:match(fullpath) ~= nil and change_type_match then + ---@type lsp.FileEvent + local change = { + uri = vim.uri_from_fname(fullpath), + type = lsp_change_type, + } + + local last_type = change_cache[client_id][change.uri] + if last_type ~= change.type then + change_queues[client_id] = change_queues[client_id] or {} + table.insert(change_queues[client_id], change) + change_cache[client_id][change.uri] = change.type + end + + if not queue_timers[client_id] then + queue_timers[client_id] = vim.defer_fn(function() + ---@type lsp.DidChangeWatchedFilesParams + local params = { + changes = change_queues[client_id], + } + client.notify(ms.workspace_didChangeWatchedFiles, params) + queue_timers[client_id] = nil + change_queues[client_id] = nil + change_cache[client_id] = nil + end, queue_timeout_ms) + end + + break -- if an event matches multiple watchers, only send one notification + end + end + end + end + + for base_dir, watches in pairs(watch_regs) do + local include_pattern = vim.iter(watches):fold(lpeg.P(false), function(acc, w) + return acc + w.pattern + end) + + table.insert( + cancels[client_id][reg.id], + M._watchfunc(base_dir, { + uvflags = { + recursive = true, + }, + -- include_pattern will ensure the pattern from *any* watcher definition for the + -- base_dir matches. This first pass prevents polling for changes to files that + -- will never be sent to the LSP server. A second pass in the callback is still necessary to + -- match a *particular* pattern+kind pair. + include_pattern = include_pattern, + exclude_pattern = M._poll_exclude_pattern, + }, callback(base_dir)) + ) + end +end + +--- Unregisters the workspace/didChangeWatchedFiles capability dynamically. +--- +---@param unreg lsp.Unregistration LSP Unregistration object. +---@param ctx lsp.HandlerContext Context from the |lsp-handler|. +function M.unregister(unreg, ctx) + local client_id = ctx.client_id + local client_cancels = cancels[client_id] + local reg_cancels = client_cancels[unreg.id] + while #reg_cancels > 0 do + table.remove(reg_cancels)() + end + client_cancels[unreg.id] = nil + if not next(cancels[client_id]) then + cancels[client_id] = nil + end +end + +return M diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index 6ac885c78f..cf9acc0808 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -2,10 +2,10 @@ local api = vim.api local validate = vim.validate local util = require('vim.lsp.util') local npcall = vim.F.npcall +local ms = require('vim.lsp.protocol').Methods local M = {} ----@private --- Sends an async request to all active clients attached to the current --- buffer. --- @@ -13,10 +13,11 @@ local M = {} ---@param params (table|nil) Parameters to send to the server ---@param handler (function|nil) See |lsp-handler|. Follows |lsp-handler-resolution| -- ----@returns 2-tuple: ---- - Map of client-id:request-id pairs for all successful requests. ---- - Function which can be used to cancel all the requests. You could instead ---- iterate all clients and call their `cancel_request()` methods. +---@return table<integer, integer> client_request_ids Map of client-id:request-id pairs +---for all successful requests. +---@return function _cancel_all_requests Function which can be used to +---cancel all the requests. You could instead +---iterate all clients and call their `cancel_request()` methods. --- ---@see |vim.lsp.buf_request()| local function request(method, params, handler) @@ -30,8 +31,10 @@ end --- Checks whether the language servers attached to the current buffer are --- ready. --- ----@returns `true` if server responds. +---@return boolean if server responds. +---@deprecated function M.server_ready() + vim.deprecate('vim.lsp.buf.server_ready', nil, '0.10.0') return not not vim.lsp.buf_notify(0, 'window/progress', {}) end @@ -39,10 +42,9 @@ end --- window. Calling the function twice will jump into the floating window. function M.hover() local params = util.make_position_params() - request('textDocument/hover', params) + request(ms.textDocument_hover, params) end ----@private local function request_with_options(name, params, options) local req_handler if options then @@ -60,66 +62,71 @@ end --- ---@param options table|nil additional options --- - reuse_win: (boolean) Jump to existing window if buffer is already open. ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.declaration(options) local params = util.make_position_params() - request_with_options('textDocument/declaration', params, options) + request_with_options(ms.textDocument_declaration, params, options) end --- Jumps to the definition of the symbol under the cursor. --- ---@param options table|nil additional options --- - reuse_win: (boolean) Jump to existing window if buffer is already open. ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.definition(options) local params = util.make_position_params() - request_with_options('textDocument/definition', params, options) + request_with_options(ms.textDocument_definition, params, options) end --- Jumps to the definition of the type of the symbol under the cursor. --- ---@param options table|nil additional options --- - reuse_win: (boolean) Jump to existing window if buffer is already open. ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.type_definition(options) local params = util.make_position_params() - request_with_options('textDocument/typeDefinition', params, options) + request_with_options(ms.textDocument_typeDefinition, params, options) end --- Lists all the implementations for the symbol under the cursor in the --- quickfix window. --- ---@param options table|nil additional options ---- - on_list: (function) handler for list results. See |lsp-on-list-handler| +--- - on_list: (function) |lsp-on-list-handler| replacing the default handler. +--- Called for any non-empty result. function M.implementation(options) local params = util.make_position_params() - request_with_options('textDocument/implementation', params, options) + request_with_options(ms.textDocument_implementation, params, options) end --- Displays signature information about the symbol under the cursor in a --- floating window. function M.signature_help() local params = util.make_position_params() - request('textDocument/signatureHelp', params) + request(ms.textDocument_signatureHelp, params) end --- Retrieves the completion items at the current cursor position. Can only be --- called in Insert mode. --- ----@param context (context support not yet implemented) Additional information +---@param context table (context support not yet implemented) Additional information --- about the context in which a completion was triggered (how it was triggered, --- and by which trigger character, if applicable) --- ----@see vim.lsp.protocol.constants.CompletionTriggerKind +---@see vim.lsp.protocol.CompletionTriggerKind function M.completion(context) local params = util.make_position_params() params.context = context - return request('textDocument/completion', params) + return request(ms.textDocument_completion, params) end ----@private ----@return table {start={row, col}, end={row, col}} using (1, 0) indexing -local function range_from_selection() +---@param bufnr integer +---@param mode "v"|"V" +---@return table {start={row,col}, end={row,col}} using (1, 0) indexing +local function range_from_selection(bufnr, mode) -- TODO: Use `vim.region()` instead https://github.com/neovim/neovim/pull/13896 -- [bufnum, lnum, col, off]; both row and column 1-indexed @@ -138,6 +145,11 @@ local function range_from_selection() start_row, end_row = end_row, start_row start_col, end_col = end_col, start_col end + if mode == 'V' then + start_col = 1 + local lines = api.nvim_buf_get_lines(bufnr, end_row - 1, end_row, true) + end_col = #lines[1] + end return { ['start'] = { start_row, start_col - 1 }, ['end'] = { end_row, end_col - 1 }, @@ -150,8 +162,8 @@ end --- @param options table|nil Optional table which holds the following optional fields: --- - formatting_options (table|nil): --- Can be used to specify FormattingOptions. Some unspecified options will be ---- automatically derived from the current Neovim options. ---- See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#formattingOptions +--- automatically derived from the current Nvim options. +--- See https://microsoft.github.io/language-server-protocol/specification/#formattingOptions --- - timeout_ms (integer|nil, default 1000): --- Time in milliseconds to block for formatting requests. No effect if async=true --- - bufnr (number|nil): @@ -160,13 +172,11 @@ end --- --- - filter (function|nil): --- Predicate used to filter clients. Receives a client as argument and must return a ---- boolean. Clients matching the predicate are included. Example: ---- ---- <pre>lua ---- -- Never request typescript-language-server for formatting ---- vim.lsp.buf.format { ---- filter = function(client) return client.name ~= "tsserver" end ---- } +--- boolean. Clients matching the predicate are included. Example: <pre>lua +--- -- Never request typescript-language-server for formatting +--- vim.lsp.buf.format { +--- filter = function(client) return client.name ~= "tsserver" end +--- } --- </pre> --- --- - async boolean|nil @@ -180,39 +190,34 @@ end --- Restrict formatting to the client with name (client.name) matching this field. --- --- - range (table|nil) Range to format. ---- Table must contain `start` and `end` keys with {row, col} tuples using +--- Table must contain `start` and `end` keys with {row,col} tuples using --- (1,0) indexing. --- Defaults to current selection in visual mode --- Defaults to `nil` in other modes, formatting the full buffer function M.format(options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() - local clients = vim.lsp.get_active_clients({ + local mode = api.nvim_get_mode().mode + local range = options.range + if not range and mode == 'v' or mode == 'V' then + range = range_from_selection(bufnr, mode) + end + local method = range and ms.textDocument_rangeFormatting or ms.textDocument_formatting + + local clients = vim.lsp.get_clients({ id = options.id, bufnr = bufnr, name = options.name, + method = method, }) - if options.filter then clients = vim.tbl_filter(options.filter, clients) end - local mode = api.nvim_get_mode().mode - local range = options.range - if not range and mode == 'v' or mode == 'V' then - range = range_from_selection() - end - local method = range and 'textDocument/rangeFormatting' or 'textDocument/formatting' - - clients = vim.tbl_filter(function(client) - return client.supports_method(method) - end, clients) - if #clients == 0 then vim.notify('[LSP] Format request failed, no matching language servers.') end - ---@private local function set_range(client, params) if range then local range_params = @@ -264,19 +269,16 @@ end function M.rename(new_name, options) options = options or {} local bufnr = options.bufnr or api.nvim_get_current_buf() - local clients = vim.lsp.get_active_clients({ + local clients = vim.lsp.get_clients({ bufnr = bufnr, name = options.name, + -- Clients must at least support rename, prepareRename is optional + method = ms.textDocument_rename, }) if options.filter then clients = vim.tbl_filter(options.filter, clients) end - -- Clients must at least support rename, prepareRename is optional - clients = vim.tbl_filter(function(client) - return client.supports_method('textDocument/rename') - end, clients) - if #clients == 0 then vim.notify('[LSP] Rename, no matching language servers with rename capability.') end @@ -286,7 +288,6 @@ function M.rename(new_name, options) -- Compute early to account for cursor movements after going async local cword = vim.fn.expand('<cword>') - ---@private local function get_text_at_range(range, offset_encoding) return api.nvim_buf_get_text( bufnr, @@ -304,21 +305,20 @@ function M.rename(new_name, options) return end - ---@private local function rename(name) local params = util.make_position_params(win, client.offset_encoding) params.newName = name - local handler = client.handlers['textDocument/rename'] - or vim.lsp.handlers['textDocument/rename'] - client.request('textDocument/rename', params, function(...) + local handler = client.handlers[ms.textDocument_rename] + or vim.lsp.handlers[ms.textDocument_rename] + client.request(ms.textDocument_rename, params, function(...) handler(...) try_use_client(next(clients, idx)) end, bufnr) end - if client.supports_method('textDocument/prepareRename') then + if client.supports_method(ms.textDocument_prepareRename) then local params = util.make_position_params(win, client.offset_encoding) - client.request('textDocument/prepareRename', params, function(err, result) + client.request(ms.textDocument_prepareRename, params, function(err, result) if err or result == nil then if next(clients, idx) then try_use_client(next(clients, idx)) @@ -357,7 +357,7 @@ function M.rename(new_name, options) end, bufnr) else assert( - client.supports_method('textDocument/rename'), + client.supports_method(ms.textDocument_rename), 'Client must support textDocument/rename' ) if new_name then @@ -393,7 +393,7 @@ function M.references(context, options) params.context = context or { includeDeclaration = true, } - request_with_options('textDocument/references', params, options) + request_with_options(ms.textDocument_references, params, options) end --- Lists all symbols in the current buffer in the quickfix window. @@ -402,10 +402,9 @@ end --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.document_symbol(options) local params = { textDocument = util.make_text_document_params() } - request_with_options('textDocument/documentSymbol', params, options) + request_with_options(ms.textDocument_documentSymbol, params, options) end ----@private local function pick_call_hierarchy_item(call_hierarchy_items) if not call_hierarchy_items then return @@ -425,10 +424,9 @@ local function pick_call_hierarchy_item(call_hierarchy_items) return choice end ----@private local function call_hierarchy(method) local params = util.make_position_params() - request('textDocument/prepareCallHierarchy', params, function(err, result, ctx) + request(ms.textDocument_prepareCallHierarchy, params, function(err, result, ctx) if err then vim.notify(err.message, vim.log.levels.WARN) return @@ -450,21 +448,21 @@ end --- |quickfix| window. If the symbol can resolve to multiple --- items, the user can pick one in the |inputlist()|. function M.incoming_calls() - call_hierarchy('callHierarchy/incomingCalls') + call_hierarchy(ms.callHierarchy_incomingCalls) end --- Lists all the items that are called by the symbol under the --- cursor in the |quickfix| window. If the symbol can resolve to --- multiple items, the user can pick one in the |inputlist()|. function M.outgoing_calls() - call_hierarchy('callHierarchy/outgoingCalls') + call_hierarchy(ms.callHierarchy_outgoingCalls) end --- List workspace folders. --- function M.list_workspace_folders() local workspace_folders = {} - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do + for _, client in pairs(vim.lsp.get_clients({ bufnr = 0 })) do for _, folder in pairs(client.workspace_folders or {}) do table.insert(workspace_folders, folder.name) end @@ -485,11 +483,13 @@ function M.add_workspace_folder(workspace_folder) print(workspace_folder, ' is not a valid directory') return end - local params = util.make_workspace_params( - { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } }, - {} - ) - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do + local new_workspace = { + uri = vim.uri_from_fname(workspace_folder), + name = workspace_folder, + } + local params = { event = { added = { new_workspace }, removed = {} } } + local bufnr = vim.api.nvim_get_current_buf() + for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do local found = false for _, folder in pairs(client.workspace_folders or {}) do if folder.name == workspace_folder then @@ -499,11 +499,11 @@ function M.add_workspace_folder(workspace_folder) end end if not found then - vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) + client.notify(ms.workspace_didChangeWorkspaceFolders, params) if not client.workspace_folders then client.workspace_folders = {} end - table.insert(client.workspace_folders, params.event.added[1]) + table.insert(client.workspace_folders, new_workspace) end end end @@ -518,14 +518,16 @@ function M.remove_workspace_folder(workspace_folder) if not (workspace_folder and #workspace_folder > 0) then return end - local params = util.make_workspace_params( - { {} }, - { { uri = vim.uri_from_fname(workspace_folder), name = workspace_folder } } - ) - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = 0 })) do + local workspace = { + uri = vim.uri_from_fname(workspace_folder), + name = workspace_folder, + } + local params = { event = { added = {}, removed = { workspace } } } + local bufnr = vim.api.nvim_get_current_buf() + for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do for idx, folder in pairs(client.workspace_folders) do if folder.name == workspace_folder then - vim.lsp.buf_notify(0, 'workspace/didChangeWorkspaceFolders', params) + client.notify(ms.workspace_didChangeWorkspaceFolders, params) client.workspace_folders[idx] = nil return end @@ -540,7 +542,7 @@ end --- call, the user is prompted to enter a string on the command line. An empty --- string means no filtering is done. --- ----@param query (string, optional) +---@param query string|nil optional ---@param options table|nil additional options --- - on_list: (function) handler for list results. See |lsp-on-list-handler| function M.workspace_symbol(query, options) @@ -549,17 +551,18 @@ function M.workspace_symbol(query, options) return end local params = { query = query } - request_with_options('workspace/symbol', params, options) + request_with_options(ms.workspace_symbol, params, options) end --- Send request to the server to resolve document highlights for the current --- text document position. This request can be triggered by a key mapping or --- by events such as `CursorHold`, e.g.: ---- <pre>vim ---- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() ---- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() ---- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() ---- </pre> +--- +--- ```vim +--- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() +--- autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight() +--- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() +--- ``` --- --- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups --- to be defined or you won't be able to see the actual highlights. @@ -568,17 +571,25 @@ end --- |hl-LspReferenceWrite| function M.document_highlight() local params = util.make_position_params() - request('textDocument/documentHighlight', params) + request(ms.textDocument_documentHighlight, params) end --- Removes document highlights from current buffer. ---- function M.clear_references() util.buf_clear_references() end ----@private --- +---@class vim.lsp.CodeActionResultEntry +---@field error? lsp.ResponseError +---@field result? (lsp.Command|lsp.CodeAction)[] +---@field ctx lsp.HandlerContext + +---@class vim.lsp.buf.code_action.opts +---@field context? lsp.CodeActionContext +---@field filter? fun(x: lsp.CodeAction|lsp.Command):boolean +---@field apply? boolean +---@field range? {start: integer[], end: integer[]} + --- This is not public because the main extension point is --- vim.ui.select which can be overridden independently. --- @@ -587,21 +598,21 @@ end --- from multiple clients to have 1 single UI prompt for the user, yet we still --- need to be able to link a `CodeAction|Command` to the right client for --- `codeAction/resolve` -local function on_code_action_results(results, ctx, options) - local action_tuples = {} - - ---@private +---@param results table<integer, vim.lsp.CodeActionResultEntry> +---@param opts? vim.lsp.buf.code_action.opts +local function on_code_action_results(results, opts) + ---@param a lsp.Command|lsp.CodeAction local function action_filter(a) -- filter by specified action kind - if options and options.context and options.context.only then + if opts and opts.context and opts.context.only then if not a.kind then return false end local found = false - for _, o in ipairs(options.context.only) do - -- action kinds are hierarchical with . as a separator: when requesting only - -- 'quickfix' this filter allows both 'quickfix' and 'quickfix.foo', for example - if a.kind:find('^' .. o .. '$') or a.kind:find('^' .. o .. '%.') then + for _, o in ipairs(opts.context.only) do + -- action kinds are hierarchical with . as a separator: when requesting only 'type-annotate' + -- this filter allows both 'type-annotate' and 'type-annotate.foo', for example + if a.kind == o or vim.startswith(a.kind, o .. '.') then found = true break end @@ -611,53 +622,43 @@ local function on_code_action_results(results, ctx, options) end end -- filter by user function - if options and options.filter and not options.filter(a) then + if opts and opts.filter and not opts.filter(a) then return false end -- no filter removed this action return true end - for client_id, result in pairs(results) do + ---@type {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext}[] + local actions = {} + for _, result in pairs(results) do for _, action in pairs(result.result or {}) do if action_filter(action) then - table.insert(action_tuples, { client_id, action }) + table.insert(actions, { action = action, ctx = result.ctx }) end end end - if #action_tuples == 0 then + if #actions == 0 then vim.notify('No code actions available', vim.log.levels.INFO) return end - ---@private - local function apply_action(action, client) + ---@param action lsp.Command|lsp.CodeAction + ---@param client lsp.Client + ---@param ctx lsp.HandlerContext + local function apply_action(action, client, ctx) if action.edit then util.apply_workspace_edit(action.edit, client.offset_encoding) end if action.command then local command = type(action.command) == 'table' and action.command or action - local fn = client.commands[command.command] or vim.lsp.commands[command.command] - if fn then - local enriched_ctx = vim.deepcopy(ctx) - enriched_ctx.client_id = client.id - fn(command, enriched_ctx) - else - -- Not using command directly to exclude extra properties, - -- see https://github.com/python-lsp/python-lsp-server/issues/146 - local params = { - command = command.command, - arguments = command.arguments, - workDoneToken = command.workDoneToken, - } - client.request('workspace/executeCommand', params, nil, ctx.bufnr) - end + client._exec_cmd(command, ctx) end end - ---@private - local function on_user_choice(action_tuple) - if not action_tuple then + ---@param choice {action: lsp.Command|lsp.CodeAction, ctx: lsp.HandlerContext} + local function on_user_choice(choice) + if not choice then return end -- textDocument/codeAction can return either Command[] or CodeAction[] @@ -672,52 +673,51 @@ local function on_code_action_results(results, ctx, options) -- command: string -- arguments?: any[] -- - local client = vim.lsp.get_client_by_id(action_tuple[1]) - local action = action_tuple[2] - if - not action.edit - and client - and vim.tbl_get(client.server_capabilities, 'codeActionProvider', 'resolveProvider') - then - client.request('codeAction/resolve', action, function(err, resolved_action) + ---@type lsp.Client + local client = assert(vim.lsp.get_client_by_id(choice.ctx.client_id)) + local action = choice.action + local bufnr = assert(choice.ctx.bufnr, 'Must have buffer number') + + local reg = client.dynamic_capabilities:get(ms.textDocument_codeAction, { bufnr = bufnr }) + + local supports_resolve = vim.tbl_get(reg or {}, 'registerOptions', 'resolveProvider') + or client.supports_method(ms.codeAction_resolve) + + if not action.edit and client and supports_resolve then + client.request(ms.codeAction_resolve, action, function(err, resolved_action) if err then - vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) - return + if action.command then + apply_action(action, client, choice.ctx) + else + vim.notify(err.code .. ': ' .. err.message, vim.log.levels.ERROR) + end + else + apply_action(resolved_action, client, choice.ctx) end - apply_action(resolved_action, client) - end) + end, bufnr) else - apply_action(action, client) + apply_action(action, client, choice.ctx) end end -- If options.apply is given, and there are just one remaining code action, -- apply it directly without querying the user. - if options and options.apply and #action_tuples == 1 then - on_user_choice(action_tuples[1]) + if opts and opts.apply and #actions == 1 then + on_user_choice(actions[1]) return end - vim.ui.select(action_tuples, { + ---@param item {action: lsp.Command|lsp.CodeAction} + local function format_item(item) + local title = item.action.title:gsub('\r\n', '\\r\\n') + return title:gsub('\n', '\\n') + end + local select_opts = { prompt = 'Code actions:', kind = 'codeaction', - format_item = function(action_tuple) - local title = action_tuple[2].title:gsub('\r\n', '\\r\\n') - return title:gsub('\n', '\\n') - end, - }, on_user_choice) -end - ---- Requests code actions from all clients and calls the handler exactly once ---- with all aggregated results ----@private -local function code_action_request(params, options) - local bufnr = api.nvim_get_current_buf() - local method = 'textDocument/codeAction' - vim.lsp.buf_request_all(bufnr, method, params, function(results) - local ctx = { bufnr = bufnr, method = method, params = params } - on_code_action_results(results, ctx, options) - end) + format_item = format_item, + } + vim.ui.select(actions, select_opts, on_user_choice) end --- Selects a code action available at the current @@ -743,11 +743,11 @@ end --- - range: (table|nil) --- Range for which code actions should be requested. --- If in visual mode this defaults to the active selection. ---- Table must contain `start` and `end` keys with {row, col} tuples +--- Table must contain `start` and `end` keys with {row,col} tuples --- using mark-like indexing. See |api-indexing| --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction ----@see vim.lsp.protocol.constants.CodeActionTriggerKind +---@see vim.lsp.protocol.CodeActionTriggerKind function M.code_action(options) validate({ options = { options, 't', true } }) options = options or {} @@ -764,21 +764,50 @@ function M.code_action(options) local bufnr = api.nvim_get_current_buf() context.diagnostics = vim.lsp.diagnostic.get_line_diagnostics(bufnr) end - local params local mode = api.nvim_get_mode().mode - if options.range then - assert(type(options.range) == 'table', 'code_action range must be a table') - local start = assert(options.range.start, 'range must have a `start` property') - local end_ = assert(options.range['end'], 'range must have a `end` property') - params = util.make_given_range_params(start, end_) - elseif mode == 'v' or mode == 'V' then - local range = range_from_selection() - params = util.make_given_range_params(range.start, range['end']) - else - params = util.make_range_params() + local bufnr = api.nvim_get_current_buf() + local win = api.nvim_get_current_win() + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_codeAction }) + local remaining = #clients + if remaining == 0 then + if next(vim.lsp.get_clients({ bufnr = bufnr })) then + vim.notify(vim.lsp._unsupported_method(ms.textDocument_codeAction), vim.log.levels.WARN) + end + return + end + + ---@type table<integer, vim.lsp.CodeActionResultEntry> + local results = {} + + ---@param err? lsp.ResponseError + ---@param result? (lsp.Command|lsp.CodeAction)[] + ---@param ctx lsp.HandlerContext + local function on_result(err, result, ctx) + results[ctx.client_id] = { error = err, result = result, ctx = ctx } + remaining = remaining - 1 + if remaining == 0 then + on_code_action_results(results, options) + end + end + + for _, client in ipairs(clients) do + ---@type lsp.CodeActionParams + local params + if options.range then + assert(type(options.range) == 'table', 'code_action range must be a table') + local start = assert(options.range.start, 'range must have a `start` property') + local end_ = assert(options.range['end'], 'range must have a `end` property') + params = util.make_given_range_params(start, end_, bufnr, client.offset_encoding) + elseif mode == 'v' or mode == 'V' then + local range = range_from_selection(bufnr, mode) + params = + util.make_given_range_params(range.start, range['end'], bufnr, client.offset_encoding) + else + params = util.make_range_params(win, client.offset_encoding) + end + params.context = context + client.request(ms.textDocument_codeAction, params, on_result, bufnr) end - params.context = context - code_action_request(params, options) end --- Executes an LSP server command. @@ -795,8 +824,7 @@ function M.execute_command(command_params) arguments = command_params.arguments, workDoneToken = command_params.workDoneToken, } - request('workspace/executeCommand', command_params) + request(ms.workspace_executeCommand, command_params) end return M --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua index 17489ed84d..9cccaa1d66 100644 --- a/runtime/lua/vim/lsp/codelens.lua +++ b/runtime/lua/vim/lsp/codelens.lua @@ -1,5 +1,6 @@ local util = require('vim.lsp.util') local log = require('vim.lsp.log') +local ms = require('vim.lsp.protocol').Methods local api = vim.api local M = {} @@ -7,6 +8,7 @@ local M = {} --- to throttle refreshes to at most one at a time local active_refreshes = {} +---@type table<integer, table<integer, lsp.CodeLens[]>> --- bufnr -> client_id -> lenses local lens_cache_by_buf = setmetatable({}, { __index = function(t, b) @@ -15,6 +17,8 @@ local lens_cache_by_buf = setmetatable({}, { end, }) +---@type table<integer, integer> +---client_id -> namespace local namespaces = setmetatable({}, { __index = function(t, key) local value = api.nvim_create_namespace('vim_lsp_codelens:' .. key) @@ -26,43 +30,34 @@ local namespaces = setmetatable({}, { ---@private M.__namespaces = namespaces ----@private +local augroup = api.nvim_create_augroup('vim_lsp_codelens', {}) + +api.nvim_create_autocmd('LspDetach', { + group = augroup, + callback = function(ev) + M.clear(ev.data.client_id, ev.buf) + end, +}) + +---@param lens lsp.CodeLens +---@param bufnr integer +---@param client_id integer local function execute_lens(lens, bufnr, client_id) local line = lens.range.start.line api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1) local client = vim.lsp.get_client_by_id(client_id) assert(client, 'Client is required to execute lens, client_id=' .. client_id) - local command = lens.command - local fn = client.commands[command.command] or vim.lsp.commands[command.command] - if fn then - fn(command, { bufnr = bufnr, client_id = client_id }) - return - end - -- Need to use the client that returned the lens → must not use buf_request - local command_provider = client.server_capabilities.executeCommandProvider - local commands = type(command_provider) == 'table' and command_provider.commands or {} - if not vim.tbl_contains(commands, command.command) then - vim.notify( - string.format( - 'Language server does not support command `%s`. This command may require a client extension.', - command.command - ), - vim.log.levels.WARN - ) - return - end - client.request('workspace/executeCommand', command, function(...) - local result = vim.lsp.handlers['workspace/executeCommand'](...) + client._exec_cmd(lens.command, { bufnr = bufnr }, function(...) + vim.lsp.handlers[ms.workspace_executeCommand](...) M.refresh() - return result - end, bufnr) + end) end --- Return all lenses for the given buffer --- ----@param bufnr number Buffer number. 0 can be used for the current buffer. ----@return table (`CodeLens[]`) +---@param bufnr integer Buffer number. 0 can be used for the current buffer. +---@return lsp.CodeLens[] function M.get(bufnr) local lenses_by_client = lens_cache_by_buf[bufnr or 0] if not lenses_by_client then @@ -97,6 +92,7 @@ function M.run() else vim.ui.select(options, { prompt = 'Code lenses:', + kind = 'codelens', format_item = function(option) return option.lens.command.title end, @@ -108,22 +104,26 @@ function M.run() end end ----@private local function resolve_bufnr(bufnr) return bufnr == 0 and api.nvim_get_current_buf() or bufnr end --- Clear the lenses --- ----@param client_id number|nil filter by client_id. All clients if nil ----@param bufnr number|nil filter by buffer. All buffers if nil +---@param client_id integer|nil filter by client_id. All clients if nil +---@param bufnr integer|nil filter by buffer. All buffers if nil function M.clear(client_id, bufnr) - local buffers = bufnr and { resolve_bufnr(bufnr) } or vim.tbl_keys(lens_cache_by_buf) + bufnr = bufnr and resolve_bufnr(bufnr) + local buffers = bufnr and { bufnr } + or vim.tbl_filter(api.nvim_buf_is_loaded, api.nvim_list_bufs()) for _, iter_bufnr in pairs(buffers) do local client_ids = client_id and { client_id } or vim.tbl_keys(namespaces) for _, iter_client_id in pairs(client_ids) do local ns = namespaces[iter_client_id] - lens_cache_by_buf[iter_bufnr][iter_client_id] = {} + -- there can be display()ed lenses, which are not stored in cache + if lens_cache_by_buf[iter_bufnr] then + lens_cache_by_buf[iter_bufnr][iter_client_id] = {} + end api.nvim_buf_clear_namespace(iter_bufnr, ns, 0, -1) end end @@ -131,16 +131,21 @@ end --- Display the lenses using virtual text --- ----@param lenses table of lenses to display (`CodeLens[] | null`) ----@param bufnr number ----@param client_id number +---@param lenses? lsp.CodeLens[] lenses to display +---@param bufnr integer +---@param client_id integer function M.display(lenses, bufnr, client_id) + if not api.nvim_buf_is_loaded(bufnr) then + return + end + local ns = namespaces[client_id] if not lenses or not next(lenses) then api.nvim_buf_clear_namespace(bufnr, ns, 0, -1) return end - local lenses_by_lnum = {} + + local lenses_by_lnum = {} ---@type table<integer, lsp.CodeLens[]> for _, lens in pairs(lenses) do local line_lenses = lenses_by_lnum[lens.range.start.line] if not line_lenses then @@ -176,17 +181,21 @@ end --- Store lenses for a specific buffer and client --- ----@param lenses table of lenses to store (`CodeLens[] | null`) ----@param bufnr number ----@param client_id number +---@param lenses? lsp.CodeLens[] lenses to store +---@param bufnr integer +---@param client_id integer function M.save(lenses, bufnr, client_id) + if not api.nvim_buf_is_loaded(bufnr) then + return + end + local lenses_by_client = lens_cache_by_buf[bufnr] if not lenses_by_client then lenses_by_client = {} lens_cache_by_buf[bufnr] = lenses_by_client local ns = namespaces[client_id] api.nvim_buf_attach(bufnr, false, { - on_detach = function(b) + on_detach = function(_, b) lens_cache_by_buf[b] = nil end, on_lines = function(_, b, _, first_lnum, last_lnum) @@ -197,7 +206,10 @@ function M.save(lenses, bufnr, client_id) lenses_by_client[client_id] = lenses end ----@private +---@param lenses? lsp.CodeLens[] +---@param bufnr integer +---@param client_id integer +---@param callback fun() local function resolve_lenses(lenses, bufnr, client_id, callback) lenses = lenses or {} local num_lens = vim.tbl_count(lenses) @@ -206,7 +218,6 @@ local function resolve_lenses(lenses, bufnr, client_id, callback) return end - ---@private local function countdown() num_lens = num_lens - 1 if num_lens == 0 then @@ -220,19 +231,24 @@ local function resolve_lenses(lenses, bufnr, client_id, callback) countdown() else client.request('codeLens/resolve', lens, function(_, result) - if result and result.command then + if api.nvim_buf_is_loaded(bufnr) and result and result.command then lens.command = result.command -- Eager display to have some sort of incremental feedback -- Once all lenses got resolved there will be a full redraw for all lenses -- So that multiple lens per line are properly displayed - api.nvim_buf_set_extmark( - bufnr, - ns, - lens.range.start.line, - 0, - { virt_text = { { lens.command.title, 'LspCodeLens' } }, hl_mode = 'combine' } - ) + + local num_lines = api.nvim_buf_line_count(bufnr) + if lens.range.start.line <= num_lines then + api.nvim_buf_set_extmark( + bufnr, + ns, + lens.range.start.line, + 0, + { virt_text = { { lens.command.title, 'LspCodeLens' } }, hl_mode = 'combine' } + ) + end end + countdown() end, bufnr) end @@ -264,10 +280,10 @@ end --- It is recommended to trigger this using an autocmd or via keymap. --- --- Example: ---- <pre>vim ---- autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() ---- </pre> --- +--- ```vim +--- autocmd BufEnter,CursorHold,InsertLeave <buffer> lua vim.lsp.codelens.refresh() +--- ``` function M.refresh() local params = { textDocument = util.make_text_document_params(), @@ -277,7 +293,7 @@ function M.refresh() return end active_refreshes[bufnr] = true - vim.lsp.buf_request(0, 'textDocument/codeLens', params, M.on_codelens) + vim.lsp.buf_request(0, ms.textDocument_codeLens, params, M.on_codelens) end return M diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua index 5e2bf75f1b..b6f0cfa0b3 100644 --- a/runtime/lua/vim/lsp/diagnostic.lua +++ b/runtime/lua/vim/lsp/diagnostic.lua @@ -1,18 +1,18 @@ ---@brief lsp-diagnostic ---- ----@class Diagnostic ----@field range Range ----@field message string ----@field severity DiagnosticSeverity|nil ----@field code number | string ----@field source string ----@field tags DiagnosticTag[] ----@field relatedInformation DiagnosticRelatedInformation[] + +local util = require('vim.lsp.util') +local protocol = require('vim.lsp.protocol') +local log = require('vim.lsp.log') +local ms = protocol.Methods + +local api = vim.api local M = {} +local augroup = api.nvim_create_augroup('vim_lsp_diagnostic', {}) + local DEFAULT_CLIENT_ID = -1 ----@private + local function get_client_id(client_id) if client_id == nil then client_id = DEFAULT_CLIENT_ID @@ -21,15 +21,15 @@ local function get_client_id(client_id) return client_id end ----@private +---@param severity lsp.DiagnosticSeverity local function severity_lsp_to_vim(severity) if type(severity) == 'string' then - severity = vim.lsp.protocol.DiagnosticSeverity[severity] + severity = protocol.DiagnosticSeverity[severity] end return severity end ----@private +---@return lsp.DiagnosticSeverity local function severity_vim_to_lsp(severity) if type(severity) == 'string' then severity = vim.diagnostic.severity[severity] @@ -37,7 +37,7 @@ local function severity_vim_to_lsp(severity) return severity end ----@private +---@return integer local function line_byte_from_position(lines, lnum, col, offset_encoding) if not lines or offset_encoding == 'utf-8' then return col @@ -52,7 +52,6 @@ local function line_byte_from_position(lines, lnum, col, offset_encoding) return col end ----@private local function get_buf_lines(bufnr) if vim.api.nvim_buf_is_loaded(bufnr) then return vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) @@ -77,12 +76,36 @@ local function get_buf_lines(bufnr) return lines end ----@private +--- @param diagnostic lsp.Diagnostic +--- @param client_id integer +--- @return table? +local function tags_lsp_to_vim(diagnostic, client_id) + local tags ---@type table? + for _, tag in ipairs(diagnostic.tags or {}) do + if tag == protocol.DiagnosticTag.Unnecessary then + tags = tags or {} + tags.unnecessary = true + elseif tag == protocol.DiagnosticTag.Deprecated then + tags = tags or {} + tags.deprecated = true + else + log.info(string.format('Unknown DiagnosticTag %d from LSP client %d', tag, client_id)) + end + end + return tags +end + +---@param diagnostics lsp.Diagnostic[] +---@param bufnr integer +---@param client_id integer +---@return Diagnostic[] local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) local buf_lines = get_buf_lines(bufnr) local client = vim.lsp.get_client_by_id(client_id) local offset_encoding = client and client.offset_encoding or 'utf-16' + ---@diagnostic disable-next-line:no-unknown return vim.tbl_map(function(diagnostic) + ---@cast diagnostic lsp.Diagnostic local start = diagnostic.range.start local _end = diagnostic.range['end'] return { @@ -94,12 +117,12 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) message = diagnostic.message, source = diagnostic.source, code = diagnostic.code, + _tags = tags_lsp_to_vim(diagnostic, client_id), user_data = { lsp = { -- usage of user_data.lsp.code is deprecated in favor of the top-level code field code = diagnostic.code, codeDescription = diagnostic.codeDescription, - tags = diagnostic.tags, relatedInformation = diagnostic.relatedInformation, data = diagnostic.data, }, @@ -108,9 +131,12 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id) end, diagnostics) end ----@private +--- @param diagnostics Diagnostic[] +--- @return lsp.Diagnostic[] local function diagnostic_vim_to_lsp(diagnostics) + ---@diagnostic disable-next-line:no-unknown return vim.tbl_map(function(diagnostic) + ---@cast diagnostic Diagnostic return vim.tbl_extend('keep', { -- "keep" the below fields over any duplicate fields in diagnostic.user_data.lsp range = { @@ -131,26 +157,53 @@ local function diagnostic_vim_to_lsp(diagnostics) end, diagnostics) end -local _client_namespaces = {} +---@type table<integer, integer> +local _client_push_namespaces = {} + +---@type table<string, integer> +local _client_pull_namespaces = {} ---- Get the diagnostic namespace associated with an LSP client |vim.diagnostic|. +--- Get the diagnostic namespace associated with an LSP client |vim.diagnostic| for diagnostics --- ----@param client_id number The id of the LSP client -function M.get_namespace(client_id) +---@param client_id integer The id of the LSP client +---@param is_pull boolean? Whether the namespace is for a pull or push client. Defaults to push +function M.get_namespace(client_id, is_pull) vim.validate({ client_id = { client_id, 'n' } }) - if not _client_namespaces[client_id] then - local client = vim.lsp.get_client_by_id(client_id) + + local client = vim.lsp.get_client_by_id(client_id) + if is_pull then + local server_id = + vim.tbl_get((client or {}).server_capabilities, 'diagnosticProvider', 'identifier') + local key = string.format('%d:%s', client_id, server_id or 'nil') + local name = string.format( + 'vim.lsp.%s.%d.%s', + client and client.name or 'unknown', + client_id, + server_id or 'nil' + ) + local ns = _client_pull_namespaces[key] + if not ns then + ns = api.nvim_create_namespace(name) + _client_pull_namespaces[key] = ns + end + return ns + else local name = string.format('vim.lsp.%s.%d', client and client.name or 'unknown', client_id) - _client_namespaces[client_id] = vim.api.nvim_create_namespace(name) + local ns = _client_push_namespaces[client_id] + if not ns then + ns = api.nvim_create_namespace(name) + _client_push_namespaces[client_id] = ns + end + return ns end - return _client_namespaces[client_id] end --- |lsp-handler| for the method "textDocument/publishDiagnostics" --- --- See |vim.diagnostic.config()| for configuration options. Handler-specific --- configuration can be set using |vim.lsp.with()|: ---- <pre>lua +--- +--- ```lua --- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( --- vim.lsp.diagnostic.on_publish_diagnostics, { --- -- Enable underline, use default values @@ -168,7 +221,7 @@ end --- update_in_insert = false, --- } --- ) ---- </pre> +--- ``` --- ---@param config table Configuration table (see |vim.diagnostic.config()|). function M.on_publish_diagnostics(_, result, ctx, config) @@ -186,7 +239,7 @@ function M.on_publish_diagnostics(_, result, ctx, config) end client_id = get_client_id(client_id) - local namespace = M.get_namespace(client_id) + local namespace = M.get_namespace(client_id, false) if config then for _, opt in pairs(config) do @@ -206,13 +259,82 @@ function M.on_publish_diagnostics(_, result, ctx, config) vim.diagnostic.set(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)) end ---- Clear diagnostics and diagnostic cache. +--- |lsp-handler| for the method "textDocument/diagnostic" +--- +--- See |vim.diagnostic.config()| for configuration options. Handler-specific +--- configuration can be set using |vim.lsp.with()|: +--- +--- ```lua +--- vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with( +--- vim.lsp.diagnostic.on_diagnostic, { +--- -- Enable underline, use default values +--- underline = true, +--- -- Enable virtual text, override spacing to 4 +--- virtual_text = { +--- spacing = 4, +--- }, +--- -- Use a function to dynamically turn signs off +--- -- and on, using buffer local variables +--- signs = function(namespace, bufnr) +--- return vim.b[bufnr].show_signs == true +--- end, +--- -- Disable a feature +--- update_in_insert = false, +--- } +--- ) +--- ``` +--- +---@param config table Configuration table (see |vim.diagnostic.config()|). +function M.on_diagnostic(_, result, ctx, config) + local client_id = ctx.client_id + local uri = ctx.params.textDocument.uri + local fname = vim.uri_to_fname(uri) + + if result == nil then + return + end + + if result.kind == 'unchanged' then + return + end + + local diagnostics = result.items + if #diagnostics == 0 and vim.fn.bufexists(fname) == 0 then + return + end + local bufnr = vim.fn.bufadd(fname) + + if not bufnr then + return + end + + client_id = get_client_id(client_id) + + local namespace = M.get_namespace(client_id, true) + + if config then + for _, opt in pairs(config) do + if type(opt) == 'table' and not opt.severity and opt.severity_limit then + opt.severity = { min = severity_lsp_to_vim(opt.severity_limit) } + end + end + + -- Persist configuration to ensure buffer reloads use the same + -- configuration. To make lsp.with configuration work (See :help + -- lsp-handler-configuration) + vim.diagnostic.config(config, namespace) + end + + vim.diagnostic.set(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)) +end + +--- Clear push diagnostics and diagnostic cache. --- --- Diagnostic producers should prefer |vim.diagnostic.reset()|. However, --- this method signature is still used internally in some parts of the LSP --- implementation so it's simply marked @private rather than @deprecated. --- ----@param client_id number +---@param client_id integer ---@param buffer_client_map table map of buffers to active clients ---@private function M.reset(client_id, buffer_client_map) @@ -220,7 +342,7 @@ function M.reset(client_id, buffer_client_map) vim.schedule(function() for bufnr, client_ids in pairs(buffer_client_map) do if client_ids[client_id] then - local namespace = M.get_namespace(client_id) + local namespace = M.get_namespace(client_id, false) vim.diagnostic.reset(namespace, bufnr) end end @@ -232,14 +354,14 @@ end --- Marked private as this is used internally by the LSP subsystem, but --- most users should instead prefer |vim.diagnostic.get()|. --- ----@param bufnr number|nil The buffer number ----@param line_nr number|nil The line number +---@param bufnr integer|nil The buffer number +---@param line_nr integer|nil The line number ---@param opts table|nil Configuration keys --- - severity: (DiagnosticSeverity, default nil) --- - Only return diagnostics with this severity. Overrides severity_limit --- - severity_limit: (DiagnosticSeverity, default nil) --- - Limit severity of diagnostics found. E.g. "Warning" means { "Error", "Warning" } will be valid. ----@param client_id|nil number the client id +---@param client_id integer|nil the client id ---@return table Table with map of line number to list of diagnostics. --- Structured: { [1] = {...}, [5] = {.... } } ---@private @@ -252,7 +374,7 @@ function M.get_line_diagnostics(bufnr, line_nr, opts, client_id) end if client_id then - opts.namespace = M.get_namespace(client_id) + opts.namespace = M.get_namespace(client_id, false) end if not line_nr then @@ -264,4 +386,95 @@ function M.get_line_diagnostics(bufnr, line_nr, opts, client_id) return diagnostic_vim_to_lsp(vim.diagnostic.get(bufnr, opts)) end +--- Clear diagnostics from pull based clients +--- @private +local function clear(bufnr) + for _, namespace in pairs(_client_pull_namespaces) do + vim.diagnostic.reset(namespace, bufnr) + end +end + +---@class lsp.diagnostic.bufstate +---@field enabled boolean Whether inlay hints are enabled for this buffer +---@type table<integer, lsp.diagnostic.bufstate> +local bufstates = {} + +--- Disable pull diagnostics for a buffer +--- @private +local function disable(bufnr) + local bufstate = bufstates[bufnr] + if bufstate then + bufstate.enabled = false + end + clear(bufnr) +end + +--- Refresh diagnostics, only if we have attached clients that support it +---@param bufnr (integer) buffer number +---@param opts? table Additional options to pass to util._refresh +---@private +local function _refresh(bufnr, opts) + opts = opts or {} + opts['bufnr'] = bufnr + util._refresh(ms.textDocument_diagnostic, opts) +end + +--- Enable pull diagnostics for a buffer +---@param bufnr (integer) Buffer handle, or 0 for current +---@private +function M._enable(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + if not bufstates[bufnr] then + bufstates[bufnr] = { enabled = true } + + api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if + opts.data.method ~= ms.textDocument_didChange + and opts.data.method ~= ms.textDocument_didOpen + then + return + end + if bufstates[bufnr] and bufstates[bufnr].enabled then + _refresh(bufnr, { only_visible = true, client_id = opts.data.client_id }) + end + end, + group = augroup, + }) + + api.nvim_buf_attach(bufnr, false, { + on_reload = function() + if bufstates[bufnr] and bufstates[bufnr].enabled then + _refresh(bufnr) + end + end, + on_detach = function() + disable(bufnr) + end, + }) + + api.nvim_create_autocmd('LspDetach', { + buffer = bufnr, + callback = function(args) + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_diagnostic }) + + if + not vim.iter(clients):any(function(c) + return c.id ~= args.data.client_id + end) + then + disable(bufnr) + end + end, + group = augroup, + }) + else + bufstates[bufnr].enabled = true + end +end + return M diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua index 5096100a60..6fde55cf04 100644 --- a/runtime/lua/vim/lsp/handlers.lua +++ b/runtime/lua/vim/lsp/handlers.lua @@ -1,5 +1,6 @@ local log = require('vim.lsp.log') local protocol = require('vim.lsp.protocol') +local ms = protocol.Methods local util = require('vim.lsp.util') local api = vim.api @@ -7,82 +8,70 @@ local M = {} -- FIXME: DOC: Expose in vimdocs ----@private --- Writes to error buffer. ----@param ... (table of strings) Will be concatenated before being written +---@param ... string Will be concatenated before being written local function err_message(...) vim.notify(table.concat(vim.tbl_flatten({ ... })), vim.log.levels.ERROR) api.nvim_command('redraw') end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand -M['workspace/executeCommand'] = function(_, _, _, _) +M[ms.workspace_executeCommand] = function(_, _, _, _) -- Error handling is done implicitly by wrapping all handlers; see end of this file end ----@private -local function progress_handler(_, result, ctx, _) - local client_id = ctx.client_id - local client = vim.lsp.get_client_by_id(client_id) - local client_name = client and client.name or string.format('id=%d', client_id) +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress +---@param result lsp.ProgressParams +---@param ctx lsp.HandlerContext +M[ms.dollar_progress] = function(_, result, ctx) + local client = vim.lsp.get_client_by_id(ctx.client_id) if not client then - err_message('LSP[', client_name, '] client has shut down during progress update') + err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update') return vim.NIL end - local val = result.value -- unspecified yet - local token = result.token -- string or number + local kind = nil + local value = result.value - if type(val) ~= 'table' then - val = { content = val } - end - if val.kind then - if val.kind == 'begin' then - client.messages.progress[token] = { - title = val.title, - cancellable = val.cancellable, - message = val.message, - percentage = val.percentage, - } - elseif val.kind == 'report' then - client.messages.progress[token].cancellable = val.cancellable - client.messages.progress[token].message = val.message - client.messages.progress[token].percentage = val.percentage - elseif val.kind == 'end' then - if client.messages.progress[token] == nil then - err_message('LSP[', client_name, '] received `end` message with no corresponding `begin`') - else - client.messages.progress[token].message = val.message - client.messages.progress[token].done = true + if type(value) == 'table' then + kind = value.kind + -- Carry over title of `begin` messages to `report` and `end` messages + -- So that consumers always have it available, even if they consume a + -- subset of the full sequence + if kind == 'begin' then + client.progress.pending[result.token] = value.title + else + value.title = client.progress.pending[result.token] + if kind == 'end' then + client.progress.pending[result.token] = nil end end - else - client.messages.progress[token] = val - client.messages.progress[token].done = true end - api.nvim_exec_autocmds('User', { pattern = 'LspProgressUpdate', modeline = false }) -end + client.progress:push(result) ---see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#progress -M['$/progress'] = progress_handler + api.nvim_exec_autocmds('LspProgress', { + pattern = kind, + modeline = false, + data = { client_id = ctx.client_id, result = result }, + }) +end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_workDoneProgress_create -M['window/workDoneProgress/create'] = function(_, result, ctx) - local client_id = ctx.client_id - local client = vim.lsp.get_client_by_id(client_id) - local token = result.token -- string or number - local client_name = client and client.name or string.format('id=%d', client_id) +---@param result lsp.WorkDoneProgressCreateParams +---@param ctx lsp.HandlerContext +M[ms.window_workDoneProgress_create] = function(_, result, ctx) + local client = vim.lsp.get_client_by_id(ctx.client_id) if not client then - err_message('LSP[', client_name, '] client has shut down while creating progress report') + err_message('LSP[id=', tostring(ctx.client_id), '] client has shut down during progress update') return vim.NIL end - client.messages.progress[token] = {} + client.progress:push(result) return vim.NIL end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessageRequest ---@param result lsp.ShowMessageRequestParams -M['window/showMessageRequest'] = function(_, result) +M[ms.window_showMessageRequest] = function(_, result) local actions = result.actions or {} local co, is_main = coroutine.running() if co and not is_main then @@ -117,20 +106,52 @@ M['window/showMessageRequest'] = function(_, result) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_registerCapability -M['client/registerCapability'] = function(_, _, ctx) +M[ms.client_registerCapability] = function(_, result, ctx) local client_id = ctx.client_id - local warning_tpl = 'The language server %s triggers a registerCapability ' - .. 'handler despite dynamicRegistration set to false. ' - .. 'Report upstream, this warning is harmless' + ---@type lsp.Client local client = vim.lsp.get_client_by_id(client_id) - local client_name = client and client.name or string.format('id=%d', client_id) - local warning = string.format(warning_tpl, client_name) - log.warn(warning) + + client.dynamic_capabilities:register(result.registrations) + for bufnr, _ in pairs(client.attached_buffers) do + vim.lsp._set_defaults(client, bufnr) + end + + ---@type string[] + local unsupported = {} + for _, reg in ipairs(result.registrations) do + if reg.method == ms.workspace_didChangeWatchedFiles then + require('vim.lsp._watchfiles').register(reg, ctx) + elseif not client.dynamic_capabilities:supports_registration(reg.method) then + unsupported[#unsupported + 1] = reg.method + end + end + if #unsupported > 0 then + local warning_tpl = 'The language server %s triggers a registerCapability ' + .. 'handler for %s despite dynamicRegistration set to false. ' + .. 'Report upstream, this warning is harmless' + local client_name = client and client.name or string.format('id=%d', client_id) + local warning = string.format(warning_tpl, client_name, table.concat(unsupported, ', ')) + log.warn(warning) + end + return vim.NIL +end + +--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#client_unregisterCapability +M[ms.client_unregisterCapability] = function(_, result, ctx) + local client_id = ctx.client_id + local client = vim.lsp.get_client_by_id(client_id) + client.dynamic_capabilities:unregister(result.unregisterations) + + for _, unreg in ipairs(result.unregisterations) do + if unreg.method == ms.workspace_didChangeWatchedFiles then + require('vim.lsp._watchfiles').unregister(unreg, ctx) + end + end return vim.NIL end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit -M['workspace/applyEdit'] = function(_, workspace_edit, ctx) +M[ms.workspace_applyEdit] = function(_, workspace_edit, ctx) assert( workspace_edit, 'workspace/applyEdit must be called with `ApplyWorkspaceEditParams`. Server is violating the specification' @@ -150,7 +171,7 @@ M['workspace/applyEdit'] = function(_, workspace_edit, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_configuration -M['workspace/configuration'] = function(_, result, ctx) +M[ms.workspace_configuration] = function(_, result, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) if not client then @@ -180,7 +201,7 @@ M['workspace/configuration'] = function(_, result, ctx) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_workspaceFolders -M['workspace/workspaceFolders'] = function(_, _, ctx) +M[ms.workspace_workspaceFolders] = function(_, _, ctx) local client_id = ctx.client_id local client = vim.lsp.get_client_by_id(client_id) if not client then @@ -190,16 +211,24 @@ M['workspace/workspaceFolders'] = function(_, _, ctx) return client.workspace_folders or vim.NIL end -M['textDocument/publishDiagnostics'] = function(...) +M[ms.textDocument_publishDiagnostics] = function(...) return require('vim.lsp.diagnostic').on_publish_diagnostics(...) end -M['textDocument/codeLens'] = function(...) +M[ms.textDocument_diagnostic] = function(...) + return require('vim.lsp.diagnostic').on_diagnostic(...) +end + +M[ms.textDocument_codeLens] = function(...) return require('vim.lsp.codelens').on_codelens(...) end +M[ms.textDocument_inlayHint] = function(...) + return require('vim.lsp.inlay_hint').on_inlayhint(...) +end + --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references -M['textDocument/references'] = function(_, result, ctx, config) +M[ms.textDocument_references] = function(_, result, ctx, config) if not result or vim.tbl_isempty(result) then vim.notify('No references found') else @@ -221,7 +250,6 @@ M['textDocument/references'] = function(_, result, ctx, config) end end ----@private --- Return a function that converts LSP responses to list items and opens the list --- --- The returned function has an optional {config} parameter that accepts a table @@ -256,7 +284,7 @@ local function response_to_list(map_result, entity, title_fn) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol -M['textDocument/documentSymbol'] = response_to_list( +M[ms.textDocument_documentSymbol] = response_to_list( util.symbols_to_items, 'document symbols', function(ctx) @@ -266,12 +294,12 @@ M['textDocument/documentSymbol'] = response_to_list( ) --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_symbol -M['workspace/symbol'] = response_to_list(util.symbols_to_items, 'symbols', function(ctx) +M[ms.workspace_symbol] = response_to_list(util.symbols_to_items, 'symbols', function(ctx) return string.format("Symbols matching '%s'", ctx.params.query) end) --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename -M['textDocument/rename'] = function(_, result, ctx, _) +M[ms.textDocument_rename] = function(_, result, ctx, _) if not result then vim.notify("Language server couldn't provide rename result", vim.log.levels.INFO) return @@ -281,7 +309,7 @@ M['textDocument/rename'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting -M['textDocument/rangeFormatting'] = function(_, result, ctx, _) +M[ms.textDocument_rangeFormatting] = function(_, result, ctx, _) if not result then return end @@ -290,7 +318,7 @@ M['textDocument/rangeFormatting'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting -M['textDocument/formatting'] = function(_, result, ctx, _) +M[ms.textDocument_formatting] = function(_, result, ctx, _) if not result then return end @@ -299,7 +327,7 @@ M['textDocument/formatting'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -M['textDocument/completion'] = function(_, result, _, _) +M[ms.textDocument_completion] = function(_, result, _, _) if vim.tbl_isempty(result or {}) then return end @@ -314,20 +342,22 @@ M['textDocument/completion'] = function(_, result, _, _) end --- |lsp-handler| for the method "textDocument/hover" ---- <pre>lua ---- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( ---- vim.lsp.handlers.hover, { ---- -- Use a sharp border with `FloatBorder` highlights ---- border = "single", ---- -- add the title in hover float window ---- title = "hover" ---- } ---- ) ---- </pre> +--- +--- ```lua +--- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( +--- vim.lsp.handlers.hover, { +--- -- Use a sharp border with `FloatBorder` highlights +--- border = "single", +--- -- add the title in hover float window +--- title = "hover" +--- } +--- ) +--- ``` +--- ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window ---- - See |nvim_open_win()| +--- - See |vim.lsp.util.open_floating_preview()| for more options. function M.hover(_, result, ctx, config) config = config or {} config.focus_id = ctx.method @@ -341,21 +371,28 @@ function M.hover(_, result, ctx, config) end return end - local markdown_lines = util.convert_input_to_markdown_lines(result.contents) - markdown_lines = util.trim_empty_lines(markdown_lines) - if vim.tbl_isempty(markdown_lines) then - vim.notify('No information available') + local format = 'markdown' + local contents ---@type string[] + if type(result.contents) == 'table' and result.contents.kind == 'plaintext' then + format = 'plaintext' + contents = vim.split(result.contents.value or '', '\n', { trimempty = true }) + else + contents = util.convert_input_to_markdown_lines(result.contents) + end + if vim.tbl_isempty(contents) then + if config.silent ~= true then + vim.notify('No information available') + end return end - return util.open_floating_preview(markdown_lines, 'markdown', config) + return util.open_floating_preview(contents, format, config) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover -M['textDocument/hover'] = M.hover +M[ms.textDocument_hover] = M.hover ----@private --- Jumps to a location. Used as a handler for multiple LSP methods. ----@param _ (not used) +---@param _ nil not used ---@param result (table) result of LSP method; a location or a list of locations. ---@param ctx (table) table containing the context of the request, including the method ---(`textDocument/definition` can return `Location` or `Location[]` @@ -370,50 +407,54 @@ local function location_handler(_, result, ctx, config) -- textDocument/definition can return Location or Location[] -- https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition + if not vim.tbl_islist(result) then + result = { result } + end - if vim.tbl_islist(result) then - local title = 'LSP locations' - local items = util.locations_to_items(result, client.offset_encoding) + local title = 'LSP locations' + local items = util.locations_to_items(result, client.offset_encoding) - if config.on_list then - assert(type(config.on_list) == 'function', 'on_list is not a function') - config.on_list({ title = title, items = items }) - else - if #result == 1 then - util.jump_to_location(result[1], client.offset_encoding, config.reuse_win) - return - end - vim.fn.setqflist({}, ' ', { title = title, items = items }) - api.nvim_command('botright copen') - end - else - util.jump_to_location(result, client.offset_encoding, config.reuse_win) + if config.on_list then + assert(type(config.on_list) == 'function', 'on_list is not a function') + config.on_list({ title = title, items = items }) + return + end + if #result == 1 then + util.jump_to_location(result[1], client.offset_encoding, config.reuse_win) + return end + vim.fn.setqflist({}, ' ', { title = title, items = items }) + api.nvim_command('botright copen') end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration -M['textDocument/declaration'] = location_handler +M[ms.textDocument_declaration] = location_handler --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition -M['textDocument/definition'] = location_handler +M[ms.textDocument_definition] = location_handler --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_typeDefinition -M['textDocument/typeDefinition'] = location_handler +M[ms.textDocument_typeDefinition] = location_handler --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_implementation -M['textDocument/implementation'] = location_handler +M[ms.textDocument_implementation] = location_handler --- |lsp-handler| for the method "textDocument/signatureHelp". +--- --- The active parameter is highlighted with |hl-LspSignatureActiveParameter|. ---- <pre>lua ---- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( ---- vim.lsp.handlers.signature_help, { ---- -- Use a sharp border with `FloatBorder` highlights ---- border = "single" ---- } ---- ) ---- </pre> +--- +--- ```lua +--- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( +--- vim.lsp.handlers.signature_help, { +--- -- Use a sharp border with `FloatBorder` highlights +--- border = "single" +--- } +--- ) +--- ``` +--- +---@param result table Response from the language server +---@param ctx table Client context ---@param config table Configuration table. --- - border: (default=nil) --- - Add borders to the floating window ---- - See |nvim_open_win()| +--- - See |vim.lsp.util.open_floating_preview()| for more options function M.signature_help(_, result, ctx, config) config = config or {} config.focus_id = ctx.method @@ -432,10 +473,9 @@ function M.signature_help(_, result, ctx, config) local client = vim.lsp.get_client_by_id(ctx.client_id) local triggers = vim.tbl_get(client.server_capabilities, 'signatureHelpProvider', 'triggerCharacters') - local ft = api.nvim_buf_get_option(ctx.bufnr, 'filetype') + local ft = vim.bo[ctx.bufnr].filetype local lines, hl = util.convert_signature_help_to_markdown_lines(result, ft, triggers) - lines = util.trim_empty_lines(lines) - if vim.tbl_isempty(lines) then + if not lines or vim.tbl_isempty(lines) then if config.silent ~= true then print('No signature help available') end @@ -443,16 +483,18 @@ function M.signature_help(_, result, ctx, config) end local fbuf, fwin = util.open_floating_preview(lines, 'markdown', config) if hl then - api.nvim_buf_add_highlight(fbuf, -1, 'LspSignatureActiveParameter', 0, unpack(hl)) + -- Highlight the second line if the signature is wrapped in a Markdown code block. + local line = vim.startswith(lines[1], '```') and 1 or 0 + api.nvim_buf_add_highlight(fbuf, -1, 'LspSignatureActiveParameter', line, unpack(hl)) end return fbuf, fwin end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp -M['textDocument/signatureHelp'] = M.signature_help +M[ms.textDocument_signatureHelp] = M.signature_help --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight -M['textDocument/documentHighlight'] = function(_, result, ctx, _) +M[ms.textDocument_documentHighlight] = function(_, result, ctx, _) if not result then return end @@ -469,8 +511,9 @@ end --- Displays call hierarchy in the quickfix window. --- ---@param direction `"from"` for incoming calls and `"to"` for outgoing calls ----@returns `CallHierarchyIncomingCall[]` if {direction} is `"from"`, ----@returns `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, +---@return function +--- `CallHierarchyIncomingCall[]` if {direction} is `"from"`, +--- `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, local make_call_hierarchy_handler = function(direction) return function(_, result) if not result then @@ -494,13 +537,13 @@ local make_call_hierarchy_handler = function(direction) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls -M['callHierarchy/incomingCalls'] = make_call_hierarchy_handler('from') +M[ms.callHierarchy_incomingCalls] = make_call_hierarchy_handler('from') --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls -M['callHierarchy/outgoingCalls'] = make_call_hierarchy_handler('to') +M[ms.callHierarchy_outgoingCalls] = make_call_hierarchy_handler('to') --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_logMessage -M['window/logMessage'] = function(_, result, ctx, _) +M[ms.window_logMessage] = function(_, result, ctx, _) local message_type = result.type local message = result.message local client_id = ctx.client_id @@ -522,7 +565,7 @@ M['window/logMessage'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showMessage -M['window/showMessage'] = function(_, result, ctx, _) +M[ms.window_showMessage] = function(_, result, ctx, _) local message_type = result.type local message = result.message local client_id = ctx.client_id @@ -541,27 +584,19 @@ M['window/showMessage'] = function(_, result, ctx, _) end --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#window_showDocument -M['window/showDocument'] = function(_, result, ctx, _) +M[ms.window_showDocument] = function(_, result, ctx, _) local uri = result.uri if result.external then -- TODO(lvimuser): ask the user for confirmation - local cmd - if vim.fn.has('win32') == 1 then - cmd = { 'cmd.exe', '/c', 'start', '""', uri } - elseif vim.fn.has('macunix') == 1 then - cmd = { 'open', uri } - else - cmd = { 'xdg-open', uri } - end + local ret, err = vim.ui.open(uri) - local ret = vim.fn.system(cmd) - if vim.v.shell_error ~= 0 then + if ret == nil or ret.code ~= 0 then return { success = false, error = { code = protocol.ErrorCodes.UnknownErrorCode, - message = ret, + message = ret and ret.stderr or err, }, } end @@ -573,7 +608,7 @@ M['window/showDocument'] = function(_, result, ctx, _) local client = vim.lsp.get_client_by_id(client_id) local client_name = client and client.name or string.format('id=%d', client_id) if not client then - err_message({ 'LSP[', client_name, '] client has shut down after sending ', ctx.method }) + err_message('LSP[', client_name, '] client has shut down after sending ', ctx.method) return vim.NIL end @@ -589,6 +624,11 @@ M['window/showDocument'] = function(_, result, ctx, _) return { success = success or false } end +---@see https://microsoft.github.io/language-server-protocol/specification/#workspace_inlayHint_refresh +M[ms.workspace_inlayHint_refresh] = function(err, result, ctx, config) + return require('vim.lsp.inlay_hint').on_refresh(err, result, ctx, config) +end + -- Add boilerplate error validation and logging for all of these. for k, fn in pairs(M) do M[k] = function(err, result, ctx, config) @@ -622,4 +662,3 @@ for k, fn in pairs(M) do end return M --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/health.lua b/runtime/lua/vim/lsp/health.lua index 987707e661..fe06006108 100644 --- a/runtime/lua/vim/lsp/health.lua +++ b/runtime/lua/vim/lsp/health.lua @@ -2,8 +2,8 @@ local M = {} --- Performs a healthcheck for LSP function M.check() - local report_info = vim.health.report_info - local report_warn = vim.health.report_warn + local report_info = vim.health.info + local report_warn = vim.health.warn local log = require('vim.lsp.log') local current_log_level = log.get_level() @@ -22,18 +22,25 @@ function M.check() local log_path = vim.lsp.get_log_path() report_info(string.format('Log path: %s', log_path)) - local log_file = vim.loop.fs_stat(log_path) + local log_file = vim.uv.fs_stat(log_path) local log_size = log_file and log_file.size or 0 local report_fn = (log_size / 1000000 > 100 and report_warn or report_info) report_fn(string.format('Log size: %d KB', log_size / 1000)) - local clients = vim.lsp.get_active_clients() - vim.health.report_start('vim.lsp: Active Clients') + local clients = vim.lsp.get_clients() + vim.health.start('vim.lsp: Active Clients') if next(clients) then for _, client in pairs(clients) do + local attached_to = table.concat(vim.tbl_keys(client.attached_buffers or {}), ',') report_info( - string.format('%s (id=%s, root_dir=%s)', client.name, client.id, client.config.root_dir) + string.format( + '%s (id=%s, root_dir=%s, attached_to=[%s])', + client.name, + client.id, + vim.fn.fnamemodify(client.config.root_dir, ':~'), + attached_to + ) ) end else diff --git a/runtime/lua/vim/lsp/inlay_hint.lua b/runtime/lua/vim/lsp/inlay_hint.lua new file mode 100644 index 0000000000..4f7a3b0076 --- /dev/null +++ b/runtime/lua/vim/lsp/inlay_hint.lua @@ -0,0 +1,377 @@ +local util = require('vim.lsp.util') +local log = require('vim.lsp.log') +local ms = require('vim.lsp.protocol').Methods +local api = vim.api +local M = {} + +---@class lsp.inlay_hint.bufstate +---@field version? integer +---@field client_hint? table<integer, table<integer, lsp.InlayHint[]>> client_id -> (lnum -> hints) +---@field applied table<integer, integer> Last version of hints applied to this line +---@field enabled boolean Whether inlay hints are enabled for this buffer +---@type table<integer, lsp.inlay_hint.bufstate> +local bufstates = {} + +local namespace = api.nvim_create_namespace('vim_lsp_inlayhint') +local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) + +--- |lsp-handler| for the method `textDocument/inlayHint` +--- Store hints for a specific buffer and client +---@private +function M.on_inlayhint(err, result, ctx, _) + if err then + local _ = log.error() and log.error('inlayhint', err) + return + end + local bufnr = ctx.bufnr + if util.buf_versions[bufnr] ~= ctx.version then + return + end + local client_id = ctx.client_id + if not result then + return + end + local bufstate = bufstates[bufnr] + if not bufstate or not bufstate.enabled then + return + end + if not (bufstate.client_hint and bufstate.version) then + bufstate.client_hint = vim.defaulttable() + bufstate.version = ctx.version + end + local hints_by_client = bufstate.client_hint + local client = vim.lsp.get_client_by_id(client_id) + + local new_hints_by_lnum = vim.defaulttable() + local num_unprocessed = #result + if num_unprocessed == 0 then + hints_by_client[client_id] = {} + bufstate.version = ctx.version + api.nvim__buf_redraw_range(bufnr, 0, -1) + return + end + + local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) + local function pos_to_byte(position) + local col = position.character + if col > 0 then + local line = lines[position.line + 1] or '' + local ok, convert_result + ok, convert_result = pcall(util._str_byteindex_enc, line, col, client.offset_encoding) + if ok then + return convert_result + end + return math.min(#line, col) + end + return col + end + + for _, hint in ipairs(result) do + local lnum = hint.position.line + hint.position.character = pos_to_byte(hint.position) + table.insert(new_hints_by_lnum[lnum], hint) + end + + hints_by_client[client_id] = new_hints_by_lnum + bufstate.version = ctx.version + api.nvim__buf_redraw_range(bufnr, 0, -1) +end + +--- |lsp-handler| for the method `textDocument/inlayHint/refresh` +---@private +function M.on_refresh(err, _, ctx, _) + if err then + return vim.NIL + end + for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do + for _, winid in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(winid) == bufnr then + local bufstate = bufstates[bufnr] + if bufstate then + util._refresh(ms.textDocument_inlayHint, { bufnr = bufnr }) + break + end + end + end + end + + return vim.NIL +end + +--- @class vim.lsp.inlay_hint.get.filter +--- @field bufnr integer? +--- @field range lsp.Range? +--- +--- @class vim.lsp.inlay_hint.get.ret +--- @field bufnr integer +--- @field client_id integer +--- @field inlay_hint lsp.InlayHint + +--- Get the list of inlay hints, (optionally) restricted by buffer or range. +--- +--- Example usage: +--- +--- ```lua +--- local hint = vim.lsp.inlay_hint.get({ bufnr = 0 })[1] -- 0 for current buffer +--- +--- local client = vim.lsp.get_client_by_id(hint.client_id) +--- resolved_hint = client.request_sync('inlayHint/resolve', hint.inlay_hint, 100, 0).result +--- vim.lsp.util.apply_text_edits(resolved_hint.textEdits, 0, client.encoding) +--- +--- location = resolved_hint.label[1].location +--- client.request('textDocument/hover', { +--- textDocument = { uri = location.uri }, +--- position = location.range.start, +--- }) +--- ``` +--- +--- @param filter vim.lsp.inlay_hint.get.filter? +--- Optional filters |kwargs|: +--- - bufnr (integer?): 0 for current buffer +--- - range (lsp.Range?) +--- +--- @return vim.lsp.inlay_hint.get.ret[] +--- Each list item is a table with the following fields: +--- - bufnr (integer) +--- - client_id (integer) +--- - inlay_hint (lsp.InlayHint) +--- +--- @since 12 +function M.get(filter) + vim.validate({ filter = { filter, 'table', true } }) + filter = filter or {} + + local bufnr = filter.bufnr + if not bufnr then + --- @type vim.lsp.inlay_hint.get.ret[] + local hints = {} + --- @param buf integer + vim.tbl_map(function(buf) + vim.list_extend(hints, M.get(vim.tbl_extend('keep', { bufnr = buf }, filter))) + end, vim.api.nvim_list_bufs()) + return hints + elseif bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + local bufstate = bufstates[bufnr] + if not (bufstate and bufstate.client_hint) then + return {} + end + + local clients = vim.lsp.get_clients({ + bufnr = bufnr, + method = ms.textDocument_inlayHint, + }) + if #clients == 0 then + return {} + end + + local range = filter.range + if not range then + range = { + start = { line = 0, character = 0 }, + ['end'] = { line = api.nvim_buf_line_count(bufnr), character = 0 }, + } + end + + --- @type vim.lsp.inlay_hint.get.ret[] + local hints = {} + for _, client in pairs(clients) do + local hints_by_lnum = bufstate.client_hint[client.id] + if hints_by_lnum then + for lnum = range.start.line, range['end'].line do + local line_hints = hints_by_lnum[lnum] or {} + for _, hint in pairs(line_hints) do + local line, char = hint.position.line, hint.position.character + if + (line > range.start.line or char >= range.start.character) + and (line < range['end'].line or char <= range['end'].character) + then + table.insert(hints, { + bufnr = bufnr, + client_id = client.id, + inlay_hint = hint, + }) + end + end + end + end + end + return hints +end + +--- Clear inlay hints +---@param bufnr (integer) Buffer handle, or 0 for current +local function clear(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + if not bufstates[bufnr] then + return + end + local bufstate = bufstates[bufnr] + local client_lens = (bufstate or {}).client_hint or {} + local client_ids = vim.tbl_keys(client_lens) + for _, iter_client_id in ipairs(client_ids) do + if bufstate then + bufstate.client_hint[iter_client_id] = {} + end + end + api.nvim_buf_clear_namespace(bufnr, namespace, 0, -1) + api.nvim__buf_redraw_range(bufnr, 0, -1) +end + +--- Disable inlay hints for a buffer +---@param bufnr (integer|nil) Buffer handle, or 0 or nil for current +local function _disable(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + clear(bufnr) + if bufstates[bufnr] then + bufstates[bufnr] = { enabled = false, applied = {} } + end +end + +--- Refresh inlay hints, only if we have attached clients that support it +---@param bufnr (integer) Buffer handle, or 0 for current +---@param opts? table Additional options to pass to util._refresh +---@private +local function _refresh(bufnr, opts) + opts = opts or {} + opts['bufnr'] = bufnr + util._refresh(ms.textDocument_inlayHint, opts) +end + +--- Enable inlay hints for a buffer +---@param bufnr (integer|nil) Buffer handle, or 0 or nil for current +local function _enable(bufnr) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + local bufstate = bufstates[bufnr] + if not bufstate then + bufstates[bufnr] = { applied = {}, enabled = true } + api.nvim_create_autocmd('LspNotify', { + buffer = bufnr, + callback = function(opts) + if + opts.data.method ~= ms.textDocument_didChange + and opts.data.method ~= ms.textDocument_didOpen + then + return + end + if bufstates[bufnr] and bufstates[bufnr].enabled then + _refresh(bufnr, { client_id = opts.data.client_id }) + end + end, + group = augroup, + }) + _refresh(bufnr) + api.nvim_buf_attach(bufnr, false, { + on_reload = function(_, cb_bufnr) + clear(cb_bufnr) + if bufstates[cb_bufnr] and bufstates[cb_bufnr].enabled then + bufstates[cb_bufnr].applied = {} + _refresh(cb_bufnr) + end + end, + on_detach = function(_, cb_bufnr) + _disable(cb_bufnr) + end, + }) + api.nvim_create_autocmd('LspDetach', { + buffer = bufnr, + callback = function(args) + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = ms.textDocument_inlayHint }) + + if + not vim.iter(clients):any(function(c) + return c.id ~= args.data.client_id + end) + then + _disable(bufnr) + end + end, + group = augroup, + }) + else + bufstate.enabled = true + _refresh(bufnr) + end +end + +api.nvim_set_decoration_provider(namespace, { + on_win = function(_, _, bufnr, topline, botline) + local bufstate = bufstates[bufnr] + if not bufstate then + return + end + + if bufstate.version ~= util.buf_versions[bufnr] then + return + end + local hints_by_client = bufstate.client_hint + + for lnum = topline, botline do + if bufstate.applied[lnum] ~= bufstate.version then + api.nvim_buf_clear_namespace(bufnr, namespace, lnum, lnum + 1) + for _, hints_by_lnum in pairs(hints_by_client) do + local line_hints = hints_by_lnum[lnum] or {} + for _, hint in pairs(line_hints) do + local text = '' + if type(hint.label) == 'string' then + text = hint.label + else + for _, part in ipairs(hint.label) do + text = text .. part.value + end + end + local vt = {} + if hint.paddingLeft then + vt[#vt + 1] = { ' ' } + end + vt[#vt + 1] = { text, 'LspInlayHint' } + if hint.paddingRight then + vt[#vt + 1] = { ' ' } + end + api.nvim_buf_set_extmark(bufnr, namespace, lnum, hint.position.character, { + virt_text_pos = 'inline', + ephemeral = false, + virt_text = vt, + }) + end + end + bufstate.applied[lnum] = bufstate.version + end + end + end, +}) + +--- @param bufnr (integer|nil) Buffer handle, or 0 or nil for current +--- @return boolean +--- @since 12 +function M.is_enabled(bufnr) + vim.validate({ bufnr = { bufnr, 'number', true } }) + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + return bufstates[bufnr] and bufstates[bufnr].enabled or false +end + +--- Enable/disable/toggle inlay hints for a buffer +--- +--- @param bufnr (integer|nil) Buffer handle, or 0 or nil for current +--- @param enable (boolean|nil) true/nil to enable, false to disable +--- @since 12 +function M.enable(bufnr, enable) + vim.validate({ enable = { enable, 'boolean', true }, bufnr = { bufnr, 'number', true } }) + if enable == false then + _disable(bufnr) + else + _enable(bufnr) + end +end + +return M diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua index d1a78572aa..6d2e0bc292 100644 --- a/runtime/lua/vim/lsp/log.lua +++ b/runtime/lua/vim/lsp/log.lua @@ -2,14 +2,12 @@ local log = {} --- FIXME: DOC --- Should be exposed in the vim docs. --- --- Log level dictionary with reverse lookup as well. --- --- Can be used to lookup the number from the name or the name from the number. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" --- Level numbers begin with "TRACE" at 0 +--- Log level dictionary with reverse lookup as well. +--- +--- Can be used to lookup the number from the name or the name from the number. +--- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" +--- Level numbers begin with "TRACE" at 0 +--- @nodoc log.levels = vim.deepcopy(vim.log.levels) -- Default log level is warn. @@ -20,7 +18,6 @@ local format_func = function(arg) end do - ---@private local function notify(msg, level) if vim.in_fast_event() then vim.schedule(function() @@ -31,8 +28,7 @@ do end end - local path_sep = vim.loop.os_uname().version:match('Windows') and '\\' or '/' - ---@private + local path_sep = vim.uv.os_uname().version:match('Windows') and '\\' or '/' local function path_join(...) return table.concat(vim.tbl_flatten({ ... }), path_sep) end @@ -44,13 +40,12 @@ do vim.fn.mkdir(vim.fn.stdpath('log'), 'p') --- Returns the log filename. - ---@returns (string) log filename + ---@return string log filename function log.get_filename() return logfilename end local logfile, openerr - ---@private --- Opens log file. Returns true if file is open, false on error local function open_logfile() -- Try to open file only once @@ -68,7 +63,7 @@ do return false end - local log_info = vim.loop.fs_stat(logfilename) + local log_info = vim.uv.fs_stat(logfilename) if log_info and log_info.size > 1e9 then local warn_msg = string.format( 'LSP client log is large (%d MB): %s', @@ -141,7 +136,7 @@ end vim.tbl_add_reverse_lookup(log.levels) --- Sets the current log level. ----@param level (string|number) One of `vim.lsp.log.levels` +---@param level (string|integer) One of `vim.lsp.log.levels` function log.set_level(level) if type(level) == 'string' then current_log_level = @@ -154,7 +149,7 @@ function log.set_level(level) end --- Gets the current log level. ----@return string current log level +---@return integer current log level function log.get_level() return current_log_level end @@ -167,11 +162,10 @@ function log.set_format_func(handle) end --- Checks whether the level is sufficient for logging. ----@param level number log level +---@param level integer log level ---@returns (bool) true if would log, false if not function log.should_log(level) return level >= current_log_level end return log --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index 12345b6c8c..a7c3914834 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -20,15 +20,8 @@ function transform_schema_to_table() end --]=] ----@class lsp.ShowMessageRequestParams ----@field type lsp.MessageType ----@field message string ----@field actions nil|lsp.MessageActionItem[] - ----@class lsp.MessageActionItem ----@field title string - local constants = { + --- @enum lsp.DiagnosticSeverity DiagnosticSeverity = { -- Reports an error. Error = 1, @@ -40,6 +33,7 @@ local constants = { Hint = 4, }, + --- @enum lsp.DiagnosticTag DiagnosticTag = { -- Unused or unnecessary code Unnecessary = 1, @@ -60,6 +54,7 @@ local constants = { }, -- The file event type. + ---@enum lsp.FileChangeType FileChangeType = { -- The file got created. Created = 1, @@ -247,6 +242,7 @@ local constants = { -- Defines whether the insert text in a completion item should be interpreted as -- plain text or a snippet. + --- @enum lsp.InsertTextFormat InsertTextFormat = { -- The primary text to be inserted is treated as a plain string. PlainText = 1, @@ -637,9 +633,29 @@ export interface WorkspaceClientCapabilities { --- Gets a new ClientCapabilities object describing the LSP client --- capabilities. +--- @return lsp.ClientCapabilities function protocol.make_client_capabilities() return { + general = { + positionEncodings = { + 'utf-16', + }, + }, textDocument = { + diagnostic = { + dynamicRegistration = false, + }, + inlayHint = { + dynamicRegistration = true, + resolveSupport = { + properties = { + 'textEdits', + 'tooltip', + 'location', + 'command', + }, + }, + }, semanticTokens = { dynamicRegistration = false, tokenTypes = { @@ -702,7 +718,7 @@ function protocol.make_client_capabilities() didSave = true, }, codeAction = { - dynamicRegistration = false, + dynamicRegistration = true, codeActionLiteralSupport = { codeActionKind = { @@ -719,6 +735,12 @@ function protocol.make_client_capabilities() properties = { 'edit' }, }, }, + formatting = { + dynamicRegistration = true, + }, + rangeFormatting = { + dynamicRegistration = true, + }, completion = { dynamicRegistration = false, completionItem = { @@ -726,7 +748,6 @@ function protocol.make_client_capabilities() -- this should be disabled out of the box. -- However, users can turn this back on if they have a snippet plugin. snippetSupport = false, - commitCharactersSupport = false, preselectSupport = false, deprecatedSupport = false, @@ -752,6 +773,7 @@ function protocol.make_client_capabilities() }, definition = { linkSupport = true, + dynamicRegistration = true, }, implementation = { linkSupport = true, @@ -760,7 +782,7 @@ function protocol.make_client_capabilities() linkSupport = true, }, hover = { - dynamicRegistration = false, + dynamicRegistration = true, contentFormat = { protocol.MarkupKind.Markdown, protocol.MarkupKind.PlainText }, }, signatureHelp = { @@ -795,7 +817,7 @@ function protocol.make_client_capabilities() hierarchicalDocumentSymbolSupport = true, }, rename = { - dynamicRegistration = false, + dynamicRegistration = true, prepareSupport = true, }, publishDiagnostics = { @@ -811,6 +833,7 @@ function protocol.make_client_capabilities() return res end)(), }, + dataSupport = true, }, callHierarchy = { dynamicRegistration = false, @@ -830,9 +853,11 @@ function protocol.make_client_capabilities() return res end)(), }, - hierarchicalWorkspaceSymbolSupport = true, }, configuration = true, + didChangeConfiguration = { + dynamicRegistration = false, + }, workspaceFolders = true, applyEdit = true, workspaceEdit = { @@ -841,6 +866,13 @@ function protocol.make_client_capabilities() semanticTokens = { refreshSupport = true, }, + didChangeWatchedFiles = { + dynamicRegistration = true, + relativePatternSupport = true, + }, + inlayHint = { + refreshSupport = true, + }, }, experimental = nil, window = { @@ -857,10 +889,9 @@ function protocol.make_client_capabilities() } end -local if_nil = vim.F.if_nil --- Creates a normalized object describing LSP server capabilities. ---@param server_capabilities table Table of capabilities supported by the server ----@return table Normalized table of capabilities +---@return table|nil Normalized table of capabilities function protocol.resolve_capabilities(server_capabilities) local TextDocumentSyncKind = protocol.TextDocumentSyncKind local textDocumentSync = server_capabilities.textDocumentSync @@ -878,7 +909,8 @@ function protocol.resolve_capabilities(server_capabilities) elseif type(textDocumentSync) == 'number' then -- Backwards compatibility if not TextDocumentSyncKind[textDocumentSync] then - return nil, 'Invalid server TextDocumentSyncKind for textDocumentSync' + vim.notify('Invalid server TextDocumentSyncKind for textDocumentSync', vim.log.levels.ERROR) + return nil end server_capabilities.textDocumentSync = { openClose = true, @@ -890,183 +922,367 @@ function protocol.resolve_capabilities(server_capabilities) }, } elseif type(textDocumentSync) ~= 'table' then - return nil, string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)) + vim.notify( + string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)), + vim.log.levels.ERROR + ) + return nil end return server_capabilities end ----@private ---- Creates a normalized object describing LSP server capabilities. --- @deprecated access resolved_capabilities instead ----@param server_capabilities table Table of capabilities supported by the server ----@return table Normalized table of capabilities -function protocol._resolve_capabilities_compat(server_capabilities) - local general_properties = {} - local text_document_sync_properties - do - local TextDocumentSyncKind = protocol.TextDocumentSyncKind - local textDocumentSync = server_capabilities.textDocumentSync - if textDocumentSync == nil then - -- Defaults if omitted. - text_document_sync_properties = { - text_document_open_close = false, - text_document_did_change = TextDocumentSyncKind.None, - -- text_document_did_change = false; - text_document_will_save = false, - text_document_will_save_wait_until = false, - text_document_save = false, - text_document_save_include_text = false, - } - elseif type(textDocumentSync) == 'number' then - -- Backwards compatibility - if not TextDocumentSyncKind[textDocumentSync] then - return nil, 'Invalid server TextDocumentSyncKind for textDocumentSync' - end - text_document_sync_properties = { - text_document_open_close = true, - text_document_did_change = textDocumentSync, - text_document_will_save = false, - text_document_will_save_wait_until = false, - text_document_save = true, - text_document_save_include_text = false, - } - elseif type(textDocumentSync) == 'table' then - text_document_sync_properties = { - text_document_open_close = if_nil(textDocumentSync.openClose, false), - text_document_did_change = if_nil(textDocumentSync.change, TextDocumentSyncKind.None), - text_document_will_save = if_nil(textDocumentSync.willSave, true), - text_document_will_save_wait_until = if_nil(textDocumentSync.willSaveWaitUntil, true), - text_document_save = if_nil(textDocumentSync.save, false), - text_document_save_include_text = if_nil( - type(textDocumentSync.save) == 'table' and textDocumentSync.save.includeText, - false - ), - } - else - return nil, string.format('Invalid type for textDocumentSync: %q', type(textDocumentSync)) - end - end - general_properties.completion = server_capabilities.completionProvider ~= nil - general_properties.hover = server_capabilities.hoverProvider or false - general_properties.goto_definition = server_capabilities.definitionProvider or false - general_properties.find_references = server_capabilities.referencesProvider or false - general_properties.document_highlight = server_capabilities.documentHighlightProvider or false - general_properties.document_symbol = server_capabilities.documentSymbolProvider or false - general_properties.workspace_symbol = server_capabilities.workspaceSymbolProvider or false - general_properties.document_formatting = server_capabilities.documentFormattingProvider or false - general_properties.document_range_formatting = server_capabilities.documentRangeFormattingProvider - or false - general_properties.call_hierarchy = server_capabilities.callHierarchyProvider or false - general_properties.execute_command = server_capabilities.executeCommandProvider ~= nil - - if server_capabilities.renameProvider == nil then - general_properties.rename = false - elseif type(server_capabilities.renameProvider) == 'boolean' then - general_properties.rename = server_capabilities.renameProvider - else - general_properties.rename = true - end - - if server_capabilities.codeLensProvider == nil then - general_properties.code_lens = false - general_properties.code_lens_resolve = false - elseif type(server_capabilities.codeLensProvider) == 'table' then - general_properties.code_lens = true - general_properties.code_lens_resolve = server_capabilities.codeLensProvider.resolveProvider - or false - else - error('The server sent invalid codeLensProvider') - end - - if server_capabilities.codeActionProvider == nil then - general_properties.code_action = false - elseif - type(server_capabilities.codeActionProvider) == 'boolean' - or type(server_capabilities.codeActionProvider) == 'table' - then - general_properties.code_action = server_capabilities.codeActionProvider - else - error('The server sent invalid codeActionProvider') - end - - if server_capabilities.declarationProvider == nil then - general_properties.declaration = false - elseif type(server_capabilities.declarationProvider) == 'boolean' then - general_properties.declaration = server_capabilities.declarationProvider - elseif type(server_capabilities.declarationProvider) == 'table' then - general_properties.declaration = server_capabilities.declarationProvider - else - error('The server sent invalid declarationProvider') - end - - if server_capabilities.typeDefinitionProvider == nil then - general_properties.type_definition = false - elseif type(server_capabilities.typeDefinitionProvider) == 'boolean' then - general_properties.type_definition = server_capabilities.typeDefinitionProvider - elseif type(server_capabilities.typeDefinitionProvider) == 'table' then - general_properties.type_definition = server_capabilities.typeDefinitionProvider - else - error('The server sent invalid typeDefinitionProvider') - end - - if server_capabilities.implementationProvider == nil then - general_properties.implementation = false - elseif type(server_capabilities.implementationProvider) == 'boolean' then - general_properties.implementation = server_capabilities.implementationProvider - elseif type(server_capabilities.implementationProvider) == 'table' then - general_properties.implementation = server_capabilities.implementationProvider - else - error('The server sent invalid implementationProvider') - end - - local workspace = server_capabilities.workspace - local workspace_properties = {} - if workspace == nil or workspace.workspaceFolders == nil then - -- Defaults if omitted. - workspace_properties = { - workspace_folder_properties = { - supported = false, - changeNotifications = false, - }, - } - elseif type(workspace.workspaceFolders) == 'table' then - workspace_properties = { - workspace_folder_properties = { - supported = if_nil(workspace.workspaceFolders.supported, false), - changeNotifications = if_nil(workspace.workspaceFolders.changeNotifications, false), - }, - } - else - error('The server sent invalid workspace') - end - - local signature_help_properties - if server_capabilities.signatureHelpProvider == nil then - signature_help_properties = { - signature_help = false, - signature_help_trigger_characters = {}, - } - elseif type(server_capabilities.signatureHelpProvider) == 'table' then - signature_help_properties = { - signature_help = true, - -- The characters that trigger signature help automatically. - signature_help_trigger_characters = server_capabilities.signatureHelpProvider.triggerCharacters - or {}, - } - else - error('The server sent invalid signatureHelpProvider') - end - - local capabilities = vim.tbl_extend( - 'error', - text_document_sync_properties, - signature_help_properties, - workspace_properties, - general_properties - ) - - return capabilities +-- Generated by gen_lsp.lua, keep at end of file. +--- LSP method names. +--- +---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#metaModel +protocol.Methods = { + --- A request to resolve the incoming calls for a given `CallHierarchyItem`. + --- @since 3.16.0 + callHierarchy_incomingCalls = 'callHierarchy/incomingCalls', + --- A request to resolve the outgoing calls for a given `CallHierarchyItem`. + --- @since 3.16.0 + callHierarchy_outgoingCalls = 'callHierarchy/outgoingCalls', + --- The `client/registerCapability` request is sent from the server to the client to register a new capability + --- handler on the client side. + client_registerCapability = 'client/registerCapability', + --- The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability + --- handler on the client side. + client_unregisterCapability = 'client/unregisterCapability', + --- Request to resolve additional information for a given code action.The request's + --- parameter is of type {@link CodeAction} the response + --- is of type {@link CodeAction} or a Thenable that resolves to such. + codeAction_resolve = 'codeAction/resolve', + --- A request to resolve a command for a given code lens. + codeLens_resolve = 'codeLens/resolve', + --- Request to resolve additional information for a given completion item.The request's + --- parameter is of type {@link CompletionItem} the response + --- is of type {@link CompletionItem} or a Thenable that resolves to such. + completionItem_resolve = 'completionItem/resolve', + --- Request to resolve additional information for a given document link. The request's + --- parameter is of type {@link DocumentLink} the response + --- is of type {@link DocumentLink} or a Thenable that resolves to such. + documentLink_resolve = 'documentLink/resolve', + dollar_cancelRequest = '$/cancelRequest', + dollar_logTrace = '$/logTrace', + dollar_progress = '$/progress', + dollar_setTrace = '$/setTrace', + --- The exit event is sent from the client to the server to + --- ask the server to exit its process. + exit = 'exit', + --- The initialize request is sent from the client to the server. + --- It is sent once as the request after starting up the server. + --- The requests parameter is of type {@link InitializeParams} + --- the response if of type {@link InitializeResult} of a Thenable that + --- resolves to such. + initialize = 'initialize', + --- The initialized notification is sent from the client to the + --- server after the client is fully initialized and the server + --- is allowed to send requests from the server to the client. + initialized = 'initialized', + --- A request to resolve additional properties for an inlay hint. + --- The request's parameter is of type {@link InlayHint}, the response is + --- of type {@link InlayHint} or a Thenable that resolves to such. + --- @since 3.17.0 + inlayHint_resolve = 'inlayHint/resolve', + notebookDocument_didChange = 'notebookDocument/didChange', + --- A notification sent when a notebook closes. + --- @since 3.17.0 + notebookDocument_didClose = 'notebookDocument/didClose', + --- A notification sent when a notebook opens. + --- @since 3.17.0 + notebookDocument_didOpen = 'notebookDocument/didOpen', + --- A notification sent when a notebook document is saved. + --- @since 3.17.0 + notebookDocument_didSave = 'notebookDocument/didSave', + --- A shutdown request is sent from the client to the server. + --- It is sent once when the client decides to shutdown the + --- server. The only notification that is sent after a shutdown request + --- is the exit event. + shutdown = 'shutdown', + --- The telemetry event notification is sent from the server to the client to ask + --- the client to log telemetry data. + telemetry_event = 'telemetry/event', + --- A request to provide commands for the given text document and range. + textDocument_codeAction = 'textDocument/codeAction', + --- A request to provide code lens for the given text document. + textDocument_codeLens = 'textDocument/codeLens', + --- A request to list all presentation for a color. The request's + --- parameter is of type {@link ColorPresentationParams} the + --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable + --- that resolves to such. + textDocument_colorPresentation = 'textDocument/colorPresentation', + --- Request to request completion at a given text document position. The request's + --- parameter is of type {@link TextDocumentPosition} the response + --- is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList} + --- or a Thenable that resolves to such. + --- The request can delay the computation of the {@link CompletionItem.detail `detail`} + --- and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve` + --- request. However, properties that are needed for the initial sorting and filtering, like `sortText`, + --- `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. + textDocument_completion = 'textDocument/completion', + --- A request to resolve the type definition locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Declaration} + --- or a typed array of {@link DeclarationLink} or a Thenable that resolves + --- to such. + textDocument_declaration = 'textDocument/declaration', + --- A request to resolve the definition location of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPosition] + --- (#TextDocumentPosition) the response is of either type {@link Definition} + --- or a typed array of {@link DefinitionLink} or a Thenable that resolves + --- to such. + textDocument_definition = 'textDocument/definition', + --- The document diagnostic request definition. + --- @since 3.17.0 + textDocument_diagnostic = 'textDocument/diagnostic', + --- The document change notification is sent from the client to the server to signal + --- changes to a text document. + textDocument_didChange = 'textDocument/didChange', + --- The document close notification is sent from the client to the server when + --- the document got closed in the client. The document's truth now exists where + --- the document's uri points to (e.g. if the document's uri is a file uri the + --- truth now exists on disk). As with the open notification the close notification + --- is about managing the document's content. Receiving a close notification + --- doesn't mean that the document was open in an editor before. A close + --- notification requires a previous open notification to be sent. + textDocument_didClose = 'textDocument/didClose', + --- The document open notification is sent from the client to the server to signal + --- newly opened text documents. The document's truth is now managed by the client + --- and the server must not try to read the document's truth using the document's + --- uri. Open in this sense means it is managed by the client. It doesn't necessarily + --- mean that its content is presented in an editor. An open notification must not + --- be sent more than once without a corresponding close notification send before. + --- This means open and close notification must be balanced and the max open count + --- is one. + textDocument_didOpen = 'textDocument/didOpen', + --- The document save notification is sent from the client to the server when + --- the document got saved in the client. + textDocument_didSave = 'textDocument/didSave', + --- A request to list all color symbols found in a given text document. The request's + --- parameter is of type {@link DocumentColorParams} the + --- response is of type {@link ColorInformation ColorInformation[]} or a Thenable + --- that resolves to such. + textDocument_documentColor = 'textDocument/documentColor', + --- Request to resolve a {@link DocumentHighlight} for a given + --- text document position. The request's parameter is of type [TextDocumentPosition] + --- (#TextDocumentPosition) the request response is of type [DocumentHighlight[]] + --- (#DocumentHighlight) or a Thenable that resolves to such. + textDocument_documentHighlight = 'textDocument/documentHighlight', + --- A request to provide document links + textDocument_documentLink = 'textDocument/documentLink', + --- A request to list all symbols found in a given text document. The request's + --- parameter is of type {@link TextDocumentIdentifier} the + --- response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable + --- that resolves to such. + textDocument_documentSymbol = 'textDocument/documentSymbol', + --- A request to provide folding ranges in a document. The request's + --- parameter is of type {@link FoldingRangeParams}, the + --- response is of type {@link FoldingRangeList} or a Thenable + --- that resolves to such. + textDocument_foldingRange = 'textDocument/foldingRange', + --- A request to to format a whole document. + textDocument_formatting = 'textDocument/formatting', + --- Request to request hover information at a given text document position. The request's + --- parameter is of type {@link TextDocumentPosition} the response is of + --- type {@link Hover} or a Thenable that resolves to such. + textDocument_hover = 'textDocument/hover', + --- A request to resolve the implementation locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a + --- Thenable that resolves to such. + textDocument_implementation = 'textDocument/implementation', + --- A request to provide inlay hints in a document. The request's parameter is of + --- type {@link InlayHintsParams}, the response is of type + --- {@link InlayHint InlayHint[]} or a Thenable that resolves to such. + --- @since 3.17.0 + textDocument_inlayHint = 'textDocument/inlayHint', + --- A request to provide inline completions in a document. The request's parameter is of + --- type {@link InlineCompletionParams}, the response is of type + --- {@link InlineCompletion InlineCompletion[]} or a Thenable that resolves to such. + --- @since 3.18.0 + textDocument_inlineCompletion = 'textDocument/inlineCompletion', + --- A request to provide inline values in a document. The request's parameter is of + --- type {@link InlineValueParams}, the response is of type + --- {@link InlineValue InlineValue[]} or a Thenable that resolves to such. + --- @since 3.17.0 + textDocument_inlineValue = 'textDocument/inlineValue', + --- A request to provide ranges that can be edited together. + --- @since 3.16.0 + textDocument_linkedEditingRange = 'textDocument/linkedEditingRange', + --- A request to get the moniker of a symbol at a given text document position. + --- The request parameter is of type {@link TextDocumentPositionParams}. + --- The response is of type {@link Moniker Moniker[]} or `null`. + textDocument_moniker = 'textDocument/moniker', + --- A request to format a document on type. + textDocument_onTypeFormatting = 'textDocument/onTypeFormatting', + --- A request to result a `CallHierarchyItem` in a document at a given position. + --- Can be used as an input to an incoming or outgoing call hierarchy. + --- @since 3.16.0 + textDocument_prepareCallHierarchy = 'textDocument/prepareCallHierarchy', + --- A request to test and perform the setup necessary for a rename. + --- @since 3.16 - support for default behavior + textDocument_prepareRename = 'textDocument/prepareRename', + --- A request to result a `TypeHierarchyItem` in a document at a given position. + --- Can be used as an input to a subtypes or supertypes type hierarchy. + --- @since 3.17.0 + textDocument_prepareTypeHierarchy = 'textDocument/prepareTypeHierarchy', + --- Diagnostics notification are sent from the server to the client to signal + --- results of validation runs. + textDocument_publishDiagnostics = 'textDocument/publishDiagnostics', + --- A request to format a range in a document. + textDocument_rangeFormatting = 'textDocument/rangeFormatting', + --- A request to format ranges in a document. + --- @since 3.18.0 + --- @proposed + textDocument_rangesFormatting = 'textDocument/rangesFormatting', + --- A request to resolve project-wide references for the symbol denoted + --- by the given text document position. The request's parameter is of + --- type {@link ReferenceParams} the response is of type + --- {@link Location Location[]} or a Thenable that resolves to such. + textDocument_references = 'textDocument/references', + --- A request to rename a symbol. + textDocument_rename = 'textDocument/rename', + --- A request to provide selection ranges in a document. The request's + --- parameter is of type {@link SelectionRangeParams}, the + --- response is of type {@link SelectionRange SelectionRange[]} or a Thenable + --- that resolves to such. + textDocument_selectionRange = 'textDocument/selectionRange', + --- @since 3.16.0 + textDocument_semanticTokens_full = 'textDocument/semanticTokens/full', + --- @since 3.16.0 + textDocument_semanticTokens_full_delta = 'textDocument/semanticTokens/full/delta', + --- @since 3.16.0 + textDocument_semanticTokens_range = 'textDocument/semanticTokens/range', + textDocument_signatureHelp = 'textDocument/signatureHelp', + --- A request to resolve the type definition locations of a symbol at a given text + --- document position. The request's parameter is of type [TextDocumentPositionParams] + --- (#TextDocumentPositionParams) the response is of type {@link Definition} or a + --- Thenable that resolves to such. + textDocument_typeDefinition = 'textDocument/typeDefinition', + --- A document will save notification is sent from the client to the server before + --- the document is actually saved. + textDocument_willSave = 'textDocument/willSave', + --- A document will save request is sent from the client to the server before + --- the document is actually saved. The request can return an array of TextEdits + --- which will be applied to the text document before it is saved. Please note that + --- clients might drop results if computing the text edits took too long or if a + --- server constantly fails on this request. This is done to keep the save fast and + --- reliable. + textDocument_willSaveWaitUntil = 'textDocument/willSaveWaitUntil', + --- A request to resolve the subtypes for a given `TypeHierarchyItem`. + --- @since 3.17.0 + typeHierarchy_subtypes = 'typeHierarchy/subtypes', + --- A request to resolve the supertypes for a given `TypeHierarchyItem`. + --- @since 3.17.0 + typeHierarchy_supertypes = 'typeHierarchy/supertypes', + --- The log message notification is sent from the server to the client to ask + --- the client to log a particular message. + window_logMessage = 'window/logMessage', + --- A request to show a document. This request might open an + --- external program depending on the value of the URI to open. + --- For example a request to open `https://code.visualstudio.com/` + --- will very likely open the URI in a WEB browser. + --- @since 3.16.0 + window_showDocument = 'window/showDocument', + --- The show message notification is sent from a server to a client to ask + --- the client to display a particular message in the user interface. + window_showMessage = 'window/showMessage', + --- The show message request is sent from the server to the client to show a message + --- and a set of options actions to the user. + window_showMessageRequest = 'window/showMessageRequest', + --- The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress + --- initiated on the server side. + window_workDoneProgress_cancel = 'window/workDoneProgress/cancel', + --- The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress + --- reporting from the server. + window_workDoneProgress_create = 'window/workDoneProgress/create', + --- A request to resolve the range inside the workspace + --- symbol's location. + --- @since 3.17.0 + workspaceSymbol_resolve = 'workspaceSymbol/resolve', + --- A request sent from the server to the client to modified certain resources. + workspace_applyEdit = 'workspace/applyEdit', + --- A request to refresh all code actions + --- @since 3.16.0 + workspace_codeLens_refresh = 'workspace/codeLens/refresh', + --- The 'workspace/configuration' request is sent from the server to the client to fetch a certain + --- configuration setting. + --- This pull model replaces the old push model were the client signaled configuration change via an + --- event. If the server still needs to react to configuration changes (since the server caches the + --- result of `workspace/configuration` requests) the server should register for an empty configuration + --- change event and empty the cache if such an event is received. + workspace_configuration = 'workspace/configuration', + --- The workspace diagnostic request definition. + --- @since 3.17.0 + workspace_diagnostic = 'workspace/diagnostic', + --- The diagnostic refresh request definition. + --- @since 3.17.0 + workspace_diagnostic_refresh = 'workspace/diagnostic/refresh', + --- The configuration change notification is sent from the client to the server + --- when the client's configuration has changed. The notification contains + --- the changed configuration as defined by the language client. + workspace_didChangeConfiguration = 'workspace/didChangeConfiguration', + --- The watched files notification is sent from the client to the server when + --- the client detects changes to file watched by the language client. + workspace_didChangeWatchedFiles = 'workspace/didChangeWatchedFiles', + --- The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace + --- folder configuration changes. + workspace_didChangeWorkspaceFolders = 'workspace/didChangeWorkspaceFolders', + --- The did create files notification is sent from the client to the server when + --- files were created from within the client. + --- @since 3.16.0 + workspace_didCreateFiles = 'workspace/didCreateFiles', + --- The will delete files request is sent from the client to the server before files are actually + --- deleted as long as the deletion is triggered from within the client. + --- @since 3.16.0 + workspace_didDeleteFiles = 'workspace/didDeleteFiles', + --- The did rename files notification is sent from the client to the server when + --- files were renamed from within the client. + --- @since 3.16.0 + workspace_didRenameFiles = 'workspace/didRenameFiles', + --- A request send from the client to the server to execute a command. The request might return + --- a workspace edit which the client will apply to the workspace. + workspace_executeCommand = 'workspace/executeCommand', + --- @since 3.17.0 + workspace_inlayHint_refresh = 'workspace/inlayHint/refresh', + --- @since 3.17.0 + workspace_inlineValue_refresh = 'workspace/inlineValue/refresh', + --- @since 3.16.0 + workspace_semanticTokens_refresh = 'workspace/semanticTokens/refresh', + --- A request to list project-wide symbols matching the query string given + --- by the {@link WorkspaceSymbolParams}. The response is + --- of type {@link SymbolInformation SymbolInformation[]} or a Thenable that + --- resolves to such. + --- @since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients + --- need to advertise support for WorkspaceSymbols via the client capability + --- `workspace.symbol.resolveSupport`. + workspace_symbol = 'workspace/symbol', + --- The will create files request is sent from the client to the server before files are actually + --- created as long as the creation is triggered from within the client. + --- The request can return a `WorkspaceEdit` which will be applied to workspace before the + --- files are created. Hence the `WorkspaceEdit` can not manipulate the content of the file + --- to be created. + --- @since 3.16.0 + workspace_willCreateFiles = 'workspace/willCreateFiles', + --- The did delete files notification is sent from the client to the server when + --- files were deleted from within the client. + --- @since 3.16.0 + workspace_willDeleteFiles = 'workspace/willDeleteFiles', + --- The will rename files request is sent from the client to the server before files are actually + --- renamed as long as the rename is triggered from within the client. + --- @since 3.16.0 + workspace_willRenameFiles = 'workspace/willRenameFiles', + --- The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders. + workspace_workspaceFolders = 'workspace/workspaceFolders', +} +local function freeze(t) + return setmetatable({}, { + __index = t, + __newindex = function() + error('cannot modify immutable table') + end, + }) end +protocol.Methods = freeze(protocol.Methods) return protocol --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua index f1492601ff..6ab5708721 100644 --- a/runtime/lua/vim/lsp/rpc.lua +++ b/runtime/lua/vim/lsp/rpc.lua @@ -1,50 +1,22 @@ -local uv = vim.loop +local uv = vim.uv local log = require('vim.lsp.log') local protocol = require('vim.lsp.protocol') local validate, schedule, schedule_wrap = vim.validate, vim.schedule, vim.schedule_wrap local is_win = uv.os_uname().version:find('Windows') ----@private --- Checks whether a given path exists and is a directory. ---@param filename (string) path to check ----@returns (bool) +---@return boolean local function is_dir(filename) local stat = uv.fs_stat(filename) return stat and stat.type == 'directory' or false end ----@private ---- Merges current process env with the given env and returns the result as ---- a list of "k=v" strings. ---- ---- <pre> ---- Example: ---- ---- in: { PRODUCTION="false", PATH="/usr/bin/", PORT=123, HOST="0.0.0.0", } ---- out: { "PRODUCTION=false", "PATH=/usr/bin/", "PORT=123", "HOST=0.0.0.0", } ---- </pre> ----@param env (table) table of environment variable assignments ----@returns (table) list of `"k=v"` strings -local function env_merge(env) - if env == nil then - return env - end - -- Merge. - env = vim.tbl_extend('force', vim.fn.environ(), env) - local final_env = {} - for k, v in pairs(env) do - assert(type(k) == 'string', 'env must be a dict') - table.insert(final_env, k .. '=' .. tostring(v)) - end - return final_env -end - ----@private --- Embeds the given string into a table and correctly computes `Content-Length`. --- ---@param encoded_message (string) ----@returns (table) table containing encoded message and `Content-Length` attribute +---@return string containing encoded message and `Content-Length` attribute local function format_message_with_content_length(encoded_message) return table.concat({ 'Content-Length: ', @@ -54,15 +26,14 @@ local function format_message_with_content_length(encoded_message) }) end ----@private --- Parses an LSP Message's header --- ---@param header string: The header to parse. ----@return table parsed headers +---@return table # parsed headers local function parse_headers(header) assert(type(header) == 'string', 'header must be a string') local headers = {} - for line in vim.gsplit(header, '\r\n', true) do + for line in vim.gsplit(header, '\r\n', { plain = true }) do if line == '' then break end @@ -86,7 +57,6 @@ local header_start_pattern = ('content'):gsub('%w', function(c) return '[' .. c .. c:upper() .. ']' end) ----@private --- The actual workhorse. local function request_parser_loop() local buffer = '' -- only for header part @@ -141,8 +111,11 @@ local function request_parser_loop() end end +local M = {} + --- Mapping of error codes used by the client -local client_errors = { +--- @nodoc +M.client_errors = { INVALID_SERVER_MESSAGE = 1, INVALID_SERVER_JSON = 2, NO_RESULT_CALLBACK_FOUND = 3, @@ -152,13 +125,13 @@ local client_errors = { SERVER_RESULT_CALLBACK_ERROR = 7, } -client_errors = vim.tbl_add_reverse_lookup(client_errors) +M.client_errors = vim.tbl_add_reverse_lookup(M.client_errors) --- Constructs an error message from an LSP error object. --- ---@param err (table) The error object ---@returns (string) The formatted error message -local function format_rpc_error(err) +function M.format_rpc_error(err) validate({ err = { err, 't' }, }) @@ -186,10 +159,10 @@ end --- Creates an RPC response object/table. --- ----@param code number RPC error code defined in `vim.lsp.protocol.ErrorCodes` +---@param code integer RPC error code defined in `vim.lsp.protocol.ErrorCodes` ---@param message string|nil arbitrary message to send to server ---@param data any|nil arbitrary data to send to server -local function rpc_response_error(code, message, data) +function M.rpc_response_error(code, message, data) -- TODO should this error or just pick a sane error (like InternalError)? local code_name = assert(protocol.ErrorCodes[code], 'Invalid RPC error code') return setmetatable({ @@ -197,7 +170,7 @@ local function rpc_response_error(code, message, data) message = message or code_name, data = data, }, { - __tostring = format_rpc_error, + __tostring = M.format_rpc_error, }) end @@ -211,37 +184,41 @@ local default_dispatchers = {} function default_dispatchers.notification(method, params) local _ = log.debug() and log.debug('notification', method, params) end + ---@private --- Default dispatcher for requests sent to an LSP server. --- ---@param method (string) The invoked LSP method ---@param params (table): Parameters for the invoked LSP method ----@returns `nil` and `vim.lsp.protocol.ErrorCodes.MethodNotFound`. +---@return nil +---@return table `vim.lsp.protocol.ErrorCodes.MethodNotFound` function default_dispatchers.server_request(method, params) local _ = log.debug() and log.debug('server_request', method, params) - return nil, rpc_response_error(protocol.ErrorCodes.MethodNotFound) + return nil, M.rpc_response_error(protocol.ErrorCodes.MethodNotFound) end + ---@private --- Default dispatcher for when a client exits. --- ----@param code (number): Exit code ----@param signal (number): Number describing the signal used to terminate (if +---@param code (integer): Exit code +---@param signal (integer): Number describing the signal used to terminate (if ---any) function default_dispatchers.on_exit(code, signal) local _ = log.info() and log.info('client_exit', { code = code, signal = signal }) end + ---@private --- Default dispatcher for client errors. --- ----@param code (number): Error code +---@param code (integer): Error code ---@param err (any): Details about the error ---any) function default_dispatchers.on_error(code, err) - local _ = log.error() and log.error('client_error:', client_errors[code], err) + local _ = log.error() and log.error('client_error:', M.client_errors[code], err) end ---@private -local function create_read_loop(handle_body, on_no_chunk, on_error) +function M.create_read_loop(handle_body, on_no_chunk, on_error) local parse_chunk = coroutine.wrap(request_parser_loop) parse_chunk() return function(err, chunk) @@ -270,7 +247,7 @@ local function create_read_loop(handle_body, on_no_chunk, on_error) end ---@class RpcClient ----@field message_index number +---@field message_index integer ---@field message_callbacks table ---@field notify_reply_callbacks table ---@field transport table @@ -294,7 +271,7 @@ end --- Sends a notification to the LSP server. ---@param method (string) The invoked LSP method ---@param params (any): Parameters for the invoked LSP method ----@returns (bool) `true` if notification could be sent, `false` if not +---@return boolean `true` if notification could be sent, `false` if not function Client:notify(method, params) return self:encode_and_send({ jsonrpc = '2.0', @@ -319,9 +296,9 @@ end --- ---@param method (string) The invoked LSP method ---@param params (table|nil) Parameters for the invoked LSP method ----@param callback (function) Callback to invoke +---@param callback fun(err: lsp.ResponseError|nil, result: any) Callback to invoke ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending ----@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not +---@return boolean success, integer|nil request_id true, request_id if request could be sent, `false` if not function Client:request(method, params, callback, notify_reply_callback) validate({ callback = { callback, 'f' }, @@ -354,7 +331,7 @@ end ---@private function Client:on_error(errkind, ...) - assert(client_errors[errkind]) + assert(M.client_errors[errkind]) -- TODO what to do if this fails? pcall(self.dispatchers.on_error, errkind, ...) end @@ -381,7 +358,7 @@ end function Client:handle_body(body) local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) if not ok then - self:on_error(client_errors.INVALID_SERVER_JSON, decoded) + self:on_error(M.client_errors.INVALID_SERVER_JSON, decoded) return end local _ = log.debug() and log.debug('rpc.receive', decoded) @@ -394,7 +371,7 @@ function Client:handle_body(body) coroutine.wrap(function() local status, result status, result, err = self:try_call( - client_errors.SERVER_REQUEST_HANDLER_ERROR, + M.client_errors.SERVER_REQUEST_HANDLER_ERROR, self.dispatchers.server_request, decoded.method, decoded.params @@ -426,7 +403,7 @@ function Client:handle_body(body) end else -- On an exception, result will contain the error message. - err = rpc_response_error(protocol.ErrorCodes.InternalError, result) + err = M.rpc_response_error(protocol.ErrorCodes.InternalError, result) result = nil end self:send_response(decoded.id, err, result) @@ -479,34 +456,33 @@ function Client:handle_body(body) }) if decoded.error then decoded.error = setmetatable(decoded.error, { - __tostring = format_rpc_error, + __tostring = M.format_rpc_error, }) end self:try_call( - client_errors.SERVER_RESULT_CALLBACK_ERROR, + M.client_errors.SERVER_RESULT_CALLBACK_ERROR, callback, decoded.error, decoded.result ) else - self:on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) + self:on_error(M.client_errors.NO_RESULT_CALLBACK_FOUND, decoded) local _ = log.error() and log.error('No callback found for server response id ' .. result_id) end elseif type(decoded.method) == 'string' then -- Notification self:try_call( - client_errors.NOTIFICATION_HANDLER_ERROR, + M.client_errors.NOTIFICATION_HANDLER_ERROR, self.dispatchers.notification, decoded.method, decoded.params ) else -- Invalid server message - self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) + self:on_error(M.client_errors.INVALID_SERVER_MESSAGE, decoded) end end ----@private ---@return RpcClient local function new_client(dispatchers, transport) local state = { @@ -519,7 +495,6 @@ local function new_client(dispatchers, transport) return setmetatable(state, { __index = Client }) end ----@private ---@param client RpcClient local function public_client(client) local result = {} @@ -538,9 +513,9 @@ local function public_client(client) --- ---@param method (string) The invoked LSP method ---@param params (table|nil) Parameters for the invoked LSP method - ---@param callback (function) Callback to invoke + ---@param callback fun(err: lsp.ResponseError | nil, result: any) Callback to invoke ---@param notify_reply_callback (function|nil) Callback to invoke as soon as a request is no longer pending - ---@returns (bool, number) `(true, message_id)` if request could be sent, `false` if not + ---@return boolean success, integer|nil request_id true, message_id if request could be sent, `false` if not function result.request(method, params, callback, notify_reply_callback) return client:request(method, params, callback, notify_reply_callback) end @@ -548,7 +523,7 @@ local function public_client(client) --- Sends a notification to the LSP server. ---@param method (string) The invoked LSP method ---@param params (table|nil): Parameters for the invoked LSP method - ---@returns (bool) `true` if notification could be sent, `false` if not + ---@return boolean `true` if notification could be sent, `false` if not function result.notify(method, params) return client:notify(method, params) end @@ -556,7 +531,6 @@ local function public_client(client) return result end ----@private local function merge_dispatchers(dispatchers) if dispatchers then local user_dispatchers = dispatchers @@ -588,9 +562,9 @@ end --- and port --- ---@param host string ----@param port number +---@param port integer ---@return function -local function connect(host, port) +function M.connect(host, port) return function(dispatchers) dispatchers = merge_dispatchers(dispatchers) local tcp = uv.new_tcp() @@ -625,8 +599,8 @@ local function connect(host, port) local handle_body = function(body) client:handle_body(body) end - tcp:read_start(create_read_loop(handle_body, transport.terminate, function(read_err) - client:on_error(client_errors.READ_ERROR, read_err) + tcp:read_start(M.create_read_loop(handle_body, transport.terminate, function(read_err) + client:on_error(M.client_errors.READ_ERROR, read_err) end)) end) @@ -650,107 +624,93 @@ end --- server process. May contain: --- - {cwd} (string) Working directory for the LSP server process --- - {env} (table) Additional environment variables for LSP server process ----@returns Client RPC object. ---- ----@returns Methods: +---@return table|nil Client RPC object, with these methods: --- - `notify()` |vim.lsp.rpc.notify()| --- - `request()` |vim.lsp.rpc.request()| --- - `is_closing()` returns a boolean indicating if the RPC is closing. --- - `terminate()` terminates the RPC client. -local function start(cmd, cmd_args, dispatchers, extra_spawn_params) - local _ = log.info() - and log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) +function M.start(cmd, cmd_args, dispatchers, extra_spawn_params) + if log.info() then + log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) + end + validate({ cmd = { cmd, 's' }, cmd_args = { cmd_args, 't' }, dispatchers = { dispatchers, 't', true }, }) - if extra_spawn_params and extra_spawn_params.cwd then + extra_spawn_params = extra_spawn_params or {} + + if extra_spawn_params.cwd then assert(is_dir(extra_spawn_params.cwd), 'cwd must be a directory') end dispatchers = merge_dispatchers(dispatchers) - local stdin = uv.new_pipe(false) - local stdout = uv.new_pipe(false) - local stderr = uv.new_pipe(false) - local handle, pid + + local sysobj ---@type vim.SystemObj local client = new_client(dispatchers, { write = function(msg) - stdin:write(msg) + sysobj:write(msg) end, is_closing = function() - return handle == nil or handle:is_closing() + return sysobj == nil or sysobj:is_closing() end, terminate = function() - if handle then - handle:kill(15) - end + sysobj:kill(15) end, }) - ---@private - --- Callback for |vim.loop.spawn()| Closes all streams and runs the `on_exit` dispatcher. - ---@param code (number) Exit code - ---@param signal (number) Signal that was used to terminate (if any) - local function onexit(code, signal) - stdin:close() - stdout:close() - stderr:close() - handle:close() - dispatchers.on_exit(code, signal) + local handle_body = function(body) + client:handle_body(body) end - local spawn_params = { - args = cmd_args, - stdio = { stdin, stdout, stderr }, - detached = not is_win, - } - if extra_spawn_params then - spawn_params.cwd = extra_spawn_params.cwd - spawn_params.env = env_merge(extra_spawn_params.env) - if extra_spawn_params.detached ~= nil then - spawn_params.detached = extra_spawn_params.detached + + local stdout_handler = M.create_read_loop(handle_body, nil, function(err) + client:on_error(M.client_errors.READ_ERROR, err) + end) + + local stderr_handler = function(_, chunk) + if chunk and log.error() then + log.error('rpc', cmd, 'stderr', chunk) end end - handle, pid = uv.spawn(cmd, spawn_params, onexit) - if handle == nil then - stdin:close() - stdout:close() - stderr:close() + + local detached = not is_win + if extra_spawn_params.detached ~= nil then + detached = extra_spawn_params.detached + end + + local cmd1 = { cmd } + vim.list_extend(cmd1, cmd_args) + + local ok, sysobj_or_err = pcall(vim.system, cmd1, { + stdin = true, + stdout = stdout_handler, + stderr = stderr_handler, + cwd = extra_spawn_params.cwd, + env = extra_spawn_params.env, + detach = detached, + }, function(obj) + dispatchers.on_exit(obj.code, obj.signal) + end) + + if not ok then + local err = sysobj_or_err --[[@as string]] local msg = string.format('Spawning language server with cmd: `%s` failed', cmd) - if string.match(pid, 'ENOENT') then + if string.match(err, 'ENOENT') then msg = msg .. '. The language server is either not installed, missing from PATH, or not executable.' else - msg = msg .. string.format(' with error message: %s', pid) + msg = msg .. string.format(' with error message: %s', err) end vim.notify(msg, vim.log.levels.WARN) return end - stderr:read_start(function(_, chunk) - if chunk then - local _ = log.error() and log.error('rpc', cmd, 'stderr', chunk) - end - end) - - local handle_body = function(body) - client:handle_body(body) - end - stdout:read_start(create_read_loop(handle_body, nil, function(err) - client:on_error(client_errors.READ_ERROR, err) - end)) + sysobj = sysobj_or_err --[[@as vim.SystemObj]] return public_client(client) end -return { - start = start, - connect = connect, - rpc_response_error = rpc_response_error, - format_rpc_error = format_rpc_error, - client_errors = client_errors, - create_read_loop = create_read_loop, -} --- vim:sw=2 ts=2 et +return M diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua index b1bc48dac6..a5831c0beb 100644 --- a/runtime/lua/vim/lsp/semantic_tokens.lua +++ b/runtime/lua/vim/lsp/semantic_tokens.lua @@ -1,46 +1,50 @@ local api = vim.api +local bit = require('bit') local handlers = require('vim.lsp.handlers') +local ms = require('vim.lsp.protocol').Methods local util = require('vim.lsp.util') +local uv = vim.uv --- @class STTokenRange ---- @field line number line number 0-based ---- @field start_col number start column 0-based ---- @field end_col number end column 0-based +--- @field line integer line number 0-based +--- @field start_col integer start column 0-based +--- @field end_col integer end column 0-based --- @field type string token type as string ---- @field modifiers string[] token modifiers as strings ---- @field extmark_added boolean whether this extmark has been added to the buffer yet +--- @field modifiers table token modifiers as a set. E.g., { static = true, readonly = true } +--- @field marked boolean whether this token has had extmarks applied --- --- @class STCurrentResult ---- @field version number document version associated with this result ---- @field result_id string resultId from the server; used with delta requests ---- @field highlights STTokenRange[] cache of highlight ranges for this document version ---- @field tokens number[] raw token array as received by the server. used for calculating delta responses ---- @field namespace_cleared boolean whether the namespace was cleared for this result yet +--- @field version? integer document version associated with this result +--- @field result_id? string resultId from the server; used with delta requests +--- @field highlights? STTokenRange[] cache of highlight ranges for this document version +--- @field tokens? integer[] raw token array as received by the server. used for calculating delta responses +--- @field namespace_cleared? boolean whether the namespace was cleared for this result yet --- --- @class STActiveRequest ---- @field request_id number the LSP request ID of the most recent request sent to the server ---- @field version number the document version associated with the most recent request +--- @field request_id integer the LSP request ID of the most recent request sent to the server +--- @field version integer the document version associated with the most recent request --- --- @class STClientState ---- @field namespace number +--- @field namespace integer --- @field active_request STActiveRequest --- @field current_result STCurrentResult ---@class STHighlighter ----@field active table<number, STHighlighter> ----@field bufnr number ----@field augroup number augroup for buffer events ----@field debounce number milliseconds to debounce requests for new tokens +---@field active table<integer, STHighlighter> +---@field bufnr integer +---@field augroup integer augroup for buffer events +---@field debounce integer milliseconds to debounce requests for new tokens ---@field timer table uv_timer for debouncing requests for new tokens ----@field client_state table<number, STClientState> +---@field client_state table<integer, STClientState> local STHighlighter = { active = {} } ----@private -local function binary_search(tokens, line) - local lo = 1 - local hi = #tokens +--- Do a binary search of the tokens in the half-open range [lo, hi). +--- +--- Return the index i in range such that tokens[j].line < line for all j < i, and +--- tokens[j].line >= line for all j >= i, or return hi if no such index is found. +local function lower_bound(tokens, line, lo, hi) while lo < hi do - local mid = math.floor((lo + hi) / 2) + local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). if tokens[mid].line < line then lo = mid + 1 else @@ -50,26 +54,33 @@ local function binary_search(tokens, line) return lo end +--- Do a binary search of the tokens in the half-open range [lo, hi). +--- +--- Return the index i in range such that tokens[j].line <= line for all j < i, and +--- tokens[j].line > line for all j >= i, or return hi if no such index is found. +local function upper_bound(tokens, line, lo, hi) + while lo < hi do + local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). + if line < tokens[mid].line then + hi = mid + else + lo = mid + 1 + end + end + return lo +end + --- Extracts modifier strings from the encoded number in the token array --- ----@private ----@return string[] +---@return table<string, boolean> local function modifiers_from_number(x, modifiers_table) local modifiers = {} local idx = 1 while x > 0 do - if _G.bit then - if _G.bit.band(x, 1) == 1 then - modifiers[#modifiers + 1] = modifiers_table[idx] - end - x = _G.bit.rshift(x, 1) - else - --TODO(jdrouhard): remove this branch once `bit` module is available for non-LuaJIT (#21222) - if x % 2 == 1 then - modifiers[#modifiers + 1] = modifiers_table[idx] - end - x = math.floor(x / 2) + if bit.band(x, 1) == 1 then + modifiers[modifiers_table[idx]] = true end + x = bit.rshift(x, 1) idx = idx + 1 end @@ -78,17 +89,40 @@ end --- Converts a raw token list to a list of highlight ranges used by the on_win callback --- ----@private ---@return STTokenRange[] -local function tokens_to_ranges(data, bufnr, client) +local function tokens_to_ranges(data, bufnr, client, request) local legend = client.server_capabilities.semanticTokensProvider.legend local token_types = legend.tokenTypes local token_modifiers = legend.tokenModifiers + local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) local ranges = {} + local start = uv.hrtime() + local ms_to_ns = 1000 * 1000 + local yield_interval_ns = 5 * ms_to_ns + local co, is_main = coroutine.running() + local line local start_char = 0 for i = 1, #data, 5 do + -- if this function is called from the main coroutine, let it run to completion with no yield + if not is_main then + local elapsed_ns = uv.hrtime() - start + + if elapsed_ns > yield_interval_ns then + vim.schedule(function() + coroutine.resume(co, util.buf_versions[bufnr]) + end) + if request.version ~= coroutine.yield() then + -- request became stale since the last time the coroutine ran. + -- abandon it by yielding without a way to resume + coroutine.yield() + end + + start = uv.hrtime() + end + end + local delta_line = data[i] line = line and line + delta_line or delta_line local delta_start = data[i + 1] @@ -98,12 +132,17 @@ local function tokens_to_ranges(data, bufnr, client) local token_type = token_types[data[i + 3] + 1] local modifiers = modifiers_from_number(data[i + 4], token_modifiers) - ---@private - local function _get_byte_pos(char_pos) - return util._get_line_byte_from_position(bufnr, { - line = line, - character = char_pos, - }, client.offset_encoding) + local function _get_byte_pos(col) + if col > 0 then + local buf_line = lines[line + 1] or '' + local ok, result + ok, result = pcall(util._str_byteindex_enc, buf_line, col, client.offset_encoding) + if ok then + return result + end + return math.min(#buf_line, col) + end + return col end local start_col = _get_byte_pos(start_char) @@ -116,7 +155,7 @@ local function tokens_to_ranges(data, bufnr, client) end_col = end_col, type = token_type, modifiers = modifiers, - extmark_added = false, + marked = false, } end end @@ -127,7 +166,7 @@ end --- Construct a new STHighlighter for the buffer --- ---@private ----@param bufnr number +---@param bufnr integer function STHighlighter.new(bufnr) local self = setmetatable({}, { __index = STHighlighter }) @@ -254,7 +293,7 @@ function STHighlighter:send_request() local hasEditProvider = type(spec) == 'table' and spec.delta local params = { textDocument = util.make_text_document_params(self.bufnr) } - local method = 'textDocument/semanticTokens/full' + local method = ms.textDocument_semanticTokens_full if hasEditProvider and current_result.result_id then method = method .. '/delta' @@ -266,7 +305,7 @@ function STHighlighter:send_request() local c = vim.lsp.get_client_by_id(ctx.client_id) local highlighter = STHighlighter.active[ctx.bufnr] if not err and c and highlighter then - highlighter:process_response(response, c, version) + coroutine.wrap(STHighlighter.process_response)(highlighter, response, c, version) end end, self.bufnr) @@ -301,11 +340,9 @@ function STHighlighter:process_response(response, client, version) return end - -- reset active request - state.active_request = {} - -- skip nil responses if response == nil then + state.active_request = {} return end @@ -333,15 +370,23 @@ function STHighlighter:process_response(response, client, version) tokens = response.data end - -- Update the state with the new results + -- convert token list to highlight ranges + -- this could yield and run over multiple event loop iterations + local highlights = tokens_to_ranges(tokens, self.bufnr, client, state.active_request) + + -- reset active request + state.active_request = {} + + -- update the state with the new results local current_result = state.current_result current_result.version = version current_result.result_id = response.resultId current_result.tokens = tokens - current_result.highlights = tokens_to_ranges(tokens, self.bufnr, client) + current_result.highlights = highlights current_result.namespace_cleared = false - api.nvim_command('redraw!') + -- redraw all windows displaying buffer + api.nvim__buf_redraw_range(self.bufnr, 0, -1) end --- on_win handler for the decoration provider (see |nvim_set_decoration_provider|) @@ -361,7 +406,7 @@ end --- ---@private function STHighlighter:on_win(topline, botline) - for _, state in pairs(self.client_state) do + for client_id, state in pairs(self.client_state) do local current_result = state.current_result if current_result.version and current_result.version == util.buf_versions[self.bufnr] then if not current_result.namespace_cleared then @@ -378,52 +423,55 @@ function STHighlighter:on_win(topline, botline) -- -- Instead, we have to use normal extmarks that can attach to locations -- in the buffer and are persisted between redraws. + -- + -- `strict = false` is necessary here for the 1% of cases where the + -- current result doesn't actually match the buffer contents. Some + -- LSP servers can respond with stale tokens on requests if they are + -- still processing changes from a didChange notification. + -- + -- LSP servers that do this _should_ follow up known stale responses + -- with a refresh notification once they've finished processing the + -- didChange notification, which would re-synchronize the tokens from + -- our end. + -- + -- The server I know of that does this is clangd when the preamble of + -- a file changes and the token request is processed with a stale + -- preamble while the new one is still being built. Once the preamble + -- finishes, clangd sends a refresh request which lets the client + -- re-synchronize the tokens. + + local set_mark = function(token, hl_group, delta) + vim.api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { + hl_group = hl_group, + end_col = token.end_col, + priority = vim.highlight.priorities.semantic_tokens + delta, + strict = false, + }) + end + + local ft = vim.bo[self.bufnr].filetype local highlights = current_result.highlights - local idx = binary_search(highlights, topline) + local first = lower_bound(highlights, topline, 1, #highlights + 1) + local last = upper_bound(highlights, botline, first, #highlights + 1) - 1 - for i = idx, #highlights do + for i = first, last do local token = highlights[i] - - if token.line > botline then - break - end - - if not token.extmark_added then - -- `strict = false` is necessary here for the 1% of cases where the - -- current result doesn't actually match the buffer contents. Some - -- LSP servers can respond with stale tokens on requests if they are - -- still processing changes from a didChange notification. - -- - -- LSP servers that do this _should_ follow up known stale responses - -- with a refresh notification once they've finished processing the - -- didChange notification, which would re-synchronize the tokens from - -- our end. - -- - -- The server I know of that does this is clangd when the preamble of - -- a file changes and the token request is processed with a stale - -- preamble while the new one is still being built. Once the preamble - -- finishes, clangd sends a refresh request which lets the client - -- re-synchronize the tokens. - api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { - hl_group = '@' .. token.type, - end_col = token.end_col, - priority = vim.highlight.priorities.semantic_tokens, - strict = false, - }) - - -- TODO(bfredl) use single extmark when hl_group supports table - if #token.modifiers > 0 then - for _, modifier in pairs(token.modifiers) do - api.nvim_buf_set_extmark(self.bufnr, state.namespace, token.line, token.start_col, { - hl_group = '@' .. modifier, - end_col = token.end_col, - priority = vim.highlight.priorities.semantic_tokens + 1, - strict = false, - }) - end + if not token.marked then + set_mark(token, string.format('@lsp.type.%s.%s', token.type, ft), 0) + for modifier, _ in pairs(token.modifiers) do + set_mark(token, string.format('@lsp.mod.%s.%s', modifier, ft), 1) + set_mark(token, string.format('@lsp.typemod.%s.%s.%s', token.type, modifier, ft), 2) end - - token.extmark_added = true + token.marked = true + + api.nvim_exec_autocmds('LspTokenUpdate', { + buffer = self.bufnr, + modeline = false, + data = { + token = token, + client_id = client_id, + }, + }) end end end @@ -452,7 +500,7 @@ end --- in case the server supports delta requests. --- ---@private ----@param client_id number +---@param client_id integer function STHighlighter:mark_dirty(client_id) local state = self.client_state[client_id] assert(state) @@ -507,14 +555,15 @@ local M = {} --- delete the semanticTokensProvider table from the {server_capabilities} of --- your client in your |LspAttach| callback or your configuration's --- `on_attach` callback: ---- <pre>lua ---- client.server_capabilities.semanticTokensProvider = nil ---- </pre> --- ----@param bufnr number ----@param client_id number +--- ```lua +--- client.server_capabilities.semanticTokensProvider = nil +--- ``` +--- +---@param bufnr integer +---@param client_id integer ---@param opts (nil|table) Optional keyword arguments ---- - debounce (number, default: 200): Debounce token requests +--- - debounce (integer, default: 200): Debounce token requests --- to the server by the given number in milliseconds function M.start(bufnr, client_id, opts) vim.validate({ @@ -567,8 +616,8 @@ end --- of `start()`, so you should only need this function to manually disengage the semantic --- token engine without fully detaching the LSP client from the buffer. --- ----@param bufnr number ----@param client_id number +---@param bufnr integer +---@param client_id integer function M.stop(bufnr, client_id) vim.validate({ bufnr = { bufnr, 'n', false }, @@ -590,11 +639,17 @@ end --- Return the semantic token(s) at the given position. --- If called without arguments, returns the token under the cursor. --- ----@param bufnr number|nil Buffer number (0 for current buffer, default) ----@param row number|nil Position row (default cursor position) ----@param col number|nil Position column (default cursor position) +---@param bufnr integer|nil Buffer number (0 for current buffer, default) +---@param row integer|nil Position row (default cursor position) +---@param col integer|nil Position column (default cursor position) --- ----@return table|nil (table|nil) List of tokens at position +---@return table|nil (table|nil) List of tokens at position. Each token has +--- the following fields: +--- - line (integer) line number, 0-based +--- - start_col (integer) start column, 0-based +--- - end_col (integer) end column, 0-based +--- - type (string) token type as string, e.g. "variable" +--- - modifiers (table) token modifiers as a set. E.g., { static = true, readonly = true } function M.get_at_pos(bufnr, row, col) if bufnr == nil or bufnr == 0 then bufnr = api.nvim_get_current_buf() @@ -614,7 +669,7 @@ function M.get_at_pos(bufnr, row, col) for client_id, client in pairs(highlighter.client_state) do local highlights = client.current_result.highlights if highlights then - local idx = binary_search(highlights, row) + local idx = lower_bound(highlights, row, 1, #highlights + 1) for i = idx, #highlights do local token = highlights[i] @@ -637,23 +692,59 @@ end --- Only has an effect if the buffer is currently active for semantic token --- highlighting (|vim.lsp.semantic_tokens.start()| has been called for it) --- ----@param bufnr (nil|number) default: current buffer +---@param bufnr (integer|nil) filter by buffer. All buffers if nil, current +--- buffer if 0 function M.force_refresh(bufnr) vim.validate({ bufnr = { bufnr, 'n', true }, }) - if bufnr == nil or bufnr == 0 then - bufnr = api.nvim_get_current_buf() + local buffers = bufnr == nil and vim.tbl_keys(STHighlighter.active) + or bufnr == 0 and { api.nvim_get_current_buf() } + or { bufnr } + + for _, buffer in ipairs(buffers) do + local highlighter = STHighlighter.active[buffer] + if highlighter then + highlighter:reset() + highlighter:send_request() + end end +end +--- Highlight a semantic token. +--- +--- Apply an extmark with a given highlight group for a semantic token. The +--- mark will be deleted by the semantic token engine when appropriate; for +--- example, when the LSP sends updated tokens. This function is intended for +--- use inside |LspTokenUpdate| callbacks. +---@param token (table) a semantic token, found as `args.data.token` in |LspTokenUpdate|. +---@param bufnr (integer) the buffer to highlight +---@param client_id (integer) The ID of the |vim.lsp.client| +---@param hl_group (string) Highlight group name +---@param opts (table|nil) Optional parameters. +--- - priority: (integer|nil) Priority for the applied extmark. Defaults +--- to `vim.highlight.priorities.semantic_tokens + 3` +function M.highlight_token(token, bufnr, client_id, hl_group, opts) local highlighter = STHighlighter.active[bufnr] if not highlighter then return end - highlighter:reset() - highlighter:send_request() + local state = highlighter.client_state[client_id] + if not state then + return + end + + opts = opts or {} + local priority = opts.priority or vim.highlight.priorities.semantic_tokens + 3 + + vim.api.nvim_buf_set_extmark(bufnr, state.namespace, token.line, token.start_col, { + hl_group = hl_group, + end_col = token.end_col, + priority = priority, + strict = false, + }) end --- |lsp-handler| for the method `workspace/semanticTokens/refresh` @@ -665,7 +756,7 @@ end --- the BufWinEnter event should take care of it next time it's displayed. --- ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#semanticTokens_refreshRequest -handlers['workspace/semanticTokens/refresh'] = function(err, _, ctx) +handlers[ms.workspace_semanticTokens_refresh] = function(err, _, ctx) if err then return vim.NIL end diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua index 826352f036..ca01cdc08b 100644 --- a/runtime/lua/vim/lsp/sync.lua +++ b/runtime/lua/vim/lsp/sync.lua @@ -48,7 +48,6 @@ local str_utfindex = vim.str_utfindex local str_utf_start = vim.str_utf_start local str_utf_end = vim.str_utf_end ----@private -- Given a line, byte idx, and offset_encoding convert to the -- utf-8, utf-16, or utf-32 index. ---@param line string the line to index into @@ -74,7 +73,6 @@ local function byte_to_utf(line, byte, offset_encoding) return utf_idx + 1 end ----@private local function compute_line_length(line, offset_encoding) local length local _ @@ -88,13 +86,13 @@ local function compute_line_length(line, offset_encoding) return length end ----@private -- Given a line, byte idx, alignment, and offset_encoding convert to the aligned -- utf-8 index and either the utf-16, or utf-32 index. ---@param line string the line to index into ---@param byte integer the byte idx ---@param offset_encoding string utf-8|utf-16|utf-32|nil (default: utf-8) ----@returns table<string, int> byte_idx and char_idx of first change position +---@return integer byte_idx of first change position +---@return integer char_idx of first change position local function align_end_position(line, byte, offset_encoding) local char -- If on the first byte, or an empty string: the trivial case @@ -121,7 +119,6 @@ local function align_end_position(line, byte, offset_encoding) return byte, char end ----@private --- Finds the first line, byte, and char index of the difference between the previous and current lines buffer normalized to the previous codepoint. ---@param prev_lines table list of lines from previous buffer ---@param curr_lines table list of lines from current buffer @@ -129,7 +126,7 @@ end ---@param lastline integer lastline from on_lines, adjusted to 1-index ---@param new_lastline integer new_lastline from on_lines, adjusted to 1-index ---@param offset_encoding string utf-8|utf-16|utf-32|nil (fallback to utf-8) ----@returns table<int, int> line_idx, byte_idx, and char_idx of first change position +---@return table result table include line_idx, byte_idx, and char_idx of first change position local function compute_start_range( prev_lines, curr_lines, @@ -197,7 +194,6 @@ local function compute_start_range( return { line_idx = firstline, byte_idx = byte_idx, char_idx = char_idx } end ----@private --- Finds the last line and byte index of the differences between prev and current buffer. --- Normalized to the next codepoint. --- prev_end_range is the text range sent to the server representing the changed region. @@ -209,7 +205,8 @@ end ---@param lastline integer ---@param new_lastline integer ---@param offset_encoding string ----@returns (int, int) end_line_idx and end_col_idx of range +---@return integer|table end_line_idx and end_col_idx of range +---@return table|nil end_col_idx of range local function compute_end_range( prev_lines, curr_lines, @@ -305,12 +302,11 @@ local function compute_end_range( return prev_end_range, curr_end_range end ----@private --- Get the text of the range defined by start and end line/column ---@param lines table list of lines ---@param start_range table table returned by first_difference ---@param end_range table new_end_range returned by last_difference ----@returns string text extracted from defined region +---@return string text extracted from defined region local function extract_text(lines, start_range, end_range, line_ending) if not lines[start_range.line_idx] then return '' @@ -341,7 +337,6 @@ local function extract_text(lines, start_range, end_range, line_ending) end end ----@private -- rangelength depends on the offset encoding -- bytes for utf-8 (clangd with extension) -- codepoints for utf-16 @@ -388,11 +383,11 @@ end --- Returns the range table for the difference between prev and curr lines ---@param prev_lines table list of lines ---@param curr_lines table list of lines ----@param firstline number line to begin search for first difference ----@param lastline number line to begin search in old_lines for last difference ----@param new_lastline number line to begin search in new_lines for last difference +---@param firstline integer line to begin search for first difference +---@param lastline integer line to begin search in old_lines for last difference +---@param new_lastline integer line to begin search in new_lines for last difference ---@param offset_encoding string encoding requested by language server ----@returns table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent +---@return table TextDocumentContentChangeEvent see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent function M.compute_diff( prev_lines, curr_lines, diff --git a/runtime/lua/vim/lsp/tagfunc.lua b/runtime/lua/vim/lsp/tagfunc.lua index 49029f8599..4ad50e4a58 100644 --- a/runtime/lua/vim/lsp/tagfunc.lua +++ b/runtime/lua/vim/lsp/tagfunc.lua @@ -1,7 +1,12 @@ local lsp = vim.lsp local util = lsp.util +local ms = lsp.protocol.Methods ----@private +---@param name string +---@param range lsp.Range +---@param uri string +---@param offset_encoding string +---@return {name: string, filename: string, cmd: string, kind?: string} local function mk_tag_item(name, range, uri, offset_encoding) local bufnr = vim.uri_to_bufnr(uri) -- This is get_line_byte_from_position is 0-indexed, call cursor expects a 1-indexed position @@ -9,14 +14,15 @@ local function mk_tag_item(name, range, uri, offset_encoding) return { name = name, filename = vim.uri_to_fname(uri), - cmd = string.format('call cursor(%d, %d)|', range.start.line + 1, byte), + cmd = string.format([[/\%%%dl\%%%dc/]], range.start.line + 1, byte), } end ----@private +---@param pattern string +---@return table[] local function query_definition(pattern) local params = util.make_position_params() - local results_by_client, err = lsp.buf_request_sync(0, 'textDocument/definition', params, 1000) + local results_by_client, err = lsp.buf_request_sync(0, ms.textDocument_definition, params, 1000) if err then return {} end @@ -24,17 +30,19 @@ local function query_definition(pattern) local add = function(range, uri, offset_encoding) table.insert(results, mk_tag_item(pattern, range, uri, offset_encoding)) end - for client_id, lsp_results in pairs(results_by_client) do + for client_id, lsp_results in pairs(assert(results_by_client)) do local client = lsp.get_client_by_id(client_id) + local offset_encoding = client and client.offset_encoding or 'utf-16' local result = lsp_results.result or {} if result.range then -- Location add(result.range, result.uri) - else -- Location[] or LocationLink[] + else + result = result --[[@as (lsp.Location[]|lsp.LocationLink[])]] for _, item in pairs(result) do if item.range then -- Location - add(item.range, item.uri, client.offset_encoding) + add(item.range, item.uri, offset_encoding) else -- LocationLink - add(item.targetSelectionRange, item.targetUri, client.offset_encoding) + add(item.targetSelectionRange, item.targetUri, offset_encoding) end end end @@ -42,19 +50,22 @@ local function query_definition(pattern) return results end ----@private +---@param pattern string +---@return table[] local function query_workspace_symbols(pattern) local results_by_client, err = - lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000) + lsp.buf_request_sync(0, ms.workspace_symbol, { query = pattern }, 1000) if err then return {} end local results = {} - for client_id, symbols in pairs(results_by_client) do + for client_id, responses in pairs(assert(results_by_client)) do local client = lsp.get_client_by_id(client_id) - for _, symbol in pairs(symbols.result or {}) do + local offset_encoding = client and client.offset_encoding or 'utf-16' + local symbols = responses.result --[[@as lsp.SymbolInformation[]|nil]] + for _, symbol in pairs(symbols or {}) do local loc = symbol.location - local item = mk_tag_item(symbol.name, loc.range, loc.uri, client.offset_encoding) + local item = mk_tag_item(symbol.name, loc.range, loc.uri, offset_encoding) item.kind = lsp.protocol.SymbolKind[symbol.kind] or 'Unknown' table.insert(results, item) end @@ -62,14 +73,9 @@ local function query_workspace_symbols(pattern) return results end ----@private local function tagfunc(pattern, flags) - local matches - if string.match(flags, 'c') then - matches = query_definition(pattern) - else - matches = query_workspace_symbols(pattern) - end + local matches = string.match(flags, 'c') and query_definition(pattern) + or query_workspace_symbols(pattern) -- fall back to tags if no matches return #matches > 0 and matches or vim.NIL end diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 38051e6410..32b220746f 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -1,10 +1,10 @@ local protocol = require('vim.lsp.protocol') -local snippet = require('vim.lsp._snippet') +local snippet = require('vim.lsp._snippet_grammar') local validate = vim.validate local api = vim.api local list_extend = vim.list_extend local highlight = require('vim.highlight') -local uv = vim.loop +local uv = vim.uv local npcall = vim.F.npcall local split = vim.split @@ -22,12 +22,11 @@ local default_border = { { ' ', 'NormalFloat' }, } ----@private --- Check the border given by opts or the default border for the additional --- size it adds to a float. ----@param opts (table, optional) options for the floating window +---@param opts table optional options for the floating window --- - border (string or table) the border ----@returns (table) size of border in the form of { height = height, width = width } +---@return table size of border in the form of { height = height, width = width } local function get_border_size(opts) local border = opts and opts.border or default_border local height = 0 @@ -60,7 +59,6 @@ local function get_border_size(opts) ) ) end - ---@private local function border_width(id) id = (id - 1) % #border + 1 if type(border[id]) == 'table' then @@ -77,7 +75,6 @@ local function get_border_size(opts) ) ) end - ---@private local function border_height(id) id = (id - 1) % #border + 1 if type(border[id]) == 'table' then @@ -103,13 +100,11 @@ local function get_border_size(opts) return { height = height, width = width } end ----@private local function split_lines(value) value = string.gsub(value, '\r\n?', '\n') - return split(value, '\n', true) + return split(value, '\n', { plain = true, trimempty = true }) end ----@private local function create_window_without_focus() local prev = vim.api.nvim_get_current_win() vim.cmd.new() @@ -121,9 +116,9 @@ end --- Convert byte index to `encoding` index. --- Convenience wrapper around vim.str_utfindex ---@param line string line to be indexed ----@param index number|nil byte index (utf-8), or `nil` for length ----@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ----@return number `encoding` index of `index` in `line` +---@param index integer|nil byte index (utf-8), or `nil` for length +---@param encoding string|nil utf-8|utf-16|utf-32|nil defaults to utf-16 +---@return integer `encoding` index of `index` in `line` function M._str_utfindex_enc(line, index, encoding) if not encoding then encoding = 'utf-16' @@ -149,9 +144,9 @@ end --- Convenience wrapper around vim.str_byteindex ---Alternative to vim.str_byteindex that takes an encoding. ---@param line string line to be indexed ----@param index number UTF index ----@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16 ----@return number byte (utf-8) index of `encoding` index `index` in `line` +---@param index integer UTF index +---@param encoding string utf-8|utf-16|utf-32| defaults to utf-16 +---@return integer byte (utf-8) index of `encoding` index `index` in `line` function M._str_byteindex_enc(line, index, encoding) if not encoding then encoding = 'utf-16' @@ -173,15 +168,17 @@ end local _str_utfindex_enc = M._str_utfindex_enc local _str_byteindex_enc = M._str_byteindex_enc + --- Replaces text in a range with new text. --- --- CAUTION: Changes in-place! --- +---@deprecated ---@param lines (table) Original list of strings ----@param A (table) Start position; a 2-tuple of {line, col} numbers ----@param B (table) End position; a 2-tuple of {line, col} numbers ----@param new_lines A list of strings to replace the original ----@returns (table) The modified {lines} object +---@param A (table) Start position; a 2-tuple of {line,col} numbers +---@param B (table) End position; a 2-tuple of {line,col} numbers +---@param new_lines (table) list of strings to replace the original +---@return table The modified {lines} object function M.set_lines(lines, A, B, new_lines) -- 0-indexing to 1-indexing local i_0 = A[1] + 1 @@ -219,7 +216,6 @@ function M.set_lines(lines, A, B, new_lines) return lines end ----@private local function sort_by_key(fn) return function(a, b) local ka, kb = fn(a), fn(b) @@ -234,14 +230,13 @@ local function sort_by_key(fn) end end ----@private --- Gets the zero-indexed lines from the given buffer. --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. --- ----@param bufnr number bufnr to get the lines from ----@param rows number[] zero-indexed line numbers ----@return table<number string> a table mapping rows to lines +---@param bufnr integer bufnr to get the lines from +---@param rows integer[] zero-indexed line numbers +---@return table<integer, string>|string a table mapping rows to lines local function get_lines(bufnr, rows) rows = type(rows) == 'table' and rows or { rows } @@ -250,15 +245,19 @@ local function get_lines(bufnr, rows) bufnr = api.nvim_get_current_buf() end - ---@private local function buf_lines() local lines = {} - for _, row in pairs(rows) do + for _, row in ipairs(rows) do lines[row] = (api.nvim_buf_get_lines(bufnr, row, row + 1, false) or { '' })[1] end return lines end + -- use loaded buffers if available + if vim.fn.bufloaded(bufnr) == 1 then + return buf_lines() + end + local uri = vim.uri_from_bufnr(bufnr) -- load the buffer if this is not a file uri @@ -268,11 +267,6 @@ local function get_lines(bufnr, rows) return buf_lines() end - -- use loaded buffers if available - if vim.fn.bufloaded(bufnr) == 1 then - return buf_lines() - end - local filename = api.nvim_buf_get_name(bufnr) -- get the data from the file @@ -316,23 +310,20 @@ local function get_lines(bufnr, rows) return lines end ----@private --- Gets the zero-indexed line from the given buffer. --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. --- ----@param bufnr number ----@param row number zero-indexed line number +---@param bufnr integer +---@param row integer zero-indexed line number ---@return string the line at row in filename local function get_line(bufnr, row) return get_lines(bufnr, { row })[row] end ----@private --- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position ---- Returns a zero-indexed column, since set_lines() does the conversion to ----@param offset_encoding string utf-8|utf-16|utf-32 ---- 1-indexed +---@param offset_encoding string|nil utf-8|utf-16|utf-32 +---@return integer local function get_line_byte_from_position(bufnr, position, offset_encoding) -- LSP's line and characters are 0-indexed -- Vim's line and columns are 1-indexed @@ -353,11 +344,40 @@ end --- Process and return progress reports from lsp server ---@private +---@deprecated Use vim.lsp.status() or access client.progress directly function M.get_progress_messages() + vim.deprecate('vim.lsp.util.get_progress_messages', 'vim.lsp.status', '0.11.0') local new_messages = {} local progress_remove = {} - for _, client in ipairs(vim.lsp.get_active_clients()) do + for _, client in ipairs(vim.lsp.get_clients()) do + local groups = {} + for progress in client.progress do + local value = progress.value + if type(value) == 'table' and value.kind then + local group = groups[progress.token] + if not group then + group = { + done = false, + progress = true, + title = 'empty title', + } + groups[progress.token] = group + end + group.title = value.title or group.title + group.cancellable = value.cancellable or group.cancellable + if value.kind == 'end' then + group.done = true + end + group.message = value.message or group.message + group.percentage = value.percentage or group.percentage + end + end + + for _, group in pairs(groups) do + table.insert(new_messages, group) + end + local messages = client.messages local data = messages for token, ctx in pairs(data.progress) do @@ -386,7 +406,7 @@ end --- Applies a list of text edits to a buffer. ---@param text_edits table list of `TextEdit` objects ----@param bufnr number Buffer id +---@param bufnr integer Buffer id ---@param offset_encoding string utf-8|utf-16|utf-32 ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit function M.apply_text_edits(text_edits, bufnr, offset_encoding) @@ -401,7 +421,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) if not api.nvim_buf_is_loaded(bufnr) then vim.fn.bufload(bufnr) end - api.nvim_buf_set_option(bufnr, 'buflisted', true) + vim.bo[bufnr].buflisted = true -- Fix reversed range and indexing each text_edits local index = 0 @@ -434,25 +454,15 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) end end) - -- Some LSP servers are depending on the VSCode behavior. - -- The VSCode will re-locate the cursor position after applying TextEdit so we also do it. - local is_current_buf = api.nvim_get_current_buf() == bufnr - local cursor = (function() - if not is_current_buf then - return { - row = -1, - col = -1, - } + -- save and restore local marks since they get deleted by nvim_buf_set_lines + local marks = {} + for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do + if m.mark:match("^'[a-z]$") then + marks[m.mark:sub(2, 2)] = { m.pos[2], m.pos[3] - 1 } -- api-indexed end - local cursor = api.nvim_win_get_cursor(0) - return { - row = cursor[1] - 1, - col = cursor[2], - } - end)() + end -- Apply text edits. - local is_cursor_fixed = false local has_eol_text_edit = false for _, text_edit in ipairs(text_edits) do -- Normalize line ending @@ -464,7 +474,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) start_col = get_line_byte_from_position(bufnr, text_edit.range.start, offset_encoding), end_row = text_edit.range['end'].line, end_col = get_line_byte_from_position(bufnr, text_edit.range['end'], offset_encoding), - text = split(text_edit.newText, '\n', true), + text = split(text_edit.newText, '\n', { plain = true }), } local max = api.nvim_buf_line_count(bufnr) @@ -499,42 +509,28 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding) e.end_col = math.min(last_line_len, e.end_col) api.nvim_buf_set_text(bufnr, e.start_row, e.start_col, e.end_row, e.end_col, e.text) - - -- Fix cursor position. - local row_count = (e.end_row - e.start_row) + 1 - if e.end_row < cursor.row then - cursor.row = cursor.row + (#e.text - row_count) - is_cursor_fixed = true - elseif e.end_row == cursor.row and e.end_col <= cursor.col then - cursor.row = cursor.row + (#e.text - row_count) - cursor.col = #e.text[#e.text] + (cursor.col - e.end_col) - if #e.text == 1 then - cursor.col = cursor.col + e.start_col - end - is_cursor_fixed = true - end end end local max = api.nvim_buf_line_count(bufnr) - -- Apply fixed cursor position. - if is_cursor_fixed then - local is_valid_cursor = true - is_valid_cursor = is_valid_cursor and cursor.row < max - is_valid_cursor = is_valid_cursor and cursor.col <= #(get_line(bufnr, max - 1) or '') - if is_valid_cursor then - api.nvim_win_set_cursor(0, { cursor.row + 1, cursor.col }) + -- no need to restore marks that still exist + for _, m in pairs(vim.fn.getmarklist(bufnr or vim.api.nvim_get_current_buf())) do + marks[m.mark:sub(2, 2)] = nil + end + -- restore marks + for mark, pos in pairs(marks) do + if pos then + -- make sure we don't go out of bounds + pos[1] = math.min(pos[1], max) + pos[2] = math.min(pos[2], #(get_line(bufnr, pos[1] - 1) or '')) + vim.api.nvim_buf_set_mark(bufnr or 0, mark, pos[1], pos[2], {}) end end -- Remove final line if needed local fix_eol = has_eol_text_edit - fix_eol = fix_eol - and ( - api.nvim_buf_get_option(bufnr, 'eol') - or (api.nvim_buf_get_option(bufnr, 'fixeol') and not api.nvim_buf_get_option(bufnr, 'binary')) - ) + fix_eol = fix_eol and (vim.bo[bufnr].eol or (vim.bo[bufnr].fixeol and not vim.bo[bufnr].binary)) fix_eol = fix_eol and get_line(bufnr, max - 1) == '' if fix_eol then api.nvim_buf_set_lines(bufnr, -2, -1, false, {}) @@ -551,10 +547,12 @@ end --- Can be used to extract the completion items from a --- `textDocument/completion` request, which may return one of --- `CompletionItem[]`, `CompletionList` or null. ----@param result (table) The result of a `textDocument/completion` request ----@returns (table) List of completion items +---@deprecated +---@param result table The result of a `textDocument/completion` request +---@return lsp.CompletionItem[] List of completion items ---@see https://microsoft.github.io/language-server-protocol/specification#textDocument_completion function M.extract_completion_items(result) + vim.deprecate('vim.lsp.util.extract_completion_items', nil, '0.11') if type(result) == 'table' and result.items then -- result is a `CompletionList` return result.items @@ -571,7 +569,7 @@ end --- document. --- ---@param text_document_edit table: a `TextDocumentEdit` object ----@param index number: Optional index of the edit, if from a list of edits (or nil, if not from a list) +---@param index integer: Optional index of the edit, if from a list of edits (or nil, if not from a list) ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit function M.apply_text_document_edit(text_document_edit, index, offset_encoding) local text_document = text_document_edit.textDocument @@ -610,130 +608,36 @@ end --- Parses snippets in a completion entry. --- +---@deprecated ---@param input string unparsed snippet ----@returns string parsed snippet +---@return string parsed snippet function M.parse_snippet(input) + vim.deprecate('vim.lsp.util.parse_snippet', nil, '0.11') local ok, parsed = pcall(function() - return tostring(snippet.parse(input)) + return snippet.parse(input) end) if not ok then return input end - return parsed -end - ----@private ---- Sorts by CompletionItem.sortText. ---- ---see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -local function sort_completion_items(items) - table.sort(items, function(a, b) - return (a.sortText or a.label) < (b.sortText or b.label) - end) -end - ----@private ---- Returns text that should be inserted when selecting completion item. The ---- precedence is as follows: textEdit.newText > insertText > label ---see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -local function get_completion_word(item) - if item.textEdit ~= nil and item.textEdit.newText ~= nil and item.textEdit.newText ~= '' then - local insert_text_format = protocol.InsertTextFormat[item.insertTextFormat] - if insert_text_format == 'PlainText' or insert_text_format == nil then - return item.textEdit.newText - else - return M.parse_snippet(item.textEdit.newText) - end - elseif item.insertText ~= nil and item.insertText ~= '' then - local insert_text_format = protocol.InsertTextFormat[item.insertTextFormat] - if insert_text_format == 'PlainText' or insert_text_format == nil then - return item.insertText - else - return M.parse_snippet(item.insertText) - end - end - return item.label -end ----@private ---- Some language servers return complementary candidates whose prefixes do not ---- match are also returned. So we exclude completion candidates whose prefix ---- does not match. -local function remove_unmatch_completion_items(items, prefix) - return vim.tbl_filter(function(item) - local word = get_completion_word(item) - return vim.startswith(word, prefix) - end, items) -end - ---- According to LSP spec, if the client set `completionItemKind.valueSet`, ---- the client must handle it properly even if it receives a value outside the ---- specification. ---- ----@param completion_item_kind (`vim.lsp.protocol.completionItemKind`) ----@returns (`vim.lsp.protocol.completionItemKind`) ----@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion -function M._get_completion_item_kind_name(completion_item_kind) - return protocol.CompletionItemKind[completion_item_kind] or 'Unknown' + return tostring(parsed) end --- Turns the result of a `textDocument/completion` request into vim-compatible --- |complete-items|. --- ----@param result The result of a `textDocument/completion` call, e.g. from ----|vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, +---@deprecated +---@param result table The result of a `textDocument/completion` call, e.g. +--- from |vim.lsp.buf.completion()|, which may be one of `CompletionItem[]`, --- `CompletionList` or `null` ---@param prefix (string) the prefix to filter the completion items ----@returns { matches = complete-items table, incomplete = bool } ----@see |complete-items| +---@return table[] items +---@see complete-items function M.text_document_completion_list_to_complete_items(result, prefix) - local items = M.extract_completion_items(result) - if vim.tbl_isempty(items) then - return {} - end - - items = remove_unmatch_completion_items(items, prefix) - sort_completion_items(items) - - local matches = {} - - for _, completion_item in ipairs(items) do - local info = ' ' - local documentation = completion_item.documentation - if documentation then - if type(documentation) == 'string' and documentation ~= '' then - info = documentation - elseif type(documentation) == 'table' and type(documentation.value) == 'string' then - info = documentation.value - -- else - -- TODO(ashkan) Validation handling here? - end - end - - local word = get_completion_word(completion_item) - table.insert(matches, { - word = word, - abbr = completion_item.label, - kind = M._get_completion_item_kind_name(completion_item.kind), - menu = completion_item.detail or '', - info = info, - icase = 1, - dup = 1, - empty = 1, - user_data = { - nvim = { - lsp = { - completion_item = completion_item, - }, - }, - }, - }) - end - - return matches + vim.deprecate('vim.lsp.util.text_document_completion_list_to_complete_items', nil, '0.11') + return require('vim.lsp._completion')._lsp_to_complete_items(result, prefix) end ----@private --- Like vim.fn.bufwinid except it works across tabpages. local function bufwinid(bufnr) for _, win in ipairs(api.nvim_list_wins()) do @@ -743,6 +647,19 @@ local function bufwinid(bufnr) end end +--- Get list of buffers for a directory +local function get_dir_bufs(path) + path = path:gsub('([^%w])', '%%%1') + local buffers = {} + for _, v in ipairs(vim.api.nvim_list_bufs()) do + local bufname = vim.api.nvim_buf_get_name(v):gsub('buffer://', '') + if bufname:find(path) then + table.insert(buffers, v) + end + end + return buffers +end + --- Rename old_fname to new_fname --- ---@param opts (table) @@ -755,26 +672,41 @@ function M.rename(old_fname, new_fname, opts) vim.notify('Rename target already exists. Skipping rename.') return end - local oldbuf = vim.fn.bufadd(old_fname) - vim.fn.bufload(oldbuf) - -- The there may be pending changes in the buffer - api.nvim_buf_call(oldbuf, function() - vim.cmd('w!') - end) + local oldbufs = {} + local win = nil + + if vim.fn.isdirectory(old_fname) == 1 then + oldbufs = get_dir_bufs(old_fname) + else + local oldbuf = vim.fn.bufadd(old_fname) + table.insert(oldbufs, oldbuf) + win = bufwinid(oldbuf) + end + + for _, b in ipairs(oldbufs) do + vim.fn.bufload(b) + -- The there may be pending changes in the buffer + api.nvim_buf_call(b, function() + vim.cmd('w!') + end) + end local ok, err = os.rename(old_fname, new_fname) assert(ok, err) - local newbuf = vim.fn.bufadd(new_fname) - local win = bufwinid(oldbuf) - if win then - api.nvim_win_set_buf(win, newbuf) + if vim.fn.isdirectory(new_fname) == 0 then + local newbuf = vim.fn.bufadd(new_fname) + if win then + api.nvim_win_set_buf(win, newbuf) + end + end + + for _, b in ipairs(oldbufs) do + api.nvim_buf_delete(b, {}) end - api.nvim_buf_delete(oldbuf, { force = true }) end ----@private local function create_file(change) local opts = change.options or {} -- from spec: Overwrite wins over `ignoreIfExists` @@ -789,7 +721,6 @@ local function create_file(change) vim.fn.bufadd(fname) end ----@private local function delete_file(change) local opts = change.options or {} local fname = vim.uri_to_fname(change.uri) @@ -855,9 +786,12 @@ end --- window for `textDocument/hover`, for parsing the result of --- `textDocument/signatureHelp`, and potentially others. --- +--- Note that if the input is of type `MarkupContent` and its kind is `plaintext`, +--- then the corresponding value is returned without further modifications. +--- ---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ----@returns {contents}, extended with lines of converted markdown. +---@return string[] extended with lines of converted markdown. ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover function M.convert_input_to_markdown_lines(input, contents) contents = contents or {} @@ -865,27 +799,13 @@ function M.convert_input_to_markdown_lines(input, contents) if type(input) == 'string' then list_extend(contents, split_lines(input)) else - assert(type(input) == 'table', 'Expected a table for Hover.contents') + assert(type(input) == 'table', 'Expected a table for LSP input') -- MarkupContent if input.kind then - -- The kind can be either plaintext or markdown. - -- If it's plaintext, then wrap it in a <text></text> block - - -- Some servers send input.value as empty, so let's ignore this :( local value = input.value or '' - - if input.kind == 'plaintext' then - -- wrap this in a <text></text> block so that stylize_markdown - -- can properly process it as plaintext - value = string.format('<text>\n%s\n</text>', value) - end - - -- assert(type(value) == 'string') list_extend(contents, split_lines(value)) -- MarkupString variation 2 elseif input.language then - -- Some servers send input.value as empty, so let's ignore this :( - -- assert(type(input.value) == 'string') table.insert(contents, '```' .. input.language) list_extend(contents, split_lines(input.value or '')) table.insert(contents, '```') @@ -903,12 +823,13 @@ function M.convert_input_to_markdown_lines(input, contents) return contents end ---- Converts `textDocument/SignatureHelp` response to markdown lines. +--- Converts `textDocument/signatureHelp` response to markdown lines. --- ----@param signature_help Response of `textDocument/SignatureHelp` ----@param ft optional filetype that will be use as the `lang` for the label markdown code block ----@param triggers optional list of trigger characters from the lsp server. used to better determine parameter offsets ----@returns list of lines of converted markdown. +---@param signature_help table Response of `textDocument/SignatureHelp` +---@param ft string|nil filetype that will be use as the `lang` for the label markdown code block +---@param triggers table|nil list of trigger characters from the lsp server. used to better determine parameter offsets +---@return table|nil table list of lines of converted markdown. +---@return table|nil table of active hl ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers) if not signature_help.signatures then @@ -932,11 +853,17 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers end local label = signature.label if ft then - -- wrap inside a code block so stylize_markdown can render it properly + -- wrap inside a code block for proper rendering label = ('```%s\n%s\n```'):format(ft, label) end - list_extend(contents, split(label, '\n', true)) + list_extend(contents, split(label, '\n', { plain = true, trimempty = true })) if signature.documentation then + -- if LSP returns plain string, we treat it as plaintext. This avoids + -- special characters like underscore or similar from being interpreted + -- as markdown font modifiers + if type(signature.documentation) == 'string' then + signature.documentation = { kind = 'plaintext', value = signature.documentation } + end M.convert_input_to_markdown_lines(signature.documentation, contents) end if signature.parameters and #signature.parameters > 0 then @@ -1007,16 +934,22 @@ end --- Creates a table with sensible default options for a floating window. The --- table can be passed to |nvim_open_win()|. --- ----@param width (number) window width (in character cells) ----@param height (number) window height (in character cells) ----@param opts (table, optional) ---- - offset_x (number) offset to add to `col` ---- - offset_y (number) offset to add to `row` +---@param width integer window width (in character cells) +---@param height integer window height (in character cells) +---@param opts table optional +--- - offset_x (integer) offset to add to `col` +--- - offset_y (integer) offset to add to `row` --- - border (string or table) override `border` --- - focusable (string or table) override `focusable` --- - zindex (string or table) override `zindex`, defaults to 50 --- - relative ("mouse"|"cursor") defaults to "cursor" ----@returns (table) Options +--- - anchor_bias ("auto"|"above"|"below") defaults to "auto" +--- - "auto": place window based on which side of the cursor has more lines +--- - "above": place the window above the cursor unless there are not enough lines +--- to display the full window height. +--- - "below": place the window below the cursor unless there are not enough lines +--- to display the full window height. +---@return table Options function M.make_floating_popup_options(width, height, opts) validate({ opts = { opts, 't', true }, @@ -1034,19 +967,33 @@ function M.make_floating_popup_options(width, height, opts) or vim.fn.winline() - 1 local lines_below = vim.fn.winheight(0) - lines_above - if lines_above < lines_below then + local anchor_bias = opts.anchor_bias or 'auto' + + local anchor_below + + if anchor_bias == 'below' then + anchor_below = (lines_below > lines_above) or (height <= lines_below) + elseif anchor_bias == 'above' then + local anchor_above = (lines_above > lines_below) or (height <= lines_above) + anchor_below = not anchor_above + else + anchor_below = lines_below > lines_above + end + + local border_height = get_border_size(opts).height + if anchor_below then anchor = anchor .. 'N' - height = math.min(lines_below, height) + height = math.max(math.min(lines_below - border_height, height), 0) row = 1 else anchor = anchor .. 'S' - height = math.min(lines_above, height) + height = math.max(math.min(lines_above - border_height, height), 0) row = 0 end local wincol = opts.relative == 'mouse' and vim.fn.getmousepos().column or vim.fn.wincol() - if wincol + width + (opts.offset_x or 0) <= api.nvim_get_option('columns') then + if wincol + width + (opts.offset_x or 0) <= vim.o.columns then anchor = anchor .. 'W' col = 0 else @@ -1080,7 +1027,7 @@ end --- Shows document and optionally jumps to the location. --- ---@param location table (`Location`|`LocationLink`) ----@param offset_encoding "utf-8" | "utf-16" | "utf-32" +---@param offset_encoding string|nil utf-8|utf-16|utf-32 ---@param opts table|nil options --- - reuse_win (boolean) Jump to existing window if buffer is already open. --- - focus (boolean) Whether to focus/jump to location if possible. Defaults to true. @@ -1112,7 +1059,7 @@ function M.show_document(location, offset_encoding, opts) or focus and api.nvim_get_current_win() or create_window_without_focus() - api.nvim_buf_set_option(bufnr, 'buflisted', true) + vim.bo[bufnr].buflisted = true api.nvim_win_set_buf(win, bufnr) if focus then api.nvim_set_current_win(win) @@ -1137,7 +1084,7 @@ end --- Jumps to a location. --- ---@param location table (`Location`|`LocationLink`) ----@param offset_encoding "utf-8" | "utf-16" | "utf-32" +---@param offset_encoding string|nil utf-8|utf-16|utf-32 ---@param reuse_win boolean|nil Jump to existing window if buffer is already open. ---@return boolean `true` if the jump succeeded function M.jump_to_location(location, offset_encoding, reuse_win) @@ -1157,8 +1104,9 @@ end --- - for Location, range is shown (e.g., function definition) --- - for LocationLink, targetRange is shown (e.g., body of function definition) --- ----@param location a single `Location` or `LocationLink` ----@returns (bufnr,winnr) buffer and window number of floating window or nil +---@param location table a single `Location` or `LocationLink` +---@return integer|nil buffer id of float window +---@return integer|nil window id of float window function M.preview_location(location, opts) -- location may be LocationLink or Location (more useful for the former) local uri = location.targetUri or location.uri @@ -1171,19 +1119,18 @@ function M.preview_location(location, opts) end local range = location.targetRange or location.range local contents = api.nvim_buf_get_lines(bufnr, range.start.line, range['end'].line + 1, false) - local syntax = api.nvim_buf_get_option(bufnr, 'syntax') + local syntax = vim.bo[bufnr].syntax if syntax == '' then -- When no syntax is set, we use filetype as fallback. This might not result - -- in a valid syntax definition. See also ft detection in stylize_markdown. + -- in a valid syntax definition. -- An empty syntax is more common now with TreeSitter, since TS disables syntax. - syntax = api.nvim_buf_get_option(bufnr, 'filetype') + syntax = vim.bo[bufnr].filetype end opts = opts or {} opts.focus_id = 'location' return M.open_floating_preview(contents, syntax, opts) end ----@private local function find_window_by_var(name, value) for _, win in ipairs(api.nvim_list_wins()) do if npcall(api.nvim_win_get_var, win, name) == value then @@ -1192,37 +1139,65 @@ local function find_window_by_var(name, value) end end ---- Trims empty lines from input and pad top and bottom with empty lines ---- ----@param contents table of lines to trim and pad ----@param opts dictionary with optional fields ---- - pad_top number of lines to pad contents at top (default 0) ---- - pad_bottom number of lines to pad contents at bottom (default 0) ----@return contents table of trimmed and padded lines -function M._trim(contents, opts) - validate({ - contents = { contents, 't' }, - opts = { opts, 't', true }, - }) - opts = opts or {} - contents = M.trim_empty_lines(contents) - if opts.pad_top then - for _ = 1, opts.pad_top do - table.insert(contents, 1, '') +---Returns true if the line is empty or only contains whitespace. +---@param line string +---@return boolean +local function is_blank_line(line) + return line and line:match('^%s*$') +end + +---Returns true if the line corresponds to a Markdown thematic break. +---@param line string +---@return boolean +local function is_separator_line(line) + return line and line:match('^ ? ? ?%-%-%-+%s*$') +end + +---Replaces separator lines by the given divider and removing surrounding blank lines. +---@param contents string[] +---@param divider string +---@return string[] +local function replace_separators(contents, divider) + local trimmed = {} + local l = 1 + while l <= #contents do + local line = contents[l] + if is_separator_line(line) then + if l > 1 and is_blank_line(contents[l - 1]) then + table.remove(trimmed) + end + table.insert(trimmed, divider) + if is_blank_line(contents[l + 1]) then + l = l + 1 + end + else + table.insert(trimmed, line) end + l = l + 1 end - if opts.pad_bottom then - for _ = 1, opts.pad_bottom do - table.insert(contents, '') + + return trimmed +end + +---Collapses successive blank lines in the input table into a single one. +---@param contents string[] +---@return string[] +local function collapse_blank_lines(contents) + local collapsed = {} + local l = 1 + while l <= #contents do + local line = contents[l] + if is_blank_line(line) then + while is_blank_line(contents[l + 1]) do + l = l + 1 + end end + table.insert(collapsed, line) + l = l + 1 end - return contents + return collapsed end ---- Generates a table mapping markdown code block lang to vim syntax, ---- based on g:markdown_fenced_languages ----@return a table of lang -> syntax mappings ----@private local function get_markdown_fences() local fences = {} for _, fence in pairs(vim.g.markdown_fenced_languages or {}) do @@ -1244,16 +1219,14 @@ end --- If you want to open a popup with fancy markdown, use `open_floating_preview` instead --- ---@param contents table of lines to show in window ----@param opts dictionary with optional fields +---@param opts table with optional fields --- - height of floating window --- - width of floating window --- - wrap_at character to wrap at for computing height --- - max_width maximal width of floating window --- - max_height maximal height of floating window ---- - pad_top number of lines to pad contents at top ---- - pad_bottom number of lines to pad contents at bottom --- - separator insert separator after code block ----@returns width,height size of float +---@return table stripped content function M.stylize_markdown(bufnr, contents, opts) validate({ contents = { contents, 't' }, @@ -1264,7 +1237,7 @@ function M.stylize_markdown(bufnr, contents, opts) -- table of fence types to {ft, begin, end} -- when ft is nil, we get the ft from the regex match local matchers = { - block = { nil, '```+([a-zA-Z0-9_]*)', '```+' }, + block = { nil, '```+%s*([a-zA-Z0-9_]*)', '```+' }, pre = { nil, '<pre>([a-z0-9]*)', '</pre>' }, code = { '', '<code>', '</code>' }, text = { 'text', '<text>', '</text>' }, @@ -1288,7 +1261,7 @@ function M.stylize_markdown(bufnr, contents, opts) end -- Clean up - contents = M._trim(contents, opts) + contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true }) local stripped = {} local highlights = {} @@ -1348,6 +1321,20 @@ function M.stylize_markdown(bufnr, contents, opts) end end + -- Handle some common html escape sequences + stripped = vim.tbl_map(function(line) + local escapes = { + ['>'] = '>', + ['<'] = '<', + ['"'] = '"', + ['''] = "'", + [' '] = ' ', + [' '] = ' ', + ['&'] = '&', + } + return (string.gsub(line, '&[^ ;]+;', escapes)) + end, stripped) + -- Compute size of float needed to show (wrapped) lines opts.wrap_at = opts.wrap_at or (vim.wo['wrap'] and api.nvim_win_get_width(0)) local width = M._make_floating_popup_size(stripped, opts) @@ -1363,7 +1350,6 @@ function M.stylize_markdown(bufnr, contents, opts) api.nvim_buf_set_lines(bufnr, 0, -1, false, stripped) local idx = 1 - ---@private -- keep track of syntaxes we already included. -- no need to include the same syntax more than once local langs = {} @@ -1386,10 +1372,10 @@ function M.stylize_markdown(bufnr, contents, opts) if not langs[lang] then -- HACK: reset current_syntax, since some syntax files like markdown won't load if it is already set pcall(api.nvim_buf_del_var, bufnr, 'current_syntax') - -- TODO(ashkan): better validation before this. - if not pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft)) then + if #api.nvim_get_runtime_file(('syntax/%s.vim'):format(ft), true) == 0 then return end + pcall(vim.cmd, string.format('syntax include %s syntax/%s.vim', lang, ft)) langs[lang] = true end vim.cmd( @@ -1424,15 +1410,53 @@ function M.stylize_markdown(bufnr, contents, opts) return stripped end +--- @class lsp.util.NormalizeMarkdownOptions +--- @field width integer Thematic breaks are expanded to this size. Defaults to 80. + +--- Normalizes Markdown input to a canonical form. +--- +--- The returned Markdown adheres to the GitHub Flavored Markdown (GFM) +--- specification. +--- +--- The following transformations are made: +--- +--- 1. Carriage returns ('\r') and empty lines at the beginning and end are removed +--- 2. Successive empty lines are collapsed into a single empty line +--- 3. Thematic breaks are expanded to the given width +--- ---@private +---@param contents string[] +---@param opts? lsp.util.NormalizeMarkdownOptions +---@return string[] table of lines containing normalized Markdown +---@see https://github.github.com/gfm +function M._normalize_markdown(contents, opts) + validate({ + contents = { contents, 't' }, + opts = { opts, 't', true }, + }) + opts = opts or {} + + -- 1. Carriage returns are removed + contents = vim.split(table.concat(contents, '\n'):gsub('\r', ''), '\n', { trimempty = true }) + + -- 2. Successive empty lines are collapsed into a single empty line + contents = collapse_blank_lines(contents) + + -- 3. Thematic breaks are expanded to the given width + local divider = string.rep('─', opts.width or 80) + contents = replace_separators(contents, divider) + + return contents +end + --- Closes the preview window --- ----@param winnr number window id of preview window +---@param winnr integer window id of preview window ---@param bufnrs table|nil optional list of ignored buffers local function close_preview_window(winnr, bufnrs) vim.schedule(function() -- exit if we are in one of ignored buffers - if bufnrs and vim.tbl_contains(bufnrs, api.nvim_get_current_buf()) then + if bufnrs and vim.list_contains(bufnrs, api.nvim_get_current_buf()) then return end @@ -1442,13 +1466,12 @@ local function close_preview_window(winnr, bufnrs) end) end ----@private --- Creates autocommands to close a preview window when events happen. --- ---@param events table list of events ----@param winnr number window id of preview window +---@param winnr integer window id of preview window ---@param bufnrs table list of buffers where the preview window will remain visible ----@see |autocmd-events| +---@see autocmd-events local function close_preview_autocmd(events, winnr, bufnrs) local augroup = api.nvim_create_augroup('preview_window_' .. winnr, { clear = true, @@ -1478,13 +1501,14 @@ end --- Computes size of float needed to show contents (with optional wrapping) --- ---@param contents table of lines to show in window ----@param opts dictionary with optional fields +---@param opts table with optional fields --- - height of floating window --- - width of floating window --- - wrap_at character to wrap at for computing height --- - max_width maximal width of floating window --- - max_height maximal height of floating window ----@returns width,height size of float +---@return integer width size of float +---@return integer height size of float function M._make_floating_popup_size(contents, opts) validate({ contents = { contents, 't' }, @@ -1503,7 +1527,7 @@ function M._make_floating_popup_size(contents, opts) width = 0 for i, line in ipairs(contents) do -- TODO(ashkan) use nvim_strdisplaywidth if/when that is introduced. - line_widths[i] = vim.fn.strdisplaywidth(line) + line_widths[i] = vim.fn.strdisplaywidth(line:gsub('%z', '\n')) width = math.max(line_widths[i], width) end end @@ -1532,7 +1556,7 @@ function M._make_floating_popup_size(contents, opts) height = 0 if vim.tbl_isempty(line_widths) then for _, line in ipairs(contents) do - local line_width = vim.fn.strdisplaywidth(line) + local line_width = vim.fn.strdisplaywidth(line:gsub('%z', '\n')) height = height + math.ceil(line_width / wrap_at) end else @@ -1553,23 +1577,22 @@ end --- ---@param contents table of lines to show in window ---@param syntax string of syntax to set for opened buffer ----@param opts table with optional fields (additional keys are passed on to |nvim_open_win()|) ---- - height: (number) height of floating window ---- - width: (number) width of floating window +---@param opts table with optional fields (additional keys are filtered with |vim.lsp.util.make_floating_popup_options()| +--- before they are passed on to |nvim_open_win()|) +--- - height: (integer) height of floating window +--- - width: (integer) width of floating window --- - wrap: (boolean, default true) wrap long lines ---- - wrap_at: (number) character to wrap at for computing height when wrap is enabled ---- - max_width: (number) maximal width of floating window ---- - max_height: (number) maximal height of floating window ---- - pad_top: (number) number of lines to pad contents at top ---- - pad_bottom: (number) number of lines to pad contents at bottom +--- - wrap_at: (integer) character to wrap at for computing height when wrap is enabled +--- - max_width: (integer) maximal width of floating window +--- - max_height: (integer) maximal height of floating window --- - focus_id: (string) if a popup with this id is opened, then focus it --- - close_events: (table) list of events that closes the floating window --- - focusable: (boolean, default true) Make float focusable --- - focus: (boolean, default true) If `true`, and if {focusable} --- is also `true`, focus an existing floating window with the same --- {focus_id} ----@returns bufnr,winnr buffer and window number of the newly created floating ----preview window +---@return integer bufnr of newly created float window +---@return integer winid of newly created float window preview window function M.open_floating_preview(contents, syntax, opts) validate({ contents = { contents, 't' }, @@ -1578,7 +1601,6 @@ function M.open_floating_preview(contents, syntax, opts) }) opts = opts or {} opts.wrap = opts.wrap ~= false -- wrapping by default - opts.stylize_markdown = opts.stylize_markdown ~= false and vim.g.syntax_on ~= nil opts.focus = opts.focus ~= false opts.close_events = opts.close_events or { 'CursorMoved', 'CursorMovedI', 'InsertCharPre' } @@ -1610,18 +1632,23 @@ function M.open_floating_preview(contents, syntax, opts) api.nvim_win_close(existing_float, true) end + -- Create the buffer local floating_bufnr = api.nvim_create_buf(false, true) - local do_stylize = syntax == 'markdown' and opts.stylize_markdown - - -- Clean up input: trim empty lines from the end, pad - contents = M._trim(contents, opts) + -- Set up the contents, using treesitter for markdown + local do_stylize = syntax == 'markdown' and vim.g.syntax_on ~= nil if do_stylize then - -- applies the syntax and sets the lines to the buffer - contents = M.stylize_markdown(floating_bufnr, contents, opts) + local width = M._make_floating_popup_size(contents, opts) + contents = M._normalize_markdown(contents, { width = width }) + vim.bo[floating_bufnr].filetype = 'markdown' + vim.treesitter.start(floating_bufnr) + api.nvim_buf_set_lines(floating_bufnr, 0, -1, false, contents) else + -- Clean up input: trim empty lines + contents = vim.split(table.concat(contents, '\n'), '\n', { trimempty = true }) + if syntax then - api.nvim_buf_set_option(floating_bufnr, 'syntax', syntax) + vim.bo[floating_bufnr].syntax = syntax end api.nvim_buf_set_lines(floating_bufnr, 0, -1, true, contents) end @@ -1636,17 +1663,18 @@ function M.open_floating_preview(contents, syntax, opts) local float_option = M.make_floating_popup_options(width, height, opts) local floating_winnr = api.nvim_open_win(floating_bufnr, false, float_option) + if do_stylize then - api.nvim_win_set_option(floating_winnr, 'conceallevel', 2) - api.nvim_win_set_option(floating_winnr, 'concealcursor', 'n') + vim.wo[floating_winnr].conceallevel = 2 end -- disable folding - api.nvim_win_set_option(floating_winnr, 'foldenable', false) + vim.wo[floating_winnr].foldenable = false -- soft wrapping - api.nvim_win_set_option(floating_winnr, 'wrap', opts.wrap) + vim.wo[floating_winnr].wrap = opts.wrap + + vim.bo[floating_bufnr].modifiable = false + vim.bo[floating_bufnr].bufhidden = 'wipe' - api.nvim_buf_set_option(floating_bufnr, 'modifiable', false) - api.nvim_buf_set_option(floating_bufnr, 'bufhidden', 'wipe') api.nvim_buf_set_keymap( floating_bufnr, 'n', @@ -1670,18 +1698,18 @@ do --[[ References ]] --- Removes document highlights from a buffer. --- - ---@param bufnr number Buffer id + ---@param bufnr integer|nil Buffer id function M.buf_clear_references(bufnr) - validate({ bufnr = { bufnr, 'n', true } }) + validate({ bufnr = { bufnr, { 'n' }, true } }) api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1) end --- Shows a list of document highlights for a certain buffer. --- - ---@param bufnr number Buffer id + ---@param bufnr integer Buffer id ---@param references table List of `DocumentHighlight` objects to highlight ---@param offset_encoding string One of "utf-8", "utf-16", "utf-32". - ---@see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentContentChangeEvent + ---@see https://microsoft.github.io/language-server-protocol/specification/#textDocumentContentChangeEvent function M.buf_highlight_references(bufnr, references, offset_encoding) validate({ bufnr = { bufnr, 'n', true }, @@ -1729,18 +1757,23 @@ end) --- Returns the items with the byte position calculated correctly and in sorted --- order, for display in quickfix and location lists. --- +--- The `user_data` field of each resulting item will contain the original +--- `Location` or `LocationLink` it was computed from. +--- --- The result can be passed to the {list} argument of |setqflist()| or --- |setloclist()|. --- ---@param locations table list of `Location`s or `LocationLink`s ---@param offset_encoding string offset_encoding for locations utf-8|utf-16|utf-32 ----@returns (table) list of items +--- default to first client of buffer +---@return table list of items function M.locations_to_items(locations, offset_encoding) if offset_encoding == nil then vim.notify_once( 'locations_to_items must be called with valid offset encoding', vim.log.levels.WARN ) + offset_encoding = vim.lsp.get_clients({ bufnr = 0 })[1].offset_encoding end local items = {} @@ -1755,7 +1788,7 @@ function M.locations_to_items(locations, offset_encoding) -- locations may be Location or LocationLink local uri = d.uri or d.targetUri local range = d.range or d.targetSelectionRange - table.insert(grouped[uri], { start = range.start }) + table.insert(grouped[uri], { start = range.start, location = d }) end local keys = vim.tbl_keys(grouped) @@ -1787,6 +1820,7 @@ function M.locations_to_items(locations, offset_encoding) lnum = row + 1, col = col + 1, text = line, + user_data = temp.location, }) end end @@ -1802,9 +1836,8 @@ end --- Converts symbols to quickfix list items. --- ----@param symbols DocumentSymbol[] or SymbolInformation[] +---@param symbols table DocumentSymbol[] or SymbolInformation[] function M.symbols_to_items(symbols, bufnr) - ---@private local function _symbols_to_items(_symbols, _items, _bufnr) for _, symbol in ipairs(_symbols) do if symbol.location then -- SymbolInformation type @@ -1842,8 +1875,9 @@ function M.symbols_to_items(symbols, bufnr) end --- Removes empty lines from the beginning and end. ----@param lines (table) list of lines to trim ----@returns (table) trimmed list of lines +---@deprecated use `vim.split()` with `trimempty` instead +---@param lines table list of lines to trim +---@return table trimmed list of lines function M.trim_empty_lines(lines) local start = 1 for i = 1, #lines do @@ -1867,8 +1901,9 @@ end --- --- CAUTION: Modifies the input in-place! --- ----@param lines (table) list of lines ----@returns (string) filetype or "markdown" if it was unchanged. +---@deprecated +---@param lines table list of lines +---@return string filetype or "markdown" if it was unchanged. function M.try_trim_markdown_code_blocks(lines) local language_id = lines[1]:match('^```(.*)') if language_id then @@ -1890,8 +1925,7 @@ function M.try_trim_markdown_code_blocks(lines) return 'markdown' end ----@private ----@param window number|nil: window handle or 0 for current, defaults to current +---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` local function make_position_param(window, offset_encoding) window = window or 0 @@ -1911,9 +1945,9 @@ end --- Creates a `TextDocumentPositionParams` object for the current buffer and cursor position. --- ----@param window number|nil: window handle or 0 for current, defaults to current +---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding string|nil utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` ----@returns `TextDocumentPositionParams` object +---@return table `TextDocumentPositionParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams function M.make_position_params(window, offset_encoding) window = window or 0 @@ -1926,8 +1960,8 @@ function M.make_position_params(window, offset_encoding) end --- Utility function for getting the encoding of the first LSP client on the given buffer. ----@param bufnr (number) buffer handle or 0 for current, defaults to current ----@returns (string) encoding first client if there is one, nil otherwise +---@param bufnr (integer) buffer handle or 0 for current, defaults to current +---@return string encoding first client if there is one, nil otherwise function M._get_offset_encoding(bufnr) validate({ bufnr = { bufnr, 'n', true }, @@ -1935,7 +1969,7 @@ function M._get_offset_encoding(bufnr) local offset_encoding - for _, client in pairs(vim.lsp.get_active_clients({ bufnr = bufnr })) do + for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do if client.offset_encoding == nil then vim.notify_once( string.format( @@ -1949,7 +1983,7 @@ function M._get_offset_encoding(bufnr) if not offset_encoding then offset_encoding = this_offset_encoding elseif offset_encoding ~= this_offset_encoding then - vim.notify( + vim.notify_once( 'warning: multiple different client offset_encodings detected for buffer, this is not supported yet', vim.log.levels.WARN ) @@ -1964,9 +1998,9 @@ end --- `textDocument/codeAction`, `textDocument/colorPresentation`, --- `textDocument/rangeFormatting`. --- ----@param window number|nil: window handle or 0 for current, defaults to current +---@param window integer|nil: window handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of buffer of `window` ----@returns { textDocument = { uri = `current_file_uri` }, range = { start = +---@return table { textDocument = { uri = `current_file_uri` }, range = { start = ---`current_position`, end = `current_position` } } function M.make_range_params(window, offset_encoding) local buf = api.nvim_win_get_buf(window or 0) @@ -1981,13 +2015,13 @@ end --- Using the given range in the current buffer, creates an object that --- is similar to |vim.lsp.util.make_range_params()|. --- ----@param start_pos number[]|nil {row, col} mark-indexed position. +---@param start_pos integer[]|nil {row,col} mark-indexed position. --- Defaults to the start of the last visual selection. ----@param end_pos number[]|nil {row, col} mark-indexed position. +---@param end_pos integer[]|nil {row,col} mark-indexed position. --- Defaults to the end of the last visual selection. ----@param bufnr number|nil buffer handle or 0 for current, defaults to current +---@param bufnr integer|nil buffer handle or 0 for current, defaults to current ---@param offset_encoding "utf-8"|"utf-16"|"utf-32"|nil defaults to `offset_encoding` of first client of `bufnr` ----@returns { textDocument = { uri = `current_file_uri` }, range = { start = +---@return table { textDocument = { uri = `current_file_uri` }, range = { start = ---`start_position`, end = `end_position` } } function M.make_given_range_params(start_pos, end_pos, bufnr, offset_encoding) validate({ @@ -2026,24 +2060,25 @@ end --- Creates a `TextDocumentIdentifier` object for the current buffer. --- ----@param bufnr number|nil: Buffer handle, defaults to current ----@returns `TextDocumentIdentifier` +---@param bufnr integer|nil: Buffer handle, defaults to current +---@return table `TextDocumentIdentifier` ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentIdentifier function M.make_text_document_params(bufnr) return { uri = vim.uri_from_bufnr(bufnr or 0) } end --- Create the workspace params ----@param added ----@param removed +---@param added table +---@param removed table function M.make_workspace_params(added, removed) return { event = { added = added, removed = removed } } end + --- Returns indentation size. --- ---@see 'shiftwidth' ----@param bufnr (number|nil): Buffer handle, defaults to current ----@returns (number) indentation size +---@param bufnr (integer|nil): Buffer handle, defaults to current +---@return (integer) indentation size function M.get_effective_tabstop(bufnr) validate({ bufnr = { bufnr, 'n', true } }) local bo = bufnr and vim.bo[bufnr] or vim.bo @@ -2054,7 +2089,7 @@ end --- Creates a `DocumentFormattingParams` object for the current buffer and cursor position. --- ---@param options table|nil with valid `FormattingOptions` entries ----@returns `DocumentFormattingParams` object +---@return `DocumentFormattingParams` object ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting function M.make_formatting_params(options) validate({ options = { options, 't', true } }) @@ -2070,11 +2105,11 @@ end --- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. --- ----@param buf number buffer number (0 for current) +---@param buf integer buffer number (0 for current) ---@param row 0-indexed line ---@param col 0-indexed byte offset in line ----@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of `buf` ----@returns (number, number) `offset_encoding` index of the character in line {row} column {col} in buffer {buf} +---@param offset_encoding string utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf` +---@return integer `offset_encoding` index of the character in line {row} column {col} in buffer {buf} function M.character_offset(buf, row, col, offset_encoding) local line = get_line(buf, row) if offset_encoding == nil then @@ -2082,6 +2117,7 @@ function M.character_offset(buf, row, col, offset_encoding) 'character_offset must be called with valid offset encoding', vim.log.levels.WARN ) + offset_encoding = vim.lsp.get_clients({ bufnr = buf })[1].offset_encoding end -- If the col is past the EOL, use the line length. if col > #line then @@ -2092,11 +2128,11 @@ end --- Helper function to return nested values in language server settings --- ----@param settings a table of language server settings ----@param section a string indicating the field of the settings table ----@returns (table or string) The value of settings accessed via section +---@param settings table language server settings +---@param section string indicating the field of the settings table +---@return table|string The value of settings accessed via section function M.lookup_section(settings, section) - for part in vim.gsplit(section, '.', true) do + for part in vim.gsplit(section, '.', { plain = true }) do settings = settings[part] if settings == nil then return vim.NIL @@ -2105,9 +2141,93 @@ function M.lookup_section(settings, section) return settings end +--- Converts line range (0-based, end-inclusive) to lsp range, +--- handles absence of a trailing newline +--- +---@param bufnr integer +---@param start_line integer +---@param end_line integer +---@param offset_encoding lsp.PositionEncodingKind +---@return lsp.Range +local function make_line_range_params(bufnr, start_line, end_line, offset_encoding) + local last_line = api.nvim_buf_line_count(bufnr) - 1 + + ---@type lsp.Position + local end_pos + + if end_line == last_line and not vim.api.nvim_get_option_value('endofline', { buf = bufnr }) then + end_pos = { + line = end_line, + character = M.character_offset(bufnr, end_line, #get_line(bufnr, end_line), offset_encoding), + } + else + end_pos = { line = end_line + 1, character = 0 } + end + + return { + start = { line = start_line, character = 0 }, + ['end'] = end_pos, + } +end + +---@private +--- Request updated LSP information for a buffer. +--- +---@class lsp.util.RefreshOptions +---@field bufnr integer? Buffer to refresh (default: 0) +---@field only_visible? boolean Whether to only refresh for the visible regions of the buffer (default: false) +---@field client_id? integer Client ID to refresh (default: all clients) +-- +---@param method string LSP method to call +---@param opts? lsp.util.RefreshOptions Options table +function M._refresh(method, opts) + opts = opts or {} + local bufnr = opts.bufnr + if bufnr == nil or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + local clients = vim.lsp.get_clients({ bufnr = bufnr, method = method, id = opts.client_id }) + + if #clients == 0 then + return + end + + local textDocument = M.make_text_document_params(bufnr) + + local only_visible = opts.only_visible or false + + if only_visible then + for _, window in ipairs(api.nvim_list_wins()) do + if api.nvim_win_get_buf(window) == bufnr then + local first = vim.fn.line('w0', window) + local last = vim.fn.line('w$', window) + for _, client in ipairs(clients) do + client.request(method, { + textDocument = textDocument, + range = make_line_range_params(bufnr, first - 1, last - 1, client.offset_encoding), + }, nil, bufnr) + end + end + end + else + for _, client in ipairs(clients) do + client.request(method, { + textDocument = textDocument, + range = make_line_range_params( + bufnr, + 0, + api.nvim_buf_line_count(bufnr) - 1, + client.offset_encoding + ), + }, nil, bufnr) + end + end +end + M._get_line_byte_from_position = get_line_byte_from_position +---@nodoc M.buf_versions = {} return M --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/re.lua b/runtime/lua/vim/re.lua new file mode 100644 index 0000000000..007eb27ed8 --- /dev/null +++ b/runtime/lua/vim/re.lua @@ -0,0 +1,271 @@ +-- +-- Copyright 2007-2023, Lua.org & PUC-Rio (see 'lpeg.html' for license) +-- written by Roberto Ierusalimschy +-- +--- vendored from lpeg-1.1.0 + +-- imported functions and modules +local tonumber, type, print, error = tonumber, type, print, error +local setmetatable = setmetatable +local m = require"lpeg" + +-- 'm' will be used to parse expressions, and 'mm' will be used to +-- create expressions; that is, 're' runs on 'm', creating patterns +-- on 'mm' +local mm = m + +-- patterns' metatable +local mt = getmetatable(mm.P(0)) + + +local version = _VERSION + +-- No more global accesses after this point +_ENV = nil -- does no harm in Lua 5.1 + + +local any = m.P(1) + + +-- Pre-defined names +local Predef = { nl = m.P"\n" } + + +local mem +local fmem +local gmem + + +local function updatelocale () + mm.locale(Predef) + Predef.a = Predef.alpha + Predef.c = Predef.cntrl + Predef.d = Predef.digit + Predef.g = Predef.graph + Predef.l = Predef.lower + Predef.p = Predef.punct + Predef.s = Predef.space + Predef.u = Predef.upper + Predef.w = Predef.alnum + Predef.x = Predef.xdigit + Predef.A = any - Predef.a + Predef.C = any - Predef.c + Predef.D = any - Predef.d + Predef.G = any - Predef.g + Predef.L = any - Predef.l + Predef.P = any - Predef.p + Predef.S = any - Predef.s + Predef.U = any - Predef.u + Predef.W = any - Predef.w + Predef.X = any - Predef.x + mem = {} -- restart memoization + fmem = {} + gmem = {} + local mt = {__mode = "v"} + setmetatable(mem, mt) + setmetatable(fmem, mt) + setmetatable(gmem, mt) +end + + +updatelocale() + + + +local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end) + + +local function patt_error (s, i) + local msg = (#s < i + 20) and s:sub(i) + or s:sub(i,i+20) .. "..." + msg = ("pattern error near '%s'"):format(msg) + error(msg, 2) +end + +local function mult (p, n) + local np = mm.P(true) + while n >= 1 do + if n%2 >= 1 then np = np * p end + p = p * p + n = n/2 + end + return np +end + +local function equalcap (s, i, c) + if type(c) ~= "string" then return nil end + local e = #c + i + if s:sub(i, e - 1) == c then return e else return nil end +end + + +local S = (Predef.space + "--" * (any - Predef.nl)^0)^0 + +local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0 + +local arrow = S * "<-" + +local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1 + +name = m.C(name) + + +-- a defined name only have meaning in a given environment +local Def = name * m.Carg(1) + + +local function getdef (id, defs) + local c = defs and defs[id] + if not c then error("undefined name: " .. id) end + return c +end + +-- match a name and return a group of its corresponding definition +-- and 'f' (to be folded in 'Suffix') +local function defwithfunc (f) + return m.Cg(Def / getdef * m.Cc(f)) +end + + +local num = m.C(m.R"09"^1) * S / tonumber + +local String = "'" * m.C((any - "'")^0) * "'" + + '"' * m.C((any - '"')^0) * '"' + + +local defined = "%" * Def / function (c,Defs) + local cat = Defs and Defs[c] or Predef[c] + if not cat then error ("name '" .. c .. "' undefined") end + return cat +end + +local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R + +local item = (defined + Range + m.C(any)) / m.P + +local Class = + "[" + * (m.C(m.P"^"^-1)) -- optional complement symbol + * (item * ((item % mt.__add) - "]")^0) / + function (c, p) return c == "^" and any - p or p end + * "]" + +local function adddef (t, k, exp) + if t[k] then + error("'"..k.."' already defined as a rule") + else + t[k] = exp + end + return t +end + +local function firstdef (n, r) return adddef({n}, n, r) end + + +local function NT (n, b) + if not b then + error("rule '"..n.."' used outside a grammar") + else return mm.V(n) + end +end + + +local exp = m.P{ "Exp", + Exp = S * ( m.V"Grammar" + + m.V"Seq" * ("/" * S * m.V"Seq" % mt.__add)^0 ); + Seq = (m.Cc(m.P"") * (m.V"Prefix" % mt.__mul)^0) + * (#seq_follow + patt_error); + Prefix = "&" * S * m.V"Prefix" / mt.__len + + "!" * S * m.V"Prefix" / mt.__unm + + m.V"Suffix"; + Suffix = m.V"Primary" * S * + ( ( m.P"+" * m.Cc(1, mt.__pow) + + m.P"*" * m.Cc(0, mt.__pow) + + m.P"?" * m.Cc(-1, mt.__pow) + + "^" * ( m.Cg(num * m.Cc(mult)) + + m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow)) + ) + + "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div)) + + m.P"{}" * m.Cc(nil, m.Ct) + + defwithfunc(mt.__div) + ) + + "=>" * S * defwithfunc(mm.Cmt) + + ">>" * S * defwithfunc(mt.__mod) + + "~>" * S * defwithfunc(mm.Cf) + ) % function (a,b,f) return f(a,b) end * S + )^0; + Primary = "(" * m.V"Exp" * ")" + + String / mm.P + + Class + + defined + + "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" / + function (n, p) return mm.Cg(p, n) end + + "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end + + m.P"{}" / mm.Cp + + "{~" * m.V"Exp" * "~}" / mm.Cs + + "{|" * m.V"Exp" * "|}" / mm.Ct + + "{" * m.V"Exp" * "}" / mm.C + + m.P"." * m.Cc(any) + + (name * -arrow + "<" * name * ">") * m.Cb("G") / NT; + Definition = name * arrow * m.V"Exp"; + Grammar = m.Cg(m.Cc(true), "G") * + ((m.V"Definition" / firstdef) * (m.V"Definition" % adddef)^0) / mm.P +} + +local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error) + + +local function compile (p, defs) + if mm.type(p) == "pattern" then return p end -- already compiled + local cp = pattern:match(p, 1, defs) + if not cp then error("incorrect pattern", 3) end + return cp +end + +local function match (s, p, i) + local cp = mem[p] + if not cp then + cp = compile(p) + mem[p] = cp + end + return cp:match(s, i or 1) +end + +local function find (s, p, i) + local cp = fmem[p] + if not cp then + cp = compile(p) / 0 + cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) } + fmem[p] = cp + end + local i, e = cp:match(s, i or 1) + if i then return i, e - 1 + else return i + end +end + +local function gsub (s, p, rep) + local g = gmem[p] or {} -- ensure gmem[p] is not collected while here + gmem[p] = g + local cp = g[rep] + if not cp then + cp = compile(p) + cp = mm.Cs((cp / rep + 1)^0) + g[rep] = cp + end + return cp:match(s) +end + + +-- exported names +local re = { + compile = compile, + match = match, + find = find, + gsub = gsub, + updatelocale = updatelocale, +} + +if version == "Lua 5.1" then _G.re = re end + +return re diff --git a/runtime/lua/vim/secure.lua b/runtime/lua/vim/secure.lua index 443b152273..d29c356af3 100644 --- a/runtime/lua/vim/secure.lua +++ b/runtime/lua/vim/secure.lua @@ -1,11 +1,10 @@ local M = {} ----@private --- Reads trust database from $XDG_STATE_HOME/nvim/trust. --- ----@return (table) Contents of trust database, if it exists. Empty table otherwise. +---@return table<string, string> Contents of trust database, if it exists. Empty table otherwise. local function read_trust() - local trust = {} + local trust = {} ---@type table<string, string> local f = io.open(vim.fn.stdpath('state') .. '/trust', 'r') if f then local contents = f:read('*a') @@ -22,16 +21,15 @@ local function read_trust() return trust end ----@private --- Writes provided {trust} table to trust database at --- $XDG_STATE_HOME/nvim/trust. --- ----@param trust (table) Trust table to write +---@param trust table<string, string> Trust table to write local function write_trust(trust) vim.validate({ trust = { trust, 't' } }) local f = assert(io.open(vim.fn.stdpath('state') .. '/trust', 'w')) - local t = {} + local t = {} ---@type string[] for p, h in pairs(trust) do t[#t + 1] = string.format('%s %s\n', h, p) end @@ -51,7 +49,7 @@ end --- trusted, or nil otherwise. function M.read(path) vim.validate({ path = { path, 's' } }) - local fullpath = vim.loop.fs_realpath(vim.fs.normalize(path)) + local fullpath = vim.uv.fs_realpath(vim.fs.normalize(path)) if not fullpath then return nil end @@ -63,7 +61,7 @@ function M.read(path) return nil end - local contents + local contents ---@type string? do local f = io.open(fullpath, 'r') if not f then @@ -110,6 +108,11 @@ function M.read(path) return contents end +---@class vim.trust.opts +---@field action string +---@field path? string +---@field bufnr? integer + --- Manage the trust database. --- --- The trust database is located at |$XDG_STATE_HOME|/nvim/trust. @@ -121,9 +124,8 @@ end --- - path (string|nil): Path to a file to update. Mutually exclusive with {bufnr}. --- Cannot be used when {action} is "allow". --- - bufnr (number|nil): Buffer number to update. Mutually exclusive with {path}. ----@return (boolean, string) success, msg: ---- - true and full path of target file if operation was successful ---- - false and error message on failure +---@return boolean success true if operation was successful +---@return string msg full path if operation was successful, else error message function M.trust(opts) vim.validate({ path = { opts.path, 's', true }, @@ -137,6 +139,7 @@ function M.trust(opts) }, }) + ---@cast opts vim.trust.opts local path = opts.path local bufnr = opts.bufnr local action = opts.action @@ -147,15 +150,15 @@ function M.trust(opts) assert(not path, '"path" is not valid when action is "allow"') end - local fullpath + local fullpath ---@type string? if path then - fullpath = vim.loop.fs_realpath(vim.fs.normalize(path)) + fullpath = vim.uv.fs_realpath(vim.fs.normalize(path)) elseif bufnr then local bufname = vim.api.nvim_buf_get_name(bufnr) if bufname == '' then return false, 'buffer is not associated with a file' end - fullpath = vim.loop.fs_realpath(vim.fs.normalize(bufname)) + fullpath = vim.uv.fs_realpath(vim.fs.normalize(bufname)) else error('one of "path" or "bufnr" is required') end @@ -168,7 +171,8 @@ function M.trust(opts) if action == 'allow' then local newline = vim.bo[bufnr].fileformat == 'unix' and '\n' or '\r\n' - local contents = table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, false), newline) + local contents = + table.concat(vim.api.nvim_buf_get_lines(bufnr --[[@as integer]], 0, -1, false), newline) if vim.bo[bufnr].endofline then contents = contents .. newline end diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua index cc48e3f193..9542d93789 100644 --- a/runtime/lua/vim/shared.lua +++ b/runtime/lua/vim/shared.lua @@ -6,8 +6,48 @@ -- or the test suite. (Eventually the test suite will be run in a worker process, -- so this wouldn't be a separate case to consider) +---@diagnostic disable-next-line: lowercase-global vim = vim or {} +local function _id(v) + return v +end + +local deepcopy + +local deepcopy_funcs = { + table = function(orig, cache) + if cache[orig] then + return cache[orig] + end + local copy = {} + + cache[orig] = copy + local mt = getmetatable(orig) + for k, v in pairs(orig) do + copy[deepcopy(k, cache)] = deepcopy(v, cache) + end + return setmetatable(copy, mt) + end, + number = _id, + string = _id, + ['nil'] = _id, + boolean = _id, + ['function'] = _id, +} + +deepcopy = function(orig, _cache) + local f = deepcopy_funcs[type(orig)] + if f then + return f(orig, _cache or {}) + else + if type(orig) == 'userdata' and orig == vim.NIL then + return vim.NIL + end + error('Cannot deepcopy object of type ' .. type(orig)) + end +end + --- Returns a deep copy of the given object. Non-table objects are copied as --- in a typical Lua assignment, whereas table objects are copied recursively. --- Functions are naively copied, so functions in the copied table point to the @@ -17,63 +57,60 @@ vim = vim or {} ---@generic T: table ---@param orig T Table to copy ---@return T Table of copied keys and (nested) values. -function vim.deepcopy(orig) end -- luacheck: no unused -vim.deepcopy = (function() - local function _id(v) - return v - end - - local deepcopy_funcs = { - table = function(orig, cache) - if cache[orig] then - return cache[orig] - end - local copy = {} - - cache[orig] = copy - local mt = getmetatable(orig) - for k, v in pairs(orig) do - copy[vim.deepcopy(k, cache)] = vim.deepcopy(v, cache) - end - return setmetatable(copy, mt) - end, - number = _id, - string = _id, - ['nil'] = _id, - boolean = _id, - ['function'] = _id, - } +function vim.deepcopy(orig) + return deepcopy(orig) +end - return function(orig, cache) - local f = deepcopy_funcs[type(orig)] - if f then - return f(orig, cache or {}) - else - if type(orig) == 'userdata' and orig == vim.NIL then - return vim.NIL - end - error('Cannot deepcopy object of type ' .. type(orig)) - end +--- Gets an |iterator| that splits a string at each instance of a separator, in "lazy" fashion +--- (as opposed to |vim.split()| which is "eager"). +--- +--- Example: +--- +--- ```lua +--- for s in vim.gsplit(':aa::b:', ':', {plain=true}) do +--- print(s) +--- end +--- ``` +--- +--- If you want to also inspect the separator itself (instead of discarding it), use +--- |string.gmatch()|. Example: +--- +--- ```lua +--- for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do +--- print(('word: %s num: %s'):format(word, num)) +--- end +--- ``` +--- +--- @see |string.gmatch()| +--- @see |vim.split()| +--- @see |lua-patterns| +--- @see https://www.lua.org/pil/20.2.html +--- @see http://lua-users.org/wiki/StringLibraryTutorial +--- +--- @param s string String to split +--- @param sep string Separator or pattern +--- @param opts (table|nil) Keyword arguments |kwargs|: +--- - plain: (boolean) Use `sep` literally (as in string.find). +--- - trimempty: (boolean) Discard empty segments at start and end of the sequence. +---@return fun():string|nil (function) Iterator over the split components +function vim.gsplit(s, sep, opts) + local plain + local trimempty = false + if type(opts) == 'boolean' then + plain = opts -- For backwards compatibility. + else + vim.validate({ s = { s, 's' }, sep = { sep, 's' }, opts = { opts, 't', true } }) + opts = opts or {} + plain, trimempty = opts.plain, opts.trimempty end -end)() - ---- Splits a string at each instance of a separator. ---- ----@see |vim.split()| ----@see |luaref-patterns| ----@see https://www.lua.org/pil/20.2.html ----@see http://lua-users.org/wiki/StringLibraryTutorial ---- ----@param s string String to split ----@param sep string Separator or pattern ----@param plain (boolean|nil) If `true` use `sep` literally (passed to string.find) ----@return fun():string (function) Iterator over the split components -function vim.gsplit(s, sep, plain) - vim.validate({ s = { s, 's' }, sep = { sep, 's' }, plain = { plain, 'b', true } }) local start = 1 local done = false + -- For `trimempty`: queue of collected segments, to be emitted at next pass. + local segs = {} + local empty_start = true -- Only empty segments seen so far. + local function _pass(i, j, ...) if i then assert(j + 1 > start, 'Infinite loop detected') @@ -87,72 +124,69 @@ function vim.gsplit(s, sep, plain) end return function() - if done or (s == '' and sep == '') then - return - end - if sep == '' then + if trimempty and #segs > 0 then + -- trimempty: Pop the collected segments. + return table.remove(segs) + elseif done or (s == '' and sep == '') then + return nil + elseif sep == '' then if start == #s then done = true end return _pass(start + 1, start) end - return _pass(s:find(sep, start, plain)) + + local seg = _pass(s:find(sep, start, plain)) + + -- Trim empty segments from start/end. + if trimempty and seg ~= '' then + empty_start = false + elseif trimempty and seg == '' then + while not done and seg == '' do + table.insert(segs, 1, '') + seg = _pass(s:find(sep, start, plain)) + end + if done and seg == '' then + return nil + elseif empty_start then + empty_start = false + segs = {} + return seg + end + if seg ~= '' then + table.insert(segs, 1, seg) + end + return table.remove(segs) + end + + return seg end end ---- Splits a string at each instance of a separator. +--- Splits a string at each instance of a separator and returns the result as a table (unlike +--- |vim.gsplit()|). --- --- Examples: ---- <pre>lua ---- split(":aa::b:", ":") --> {'','aa','','b',''} ---- split("axaby", "ab?") --> {'','x','y'} ---- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} ---- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} ---- </pre> +--- +--- ```lua +--- split(":aa::b:", ":") --> {'','aa','','b',''} +--- split("axaby", "ab?") --> {'','x','y'} +--- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} +--- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} +--- ``` --- ---@see |vim.gsplit()| +---@see |string.gmatch()| --- ---@param s string String to split ---@param sep string Separator or pattern ----@param kwargs (table|nil) Keyword arguments: ---- - plain: (boolean) If `true` use `sep` literally (passed to string.find) ---- - trimempty: (boolean) If `true` remove empty items from the front ---- and back of the list +---@param opts (table|nil) Keyword arguments |kwargs| accepted by |vim.gsplit()| ---@return string[] List of split components -function vim.split(s, sep, kwargs) - local plain - local trimempty = false - if type(kwargs) == 'boolean' then - -- Support old signature for backward compatibility - plain = kwargs - else - vim.validate({ kwargs = { kwargs, 't', true } }) - kwargs = kwargs or {} - plain = kwargs.plain - trimempty = kwargs.trimempty - end - +function vim.split(s, sep, opts) local t = {} - local skip = trimempty - for c in vim.gsplit(s, sep, plain) do - if c ~= '' then - skip = false - end - - if not skip then - table.insert(t, c) - end - end - - if trimempty then - for i = #t, 1, -1 do - if t[i] ~= '' then - break - end - table.remove(t, i) - end + for c in vim.gsplit(s, sep, opts) do + table.insert(t, c) end - return t end @@ -224,12 +258,54 @@ function vim.tbl_filter(func, t) return rettab end ---- Checks if a list-like (vector) table contains `value`. +--- Checks if a table contains a given value, specified either directly or via +--- a predicate that is checked for each value. +--- +--- Example: +--- +--- ```lua +--- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v) +--- return vim.deep_equal(v, { 'b', 'c' }) +--- end, { predicate = true }) +--- -- true +--- ``` +--- +---@see |vim.list_contains()| for checking values in list-like tables --- ---@param t table Table to check +---@param value any Value to compare or predicate function reference +---@param opts (table|nil) Keyword arguments |kwargs|: +--- - predicate: (boolean) `value` is a function reference to be checked (default false) +---@return boolean `true` if `t` contains `value` +function vim.tbl_contains(t, value, opts) + vim.validate({ t = { t, 't' }, opts = { opts, 't', true } }) + + local pred + if opts and opts.predicate then + vim.validate({ value = { value, 'c' } }) + pred = value + else + pred = function(v) + return v == value + end + end + + for _, v in pairs(t) do + if pred(v) then + return true + end + end + return false +end + +--- Checks if a list-like table (integer keys without gaps) contains `value`. +--- +---@see |vim.tbl_contains()| for checking values in general tables +--- +---@param t table Table to check (must be list-like, not validated) ---@param value any Value to compare ---@return boolean `true` if `t` contains `value` -function vim.tbl_contains(t, value) +function vim.list_contains(t, value) vim.validate({ t = { t, 't' } }) for _, v in ipairs(t) do @@ -251,10 +327,9 @@ function vim.tbl_isempty(t) return next(t) == nil end ---- We only merge empty tables or tables that are not a list ----@private +--- We only merge empty tables or tables that are not an array (indexed by integers) local function can_merge(v) - return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_islist(v)) + return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_isarray(v)) end local function tbl_extend(behavior, deep_extend, ...) @@ -295,7 +370,7 @@ local function tbl_extend(behavior, deep_extend, ...) return ret end ---- Merges two or more map-like tables. +--- Merges two or more tables. --- ---@see |extend()| --- @@ -303,13 +378,13 @@ end --- - "error": raise an error --- - "keep": use value from the leftmost map --- - "force": use value from the rightmost map ----@param ... table Two or more map-like tables +---@param ... table Two or more tables ---@return table Merged table function vim.tbl_extend(behavior, ...) return tbl_extend(behavior, false, ...) end ---- Merges recursively two or more map-like tables. +--- Merges recursively two or more tables. --- ---@see |vim.tbl_extend()| --- @@ -319,7 +394,7 @@ end --- - "error": raise an error --- - "keep": use value from the leftmost map --- - "force": use value from the rightmost map ----@param ... T2 Two or more map-like tables +---@param ... T2 Two or more tables ---@return T1|T2 (table) Merged table function vim.tbl_deep_extend(behavior, ...) return tbl_extend(behavior, true, ...) @@ -384,13 +459,14 @@ end --- Return `nil` if the key does not exist. --- --- Examples: ---- <pre>lua ---- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true ---- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil ---- </pre> +--- +--- ```lua +--- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true +--- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil +--- ``` --- ---@param o table Table to index ----@param ... string Optional strings (0 or more, variadic) via which to index the table +---@param ... any Optional keys (0 or more, variadic) via which to index the table --- ---@return any Nested value indexed by key (if it exists), else nil function vim.tbl_get(o, ...) @@ -418,8 +494,8 @@ end ---@generic T: table ---@param dst T List which will be modified and appended to ---@param src table List from which values will be inserted ----@param start (number|nil) Start index on src. Defaults to 1 ----@param finish (number|nil) Final index on src. Defaults to `#src` +---@param start (integer|nil) Start index on src. Defaults to 1 +---@param finish (integer|nil) Final index on src. Defaults to `#src` ---@return T dst function vim.list_extend(dst, src, start, finish) vim.validate({ @@ -458,12 +534,12 @@ function vim.tbl_flatten(t) return result end ---- Enumerate a table sorted by its keys. +--- Enumerates key-value pairs of a table, ordered by key. --- ---@see Based on https://github.com/premake/premake-core/blob/master/src/base/table.lua --- ----@param t table List-like table ----@return iterator over sorted keys and their values +---@param t table Dict-like table +---@return function # |for-in| iterator over sorted keys and their values function vim.spairs(t) assert(type(t) == 'table', string.format('Expected table, got %s', type(t))) @@ -475,7 +551,6 @@ function vim.spairs(t) table.sort(keys) -- Return the iterator function. - -- TODO(justinmk): Return "iterator function, table {t}, and nil", like pairs()? local i = 0 return function() i = i + 1 @@ -485,15 +560,18 @@ function vim.spairs(t) end end ---- Tests if a Lua table can be treated as an array. +--- Tests if `t` is an "array": a table indexed _only_ by integers (potentially non-contiguous). --- ---- Empty table `{}` is assumed to be an array, unless it was created by ---- |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result, ---- for example from |rpcrequest()| or |vim.fn|. +--- If the indexes start from 1 and are contiguous then the array is also a list. |vim.tbl_islist()| --- ----@param t table Table ----@return boolean `true` if array-like table, else `false` -function vim.tbl_islist(t) +--- Empty table `{}` is an array, unless it was created by |vim.empty_dict()| or returned as +--- a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|. +--- +---@see https://github.com/openresty/luajit2#tableisarray +--- +---@param t table +---@return boolean `true` if array-like table, else `false`. +function vim.tbl_isarray(t) if type(t) ~= 'table' then return false end @@ -501,7 +579,8 @@ function vim.tbl_islist(t) local count = 0 for k, _ in pairs(t) do - if type(k) == 'number' then + --- Check if the number k is an integer + if type(k) == 'number' and k == math.floor(k) then count = count + 1 else return false @@ -520,16 +599,50 @@ function vim.tbl_islist(t) end end +--- Tests if `t` is a "list": a table indexed _only_ by contiguous integers starting from 1 (what +--- |lua-length| calls a "regular array"). +--- +--- Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or returned as +--- a dict-like |API| or Vimscript result, for example from |rpcrequest()| or |vim.fn|. +--- +---@see |vim.tbl_isarray()| +--- +---@param t table +---@return boolean `true` if list-like table, else `false`. +function vim.tbl_islist(t) + if type(t) ~= 'table' then + return false + end + + local num_elem = vim.tbl_count(t) + + if num_elem == 0 then + -- TODO(bfredl): in the future, we will always be inside nvim + -- then this check can be deleted. + if vim._empty_dict_mt == nil then + return nil + end + return getmetatable(t) ~= vim._empty_dict_mt + else + for i = 1, num_elem do + if t[i] == nil then + return false + end + end + return true + end +end + --- Counts the number of non-nil values in table `t`. --- ---- <pre>lua +--- ```lua --- vim.tbl_count({ a=1, b=2 }) --> 2 --- vim.tbl_count({ 1, 2 }) --> 2 ---- </pre> +--- ``` --- ---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua ---@param t table Table ----@return number Number of non-nil values in table +---@return integer Number of non-nil values in table function vim.tbl_count(t) vim.validate({ t = { t, 't' } }) @@ -544,8 +657,8 @@ end --- ---@generic T ---@param list T[] (list) Table ----@param start number|nil Start range of slice ----@param finish number|nil End range of slice +---@param start integer|nil Start range of slice +---@param finish integer|nil End range of slice ---@return T[] (list) Copy of table sliced from start to finish (inclusive) function vim.list_slice(list, start, finish) local new_list = {} @@ -557,7 +670,7 @@ end --- Trim whitespace (Lua pattern "%s") from both sides of a string. --- ----@see |luaref-patterns| +---@see |lua-patterns| ---@see https://www.lua.org/pil/20.2.html ---@param s string String to trim ---@return string String with whitespace removed from its beginning and end @@ -596,58 +709,6 @@ function vim.endswith(s, suffix) return #suffix == 0 or s:sub(-#suffix) == suffix end ---- Validates a parameter specification (types and values). ---- ---- Usage example: ---- <pre>lua ---- function user.new(name, age, hobbies) ---- vim.validate{ ---- name={name, 'string'}, ---- age={age, 'number'}, ---- hobbies={hobbies, 'table'}, ---- } ---- ... ---- end ---- </pre> ---- ---- Examples with explicit argument values (can be run directly): ---- <pre>lua ---- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} ---- --> NOP (success) ---- ---- vim.validate{arg1={1, 'table'}} ---- --> error('arg1: expected table, got number') ---- ---- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} ---- --> error('arg1: expected even number, got 3') ---- </pre> ---- ---- If multiple types are valid they can be given as a list. ---- <pre>lua ---- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} ---- --> NOP (success) ---- ---- vim.validate{arg1={1, {'string', table'}}} ---- --> error('arg1: expected string|table, got number') ---- ---- </pre> ---- ----@param opt table Names of parameters to validate. Each key is a parameter ---- name; each value is a tuple in one of these forms: ---- 1. (arg_value, type_name, optional) ---- - arg_value: argument value ---- - type_name: string|table type name, one of: ("table", "t", "string", ---- "s", "number", "n", "boolean", "b", "function", "f", "nil", ---- "thread", "userdata") or list of them. ---- - optional: (optional) boolean, if true, `nil` is valid ---- 2. (arg_value, fn, msg) ---- - arg_value: argument value ---- - fn: any function accepting one argument, returns true if and ---- only if the argument is valid. Can optionally return an additional ---- informative error message as the second returned value. ---- - msg: (optional) error string if validation fails -function vim.validate(opt) end -- luacheck: no unused - do local type_names = { ['table'] = 'table', @@ -671,7 +732,6 @@ do return type(val) == t or (t == 'callable' and vim.is_callable(val)) end - ---@private local function is_valid(opt) if type(opt) ~= 'table' then return false, string.format('opt: expected table, got %s', type(opt)) @@ -733,6 +793,59 @@ do return true, nil end + --- Validates a parameter specification (types and values). + --- + --- Usage example: + --- + --- ```lua + --- function user.new(name, age, hobbies) + --- vim.validate{ + --- name={name, 'string'}, + --- age={age, 'number'}, + --- hobbies={hobbies, 'table'}, + --- } + --- ... + --- end + --- ``` + --- + --- Examples with explicit argument values (can be run directly): + --- + --- ```lua + --- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} + --- --> NOP (success) + --- + --- vim.validate{arg1={1, 'table'}} + --- --> error('arg1: expected table, got number') + --- + --- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} + --- --> error('arg1: expected even number, got 3') + --- ``` + --- + --- If multiple types are valid they can be given as a list. + --- + --- ```lua + --- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} + --- -- NOP (success) + --- + --- vim.validate{arg1={1, {'string', 'table'}}} + --- -- error('arg1: expected string|table, got number') + --- + --- ``` + --- + ---@param opt table Names of parameters to validate. Each key is a parameter + --- name; each value is a tuple in one of these forms: + --- 1. (arg_value, type_name, optional) + --- - arg_value: argument value + --- - type_name: string|table type name, one of: ("table", "t", "string", + --- "s", "number", "n", "boolean", "b", "function", "f", "nil", + --- "thread", "userdata") or list of them. + --- - optional: (optional) boolean, if true, `nil` is valid + --- 2. (arg_value, fn, msg) + --- - arg_value: argument value + --- - fn: any function accepting one argument, returns true if and + --- only if the argument is valid. Can optionally return an additional + --- informative error message as the second returned value. + --- - msg: (optional) error string if validation fails function vim.validate(opt) local ok, err_msg = is_valid(opt) if not ok then @@ -755,30 +868,122 @@ function vim.is_callable(f) return type(m.__call) == 'function' end ---- Creates a table whose members are automatically created when accessed, if they don't already ---- exist. ---- ---- They mimic defaultdict in python. +--- Creates a table whose missing keys are provided by {createfn} (like Python's "defaultdict"). --- ---- If {create} is `nil`, this will create a defaulttable whose constructor function is ---- this function, effectively allowing to create nested tables on the fly: +--- If {createfn} is `nil` it defaults to defaulttable() itself, so accessing nested keys creates +--- nested tables: --- ---- <pre>lua +--- ```lua --- local a = vim.defaulttable() --- a.b.c = 1 ---- </pre> +--- ``` --- ----@param create function|nil The function called to create a missing value. ----@return table Empty table with metamethod -function vim.defaulttable(create) - create = create or vim.defaulttable +---@param createfn function?(key:any):any Provides the value for a missing `key`. +---@return table # Empty table with `__index` metamethod. +function vim.defaulttable(createfn) + createfn = createfn or function(_) + return vim.defaulttable() + end return setmetatable({}, { __index = function(tbl, key) - rawset(tbl, key, create()) + rawset(tbl, key, createfn(key)) return rawget(tbl, key) end, }) end +do + ---@class vim.Ringbuf<T> + ---@field private _items table[] + ---@field private _idx_read integer + ---@field private _idx_write integer + ---@field private _size integer + local Ringbuf = {} + + --- Clear all items + function Ringbuf.clear(self) + self._items = {} + self._idx_read = 0 + self._idx_write = 0 + end + + --- Adds an item, overriding the oldest item if the buffer is full. + ---@generic T + ---@param item T + function Ringbuf.push(self, item) + self._items[self._idx_write] = item + self._idx_write = (self._idx_write + 1) % self._size + if self._idx_write == self._idx_read then + self._idx_read = (self._idx_read + 1) % self._size + end + end + + --- Removes and returns the first unread item + ---@generic T + ---@return T? + function Ringbuf.pop(self) + local idx_read = self._idx_read + if idx_read == self._idx_write then + return nil + end + local item = self._items[idx_read] + self._items[idx_read] = nil + self._idx_read = (idx_read + 1) % self._size + return item + end + + --- Returns the first unread item without removing it + ---@generic T + ---@return T? + function Ringbuf.peek(self) + if self._idx_read == self._idx_write then + return nil + end + return self._items[self._idx_read] + end + + --- Create a ring buffer limited to a maximal number of items. + --- Once the buffer is full, adding a new entry overrides the oldest entry. + --- + --- ```lua + --- local ringbuf = vim.ringbuf(4) + --- ringbuf:push("a") + --- ringbuf:push("b") + --- ringbuf:push("c") + --- ringbuf:push("d") + --- ringbuf:push("e") -- overrides "a" + --- print(ringbuf:pop()) -- returns "b" + --- print(ringbuf:pop()) -- returns "c" + --- + --- -- Can be used as iterator. Pops remaining items: + --- for val in ringbuf do + --- print(val) + --- end + --- ``` + --- + --- Returns a Ringbuf instance with the following methods: + --- + --- - |Ringbuf:push()| + --- - |Ringbuf:pop()| + --- - |Ringbuf:peek()| + --- - |Ringbuf:clear()| + --- + ---@param size integer + ---@return vim.Ringbuf ringbuf (table) + function vim.ringbuf(size) + local ringbuf = { + _items = {}, + _size = size + 1, + _idx_read = 0, + _idx_write = 0, + } + return setmetatable(ringbuf, { + __index = Ringbuf, + __call = function(self) + return self:pop() + end, + }) + end +end + return vim --- vim:sw=2 ts=2 et diff --git a/runtime/lua/vim/snippet.lua b/runtime/lua/vim/snippet.lua new file mode 100644 index 0000000000..32a8ea0b0d --- /dev/null +++ b/runtime/lua/vim/snippet.lua @@ -0,0 +1,591 @@ +local G = require('vim.lsp._snippet_grammar') +local snippet_group = vim.api.nvim_create_augroup('vim/snippet', {}) +local snippet_ns = vim.api.nvim_create_namespace('vim/snippet') + +--- Returns the 0-based cursor position. +--- +--- @return integer, integer +local function cursor_pos() + local cursor = vim.api.nvim_win_get_cursor(0) + return cursor[1] - 1, cursor[2] +end + +--- Resolves variables (like `$name` or `${name:default}`) as follows: +--- - When a variable is unknown (i.e.: its name is not recognized in any of the cases below), return `nil`. +--- - When a variable isn't set, return its default (if any) or an empty string. +--- +--- Note that in some cases, the default is ignored since it's not clear how to distinguish an empty +--- value from an unset value (e.g.: `TM_CURRENT_LINE`). +--- +--- @param var string +--- @param default string +--- @return string? +local function resolve_variable(var, default) + --- @param str string + --- @return string + local function expand_or_default(str) + local expansion = vim.fn.expand(str) --[[@as string]] + return expansion == '' and default or expansion + end + + if var == 'TM_SELECTED_TEXT' then + -- Snippets are expanded in insert mode only, so there's no selection. + return default + elseif var == 'TM_CURRENT_LINE' then + return vim.api.nvim_get_current_line() + elseif var == 'TM_CURRENT_WORD' then + return expand_or_default('<cword>') + elseif var == 'TM_LINE_INDEX' then + return tostring(vim.fn.line('.') - 1) + elseif var == 'TM_LINE_NUMBER' then + return tostring(vim.fn.line('.')) + elseif var == 'TM_FILENAME' then + return expand_or_default('%:t') + elseif var == 'TM_FILENAME_BASE' then + -- Not using '%:t:r' since we want to remove all extensions. + local filename_base = expand_or_default('%:t'):gsub('%.[^%.]*$', '') + return filename_base + elseif var == 'TM_DIRECTORY' then + return expand_or_default('%:p:h:t') + elseif var == 'TM_FILEPATH' then + return expand_or_default('%:p') + end + + -- Unknown variable. + return nil +end + +--- Transforms the given text into an array of lines (so no line contains `\n`). +--- +--- @param text string|string[] +--- @return string[] +local function text_to_lines(text) + text = type(text) == 'string' and { text } or text + --- @cast text string[] + return vim.split(table.concat(text), '\n', { plain = true }) +end + +--- Computes the 0-based position of a tabstop located at the end of `snippet` and spanning +--- `placeholder` (if given). +--- +--- @param snippet string[] +--- @param placeholder string? +--- @return Range4 +local function compute_tabstop_range(snippet, placeholder) + local cursor_row, cursor_col = cursor_pos() + local snippet_text = text_to_lines(snippet) + local placeholder_text = text_to_lines(placeholder or '') + local start_row = cursor_row + #snippet_text - 1 + local start_col = #(snippet_text[#snippet_text] or '') + + -- Add the cursor's column offset to the first line. + if start_row == cursor_row then + start_col = start_col + cursor_col + end + + local end_row = start_row + #placeholder_text - 1 + local end_col = (start_row == end_row and start_col or 0) + + #(placeholder_text[#placeholder_text] or '') + + return { start_row, start_col, end_row, end_col } +end + +--- Returns the range spanned by the respective extmark. +--- +--- @param bufnr integer +--- @param extmark_id integer +--- @return Range4 +local function get_extmark_range(bufnr, extmark_id) + local mark = vim.api.nvim_buf_get_extmark_by_id(bufnr, snippet_ns, extmark_id, { details = true }) + + --- @diagnostic disable-next-line: undefined-field + return { mark[1], mark[2], mark[3].end_row, mark[3].end_col } +end + +--- @class vim.snippet.Tabstop +--- @field extmark_id integer +--- @field bufnr integer +--- @field index integer +--- @field choices? string[] +local Tabstop = {} + +--- Creates a new tabstop. +--- +--- @package +--- @param index integer +--- @param bufnr integer +--- @param range Range4 +--- @param choices? string[] +--- @return vim.snippet.Tabstop +function Tabstop.new(index, bufnr, range, choices) + local extmark_id = vim.api.nvim_buf_set_extmark(bufnr, snippet_ns, range[1], range[2], { + right_gravity = false, + end_right_gravity = true, + end_line = range[3], + end_col = range[4], + hl_group = 'SnippetTabstop', + }) + + local self = setmetatable( + { extmark_id = extmark_id, bufnr = bufnr, index = index, choices = choices }, + { __index = Tabstop } + ) + + return self +end + +--- Returns the tabstop's range. +--- +--- @package +--- @return Range4 +function Tabstop:get_range() + return get_extmark_range(self.bufnr, self.extmark_id) +end + +--- Returns the text spanned by the tabstop. +--- +--- @package +--- @return string +function Tabstop:get_text() + local range = self:get_range() + return table.concat( + vim.api.nvim_buf_get_text(self.bufnr, range[1], range[2], range[3], range[4], {}), + '\n' + ) +end + +--- Sets the tabstop's text. +--- +--- @package +--- @param text string +function Tabstop:set_text(text) + local range = self:get_range() + vim.api.nvim_buf_set_text(self.bufnr, range[1], range[2], range[3], range[4], text_to_lines(text)) +end + +--- @class vim.snippet.Session +--- @field bufnr integer +--- @field extmark_id integer +--- @field tabstops table<integer, vim.snippet.Tabstop[]> +--- @field current_tabstop vim.snippet.Tabstop +local Session = {} + +--- Creates a new snippet session in the current buffer. +--- +--- @package +--- @param bufnr integer +--- @param snippet_extmark integer +--- @param tabstop_data table<integer, { range: Range4, choices?: string[] }[]> +--- @return vim.snippet.Session +function Session.new(bufnr, snippet_extmark, tabstop_data) + local self = setmetatable({ + bufnr = bufnr, + extmark_id = snippet_extmark, + tabstops = {}, + current_tabstop = Tabstop.new(0, bufnr, { 0, 0, 0, 0 }), + }, { __index = Session }) + + -- Create the tabstops. + for index, ranges in pairs(tabstop_data) do + for _, data in ipairs(ranges) do + self.tabstops[index] = self.tabstops[index] or {} + table.insert(self.tabstops[index], Tabstop.new(index, self.bufnr, data.range, data.choices)) + end + end + + return self +end + +--- Returns the destination tabstop index when jumping in the given direction. +--- +--- @package +--- @param direction vim.snippet.Direction +--- @return integer? +function Session:get_dest_index(direction) + local tabstop_indexes = vim.tbl_keys(self.tabstops) --- @type integer[] + table.sort(tabstop_indexes) + for i, index in ipairs(tabstop_indexes) do + if index == self.current_tabstop.index then + local dest_index = tabstop_indexes[i + direction] --- @type integer? + -- When jumping forwards, $0 is the last tabstop. + if not dest_index and direction == 1 then + dest_index = 0 + end + -- When jumping backwards, make sure we don't think that $0 is the first tabstop. + if dest_index == 0 and direction == -1 then + dest_index = nil + end + return dest_index + end + end +end + +--- @class vim.snippet.Snippet +--- @field private _session? vim.snippet.Session +local M = { session = nil } + +--- Displays the choices for the given tabstop as completion items. +--- +--- @param tabstop vim.snippet.Tabstop +local function display_choices(tabstop) + assert(tabstop.choices, 'Tabstop has no choices') + + local start_col = tabstop:get_range()[2] + 1 + local matches = vim.iter.map(function(choice) + return { word = choice } + end, tabstop.choices) + + vim.defer_fn(function() + vim.fn.complete(start_col, matches) + end, 100) +end + +--- Select the given tabstop range. +--- +--- @param tabstop vim.snippet.Tabstop +local function select_tabstop(tabstop) + --- @param keys string + local function feedkeys(keys) + keys = vim.api.nvim_replace_termcodes(keys, true, false, true) + vim.api.nvim_feedkeys(keys, 'n', true) + end + + --- NOTE: We don't use `vim.api.nvim_win_set_cursor` here because it causes the cursor to end + --- at the end of the selection instead of the start. + --- + --- @param row integer + --- @param col integer + local function move_cursor_to(row, col) + local line = vim.fn.getline(row) --[[ @as string ]] + col = math.max(vim.fn.strchars(line:sub(1, col)) - 1, 0) + feedkeys(string.format('%sG0%s', row, string.rep('<Right>', col))) + end + + local range = tabstop:get_range() + local mode = vim.fn.mode() + + if vim.fn.pumvisible() ~= 0 then + -- Close the choice completion menu if open. + vim.fn.complete(vim.fn.col('.'), {}) + end + + -- Move the cursor to the start of the tabstop. + vim.api.nvim_win_set_cursor(0, { range[1] + 1, range[2] }) + + -- For empty, choice and the final tabstops, start insert mode at the end of the range. + if tabstop.choices or tabstop.index == 0 or (range[1] == range[3] and range[2] == range[4]) then + if mode ~= 'i' then + if mode == 's' then + feedkeys('<Esc>') + end + vim.cmd.startinsert({ bang = range[4] >= #vim.api.nvim_get_current_line() }) + end + if tabstop.choices then + display_choices(tabstop) + end + else + -- Else, select the tabstop's text. + if mode ~= 'n' then + feedkeys('<Esc>') + end + move_cursor_to(range[1] + 1, range[2] + 1) + feedkeys('v') + move_cursor_to(range[3] + 1, range[4]) + feedkeys('o<c-g>') + end +end + +--- Sets up the necessary autocommands for snippet expansion. +--- +--- @param bufnr integer +local function setup_autocmds(bufnr) + vim.api.nvim_create_autocmd({ 'CursorMoved', 'CursorMovedI' }, { + group = snippet_group, + desc = 'Update snippet state when the cursor moves', + buffer = bufnr, + callback = function() + -- Just update the tabstop in insert and select modes. + if not vim.fn.mode():match('^[isS]') then + return + end + + local cursor_row, cursor_col = cursor_pos() + + -- The cursor left the snippet region. + local snippet_range = get_extmark_range(bufnr, M._session.extmark_id) + if + cursor_row < snippet_range[1] + or (cursor_row == snippet_range[1] and cursor_col < snippet_range[2]) + or cursor_row > snippet_range[3] + or (cursor_row == snippet_range[3] and cursor_col > snippet_range[4]) + then + M.exit() + return true + end + + for tabstop_index, tabstops in pairs(M._session.tabstops) do + for _, tabstop in ipairs(tabstops) do + local range = tabstop:get_range() + if + (cursor_row > range[1] or (cursor_row == range[1] and cursor_col >= range[2])) + and (cursor_row < range[3] or (cursor_row == range[3] and cursor_col <= range[4])) + then + if tabstop_index ~= 0 then + return + end + end + end + end + + -- The cursor is either not on a tabstop or we reached the end, so exit the session. + M.exit() + return true + end, + }) + + vim.api.nvim_create_autocmd({ 'TextChanged', 'TextChangedI' }, { + group = snippet_group, + desc = 'Update active tabstops when buffer text changes', + buffer = bufnr, + callback = function() + -- Check that the snippet hasn't been deleted. + local snippet_range = get_extmark_range(M._session.bufnr, M._session.extmark_id) + if + (snippet_range[1] == snippet_range[3] and snippet_range[2] == snippet_range[4]) + or snippet_range[3] + 1 > vim.fn.line('$') + then + M.exit() + end + + if not M.active() then + return true + end + + -- Sync the tabstops in the current group. + local current_tabstop = M._session.current_tabstop + local current_text = current_tabstop:get_text() + for _, tabstop in ipairs(M._session.tabstops[current_tabstop.index]) do + if tabstop.extmark_id ~= current_tabstop.extmark_id then + tabstop:set_text(current_text) + end + end + end, + }) +end + +--- Expands the given snippet text. +--- Refer to https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax +--- for the specification of valid input. +--- +--- Tabstops are highlighted with hl-SnippetTabstop. +--- +--- @param input string +function M.expand(input) + local snippet = G.parse(input) + local snippet_text = {} + local base_indent = vim.api.nvim_get_current_line():match('^%s*') or '' + + -- Get the placeholders we should use for each tabstop index. + --- @type table<integer, string> + local placeholders = {} + for _, child in ipairs(snippet.data.children) do + local type, data = child.type, child.data + if type == G.NodeType.Placeholder then + --- @cast data vim.snippet.PlaceholderData + local tabstop, value = data.tabstop, tostring(data.value) + if placeholders[tabstop] and placeholders[tabstop] ~= value then + error('Snippet has multiple placeholders for tabstop $' .. tabstop) + end + placeholders[tabstop] = value + end + end + + -- Keep track of tabstop nodes during expansion. + --- @type table<integer, { range: Range4, choices?: string[] }[]> + local tabstop_data = {} + + --- @param index integer + --- @param placeholder? string + --- @param choices? string[] + local function add_tabstop(index, placeholder, choices) + tabstop_data[index] = tabstop_data[index] or {} + local range = compute_tabstop_range(snippet_text, placeholder) + table.insert(tabstop_data[index], { range = range, choices = choices }) + end + + --- Appends the given text to the snippet, taking care of indentation. + --- + --- @param text string|string[] + local function append_to_snippet(text) + local snippet_lines = text_to_lines(snippet_text) + -- Get the base indentation based on the current line and the last line of the snippet. + if #snippet_lines > 0 then + base_indent = base_indent .. (snippet_lines[#snippet_lines]:match('(^%s*)%S') or '') --- @type string + end + + local lines = vim.iter.map(function(i, line) + -- Replace tabs by spaces. + if vim.o.expandtab then + line = line:gsub('\t', (' '):rep(vim.fn.shiftwidth())) --- @type string + end + -- Add the base indentation. + if i > 1 then + line = base_indent .. line + end + return line + end, ipairs(text_to_lines(text))) + + table.insert(snippet_text, table.concat(lines, '\n')) + end + + for _, child in ipairs(snippet.data.children) do + local type, data = child.type, child.data + if type == G.NodeType.Tabstop then + --- @cast data vim.snippet.TabstopData + local placeholder = placeholders[data.tabstop] + add_tabstop(data.tabstop, placeholder) + if placeholder then + append_to_snippet(placeholder) + end + elseif type == G.NodeType.Placeholder then + --- @cast data vim.snippet.PlaceholderData + local value = placeholders[data.tabstop] + add_tabstop(data.tabstop, value) + append_to_snippet(value) + elseif type == G.NodeType.Choice then + --- @cast data vim.snippet.ChoiceData + add_tabstop(data.tabstop, nil, data.values) + elseif type == G.NodeType.Variable then + --- @cast data vim.snippet.VariableData + -- Try to get the variable's value. + local value = resolve_variable(data.name, data.default and tostring(data.default) or '') + if not value then + -- Unknown variable, make this a tabstop and use the variable name as a placeholder. + value = data.name + local tabstop_indexes = vim.tbl_keys(tabstop_data) + local index = math.max(unpack((#tabstop_indexes == 0 and { 0 }) or tabstop_indexes)) + 1 + add_tabstop(index, value) + end + append_to_snippet(value) + elseif type == G.NodeType.Text then + --- @cast data vim.snippet.TextData + append_to_snippet(data.text) + end + end + + -- $0, which defaults to the end of the snippet, defines the final cursor position. + -- Make sure the snippet has exactly one of these. + if vim.tbl_contains(vim.tbl_keys(tabstop_data), 0) then + assert(#tabstop_data[0] == 1, 'Snippet has multiple $0 tabstops') + else + add_tabstop(0) + end + + snippet_text = text_to_lines(snippet_text) + + -- Insert the snippet text. + local bufnr = vim.api.nvim_get_current_buf() + local cursor_row, cursor_col = cursor_pos() + vim.api.nvim_buf_set_text(bufnr, cursor_row, cursor_col, cursor_row, cursor_col, snippet_text) + + -- Create the session. + local snippet_extmark = vim.api.nvim_buf_set_extmark(bufnr, snippet_ns, cursor_row, cursor_col, { + end_line = cursor_row + #snippet_text - 1, + end_col = #snippet_text > 1 and #snippet_text[#snippet_text] or cursor_col + #snippet_text[1], + right_gravity = false, + end_right_gravity = true, + }) + M._session = Session.new(bufnr, snippet_extmark, tabstop_data) + + -- Jump to the first tabstop. + M.jump(1) +end + +--- @alias vim.snippet.Direction -1 | 1 + +--- Returns `true` if there is an active snippet which can be jumped in the given direction. +--- You can use this function to navigate a snippet as follows: +--- +--- ```lua +--- vim.keymap.set({ 'i', 's' }, '<Tab>', function() +--- if vim.snippet.jumpable(1) then +--- return '<cmd>lua vim.snippet.jump(1)<cr>' +--- else +--- return '<Tab>' +--- end +--- end, { expr = true }) +--- ``` +--- +--- @param direction (vim.snippet.Direction) Navigation direction. -1 for previous, 1 for next. +--- @return boolean +function M.jumpable(direction) + if not M.active() then + return false + end + + return M._session:get_dest_index(direction) ~= nil +end + +--- Jumps within the active snippet in the given direction. +--- If the jump isn't possible, the function call does nothing. +--- +--- You can use this function to navigate a snippet as follows: +--- +--- ```lua +--- vim.keymap.set({ 'i', 's' }, '<Tab>', function() +--- if vim.snippet.jumpable(1) then +--- return '<cmd>lua vim.snippet.jump(1)<cr>' +--- else +--- return '<Tab>' +--- end +--- end, { expr = true }) +--- ``` +--- +--- @param direction (vim.snippet.Direction) Navigation direction. -1 for previous, 1 for next. +function M.jump(direction) + -- Get the tabstop index to jump to. + local dest_index = M._session and M._session:get_dest_index(direction) + if not dest_index then + return + end + + -- Find the tabstop with the lowest range. + local tabstops = M._session.tabstops[dest_index] + local dest = tabstops[1] + for _, tabstop in ipairs(tabstops) do + local dest_range, range = dest:get_range(), tabstop:get_range() + if (range[1] < dest_range[1]) or (range[1] == dest_range[1] and range[2] < dest_range[2]) then + dest = tabstop + end + end + + -- Clear the autocommands so that we can move the cursor freely while selecting the tabstop. + vim.api.nvim_clear_autocmds({ group = snippet_group, buffer = M._session.bufnr }) + + M._session.current_tabstop = dest + select_tabstop(dest) + + -- Restore the autocommands. + setup_autocmds(M._session.bufnr) +end + +--- Returns `true` if there's an active snippet in the current buffer. +--- +--- @return boolean +function M.active() + return M._session ~= nil and M._session.bufnr == vim.api.nvim_get_current_buf() +end + +--- Exits the current snippet. +function M.exit() + if not M.active() then + return + end + + vim.api.nvim_clear_autocmds({ group = snippet_group, buffer = M._session.bufnr }) + vim.api.nvim_buf_clear_namespace(M._session.bufnr, snippet_ns, 0, -1) + + M._session = nil +end + +return M diff --git a/runtime/lua/vim/termcap.lua b/runtime/lua/vim/termcap.lua new file mode 100644 index 0000000000..862cc52149 --- /dev/null +++ b/runtime/lua/vim/termcap.lua @@ -0,0 +1,62 @@ +local M = {} + +--- Query the host terminal emulator for terminfo capabilities. +--- +--- This function sends the XTGETTCAP DCS sequence to the host terminal emulator asking the terminal +--- to send us its terminal capabilities. These are strings that are normally taken from a terminfo +--- file, however an up to date terminfo database is not always available (particularly on remote +--- machines), and many terminals continue to misidentify themselves or do not provide their own +--- terminfo file, making the terminfo database unreliable. +--- +--- Querying the terminal guarantees that we get a truthful answer, but only if the host terminal +--- emulator supports the XTGETTCAP sequence. +--- +--- @param caps string|table A terminal capability or list of capabilities to query +--- @param cb function(cap:string, seq:string) Function to call when a response is received +function M.query(caps, cb) + vim.validate({ + caps = { caps, { 'string', 'table' } }, + cb = { cb, 'f' }, + }) + + if type(caps) ~= 'table' then + caps = { caps } + end + + local count = #caps + + vim.api.nvim_create_autocmd('TermResponse', { + callback = function(args) + local resp = args.data ---@type string + local k, v = resp:match('^\027P1%+r(%x+)=(%x+)$') + if k and v then + local cap = vim.text.hexdecode(k) + local seq = + vim.text.hexdecode(v):gsub('\\E', '\027'):gsub('%%p%d', ''):gsub('\\(%d+)', string.char) + + cb(cap, seq) + + count = count - 1 + if count == 0 then + return true + end + end + end, + }) + + local encoded = {} ---@type string[] + for i = 1, #caps do + encoded[i] = vim.text.hexencode(caps[i]) + end + + local query = string.format('\027P+q%s\027\\', table.concat(encoded, ';')) + + -- If running in tmux, wrap with the passthrough sequence + if os.getenv('TMUX') then + query = string.format('\027Ptmux;%s\027\\', query:gsub('\027', '\027\027')) + end + + io.stdout:write(query) +end + +return M diff --git a/runtime/lua/vim/text.lua b/runtime/lua/vim/text.lua new file mode 100644 index 0000000000..cfb0f9b821 --- /dev/null +++ b/runtime/lua/vim/text.lua @@ -0,0 +1,32 @@ +--- Text processing functions. + +local M = {} + +--- Hex encode a string. +--- +--- @param str string String to encode +--- @return string Hex encoded string +function M.hexencode(str) + local bytes = { str:byte(1, #str) } + local enc = {} ---@type string[] + for i = 1, #bytes do + enc[i] = string.format('%02X', bytes[i]) + end + return table.concat(enc) +end + +--- Hex decode a string. +--- +--- @param enc string String to decode +--- @return string Decoded string +function M.hexdecode(enc) + assert(#enc % 2 == 0, 'string must have an even number of hex characters') + local str = {} ---@type string[] + for i = 1, #enc, 2 do + local n = assert(tonumber(enc:sub(i, i + 1), 16)) + str[#str + 1] = string.char(n) + end + return table.concat(str) +end + +return M diff --git a/runtime/lua/vim/treesitter.lua b/runtime/lua/vim/treesitter.lua index 582922ecb6..e7a66c00b2 100644 --- a/runtime/lua/vim/treesitter.lua +++ b/runtime/lua/vim/treesitter.lua @@ -1,17 +1,17 @@ -local a = vim.api -local query = require('vim.treesitter.query') -local language = require('vim.treesitter.language') +local api = vim.api local LanguageTree = require('vim.treesitter.languagetree') +local Range = require('vim.treesitter._range') +---@type table<integer,LanguageTree> local parsers = setmetatable({}, { __mode = 'v' }) -local M = vim.tbl_extend('error', query, language) - -M.language_version = vim._ts_get_language_version() -M.minimum_language_version = vim._ts_get_minimum_language_version() - -setmetatable(M, { +---@class TreesitterModule +---@field highlighter TSHighlighter +---@field query TSQueryModule +---@field language TSLanguageModule +local M = setmetatable({}, { __index = function(t, k) + ---@diagnostic disable:no-unknown if k == 'highlighter' then t[k] = require('vim.treesitter.highlighter') return t[k] @@ -22,34 +22,51 @@ setmetatable(M, { t[k] = require('vim.treesitter.query') return t[k] end + + local query = require('vim.treesitter.query') + if query[k] then + vim.deprecate('vim.treesitter.' .. k .. '()', 'vim.treesitter.query.' .. k .. '()', '0.10') + t[k] = query[k] + return t[k] + end + + local language = require('vim.treesitter.language') + if language[k] then + vim.deprecate('vim.treesitter.' .. k .. '()', 'vim.treesitter.language.' .. k .. '()', '0.10') + t[k] = language[k] + return t[k] + end end, }) +--- @nodoc +M.language_version = vim._ts_get_language_version() + +--- @nodoc +M.minimum_language_version = vim._ts_get_minimum_language_version() + --- Creates a new parser --- --- It is not recommended to use this; use |get_parser()| instead. --- ----@param bufnr string Buffer the parser will be tied to (0 for current buffer) +---@param bufnr integer Buffer the parser will be tied to (0 for current buffer) ---@param lang string Language of the parser ---@param opts (table|nil) Options to pass to the created language tree --- ----@return LanguageTree |LanguageTree| object to use for parsing +---@return LanguageTree object to use for parsing function M._create_parser(bufnr, lang, opts) - language.require_language(lang) if bufnr == 0 then - bufnr = a.nvim_get_current_buf() + bufnr = vim.api.nvim_get_current_buf() end vim.fn.bufload(bufnr) local self = LanguageTree.new(bufnr, lang, opts) - ---@private local function bytes_cb(_, ...) self:_on_bytes(...) end - ---@private local function detach_cb(_, ...) if parsers[bufnr] == self then parsers[bufnr] = nil @@ -57,13 +74,14 @@ function M._create_parser(bufnr, lang, opts) self:_on_detach(...) end - ---@private - local function reload_cb(_, ...) - self:_on_reload(...) + local function reload_cb(_) + self:_on_reload() end - a.nvim_buf_attach( - self:source(), + local source = self:source() --[[@as integer]] + + api.nvim_buf_attach( + source, false, { on_bytes = bytes_cb, on_detach = detach_cb, on_reload = reload_cb, preview = true } ) @@ -73,26 +91,43 @@ function M._create_parser(bufnr, lang, opts) return self end ---- Returns the parser for a specific buffer and filetype and attaches it to the buffer +local function valid_lang(lang) + return lang and lang ~= '' +end + +--- Returns the parser for a specific buffer and attaches it to the buffer --- --- If needed, this will create the parser. --- ----@param bufnr (number|nil) Buffer the parser should be tied to (default: current buffer) +---@param bufnr (integer|nil) Buffer the parser should be tied to (default: current buffer) ---@param lang (string|nil) Filetype of this parser (default: buffer filetype) ---@param opts (table|nil) Options to pass to the created language tree --- ----@return LanguageTree |LanguageTree| object to use for parsing +---@return LanguageTree object to use for parsing function M.get_parser(bufnr, lang, opts) opts = opts or {} if bufnr == nil or bufnr == 0 then - bufnr = a.nvim_get_current_buf() + bufnr = api.nvim_get_current_buf() end - if lang == nil then - lang = a.nvim_buf_get_option(bufnr, 'filetype') + + if not valid_lang(lang) then + lang = M.language.get_lang(vim.bo[bufnr].filetype) or vim.bo[bufnr].filetype end - if parsers[bufnr] == nil or parsers[bufnr]:lang() ~= lang then + if not valid_lang(lang) then + if not parsers[bufnr] then + error( + string.format( + 'There is no parser available for buffer %d and one could not be' + .. ' created because lang could not be determined. Either pass lang' + .. ' or set the buffer filetype', + bufnr + ) + ) + end + elseif parsers[bufnr] == nil or parsers[bufnr]:lang() ~= lang then + assert(lang, 'lang should be valid') parsers[bufnr] = M._create_parser(bufnr, lang, opts) end @@ -107,21 +142,20 @@ end ---@param lang string Language of this string ---@param opts (table|nil) Options to pass to the created language tree --- ----@return LanguageTree |LanguageTree| object to use for parsing +---@return LanguageTree object to use for parsing function M.get_string_parser(str, lang, opts) vim.validate({ str = { str, 'string' }, lang = { lang, 'string' }, }) - language.require_language(lang) return LanguageTree.new(str, lang, opts) end --- Determines whether a node is the ancestor of another --- ----@param dest userdata Possible ancestor |tsnode| ----@param source userdata Possible descendant |tsnode| +---@param dest TSNode Possible ancestor +---@param source TSNode Possible descendant --- ---@return boolean True if {dest} is an ancestor of {source} function M.is_ancestor(dest, source) @@ -129,7 +163,7 @@ function M.is_ancestor(dest, source) return false end - local current = source + local current = source ---@type TSNode? while current ~= nil do if current == dest then return true @@ -143,9 +177,12 @@ end --- Returns the node's range or an unpacked range table --- ----@param node_or_range (userdata|table) |tsnode| or table of positions +---@param node_or_range (TSNode | table) Node or table of positions --- ----@return table `{ start_row, start_col, end_row, end_col }` +---@return integer start_row +---@return integer start_col +---@return integer end_row +---@return integer end_col function M.get_node_range(node_or_range) if type(node_or_range) == 'table' then return unpack(node_or_range) @@ -154,42 +191,84 @@ function M.get_node_range(node_or_range) end end +---Get the range of a |TSNode|. Can also supply {source} and {metadata} +---to get the range with directives applied. +---@param node TSNode +---@param source integer|string|nil Buffer or string from which the {node} is extracted +---@param metadata TSMetadata|nil +---@return Range6 +function M.get_range(node, source, metadata) + if metadata and metadata.range then + assert(source) + return Range.add_bytes(source, metadata.range) + end + return { node:range(true) } +end + +---@param buf integer +---@param range Range +---@returns string +local function buf_range_get_text(buf, range) + local start_row, start_col, end_row, end_col = Range.unpack4(range) + if end_col == 0 then + if start_row == end_row then + start_col = -1 + start_row = start_row - 1 + end + end_col = -1 + end_row = end_row - 1 + end + local lines = api.nvim_buf_get_text(buf, start_row, start_col, end_row, end_col, {}) + return table.concat(lines, '\n') +end + +--- Gets the text corresponding to a given node +--- +---@param node TSNode +---@param source (integer|string) Buffer or string from which the {node} is extracted +---@param opts (table|nil) Optional parameters. +--- - metadata (table) Metadata of a specific capture. This would be +--- set to `metadata[capture_id]` when using |vim.treesitter.query.add_directive()|. +---@return string +function M.get_node_text(node, source, opts) + opts = opts or {} + local metadata = opts.metadata or {} + + if metadata.text then + return metadata.text + elseif type(source) == 'number' then + local range = vim.treesitter.get_range(node, source, metadata) + return buf_range_get_text(source, range) + end + + ---@cast source string + return source:sub(select(3, node:start()) + 1, select(3, node:end_())) +end + --- Determines whether (line, col) position is in node range --- ----@param node userdata |tsnode| defining the range ----@param line number Line (0-based) ----@param col number Column (0-based) +---@param node TSNode defining the range +---@param line integer Line (0-based) +---@param col integer Column (0-based) --- ---@return boolean True if the position is in node range function M.is_in_node_range(node, line, col) - local start_line, start_col, end_line, end_col = M.get_node_range(node) - if line >= start_line and line <= end_line then - if line == start_line and line == end_line then - return col >= start_col and col < end_col - elseif line == start_line then - return col >= start_col - elseif line == end_line then - return col < end_col - else - return true - end - else - return false - end + return M.node_contains(node, { line, col, line, col + 1 }) end --- Determines if a node contains a range --- ----@param node userdata |tsnode| +---@param node TSNode ---@param range table --- ---@return boolean True if the {node} contains the {range} function M.node_contains(node, range) - local start_row, start_col, end_row, end_col = node:range() - local start_fits = start_row < range[1] or (start_row == range[1] and start_col <= range[2]) - local end_fits = end_row > range[3] or (end_row == range[3] and end_col >= range[4]) - - return start_fits and end_fits + vim.validate({ + -- allow a table so nodes can be mocked + node = { node, { 'userdata', 'table' } }, + range = { range, Range.validate, 'integer list with 4 or 6 elements' }, + }) + return Range.contains({ node:range() }, range) end --- Returns a list of highlight captures at the given position @@ -197,14 +276,14 @@ end --- Each capture is represented by a table containing the capture name as a string as --- well as a table of metadata (`priority`, `conceal`, ...; empty if none are defined). --- ----@param bufnr number Buffer number (0 for current buffer) ----@param row number Position row ----@param col number Position column +---@param bufnr integer Buffer number (0 for current buffer) +---@param row integer Position row +---@param col integer Position column --- ----@return table[] List of captures `{ capture = "capture name", metadata = { ... } }` +---@return table[] List of captures `{ capture = "name", metadata = { ... } }` function M.get_captures_at_pos(bufnr, row, col) if bufnr == 0 then - bufnr = a.nvim_get_current_buf() + bufnr = api.nvim_get_current_buf() end local buf_highlighter = M.highlighter.active[bufnr] @@ -244,19 +323,19 @@ function M.get_captures_at_pos(bufnr, row, col) end end end - end, true) + end) return matches end --- Returns a list of highlight capture names under the cursor --- ----@param winnr (number|nil) Window handle or 0 for current window (default) +---@param winnr (integer|nil) Window handle or 0 for current window (default) --- ---@return string[] List of capture names function M.get_captures_at_cursor(winnr) winnr = winnr or 0 - local bufnr = a.nvim_win_get_buf(winnr) - local cursor = a.nvim_win_get_cursor(winnr) + local bufnr = api.nvim_win_get_buf(winnr) + local cursor = api.nvim_win_get_cursor(winnr) local data = M.get_captures_at_pos(bufnr, cursor[1] - 1, cursor[2]) @@ -271,20 +350,76 @@ end --- Returns the smallest named node at the given position --- ----@param bufnr number Buffer number (0 for current buffer) ----@param row number Position row ----@param col number Position column +--- NOTE: Calling this on an unparsed tree can yield an invalid node. +--- If the tree is not known to be parsed by, e.g., an active highlighter, +--- parse the tree first via +--- +--- ```lua +--- vim.treesitter.get_parser(bufnr):parse(range) +--- ``` +--- +---@param opts table|nil Optional keyword arguments: +--- - bufnr integer|nil Buffer number (nil or 0 for current buffer) +--- - pos table|nil 0-indexed (row, col) tuple. Defaults to cursor position in the +--- current window. Required if {bufnr} is not the current buffer +--- - ignore_injections boolean Ignore injected languages (default true) +--- +---@return TSNode | nil Node at the given position +function M.get_node(opts) + opts = opts or {} + + local bufnr = opts.bufnr + + if not bufnr or bufnr == 0 then + bufnr = api.nvim_get_current_buf() + end + + local row, col + if opts.pos then + assert(#opts.pos == 2, 'Position must be a (row, col) tuple') + row, col = opts.pos[1], opts.pos[2] + else + assert( + bufnr == api.nvim_get_current_buf(), + 'Position must be explicitly provided when not using the current buffer' + ) + local pos = api.nvim_win_get_cursor(0) + -- Subtract one to account for 1-based row indexing in nvim_win_get_cursor + row, col = pos[1] - 1, pos[2] + end + + assert(row >= 0 and col >= 0, 'Invalid position: row and col must be non-negative') + + local ts_range = { row, col, row, col } + + local root_lang_tree = M.get_parser(bufnr) + if not root_lang_tree then + return + end + + return root_lang_tree:named_node_for_range(ts_range, opts) +end + +--- Returns the smallest named node at the given position +--- +---@param bufnr integer Buffer number (0 for current buffer) +---@param row integer Position row +---@param col integer Position column ---@param opts table Optional keyword arguments: --- - lang string|nil Parser language --- - ignore_injections boolean Ignore injected languages (default true) --- ----@return userdata|nil |tsnode| under the cursor +---@return TSNode | nil Node at the given position +---@deprecated function M.get_node_at_pos(bufnr, row, col, opts) + vim.deprecate('vim.treesitter.get_node_at_pos()', 'vim.treesitter.get_node()', '0.10') if bufnr == 0 then - bufnr = a.nvim_get_current_buf() + bufnr = api.nvim_get_current_buf() end local ts_range = { row, col, row, col } + opts = opts or {} + local root_lang_tree = M.get_parser(bufnr, opts.lang) if not root_lang_tree then return @@ -295,15 +430,16 @@ end --- Returns the smallest named node under the cursor --- ----@param winnr (number|nil) Window handle or 0 for current window (default) +---@param winnr (integer|nil) Window handle or 0 for current window (default) --- ---@return string Name of node under the cursor +---@deprecated function M.get_node_at_cursor(winnr) + vim.deprecate('vim.treesitter.get_node_at_cursor()', 'vim.treesitter.get_node():type()', '0.10') winnr = winnr or 0 - local bufnr = a.nvim_win_get_buf(winnr) - local cursor = a.nvim_win_get_cursor(winnr) + local bufnr = api.nvim_win_get_buf(winnr) - return M.get_node_at_pos(bufnr, cursor[1] - 1, cursor[2], { ignore_injections = false }):type() + return M.get_node({ bufnr = bufnr, ignore_injections = false }):type() end --- Starts treesitter highlighting for a buffer @@ -314,28 +450,29 @@ end --- In this case, add ``vim.bo.syntax = 'on'`` after the call to `start`. --- --- Example: ---- <pre>lua +--- +--- ```lua --- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', --- callback = function(args) --- vim.treesitter.start(args.buf, 'latex') --- vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed --- end --- }) ---- </pre> +--- ``` --- ----@param bufnr (number|nil) Buffer to be highlighted (default: current buffer) +---@param bufnr (integer|nil) Buffer to be highlighted (default: current buffer) ---@param lang (string|nil) Language of the parser (default: buffer filetype) function M.start(bufnr, lang) - bufnr = bufnr or a.nvim_get_current_buf() + bufnr = bufnr or api.nvim_get_current_buf() local parser = M.get_parser(bufnr, lang) M.highlighter.new(parser) end --- Stops treesitter highlighting for a buffer --- ----@param bufnr (number|nil) Buffer to stop highlighting (default: current buffer) +---@param bufnr (integer|nil) Buffer to stop highlighting (default: current buffer) function M.stop(bufnr) - bufnr = bufnr or a.nvim_get_current_buf() + bufnr = (bufnr and bufnr ~= 0) and bufnr or api.nvim_get_current_buf() if M.highlighter.active[bufnr] then M.highlighter.active[bufnr]:destroy() @@ -345,198 +482,50 @@ end --- Open a window that displays a textual representation of the nodes in the language tree. --- --- While in the window, press "a" to toggle display of anonymous nodes, "I" to toggle the ---- display of the source language of each node, and press <Enter> to jump to the node under the ---- cursor in the source buffer. +--- display of the source language of each node, "o" to toggle the query editor, and press +--- <Enter> to jump to the node under the cursor in the source buffer. +--- +--- Can also be shown with `:InspectTree`. *:InspectTree* --- ---@param opts table|nil Optional options table with the following possible keys: --- - lang (string|nil): The language of the source buffer. If omitted, the --- filetype of the source buffer is used. ---- - bufnr (number|nil): Buffer to draw the tree into. If omitted, a new +--- - bufnr (integer|nil): Buffer to draw the tree into. If omitted, a new --- buffer is created. ---- - winid (number|nil): Window id to display the tree buffer in. If omitted, +--- - winid (integer|nil): Window id to display the tree buffer in. If omitted, --- a new window is created with {command}. --- - command (string|nil): Vimscript command to create the window. Default ---- value is "topleft 60vnew". Only used when {winid} is nil. ---- - title (string|fun(bufnr:number):string|nil): Title of the window. If a +--- value is "60vnew". Only used when {winid} is nil. +--- - title (string|fun(bufnr:integer):string|nil): Title of the window. If a --- function, it accepts the buffer number of the source buffer as its only --- argument and should return a string. -function M.show_tree(opts) - vim.validate({ - opts = { opts, 't', true }, - }) - - opts = opts or {} - - local Playground = require('vim.treesitter.playground') - local buf = a.nvim_get_current_buf() - local win = a.nvim_get_current_win() - local pg = assert(Playground:new(buf, opts.lang)) - - -- Close any existing playground window - if vim.b[buf].playground then - local w = vim.b[buf].playground - if a.nvim_win_is_valid(w) then - a.nvim_win_close(w, true) - end - end - - local w = opts.winid - if not w then - vim.cmd(opts.command or 'topleft 60vnew') - w = a.nvim_get_current_win() - end - - local b = opts.bufnr - if b then - a.nvim_win_set_buf(w, b) - else - b = a.nvim_win_get_buf(w) - end - - vim.b[buf].playground = w - - vim.wo[w].scrolloff = 5 - vim.wo[w].wrap = false - vim.bo[b].buflisted = false - vim.bo[b].buftype = 'nofile' - vim.bo[b].bufhidden = 'wipe' - - local title = opts.title - if not title then - local bufname = a.nvim_buf_get_name(buf) - title = string.format('Syntax tree for %s', vim.fn.fnamemodify(bufname, ':.')) - elseif type(title) == 'function' then - title = title(buf) - end - - assert(type(title) == 'string', 'Window title must be a string') - a.nvim_buf_set_name(b, title) - - pg:draw(b) - - vim.fn.matchadd('Comment', '\\[[0-9:-]\\+\\]') - vim.fn.matchadd('String', '".*"') - - a.nvim_buf_clear_namespace(buf, pg.ns, 0, -1) - a.nvim_buf_set_keymap(b, 'n', '<CR>', '', { - desc = 'Jump to the node under the cursor in the source buffer', - callback = function() - local row = a.nvim_win_get_cursor(w)[1] - local pos = pg:get(row) - a.nvim_set_current_win(win) - a.nvim_win_set_cursor(win, { pos.lnum + 1, pos.col }) - end, - }) - a.nvim_buf_set_keymap(b, 'n', 'a', '', { - desc = 'Toggle anonymous nodes', - callback = function() - pg.opts.anon = not pg.opts.anon - pg:draw(b) - end, - }) - a.nvim_buf_set_keymap(b, 'n', 'I', '', { - desc = 'Toggle language display', - callback = function() - pg.opts.lang = not pg.opts.lang - pg:draw(b) - end, - }) - - local group = a.nvim_create_augroup('treesitter/playground', {}) - - a.nvim_create_autocmd('CursorMoved', { - group = group, - buffer = b, - callback = function() - a.nvim_buf_clear_namespace(buf, pg.ns, 0, -1) - local row = a.nvim_win_get_cursor(w)[1] - local pos = pg:get(row) - a.nvim_buf_set_extmark(buf, pg.ns, pos.lnum, pos.col, { - end_row = pos.end_lnum, - end_col = math.max(0, pos.end_col), - hl_group = 'Visual', - }) - end, - }) - - a.nvim_create_autocmd('CursorMoved', { - group = group, - buffer = buf, - callback = function() - if not a.nvim_buf_is_loaded(b) then - return true - end - - a.nvim_buf_clear_namespace(b, pg.ns, 0, -1) - - local cursor = a.nvim_win_get_cursor(win) - local cursor_node = M.get_node_at_pos(buf, cursor[1] - 1, cursor[2], { - lang = opts.lang, - ignore_injections = false, - }) - if not cursor_node then - return - end - - local cursor_node_id = cursor_node:id() - for i, v in pg:iter() do - if v.id == cursor_node_id then - local start = v.depth - local end_col = start + #v.text - a.nvim_buf_set_extmark(b, pg.ns, i - 1, start, { - end_col = end_col, - hl_group = 'Visual', - }) - a.nvim_win_set_cursor(w, { i, 0 }) - break - end - end - end, - }) - - a.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, { - group = group, - buffer = buf, - callback = function() - if not a.nvim_buf_is_loaded(b) then - return true - end - - pg = assert(Playground:new(buf, opts.lang)) - pg:draw(b) - end, - }) - - a.nvim_create_autocmd('BufLeave', { - group = group, - buffer = b, - callback = function() - a.nvim_buf_clear_namespace(buf, pg.ns, 0, -1) - end, - }) - - a.nvim_create_autocmd('BufLeave', { - group = group, - buffer = buf, - callback = function() - if not a.nvim_buf_is_loaded(b) then - return true - end +function M.inspect_tree(opts) + ---@diagnostic disable-next-line: invisible + require('vim.treesitter.dev').inspect_tree(opts) +end - a.nvim_buf_clear_namespace(b, pg.ns, 0, -1) - end, - }) +--- Returns the fold level for {lnum} in the current buffer. Can be set directly to 'foldexpr': +--- +--- ```lua +--- vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()' +--- ``` +--- +---@param lnum integer|nil Line number to calculate fold level for +---@return string +function M.foldexpr(lnum) + return require('vim.treesitter._fold').foldexpr(lnum) +end - a.nvim_create_autocmd('BufHidden', { - group = group, - buffer = buf, - once = true, - callback = function() - if a.nvim_win_is_valid(w) then - a.nvim_win_close(w, true) - end - end, - }) +--- Returns the highlighted content of the first line of the fold or falls back to |foldtext()| +--- if no treesitter parser is found. Can be set directly to 'foldtext': +--- +--- ```lua +--- vim.wo.foldtext = 'v:lua.vim.treesitter.foldtext()' +--- ``` +--- +---@return { [1]: string, [2]: string[] }[] | string +function M.foldtext() + return require('vim.treesitter._fold').foldtext() end return M diff --git a/runtime/lua/vim/treesitter/_fold.lua b/runtime/lua/vim/treesitter/_fold.lua new file mode 100644 index 0000000000..5c1cc06908 --- /dev/null +++ b/runtime/lua/vim/treesitter/_fold.lua @@ -0,0 +1,456 @@ +local ts = vim.treesitter + +local Range = require('vim.treesitter._range') + +local api = vim.api + +---@class TS.FoldInfo +---@field levels table<integer,string> +---@field levels0 table<integer,integer> +---@field private start_counts table<integer,integer> +---@field private stop_counts table<integer,integer> +local FoldInfo = {} +FoldInfo.__index = FoldInfo + +---@private +function FoldInfo.new() + return setmetatable({ + start_counts = {}, + stop_counts = {}, + levels0 = {}, + levels = {}, + }, FoldInfo) +end + +---@package +---@param srow integer +---@param erow integer +function FoldInfo:invalidate_range(srow, erow) + for i = srow, erow do + self.start_counts[i + 1] = nil + self.stop_counts[i + 1] = nil + self.levels0[i + 1] = nil + self.levels[i + 1] = nil + end +end + +--- Efficiently remove items from middle of a list a list. +--- +--- Calling table.remove() in a loop will re-index the tail of the table on +--- every iteration, instead this function will re-index the table exactly +--- once. +--- +--- Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524 +--- +---@param t any[] +---@param first integer +---@param last integer +local function list_remove(t, first, last) + local n = #t + for i = 0, n - first do + t[first + i] = t[last + 1 + i] + t[last + 1 + i] = nil + end +end + +---@package +---@param srow integer +---@param erow integer +function FoldInfo:remove_range(srow, erow) + list_remove(self.levels, srow + 1, erow) + list_remove(self.levels0, srow + 1, erow) + list_remove(self.start_counts, srow + 1, erow) + list_remove(self.stop_counts, srow + 1, erow) +end + +--- Efficiently insert items into the middle of a list. +--- +--- Calling table.insert() in a loop will re-index the tail of the table on +--- every iteration, instead this function will re-index the table exactly +--- once. +--- +--- Based on https://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating/53038524#53038524 +--- +---@param t any[] +---@param first integer +---@param last integer +---@param v any +local function list_insert(t, first, last, v) + local n = #t + + -- Shift table forward + for i = n - first, 0, -1 do + t[last + 1 + i] = t[first + i] + end + + -- Fill in new values + for i = first, last do + t[i] = v + end +end + +---@package +---@param srow integer +---@param erow integer +function FoldInfo:add_range(srow, erow) + list_insert(self.levels, srow + 1, erow, '-1') + list_insert(self.levels0, srow + 1, erow, -1) + list_insert(self.start_counts, srow + 1, erow, nil) + list_insert(self.stop_counts, srow + 1, erow, nil) +end + +---@package +---@param lnum integer +function FoldInfo:add_start(lnum) + self.start_counts[lnum] = (self.start_counts[lnum] or 0) + 1 +end + +---@package +---@param lnum integer +function FoldInfo:add_stop(lnum) + self.stop_counts[lnum] = (self.stop_counts[lnum] or 0) + 1 +end + +---@package +---@param lnum integer +---@return integer +function FoldInfo:get_start(lnum) + return self.start_counts[lnum] or 0 +end + +---@package +---@param lnum integer +---@return integer +function FoldInfo:get_stop(lnum) + return self.stop_counts[lnum] or 0 +end + +local function trim_level(level) + local max_fold_level = vim.wo.foldnestmax + if level > max_fold_level then + return max_fold_level + end + return level +end + +--- If a parser doesn't have any ranges explicitly set, treesitter will +--- return a range with end_row and end_bytes with a value of UINT32_MAX, +--- so clip end_row to the max buffer line. +--- +--- TODO(lewis6991): Handle this generally +--- +--- @param bufnr integer +--- @param erow integer? +--- @return integer +local function normalise_erow(bufnr, erow) + local max_erow = api.nvim_buf_line_count(bufnr) - 1 + return math.min(erow or max_erow, max_erow) +end + +-- TODO(lewis6991): Setup a decor provider so injections folds can be parsed +-- as the window is redrawn +---@param bufnr integer +---@param info TS.FoldInfo +---@param srow integer? +---@param erow integer? +---@param parse_injections? boolean +local function get_folds_levels(bufnr, info, srow, erow, parse_injections) + srow = srow or 0 + erow = normalise_erow(bufnr, erow) + + info:invalidate_range(srow, erow) + + local prev_start = -1 + local prev_stop = -1 + + local parser = ts.get_parser(bufnr) + + parser:parse(parse_injections and { srow, erow } or nil) + + parser:for_each_tree(function(tree, ltree) + local query = ts.query.get(ltree:lang(), 'folds') + if not query then + return + end + + -- erow in query is end-exclusive + local q_erow = erow and erow + 1 or -1 + + for id, node, metadata in query:iter_captures(tree:root(), bufnr, srow, q_erow) do + if query.captures[id] == 'fold' then + local range = ts.get_range(node, bufnr, metadata[id]) + local start, _, stop, stop_col = Range.unpack4(range) + + if stop_col == 0 then + stop = stop - 1 + end + + local fold_length = stop - start + 1 + + -- Fold only multiline nodes that are not exactly the same as previously met folds + -- Checking against just the previously found fold is sufficient if nodes + -- are returned in preorder or postorder when traversing tree + if + fold_length > vim.wo.foldminlines and not (start == prev_start and stop == prev_stop) + then + info:add_start(start + 1) + info:add_stop(stop + 1) + prev_start = start + prev_stop = stop + end + end + end + end) + + local current_level = info.levels0[srow] or 0 + + -- We now have the list of fold opening and closing, fill the gaps and mark where fold start + for lnum = srow + 1, erow + 1 do + local last_trimmed_level = trim_level(current_level) + current_level = current_level + info:get_start(lnum) + info.levels0[lnum] = current_level + + local trimmed_level = trim_level(current_level) + current_level = current_level - info:get_stop(lnum) + + -- Determine if it's the start/end of a fold + -- NB: vim's fold-expr interface does not have a mechanism to indicate that + -- two (or more) folds start at this line, so it cannot distinguish between + -- ( \n ( \n )) \n (( \n ) \n ) + -- versus + -- ( \n ( \n ) \n ( \n ) \n ) + -- If it did have such a mechanism, (trimmed_level - last_trimmed_level) + -- would be the correct number of starts to pass on. + local prefix = '' + if trimmed_level - last_trimmed_level > 0 then + prefix = '>' + end + + info.levels[lnum] = prefix .. tostring(trimmed_level) + end +end + +local M = {} + +---@type table<integer,TS.FoldInfo> +local foldinfos = {} + +local group = api.nvim_create_augroup('treesitter/fold', {}) + +--- Update the folds in the windows that contain the buffer and use expr foldmethod (assuming that +--- the user doesn't use different foldexpr for the same buffer). +--- +--- Nvim usually automatically updates folds when text changes, but it doesn't work here because +--- FoldInfo update is scheduled. So we do it manually. +local function foldupdate(bufnr) + local function do_update() + for _, win in ipairs(vim.fn.win_findbuf(bufnr)) do + api.nvim_win_call(win, function() + if vim.wo.foldmethod == 'expr' then + vim._foldupdate() + end + end) + end + end + + if api.nvim_get_mode().mode == 'i' then + -- foldUpdate() is guarded in insert mode. So update folds on InsertLeave + if #(api.nvim_get_autocmds({ + group = group, + buffer = bufnr, + })) > 0 then + return + end + api.nvim_create_autocmd('InsertLeave', { + group = group, + buffer = bufnr, + once = true, + callback = do_update, + }) + return + end + + do_update() +end + +--- Schedule a function only if bufnr is loaded. +--- We schedule fold level computation for the following reasons: +--- * queries seem to use the old buffer state in on_bytes for some unknown reason; +--- * to avoid textlock; +--- * to avoid infinite recursion: +--- get_folds_levels → parse → _do_callback → on_changedtree → get_folds_levels. +---@param bufnr integer +---@param fn function +local function schedule_if_loaded(bufnr, fn) + vim.schedule(function() + if not api.nvim_buf_is_loaded(bufnr) then + return + end + fn() + end) +end + +---@param bufnr integer +---@param foldinfo TS.FoldInfo +---@param tree_changes Range4[] +local function on_changedtree(bufnr, foldinfo, tree_changes) + schedule_if_loaded(bufnr, function() + for _, change in ipairs(tree_changes) do + local srow, _, erow = Range.unpack4(change) + get_folds_levels(bufnr, foldinfo, srow, erow) + end + if #tree_changes > 0 then + foldupdate(bufnr) + end + end) +end + +---@param bufnr integer +---@param foldinfo TS.FoldInfo +---@param start_row integer +---@param old_row integer +---@param new_row integer +local function on_bytes(bufnr, foldinfo, start_row, old_row, new_row) + local end_row_old = start_row + old_row + local end_row_new = start_row + new_row + + if new_row ~= old_row then + if new_row < old_row then + foldinfo:remove_range(end_row_new, end_row_old) + else + foldinfo:add_range(start_row, end_row_new) + end + schedule_if_loaded(bufnr, function() + get_folds_levels(bufnr, foldinfo, start_row, end_row_new) + foldupdate(bufnr) + end) + end +end + +---@package +---@param lnum integer|nil +---@return string +function M.foldexpr(lnum) + lnum = lnum or vim.v.lnum + local bufnr = api.nvim_get_current_buf() + + local parser = vim.F.npcall(ts.get_parser, bufnr) + if not parser then + return '0' + end + + if not foldinfos[bufnr] then + foldinfos[bufnr] = FoldInfo.new() + get_folds_levels(bufnr, foldinfos[bufnr]) + + parser:register_cbs({ + on_changedtree = function(tree_changes) + on_changedtree(bufnr, foldinfos[bufnr], tree_changes) + end, + + on_bytes = function(_, _, start_row, _, _, old_row, _, _, new_row, _, _) + on_bytes(bufnr, foldinfos[bufnr], start_row, old_row, new_row) + end, + + on_detach = function() + foldinfos[bufnr] = nil + end, + }) + end + + return foldinfos[bufnr].levels[lnum] or '0' +end + +---@package +---@return { [1]: string, [2]: string[] }[]|string +function M.foldtext() + local foldstart = vim.v.foldstart + local bufnr = api.nvim_get_current_buf() + + ---@type boolean, LanguageTree + local ok, parser = pcall(ts.get_parser, bufnr) + if not ok then + return vim.fn.foldtext() + end + + local query = ts.query.get(parser:lang(), 'highlights') + if not query then + return vim.fn.foldtext() + end + + local tree = parser:parse({ foldstart - 1, foldstart })[1] + + local line = api.nvim_buf_get_lines(bufnr, foldstart - 1, foldstart, false)[1] + if not line then + return vim.fn.foldtext() + end + + ---@type { [1]: string, [2]: string[], range: { [1]: integer, [2]: integer } }[] | { [1]: string, [2]: string[] }[] + local result = {} + + local line_pos = 0 + + for id, node, metadata in query:iter_captures(tree:root(), 0, foldstart - 1, foldstart) do + local name = query.captures[id] + local start_row, start_col, end_row, end_col = node:range() + + local priority = tonumber(metadata.priority or vim.highlight.priorities.treesitter) + + if start_row == foldstart - 1 and end_row == foldstart - 1 then + -- check for characters ignored by treesitter + if start_col > line_pos then + table.insert(result, { + line:sub(line_pos + 1, start_col), + {}, + range = { line_pos, start_col }, + }) + end + line_pos = end_col + + local text = line:sub(start_col + 1, end_col) + table.insert(result, { text, { { '@' .. name, priority } }, range = { start_col, end_col } }) + end + end + + local i = 1 + while i <= #result do + -- find first capture that is not in current range and apply highlights on the way + local j = i + 1 + while + j <= #result + and result[j].range[1] >= result[i].range[1] + and result[j].range[2] <= result[i].range[2] + do + for k, v in ipairs(result[i][2]) do + if not vim.tbl_contains(result[j][2], v) then + table.insert(result[j][2], k, v) + end + end + j = j + 1 + end + + -- remove the parent capture if it is split into children + if j > i + 1 then + table.remove(result, i) + else + -- highlights need to be sorted by priority, on equal prio, the deeper nested capture (earlier + -- in list) should be considered higher prio + if #result[i][2] > 1 then + table.sort(result[i][2], function(a, b) + return a[2] < b[2] + end) + end + + result[i][2] = vim.tbl_map(function(tbl) + return tbl[1] + end, result[i][2]) + result[i] = { result[i][1], result[i][2] } + + i = i + 1 + end + end + + return result +end + +return M diff --git a/runtime/lua/vim/treesitter/_meta.lua b/runtime/lua/vim/treesitter/_meta.lua new file mode 100644 index 0000000000..80c998b555 --- /dev/null +++ b/runtime/lua/vim/treesitter/_meta.lua @@ -0,0 +1,80 @@ +---@meta + +---@class TSNode: userdata +---@field id fun(self: TSNode): string +---@field tree fun(self: TSNode): TSTree +---@field range fun(self: TSNode, include_bytes: false?): integer, integer, integer, integer +---@field range fun(self: TSNode, include_bytes: true): integer, integer, integer, integer, integer, integer +---@field start fun(self: TSNode): integer, integer, integer +---@field end_ fun(self: TSNode): integer, integer, integer +---@field type fun(self: TSNode): string +---@field symbol fun(self: TSNode): integer +---@field named fun(self: TSNode): boolean +---@field missing fun(self: TSNode): boolean +---@field extra fun(self: TSNode): boolean +---@field child_count fun(self: TSNode): integer +---@field named_child_count fun(self: TSNode): integer +---@field child fun(self: TSNode, index: integer): TSNode? +---@field named_child fun(self: TSNode, index: integer): TSNode? +---@field descendant_for_range fun(self: TSNode, start_row: integer, start_col: integer, end_row: integer, end_col: integer): TSNode? +---@field named_descendant_for_range fun(self: TSNode, start_row: integer, start_col: integer, end_row: integer, end_col: integer): TSNode? +---@field parent fun(self: TSNode): TSNode? +---@field next_sibling fun(self: TSNode): TSNode? +---@field prev_sibling fun(self: TSNode): TSNode? +---@field next_named_sibling fun(self: TSNode): TSNode? +---@field prev_named_sibling fun(self: TSNode): TSNode? +---@field named_children fun(self: TSNode): TSNode[] +---@field has_changes fun(self: TSNode): boolean +---@field has_error fun(self: TSNode): boolean +---@field sexpr fun(self: TSNode): string +---@field equal fun(self: TSNode, other: TSNode): boolean +---@field iter_children fun(self: TSNode): fun(): TSNode, string +---@field field fun(self: TSNode, name: string): TSNode[] +---@field byte_length fun(self: TSNode): integer +local TSNode = {} + +---@param query userdata +---@param captures true +---@param start? integer +---@param end_? integer +---@param opts? table +---@return fun(): integer, TSNode, any +function TSNode:_rawquery(query, captures, start, end_, opts) end + +---@param query userdata +---@param captures false +---@param start? integer +---@param end_? integer +---@param opts? table +---@return fun(): string, any +function TSNode:_rawquery(query, captures, start, end_, opts) end + +---@alias TSLoggerCallback fun(logtype: 'parse'|'lex', msg: string) + +---@class TSParser +---@field parse fun(self: TSParser, tree: TSTree?, source: integer|string, include_bytes: true): TSTree, Range6[] +---@field parse fun(self: TSParser, tree: TSTree?, source: integer|string, include_bytes: false|nil): TSTree, Range4[] +---@field reset fun(self: TSParser) +---@field included_ranges fun(self: TSParser, include_bytes: boolean?): integer[] +---@field set_included_ranges fun(self: TSParser, ranges: (Range6|TSNode)[]) +---@field set_timeout fun(self: TSParser, timeout: integer) +---@field timeout fun(self: TSParser): integer +---@field _set_logger fun(self: TSParser, lex: boolean, parse: boolean, cb: TSLoggerCallback) +---@field _logger fun(self: TSParser): TSLoggerCallback + +---@class TSTree +---@field root fun(self: TSTree): TSNode +---@field edit fun(self: TSTree, _: integer, _: integer, _: integer, _: integer, _: integer, _: integer, _: integer, _: integer, _:integer) +---@field copy fun(self: TSTree): TSTree +---@field included_ranges fun(self: TSTree, include_bytes: true): Range6[] +---@field included_ranges fun(self: TSTree, include_bytes: false): Range4[] + +---@return integer +vim._ts_get_language_version = function() end + +---@return integer +vim._ts_get_minimum_language_version = function() end + +---@param lang string +---@return TSParser +vim._create_ts_parser = function(lang) end diff --git a/runtime/lua/vim/treesitter/_query_linter.lua b/runtime/lua/vim/treesitter/_query_linter.lua new file mode 100644 index 0000000000..87d74789a3 --- /dev/null +++ b/runtime/lua/vim/treesitter/_query_linter.lua @@ -0,0 +1,249 @@ +local api = vim.api + +local namespace = api.nvim_create_namespace('vim.treesitter.query_linter') + +local M = {} + +--- @class QueryLinterNormalizedOpts +--- @field langs string[] +--- @field clear boolean + +--- @alias vim.treesitter.ParseError {msg: string, range: Range4} + +--- Contains language dependent context for the query linter +--- @class QueryLinterLanguageContext +--- @field lang string? Current `lang` of the targeted parser +--- @field parser_info table? Parser info returned by vim.treesitter.language.inspect +--- @field is_first_lang boolean Whether this is the first language of a linter run checking queries for multiple `langs` + +--- Adds a diagnostic for node in the query buffer +--- @param diagnostics Diagnostic[] +--- @param range Range4 +--- @param lint string +--- @param lang string? +local function add_lint_for_node(diagnostics, range, lint, lang) + local message = lint:gsub('\n', ' ') + diagnostics[#diagnostics + 1] = { + lnum = range[1], + end_lnum = range[3], + col = range[2], + end_col = range[4], + severity = vim.diagnostic.ERROR, + message = message, + source = lang, + } +end + +--- Determines the target language of a query file by its path: <lang>/<query_type>.scm +--- @param buf integer +--- @return string? +local function guess_query_lang(buf) + local filename = api.nvim_buf_get_name(buf) + if filename ~= '' then + return vim.F.npcall(vim.fn.fnamemodify, filename, ':p:h:t') + end +end + +--- @param buf integer +--- @param opts QueryLinterOpts|QueryLinterNormalizedOpts|nil +--- @return QueryLinterNormalizedOpts +local function normalize_opts(buf, opts) + opts = opts or {} + if not opts.langs then + opts.langs = guess_query_lang(buf) + end + + if type(opts.langs) ~= 'table' then + --- @diagnostic disable-next-line:assign-type-mismatch + opts.langs = { opts.langs } + end + + --- @cast opts QueryLinterNormalizedOpts + opts.langs = opts.langs or {} + return opts +end + +local lint_query = [[;; query + (program [(named_node) (list) (grouping)] @toplevel) + (named_node + name: _ @node.named) + (anonymous_node + name: _ @node.anonymous) + (field_definition + name: (identifier) @field) + (predicate + name: (identifier) @predicate.name + type: (predicate_type) @predicate.type) + (ERROR) @error +]] + +--- @param err string +--- @param node TSNode +--- @return vim.treesitter.ParseError +local function get_error_entry(err, node) + local start_line, start_col = node:range() + local line_offset, col_offset, msg = err:gmatch('.-:%d+: Query error at (%d+):(%d+)%. ([^:]+)')() ---@type string, string, string + start_line, start_col = + start_line + tonumber(line_offset) - 1, start_col + tonumber(col_offset) - 1 + local end_line, end_col = start_line, start_col + if msg:match('^Invalid syntax') or msg:match('^Impossible') then + -- Use the length of the underlined node + local underlined = vim.split(err, '\n')[2] + end_col = end_col + #underlined + elseif msg:match('^Invalid') then + -- Use the length of the problematic type/capture/field + end_col = end_col + #msg:match('"([^"]+)"') + end + + return { + msg = msg, + range = { start_line, start_col, end_line, end_col }, + } +end + +--- @param node TSNode +--- @param buf integer +--- @param lang string +local function hash_parse(node, buf, lang) + return tostring(node:id()) .. tostring(buf) .. tostring(vim.b[buf].changedtick) .. lang +end + +--- @param node TSNode +--- @param buf integer +--- @param lang string +--- @return vim.treesitter.ParseError? +local parse = vim.func._memoize(hash_parse, function(node, buf, lang) + local query_text = vim.treesitter.get_node_text(node, buf) + local ok, err = pcall(vim.treesitter.query.parse, lang, query_text) ---@type boolean|vim.treesitter.ParseError, string|Query + + if not ok and type(err) == 'string' then + return get_error_entry(err, node) + end +end) + +--- @param buf integer +--- @param match table<integer,TSNode> +--- @param query Query +--- @param lang_context QueryLinterLanguageContext +--- @param diagnostics Diagnostic[] +local function lint_match(buf, match, query, lang_context, diagnostics) + local lang = lang_context.lang + local parser_info = lang_context.parser_info + + for id, node in pairs(match) do + local cap_id = query.captures[id] + + -- perform language-independent checks only for first lang + if lang_context.is_first_lang and cap_id == 'error' then + local node_text = vim.treesitter.get_node_text(node, buf):gsub('\n', ' ') + add_lint_for_node(diagnostics, { node:range() }, 'Syntax error: ' .. node_text) + end + + -- other checks rely on Neovim parser introspection + if lang and parser_info and cap_id == 'toplevel' then + local err = parse(node, buf, lang) + if err then + add_lint_for_node(diagnostics, err.range, err.msg, lang) + end + end + end +end + +--- @private +--- @param buf integer Buffer to lint +--- @param opts QueryLinterOpts|QueryLinterNormalizedOpts|nil Options for linting +function M.lint(buf, opts) + if buf == 0 then + buf = api.nvim_get_current_buf() + end + + local diagnostics = {} + local query = vim.treesitter.query.parse('query', lint_query) + + opts = normalize_opts(buf, opts) + + -- perform at least one iteration even with no langs to perform language independent checks + for i = 1, math.max(1, #opts.langs) do + local lang = opts.langs[i] + + --- @type (table|nil) + local parser_info = vim.F.npcall(vim.treesitter.language.inspect, lang) + + local parser = vim.treesitter.get_parser(buf) + parser:parse() + parser:for_each_tree(function(tree, ltree) + if ltree:lang() == 'query' then + for _, match, _ in query:iter_matches(tree:root(), buf, 0, -1) do + local lang_context = { + lang = lang, + parser_info = parser_info, + is_first_lang = i == 1, + } + lint_match(buf, match, query, lang_context, diagnostics) + end + end + end) + end + + vim.diagnostic.set(namespace, buf, diagnostics) +end + +--- @private +--- @param buf integer +function M.clear(buf) + vim.diagnostic.reset(namespace, buf) +end + +--- @private +--- @param findstart integer +--- @param base string +function M.omnifunc(findstart, base) + if findstart == 1 then + local result = + api.nvim_get_current_line():sub(1, api.nvim_win_get_cursor(0)[2]):find('["#%-%w]*$') + return result - 1 + end + + local buf = api.nvim_get_current_buf() + local query_lang = guess_query_lang(buf) + + local ok, parser_info = pcall(vim.treesitter.language.inspect, query_lang) + if not ok then + return -2 + end + + local items = {} + for _, f in pairs(parser_info.fields) do + if f:find(base, 1, true) then + table.insert(items, f .. ':') + end + end + for _, p in pairs(vim.treesitter.query.list_predicates()) do + local text = '#' .. p + local found = text:find(base, 1, true) + if found and found <= 2 then -- with or without '#' + table.insert(items, text) + end + text = '#not-' .. p + found = text:find(base, 1, true) + if found and found <= 2 then -- with or without '#' + table.insert(items, text) + end + end + for _, p in pairs(vim.treesitter.query.list_directives()) do + local text = '#' .. p + local found = text:find(base, 1, true) + if found and found <= 2 then -- with or without '#' + table.insert(items, text) + end + end + for _, s in pairs(parser_info.symbols) do + local text = s[2] and s[1] or '"' .. s[1]:gsub([[\]], [[\\]]) .. '"' ---@type string + if text:find(base, 1, true) then + table.insert(items, text) + end + end + return { words = items, refresh = 'always' } +end + +return M diff --git a/runtime/lua/vim/treesitter/_range.lua b/runtime/lua/vim/treesitter/_range.lua new file mode 100644 index 0000000000..8d727c3c52 --- /dev/null +++ b/runtime/lua/vim/treesitter/_range.lua @@ -0,0 +1,193 @@ +local api = vim.api + +local M = {} + +---@class Range2 +---@field [1] integer start row +---@field [2] integer end row + +---@class Range4 +---@field [1] integer start row +---@field [2] integer start column +---@field [3] integer end row +---@field [4] integer end column + +---@class Range6 +---@field [1] integer start row +---@field [2] integer start column +---@field [3] integer start bytes +---@field [4] integer end row +---@field [5] integer end column +---@field [6] integer end bytes + +---@alias Range Range2|Range4|Range6 + +---@private +---@param a_row integer +---@param a_col integer +---@param b_row integer +---@param b_col integer +---@return integer +--- 1: a > b +--- 0: a == b +--- -1: a < b +local function cmp_pos(a_row, a_col, b_row, b_col) + if a_row == b_row then + if a_col > b_col then + return 1 + elseif a_col < b_col then + return -1 + else + return 0 + end + elseif a_row > b_row then + return 1 + end + + return -1 +end + +M.cmp_pos = { + lt = function(...) + return cmp_pos(...) == -1 + end, + le = function(...) + return cmp_pos(...) ~= 1 + end, + gt = function(...) + return cmp_pos(...) == 1 + end, + ge = function(...) + return cmp_pos(...) ~= -1 + end, + eq = function(...) + return cmp_pos(...) == 0 + end, + ne = function(...) + return cmp_pos(...) ~= 0 + end, +} + +setmetatable(M.cmp_pos, { __call = cmp_pos }) + +---@private +---Check if a variable is a valid range object +---@param r any +---@return boolean +function M.validate(r) + if type(r) ~= 'table' or #r ~= 6 and #r ~= 4 then + return false + end + + for _, e in + ipairs(r --[[@as any[] ]]) + do + if type(e) ~= 'number' then + return false + end + end + + return true +end + +---@private +---@param r1 Range +---@param r2 Range +---@return boolean +function M.intercepts(r1, r2) + local srow_1, scol_1, erow_1, ecol_1 = M.unpack4(r1) + local srow_2, scol_2, erow_2, ecol_2 = M.unpack4(r2) + + -- r1 is above r2 + if M.cmp_pos.le(erow_1, ecol_1, srow_2, scol_2) then + return false + end + + -- r1 is below r2 + if M.cmp_pos.ge(srow_1, scol_1, erow_2, ecol_2) then + return false + end + + return true +end + +---@private +---@param r Range +---@return integer, integer, integer, integer +function M.unpack4(r) + if #r == 2 then + return r[1], 0, r[2], 0 + end + local off_1 = #r == 6 and 1 or 0 + return r[1], r[2], r[3 + off_1], r[4 + off_1] +end + +---@private +---@param r Range6 +---@return integer, integer, integer, integer, integer, integer +function M.unpack6(r) + return r[1], r[2], r[3], r[4], r[5], r[6] +end + +---@private +---@param r1 Range +---@param r2 Range +---@return boolean whether r1 contains r2 +function M.contains(r1, r2) + local srow_1, scol_1, erow_1, ecol_1 = M.unpack4(r1) + local srow_2, scol_2, erow_2, ecol_2 = M.unpack4(r2) + + -- start doesn't fit + if M.cmp_pos.gt(srow_1, scol_1, srow_2, scol_2) then + return false + end + + -- end doesn't fit + if M.cmp_pos.lt(erow_1, ecol_1, erow_2, ecol_2) then + return false + end + + return true +end + +--- @param source integer|string +--- @param index integer +--- @return integer +local function get_offset(source, index) + if index == 0 then + return 0 + end + + if type(source) == 'number' then + return api.nvim_buf_get_offset(source, index) + end + + local byte = 0 + local next_offset = source:gmatch('()\n') + local line = 1 + while line <= index do + byte = next_offset() --[[@as integer]] + line = line + 1 + end + + return byte +end + +---@private +---@param source integer|string +---@param range Range +---@return Range6 +function M.add_bytes(source, range) + if type(range) == 'table' and #range == 6 then + return range --[[@as Range6]] + end + + local start_row, start_col, end_row, end_col = M.unpack4(range) + -- TODO(vigoux): proper byte computation here, and account for EOL ? + local start_byte = get_offset(source, start_row) + start_col + local end_byte = get_offset(source, end_row) + end_col + + return { start_row, start_col, start_byte, end_row, end_col, end_byte } +end + +return M diff --git a/runtime/lua/vim/treesitter/dev.lua b/runtime/lua/vim/treesitter/dev.lua new file mode 100644 index 0000000000..69ddc9b558 --- /dev/null +++ b/runtime/lua/vim/treesitter/dev.lua @@ -0,0 +1,645 @@ +local api = vim.api + +---@class TSDevModule +local M = {} + +---@class TSTreeView +---@field ns integer API namespace +---@field opts table Options table with the following keys: +--- - anon (boolean): If true, display anonymous nodes +--- - lang (boolean): If true, display the language alongside each node +--- - indent (number): Number of spaces to indent nested lines. Default is 2. +---@field nodes TSP.Node[] +---@field named TSP.Node[] +local TSTreeView = {} + +---@class TSP.Node +---@field id integer Node id +---@field text string Node text +---@field named boolean True if this is a named (non-anonymous) node +---@field depth integer Depth of the node within the tree +---@field lnum integer Beginning line number of this node in the source buffer +---@field col integer Beginning column number of this node in the source buffer +---@field end_lnum integer Final line number of this node in the source buffer +---@field end_col integer Final column number of this node in the source buffer +---@field lang string Source language of this node +---@field root TSNode + +---@class TSP.Injection +---@field lang string Source language of this injection +---@field root TSNode Root node of the injection + +--- Traverse all child nodes starting at {node}. +--- +--- This is a recursive function. The {depth} parameter indicates the current recursion level. +--- {lang} is a string indicating the language of the tree currently being traversed. Each traversed +--- node is added to {tree}. When recursion completes, {tree} is an array of all nodes in the order +--- they were visited. +--- +--- {injections} is a table mapping node ids from the primary tree to language tree injections. Each +--- injected language has a series of trees nested within the primary language's tree, and the root +--- node of each of these trees is contained within a node in the primary tree. The {injections} +--- table maps nodes in the primary tree to root nodes of injected trees. +--- +---@param node TSNode Starting node to begin traversal |tsnode| +---@param depth integer Current recursion depth +---@param lang string Language of the tree currently being traversed +---@param injections table<string, TSP.Injection> Mapping of node ids to root nodes +--- of injected language trees (see explanation above) +---@param tree TSP.Node[] Output table containing a list of tables each representing a node in the tree +local function traverse(node, depth, lang, injections, tree) + local injection = injections[node:id()] + if injection then + traverse(injection.root, depth, injection.lang, injections, tree) + end + + for child, field in node:iter_children() do + local type = child:type() + local lnum, col, end_lnum, end_col = child:range() + local named = child:named() + local text ---@type string + if named then + if field then + text = string.format('%s: (%s', field, type) + else + text = string.format('(%s', type) + end + else + text = string.format('"%s"', type:gsub('\n', '\\n'):gsub('"', '\\"')) + end + + table.insert(tree, { + id = child:id(), + text = text, + named = named, + depth = depth, + lnum = lnum, + col = col, + end_lnum = end_lnum, + end_col = end_col, + lang = lang, + }) + + traverse(child, depth + 1, lang, injections, tree) + + if named then + tree[#tree].text = string.format('%s)', tree[#tree].text) + end + end + + return tree +end + +--- Create a new treesitter view. +--- +---@param bufnr integer Source buffer number +---@param lang string|nil Language of source buffer +--- +---@return TSTreeView|nil +---@return string|nil Error message, if any +--- +---@package +function TSTreeView:new(bufnr, lang) + local ok, parser = pcall(vim.treesitter.get_parser, bufnr or 0, lang) + if not ok then + return nil, 'No parser available for the given buffer' + end + + -- For each child tree (injected language), find the root of the tree and locate the node within + -- the primary tree that contains that root. Add a mapping from the node in the primary tree to + -- the root in the child tree to the {injections} table. + local root = parser:parse(true)[1]:root() + local injections = {} ---@type table<string, TSP.Injection> + + parser:for_each_tree(function(parent_tree, parent_ltree) + local parent = parent_tree:root() + for _, child in pairs(parent_ltree:children()) do + child:for_each_tree(function(tree, ltree) + local r = tree:root() + local node = assert(parent:named_descendant_for_range(r:range())) + local id = node:id() + if not injections[id] or r:byte_length() > injections[id].root:byte_length() then + injections[id] = { + lang = ltree:lang(), + root = r, + } + end + end) + end + end) + + local nodes = traverse(root, 0, parser:lang(), injections, {}) + + local named = {} ---@type TSP.Node[] + for _, v in ipairs(nodes) do + if v.named then + named[#named + 1] = v + end + end + + local t = { + ns = api.nvim_create_namespace('treesitter/dev-inspect'), + nodes = nodes, + named = named, + opts = { + anon = false, + lang = false, + indent = 2, + }, + } + + setmetatable(t, self) + self.__index = self + return t +end + +local decor_ns = api.nvim_create_namespace('ts.dev') + +---@param lnum integer +---@param col integer +---@param end_lnum integer +---@param end_col integer +---@return string +local function get_range_str(lnum, col, end_lnum, end_col) + if lnum == end_lnum then + return string.format('[%d:%d - %d]', lnum + 1, col + 1, end_col) + end + return string.format('[%d:%d - %d:%d]', lnum + 1, col + 1, end_lnum + 1, end_col) +end + +---@param w integer +---@return boolean closed Whether the window was closed. +local function close_win(w) + if api.nvim_win_is_valid(w) then + api.nvim_win_close(w, true) + return true + end + + return false +end + +---@param w integer +---@param b integer +local function set_dev_properties(w, b) + vim.wo[w].scrolloff = 5 + vim.wo[w].wrap = false + vim.wo[w].foldmethod = 'manual' -- disable folding + vim.bo[b].buflisted = false + vim.bo[b].buftype = 'nofile' + vim.bo[b].bufhidden = 'wipe' + vim.bo[b].filetype = 'query' +end + +--- Updates the cursor position in the inspector to match the node under the cursor. +--- +--- @param treeview TSTreeView +--- @param lang string +--- @param source_buf integer +--- @param inspect_buf integer +--- @param inspect_win integer +--- @param pos? { [1]: integer, [2]: integer } +local function set_inspector_cursor(treeview, lang, source_buf, inspect_buf, inspect_win, pos) + api.nvim_buf_clear_namespace(inspect_buf, treeview.ns, 0, -1) + + local cursor_node = vim.treesitter.get_node({ + bufnr = source_buf, + lang = lang, + pos = pos, + ignore_injections = false, + }) + if not cursor_node then + return + end + + local cursor_node_id = cursor_node:id() + for i, v in treeview:iter() do + if v.id == cursor_node_id then + local start = v.depth * treeview.opts.indent ---@type integer + local end_col = start + #v.text + api.nvim_buf_set_extmark(inspect_buf, treeview.ns, i - 1, start, { + end_col = end_col, + hl_group = 'Visual', + }) + api.nvim_win_set_cursor(inspect_win, { i, 0 }) + break + end + end +end + +--- Write the contents of this View into {bufnr}. +--- +---@param bufnr integer Buffer number to write into. +---@package +function TSTreeView:draw(bufnr) + vim.bo[bufnr].modifiable = true + local lines = {} ---@type string[] + local lang_hl_marks = {} ---@type table[] + + for _, item in self:iter() do + local range_str = get_range_str(item.lnum, item.col, item.end_lnum, item.end_col) + local lang_str = self.opts.lang and string.format(' %s', item.lang) or '' + local line = string.format( + '%s%s ; %s%s', + string.rep(' ', item.depth * self.opts.indent), + item.text, + range_str, + lang_str + ) + + if self.opts.lang then + lang_hl_marks[#lang_hl_marks + 1] = { + col = #line - #lang_str, + end_col = #line, + } + end + + lines[#lines + 1] = line + end + + api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) + + api.nvim_buf_clear_namespace(bufnr, decor_ns, 0, -1) + + for i, m in ipairs(lang_hl_marks) do + api.nvim_buf_set_extmark(bufnr, decor_ns, i - 1, m.col, { + hl_group = 'Title', + end_col = m.end_col, + }) + end + + vim.bo[bufnr].modifiable = false +end + +--- Get node {i} from this View. +--- +--- The node number is dependent on whether or not anonymous nodes are displayed. +--- +---@param i integer Node number to get +---@return TSP.Node +---@package +function TSTreeView:get(i) + local t = self.opts.anon and self.nodes or self.named + return t[i] +end + +--- Iterate over all of the nodes in this View. +--- +---@return (fun(): integer, TSP.Node) Iterator over all nodes in this View +---@return table +---@return integer +---@package +function TSTreeView:iter() + return ipairs(self.opts.anon and self.nodes or self.named) +end + +--- @class InspectTreeOpts +--- @field lang string? The language of the source buffer. If omitted, the +--- filetype of the source buffer is used. +--- @field bufnr integer? Buffer to draw the tree into. If omitted, a new +--- buffer is created. +--- @field winid integer? Window id to display the tree buffer in. If omitted, +--- a new window is created with {command}. +--- @field command string? Vimscript command to create the window. Default +--- value is "60vnew". Only used when {winid} is nil. +--- @field title (string|fun(bufnr:integer):string|nil) Title of the window. If a +--- function, it accepts the buffer number of the source +--- buffer as its only argument and should return a string. + +--- @private +--- +--- @param opts InspectTreeOpts? +function M.inspect_tree(opts) + vim.validate({ + opts = { opts, 't', true }, + }) + + opts = opts or {} + + local buf = api.nvim_get_current_buf() + local win = api.nvim_get_current_win() + local treeview = assert(TSTreeView:new(buf, opts.lang)) + + -- Close any existing inspector window + if vim.b[buf].dev_inspect then + close_win(vim.b[buf].dev_inspect) + end + + local w = opts.winid + if not w then + vim.cmd(opts.command or '60vnew') + w = api.nvim_get_current_win() + end + + local b = opts.bufnr + if b then + api.nvim_win_set_buf(w, b) + else + b = api.nvim_win_get_buf(w) + end + + vim.b[buf].dev_inspect = w + vim.b[b].dev_base = win -- base window handle + vim.b[b].disable_query_linter = true + set_dev_properties(w, b) + + local title --- @type string? + local opts_title = opts.title + if not opts_title then + local bufname = api.nvim_buf_get_name(buf) + title = string.format('Syntax tree for %s', vim.fn.fnamemodify(bufname, ':.')) + elseif type(opts_title) == 'function' then + title = opts_title(buf) + end + + assert(type(title) == 'string', 'Window title must be a string') + api.nvim_buf_set_name(b, title) + + treeview:draw(b) + + local cursor = api.nvim_win_get_cursor(win) + set_inspector_cursor(treeview, opts.lang, buf, b, w, { cursor[1] - 1, cursor[2] }) + + api.nvim_buf_clear_namespace(buf, treeview.ns, 0, -1) + api.nvim_buf_set_keymap(b, 'n', '<CR>', '', { + desc = 'Jump to the node under the cursor in the source buffer', + callback = function() + local row = api.nvim_win_get_cursor(w)[1] + local pos = treeview:get(row) + api.nvim_set_current_win(win) + api.nvim_win_set_cursor(win, { pos.lnum + 1, pos.col }) + end, + }) + api.nvim_buf_set_keymap(b, 'n', 'a', '', { + desc = 'Toggle anonymous nodes', + callback = function() + local row, col = unpack(api.nvim_win_get_cursor(w)) ---@type integer, integer + local curnode = treeview:get(row) + while curnode and not curnode.named do + row = row - 1 + curnode = treeview:get(row) + end + + treeview.opts.anon = not treeview.opts.anon + treeview:draw(b) + + if not curnode then + return + end + + local id = curnode.id + for i, node in treeview:iter() do + if node.id == id then + api.nvim_win_set_cursor(w, { i, col }) + break + end + end + end, + }) + api.nvim_buf_set_keymap(b, 'n', 'I', '', { + desc = 'Toggle language display', + callback = function() + treeview.opts.lang = not treeview.opts.lang + treeview:draw(b) + end, + }) + api.nvim_buf_set_keymap(b, 'n', 'o', '', { + desc = 'Toggle query editor', + callback = function() + local edit_w = vim.b[buf].dev_edit + if not edit_w or not close_win(edit_w) then + M.edit_query() + end + end, + }) + + local group = api.nvim_create_augroup('treesitter/dev', {}) + + api.nvim_create_autocmd('CursorMoved', { + group = group, + buffer = b, + callback = function() + if not api.nvim_buf_is_loaded(buf) then + return true + end + + api.nvim_buf_clear_namespace(buf, treeview.ns, 0, -1) + local row = api.nvim_win_get_cursor(w)[1] + local pos = treeview:get(row) + api.nvim_buf_set_extmark(buf, treeview.ns, pos.lnum, pos.col, { + end_row = pos.end_lnum, + end_col = math.max(0, pos.end_col), + hl_group = 'Visual', + }) + + local topline, botline = vim.fn.line('w0', win), vim.fn.line('w$', win) + + -- Move the cursor if highlighted range is completely out of view + if pos.lnum < topline and pos.end_lnum < topline then + api.nvim_win_set_cursor(win, { pos.end_lnum + 1, 0 }) + elseif pos.lnum > botline and pos.end_lnum > botline then + api.nvim_win_set_cursor(win, { pos.lnum + 1, 0 }) + end + end, + }) + + api.nvim_create_autocmd('CursorMoved', { + group = group, + buffer = buf, + callback = function() + if not api.nvim_buf_is_loaded(b) then + return true + end + + set_inspector_cursor(treeview, opts.lang, buf, b, w) + end, + }) + + api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, { + group = group, + buffer = buf, + callback = function() + if not api.nvim_buf_is_loaded(b) then + return true + end + + treeview = assert(TSTreeView:new(buf, opts.lang)) + treeview:draw(b) + end, + }) + + api.nvim_create_autocmd('BufLeave', { + group = group, + buffer = b, + callback = function() + if not api.nvim_buf_is_loaded(buf) then + return true + end + api.nvim_buf_clear_namespace(buf, treeview.ns, 0, -1) + end, + }) + + api.nvim_create_autocmd('BufLeave', { + group = group, + buffer = buf, + callback = function() + if not api.nvim_buf_is_loaded(b) then + return true + end + api.nvim_buf_clear_namespace(b, treeview.ns, 0, -1) + end, + }) + + api.nvim_create_autocmd('BufHidden', { + group = group, + buffer = buf, + once = true, + callback = function() + close_win(w) + end, + }) +end + +local edit_ns = api.nvim_create_namespace('treesitter/dev-edit') + +---@param query_win integer +---@param base_win integer +---@param lang string +local function update_editor_highlights(query_win, base_win, lang) + local base_buf = api.nvim_win_get_buf(base_win) + local query_buf = api.nvim_win_get_buf(query_win) + local parser = vim.treesitter.get_parser(base_buf, lang) + api.nvim_buf_clear_namespace(base_buf, edit_ns, 0, -1) + local query_content = table.concat(api.nvim_buf_get_lines(query_buf, 0, -1, false), '\n') + + local ok_query, query = pcall(vim.treesitter.query.parse, lang, query_content) + if not ok_query then + return + end + + local cursor_word = vim.fn.expand('<cword>') --[[@as string]] + -- Only highlight captures if the cursor is on a capture name + if cursor_word:find('^@') == nil then + return + end + -- Remove the '@' from the cursor word + cursor_word = cursor_word:sub(2) + local topline, botline = vim.fn.line('w0', base_win), vim.fn.line('w$', base_win) + for id, node in query:iter_captures(parser:trees()[1]:root(), base_buf, topline - 1, botline) do + local capture_name = query.captures[id] + if capture_name == cursor_word then + local lnum, col, end_lnum, end_col = node:range() + api.nvim_buf_set_extmark(base_buf, edit_ns, lnum, col, { + end_row = end_lnum, + end_col = end_col, + hl_group = 'Visual', + virt_text = { + { capture_name, 'Title' }, + }, + }) + end + end +end + +--- @private +--- @param lang? string language to open the query editor for. +function M.edit_query(lang) + local buf = api.nvim_get_current_buf() + local win = api.nvim_get_current_win() + + -- Close any existing editor window + if vim.b[buf].dev_edit then + close_win(vim.b[buf].dev_edit) + end + + local cmd = '60vnew' + -- If the inspector is open, place the editor above it. + local base_win = vim.b[buf].dev_base ---@type integer? + local base_buf = base_win and api.nvim_win_get_buf(base_win) + local inspect_win = base_buf and vim.b[base_buf].dev_inspect + if base_win and base_buf and api.nvim_win_is_valid(inspect_win) then + vim.api.nvim_set_current_win(inspect_win) + buf = base_buf + win = base_win + cmd = 'new' + end + vim.cmd(cmd) + + local ok, parser = pcall(vim.treesitter.get_parser, buf, lang) + if not ok then + return nil, 'No parser available for the given buffer' + end + lang = parser:lang() + + local query_win = api.nvim_get_current_win() + local query_buf = api.nvim_win_get_buf(query_win) + + vim.b[buf].dev_edit = query_win + vim.bo[query_buf].omnifunc = 'v:lua.vim.treesitter.query.omnifunc' + set_dev_properties(query_win, query_buf) + + -- Note that omnifunc guesses the language based on the containing folder, + -- so we add the parser's language to the buffer's name so that omnifunc + -- can infer the language later. + api.nvim_buf_set_name(query_buf, string.format('%s/query_editor.scm', lang)) + + local group = api.nvim_create_augroup('treesitter/dev-edit', {}) + api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, { + group = group, + buffer = query_buf, + desc = 'Update query editor diagnostics when the query changes', + callback = function() + vim.treesitter.query.lint(query_buf, { langs = lang, clear = false }) + end, + }) + api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave', 'CursorMoved', 'BufEnter' }, { + group = group, + buffer = query_buf, + desc = 'Update query editor highlights when the cursor moves', + callback = function() + if api.nvim_win_is_valid(win) then + update_editor_highlights(query_win, win, lang) + end + end, + }) + api.nvim_create_autocmd('BufLeave', { + group = group, + buffer = query_buf, + desc = 'Clear highlights when leaving the query editor', + callback = function() + api.nvim_buf_clear_namespace(buf, edit_ns, 0, -1) + end, + }) + api.nvim_create_autocmd('BufLeave', { + group = group, + buffer = buf, + desc = 'Clear the query editor highlights when leaving the source buffer', + callback = function() + if not api.nvim_buf_is_loaded(query_buf) then + return true + end + + api.nvim_buf_clear_namespace(query_buf, edit_ns, 0, -1) + end, + }) + api.nvim_create_autocmd('BufHidden', { + group = group, + buffer = buf, + desc = 'Close the editor window when the source buffer is hidden', + once = true, + callback = function() + close_win(query_win) + end, + }) + + api.nvim_buf_set_lines(query_buf, 0, -1, false, { + ';; Write queries here (see $VIMRUNTIME/queries/ for examples).', + ';; Move cursor to a capture ("@foo") to highlight matches in the source buffer.', + ';; Completion for grammar nodes is available (:help compl-omni)', + '', + '', + }) + vim.cmd('normal! G') + vim.cmd.startinsert() +end + +return M diff --git a/runtime/lua/vim/treesitter/health.lua b/runtime/lua/vim/treesitter/health.lua index c0a1eca0ce..ed1161e97f 100644 --- a/runtime/lua/vim/treesitter/health.lua +++ b/runtime/lua/vim/treesitter/health.lua @@ -2,30 +2,28 @@ local M = {} local ts = vim.treesitter local health = require('vim.health') ---- Lists the parsers currently installed ---- ----@return string[] list of parser files -function M.list_parsers() - return vim.api.nvim_get_runtime_file('parser/*', true) -end - --- Performs a healthcheck for treesitter integration function M.check() - local parsers = M.list_parsers() + local parsers = vim.api.nvim_get_runtime_file('parser/*', true) - health.report_info(string.format('Nvim runtime ABI version: %d', ts.language_version)) + health.info(string.format('Nvim runtime ABI version: %d', ts.language_version)) for _, parser in pairs(parsers) do local parsername = vim.fn.fnamemodify(parser, ':t:r') - local is_loadable, ret = pcall(ts.language.require_language, parsername) + local is_loadable, err_or_nil = pcall(ts.language.add, parsername) - if not is_loadable or not ret then - health.report_error( - string.format('Parser "%s" failed to load (path: %s): %s', parsername, parser, ret or '?') + if not is_loadable then + health.error( + string.format( + 'Parser "%s" failed to load (path: %s): %s', + parsername, + parser, + err_or_nil or '?' + ) ) - elseif ret then - local lang = ts.language.inspect_language(parsername) - health.report_ok( + else + local lang = ts.language.inspect(parsername) + health.ok( string.format('Parser: %-10s ABI: %d, path: %s', parsername, lang._abi_version, parser) ) end diff --git a/runtime/lua/vim/treesitter/highlighter.lua b/runtime/lua/vim/treesitter/highlighter.lua index d77a0d0d03..496193c6ed 100644 --- a/runtime/lua/vim/treesitter/highlighter.lua +++ b/runtime/lua/vim/treesitter/highlighter.lua @@ -1,17 +1,34 @@ -local a = vim.api -local query = require('vim.treesitter.query') +local api = vim.api +local query = vim.treesitter.query +local Range = require('vim.treesitter._range') + +---@alias TSHlIter fun(end_line: integer|nil): integer, TSNode, TSMetadata + +---@class TSHighlightState +---@field next_row integer +---@field iter TSHlIter|nil --- support reload for quick experimentation ---@class TSHighlighter +---@field active table<integer,TSHighlighter> +---@field bufnr integer +---@field orig_spelloptions string +---@field _highlight_states table<TSTree,TSHighlightState> +---@field _queries table<string,TSHighlighterQuery> +---@field tree LanguageTree +---@field redraw_count integer local TSHighlighter = rawget(vim.treesitter, 'TSHighlighter') or {} TSHighlighter.__index = TSHighlighter +--- @nodoc TSHighlighter.active = TSHighlighter.active or {} +---@class TSHighlighterQuery +---@field _query Query|nil +---@field hl_cache table<integer,integer> local TSHighlighterQuery = {} TSHighlighterQuery.__index = TSHighlighterQuery -local ns = a.nvim_create_namespace('treesitter/highlighter') +local ns = api.nvim_create_namespace('treesitter/highlighter') ---@private function TSHighlighterQuery.new(lang, query_string) @@ -22,7 +39,7 @@ function TSHighlighterQuery.new(lang, query_string) local name = self._query.captures[capture] local id = 0 if not vim.startswith(name, '_') then - id = a.nvim_get_hl_id_by_name('@' .. name .. '.' .. lang) + id = api.nvim_get_hl_id_by_name('@' .. name .. '.' .. lang) end rawset(table, capture, id) @@ -31,22 +48,24 @@ function TSHighlighterQuery.new(lang, query_string) }) if query_string then - self._query = query.parse_query(lang, query_string) + self._query = query.parse(lang, query_string) else - self._query = query.get_query(lang, 'highlights') + self._query = query.get(lang, 'highlights') end return self end ----@private +---@package function TSHighlighterQuery:query() return self._query end ---- Creates a new highlighter using @param tree +---@package +--- +--- Creates a highlighter for `tree`. --- ----@param tree LanguageTree |LanguageTree| parser object to use for highlighting +---@param tree LanguageTree parser object to use for highlighting ---@param opts (table|nil) Configuration of the highlighter: --- - queries table overwrite queries used by the highlighter ---@return TSHighlighter Created highlighter object @@ -57,27 +76,37 @@ function TSHighlighter.new(tree, opts) error('TSHighlighter can not be used with a string parser source.') end - opts = opts or {} + opts = opts or {} ---@type { queries: table<string,string> } self.tree = tree tree:register_cbs({ - on_changedtree = function(...) - self:on_changedtree(...) - end, on_bytes = function(...) self:on_bytes(...) end, - on_detach = function(...) - self:on_detach(...) + on_detach = function() + self:on_detach() end, }) - self.bufnr = tree:source() + tree:register_cbs({ + on_changedtree = function(...) + self:on_changedtree(...) + end, + on_child_removed = function(child) + child:for_each_tree(function(t) + self:on_changedtree(t:included_ranges(true)) + end) + end, + }, true) + + self.bufnr = tree:source() --[[@as integer]] self.edit_count = 0 self.redraw_count = 0 self.line_count = {} -- A map of highlight states. -- This state is kept during rendering across each line update. self._highlight_states = {} + + ---@type table<string,TSHighlighterQuery> self._queries = {} -- Queries for a specific language can be overridden by a custom @@ -103,7 +132,7 @@ function TSHighlighter.new(tree, opts) vim.cmd.runtime({ 'syntax/synload.vim', bang = true }) end - a.nvim_buf_call(self.bufnr, function() + api.nvim_buf_call(self.bufnr, function() vim.opt_local.spelloptions:append('noplainbuffer') end) @@ -112,6 +141,7 @@ function TSHighlighter.new(tree, opts) return self end +--- @nodoc --- Removes all internal references to the highlighter function TSHighlighter:destroy() if TSHighlighter.active[self.bufnr] then @@ -122,12 +152,14 @@ function TSHighlighter:destroy() vim.bo[self.bufnr].spelloptions = self.orig_spelloptions vim.b[self.bufnr].ts_highlight = nil if vim.g.syntax_on == 1 then - a.nvim_exec_autocmds('FileType', { group = 'syntaxset', buffer = self.bufnr }) + api.nvim_exec_autocmds('FileType', { group = 'syntaxset', buffer = self.bufnr }) end end end ----@private +---@package +---@param tstree TSTree +---@return TSHighlightState function TSHighlighter:get_highlight_state(tstree) if not self._highlight_states[tstree] then self._highlight_states[tstree] = { @@ -144,28 +176,31 @@ function TSHighlighter:reset_highlight_state() self._highlight_states = {} end ----@private +---@package +---@param start_row integer +---@param new_end integer function TSHighlighter:on_bytes(_, _, start_row, _, _, _, _, _, new_end) - a.nvim__buf_redraw_range(self.bufnr, start_row, start_row + new_end + 1) + api.nvim__buf_redraw_range(self.bufnr, start_row, start_row + new_end + 1) end ----@private +---@package function TSHighlighter:on_detach() self:destroy() end ----@private +---@package +---@param changes Range6[] function TSHighlighter:on_changedtree(changes) - for _, ch in ipairs(changes or {}) do - a.nvim__buf_redraw_range(self.bufnr, ch[1], ch[3] + 1) + for _, ch in ipairs(changes) do + api.nvim__buf_redraw_range(self.bufnr, ch[1], ch[4] + 1) end end --- Gets the query used for @param lang -- ----@private +---@package ---@param lang string Language used by the highlighter. ----@return Query +---@return TSHighlighterQuery function TSHighlighter:get_query(lang) if not self._queries[lang] then self._queries[lang] = TSHighlighterQuery.new(lang) @@ -174,7 +209,10 @@ function TSHighlighter:get_query(lang) return self._queries[lang] end ----@private +---@param self TSHighlighter +---@param buf integer +---@param line integer +---@param is_spell_nav boolean local function on_line_impl(self, buf, line, is_spell_nav) self.tree:for_each_tree(function(tstree, tree) if not tstree then @@ -203,45 +241,54 @@ local function on_line_impl(self, buf, line, is_spell_nav) end while line >= state.next_row do - local capture, node, metadata = state.iter() + local capture, node, metadata = state.iter(line) - if capture == nil then - break + local range = { root_end_row + 1, 0, root_end_row + 1, 0 } + if node then + range = vim.treesitter.get_range(node, buf, metadata and metadata[capture]) end - - local start_row, start_col, end_row, end_col = node:range() - local hl = highlighter_query.hl_cache[capture] - - local capture_name = highlighter_query:query().captures[capture] - local spell = nil - if capture_name == 'spell' then - spell = true - elseif capture_name == 'nospell' then - spell = false + local start_row, start_col, end_row, end_col = Range.unpack4(range) + + if capture then + local hl = highlighter_query.hl_cache[capture] + + local capture_name = highlighter_query:query().captures[capture] + local spell = nil ---@type boolean? + if capture_name == 'spell' then + spell = true + elseif capture_name == 'nospell' then + spell = false + end + + -- Give nospell a higher priority so it always overrides spell captures. + local spell_pri_offset = capture_name == 'nospell' and 1 or 0 + + if hl and end_row >= line and (not is_spell_nav or spell ~= nil) then + local priority = (tonumber(metadata.priority) or vim.highlight.priorities.treesitter) + + spell_pri_offset + api.nvim_buf_set_extmark(buf, ns, start_row, start_col, { + end_line = end_row, + end_col = end_col, + hl_group = hl, + ephemeral = true, + priority = priority, + conceal = metadata.conceal, + spell = spell, + }) + end end - -- Give nospell a higher priority so it always overrides spell captures. - local spell_pri_offset = capture_name == 'nospell' and 1 or 0 - - if hl and end_row >= line and (not is_spell_nav or spell ~= nil) then - a.nvim_buf_set_extmark(buf, ns, start_row, start_col, { - end_line = end_row, - end_col = end_col, - hl_group = hl, - ephemeral = true, - priority = (tonumber(metadata.priority) or 100) + spell_pri_offset, -- Low but leaves room below - conceal = metadata.conceal, - spell = spell, - }) - end if start_row > line then state.next_row = start_row end end - end, true) + end) end ---@private +---@param _win integer +---@param buf integer +---@param line integer function TSHighlighter._on_line(_, _win, buf, line, _) local self = TSHighlighter.active[buf] if not self then @@ -252,6 +299,9 @@ function TSHighlighter._on_line(_, _win, buf, line, _) end ---@private +---@param buf integer +---@param srow integer +---@param erow integer function TSHighlighter._on_spell_nav(_, _, buf, srow, _, erow, _) local self = TSHighlighter.active[buf] if not self then @@ -266,27 +316,22 @@ function TSHighlighter._on_spell_nav(_, _, buf, srow, _, erow, _) end ---@private -function TSHighlighter._on_buf(_, buf) - local self = TSHighlighter.active[buf] - if self then - self.tree:parse() - end -end - ----@private -function TSHighlighter._on_win(_, _win, buf, _topline) +---@param _win integer +---@param buf integer +---@param topline integer +---@param botline integer +function TSHighlighter._on_win(_, _win, buf, topline, botline) local self = TSHighlighter.active[buf] if not self then return false end - + self.tree:parse({ topline, botline + 1 }) self:reset_highlight_state() self.redraw_count = self.redraw_count + 1 return true end -a.nvim_set_decoration_provider(ns, { - on_buf = TSHighlighter._on_buf, +api.nvim_set_decoration_provider(ns, { on_win = TSHighlighter._on_win, on_line = TSHighlighter._on_line, _on_spell_nav = TSHighlighter._on_spell_nav, diff --git a/runtime/lua/vim/treesitter/language.lua b/runtime/lua/vim/treesitter/language.lua index c92d63b8c4..15bf666a1e 100644 --- a/runtime/lua/vim/treesitter/language.lua +++ b/runtime/lua/vim/treesitter/language.lua @@ -1,42 +1,132 @@ -local a = vim.api +local api = vim.api +---@class TSLanguageModule local M = {} ---- Asserts that a parser for the language {lang} is installed. +---@type table<string,string> +local ft_to_lang = { + help = 'vimdoc', +} + +--- Get the filetypes associated with the parser named {lang}. +--- @param lang string Name of parser +--- @return string[] filetypes +function M.get_filetypes(lang) + local r = {} ---@type string[] + for ft, p in pairs(ft_to_lang) do + if p == lang then + r[#r + 1] = ft + end + end + return r +end + +--- @param filetype string +--- @return string|nil +function M.get_lang(filetype) + if filetype == '' then + return + end + if ft_to_lang[filetype] then + return ft_to_lang[filetype] + end + -- support subfiletypes like html.glimmer + filetype = vim.split(filetype, '.', { plain = true })[1] + return ft_to_lang[filetype] +end + +---@deprecated +function M.require_language(lang, path, silent, symbol_name) + local opts = { + silent = silent, + path = path, + symbol_name = symbol_name, + } + + if silent then + local installed = pcall(M.add, lang, opts) + return installed + end + + M.add(lang, opts) + return true +end + +---@class treesitter.RequireLangOpts +---@field path? string +---@field silent? boolean +---@field filetype? string|string[] +---@field symbol_name? string + +--- Load parser with name {lang} --- --- Parsers are searched in the `parser` runtime directory, or the provided {path} --- ----@param lang string Language the parser should parse ----@param path (string|nil) Optional path the parser is located at ----@param silent (boolean|nil) Don't throw an error if language not found ----@param symbol_name (string|nil) Internal symbol name for the language to load ----@return boolean If the specified language is installed -function M.require_language(lang, path, silent, symbol_name) +---@param lang string Name of the parser (alphanumerical and `_` only) +---@param opts (table|nil) Options: +--- - filetype (string|string[]) Default filetype the parser should be associated with. +--- Defaults to {lang}. +--- - path (string|nil) Optional path the parser is located at +--- - symbol_name (string|nil) Internal symbol name for the language to load +function M.add(lang, opts) + ---@cast opts treesitter.RequireLangOpts + opts = opts or {} + local path = opts.path + local filetype = opts.filetype or lang + local symbol_name = opts.symbol_name + + vim.validate({ + lang = { lang, 'string' }, + path = { path, 'string', true }, + symbol_name = { symbol_name, 'string', true }, + filetype = { filetype, { 'string', 'table' }, true }, + }) + if vim._ts_has_language(lang) then - return true + M.register(lang, filetype) + return end + if path == nil then - local fname = 'parser/' .. vim.fn.fnameescape(lang) .. '.*' - local paths = a.nvim_get_runtime_file(fname, false) - if #paths == 0 then - if silent then - return false - end + if not (lang and lang:match('[%w_]+') == lang) then + error("'" .. lang .. "' is not a valid language name") + end + local fname = 'parser/' .. lang .. '.*' + local paths = api.nvim_get_runtime_file(fname, false) + if #paths == 0 then error("no parser for '" .. lang .. "' language, see :help treesitter-parsers") end path = paths[1] end - if silent then - return pcall(function() - vim._ts_add_language(path, lang, symbol_name) - end) - else - vim._ts_add_language(path, lang, symbol_name) + vim._ts_add_language(path, lang, symbol_name) + M.register(lang, filetype) +end + +--- @param x string|string[] +--- @return string[] +local function ensure_list(x) + if type(x) == 'table' then + return x end + return { x } +end - return true +--- Register a parser named {lang} to be used for {filetype}(s). +--- @param lang string Name of parser +--- @param filetype string|string[] Filetype(s) to associate with lang +function M.register(lang, filetype) + vim.validate({ + lang = { lang, 'string' }, + filetype = { filetype, { 'string', 'table' } }, + }) + + for _, f in ipairs(ensure_list(filetype)) do + if f ~= '' then + ft_to_lang[f] = lang + end + end end --- Inspects the provided language. @@ -45,9 +135,19 @@ end --- ---@param lang string Language ---@return table -function M.inspect_language(lang) - M.require_language(lang) +function M.inspect(lang) + M.add(lang) return vim._ts_inspect_language(lang) end +---@deprecated +function M.inspect_language(...) + vim.deprecate( + 'vim.treesitter.language.inspect_language()', + 'vim.treesitter.language.inspect()', + '0.10' + ) + return M.inspect(...) +end + return M diff --git a/runtime/lua/vim/treesitter/languagetree.lua b/runtime/lua/vim/treesitter/languagetree.lua index a1e96f8ef2..0171b416cd 100644 --- a/runtime/lua/vim/treesitter/languagetree.lua +++ b/runtime/lua/vim/treesitter/languagetree.lua @@ -1,85 +1,257 @@ -local a = vim.api +--- @defgroup lua-treesitter-languagetree +--- +--- @brief A \*LanguageTree\* contains a tree of parsers: the root treesitter parser for {lang} and +--- any "injected" language parsers, which themselves may inject other languages, recursively. +--- For example a Lua buffer containing some Vimscript commands needs multiple parsers to fully +--- understand its contents. +--- +--- To create a LanguageTree (parser object) for a given buffer and language, use: +--- +--- ```lua +--- local parser = vim.treesitter.get_parser(bufnr, lang) +--- ``` +--- +--- (where `bufnr=0` means current buffer). `lang` defaults to 'filetype'. +--- Note: currently the parser is retained for the lifetime of a buffer but this may change; +--- a plugin should keep a reference to the parser object if it wants incremental updates. +--- +--- Whenever you need to access the current syntax tree, parse the buffer: +--- +--- ```lua +--- local tree = parser:parse({ start_row, end_row }) +--- ``` +--- +--- This returns a table of immutable |treesitter-tree| objects representing the current state of +--- the buffer. When the plugin wants to access the state after a (possible) edit it must call +--- `parse()` again. If the buffer wasn't edited, the same tree will be returned again without extra +--- work. If the buffer was parsed before, incremental parsing will be done of the changed parts. +--- +--- Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, you must call +--- |vim.treesitter.get_parser()| before you register your callback. But preferably parsing +--- shouldn't be done directly in the change callback anyway as they will be very frequent. Rather +--- a plugin that does any kind of analysis on a tree should use a timer to throttle too frequent +--- updates. +--- + +-- Debugging: +-- +-- vim.g.__ts_debug levels: +-- - 1. Messages from languagetree.lua +-- - 2. Parse messages from treesitter +-- - 2. Lex messages from treesitter +-- +-- Log file can be found in stdpath('log')/treesitter.log + local query = require('vim.treesitter.query') local language = require('vim.treesitter.language') +local Range = require('vim.treesitter._range') + +---@alias TSCallbackName +---| 'changedtree' +---| 'bytes' +---| 'detach' +---| 'child_added' +---| 'child_removed' + +---@alias TSCallbackNameOn +---| 'on_changedtree' +---| 'on_bytes' +---| 'on_detach' +---| 'on_child_added' +---| 'on_child_removed' + +--- @type table<TSCallbackNameOn,TSCallbackName> +local TSCallbackNames = { + on_changedtree = 'changedtree', + on_bytes = 'bytes', + on_detach = 'detach', + on_child_added = 'child_added', + on_child_removed = 'child_removed', +} ---@class LanguageTree ----@field _callbacks function[] Callback handlers ----@field _children LanguageTree[] Injected languages ----@field _injection_query table Queries defining injected languages ----@field _opts table Options ----@field _parser userdata Parser for language ----@field _regions table List of regions this tree should manage and parse ----@field _lang string Language name ----@field _regions table ----@field _source (number|string) Buffer or string to parse ----@field _trees userdata[] Reference to parsed |tstree| (one for each language) ----@field _valid boolean If the parsed tree is valid - +---@field private _callbacks table<TSCallbackName,function[]> Callback handlers +---@field package _callbacks_rec table<TSCallbackName,function[]> Callback handlers (recursive) +---@field private _children table<string,LanguageTree> Injected languages +---@field private _injection_query Query Queries defining injected languages +---@field private _injections_processed boolean +---@field private _opts table Options +---@field private _parser TSParser Parser for language +---@field private _has_regions boolean +---@field private _regions table<integer, Range6[]>? +---List of regions this tree should manage and parse. If nil then regions are +---taken from _trees. This is mostly a short-lived cache for included_regions() +---@field private _lang string Language name +---@field private _parent_lang? string Parent language name +---@field private _source (integer|string) Buffer or string to parse +---@field private _trees table<integer, TSTree> Reference to parsed tree (one for each language). +---Each key is the index of region, which is synced with _regions and _valid. +---@field private _valid boolean|table<integer,boolean> If the parsed tree is valid +---@field private _logger? fun(logtype: string, msg: string) +---@field private _logfile? file* local LanguageTree = {} + +---@class LanguageTreeOpts +---@field queries table<string,string> -- Deprecated +---@field injections table<string,string> + LanguageTree.__index = LanguageTree ---- A |LanguageTree| holds the treesitter parser for a given language {lang} used ---- to parse a buffer. As the buffer may contain injected languages, the LanguageTree ---- needs to store parsers for these child languages as well (which in turn may contain ---- child languages themselves, hence the name). ---- ----@param source (number|string) Buffer or a string of text to parse ----@param lang string Root language this tree represents ----@param opts (table|nil) Optional keyword arguments: ---- - injections table Mapping language to injection query strings. ---- This is useful for overriding the built-in ---- runtime file searching for the injection language ---- query per language. ----@return LanguageTree |LanguageTree| parser object -function LanguageTree.new(source, lang, opts) - language.require_language(lang) +--- @package +--- +--- |LanguageTree| contains a tree of parsers: the root treesitter parser for {lang} and any +--- "injected" language parsers, which themselves may inject other languages, recursively. +--- +---@param source (integer|string) Buffer or text string to parse +---@param lang string Root language of this tree +---@param opts (table|nil) Optional arguments: +--- - injections table Map of language to injection query strings. Overrides the +--- built-in runtime file searching for language injections. +---@param parent_lang? string Parent language name of this tree +---@return LanguageTree parser object +function LanguageTree.new(source, lang, opts, parent_lang) + language.add(lang) + ---@type LanguageTreeOpts opts = opts or {} - if opts.queries then - a.nvim_err_writeln("'queries' is no longer supported. Use 'injections' now") - opts.injections = opts.queries + if source == 0 then + source = vim.api.nvim_get_current_buf() end local injections = opts.injections or {} - local self = setmetatable({ + + --- @type LanguageTree + local self = { _source = source, _lang = lang, + _parent_lang = parent_lang, _children = {}, - _regions = {}, _trees = {}, _opts = opts, - _injection_query = injections[lang] and query.parse_query(lang, injections[lang]) - or query.get_query(lang, 'injections'), + _injection_query = injections[lang] and query.parse(lang, injections[lang]) + or query.get(lang, 'injections'), + _has_regions = false, + _injections_processed = false, _valid = false, _parser = vim._create_ts_parser(lang), - _callbacks = { - changedtree = {}, - bytes = {}, - detach = {}, - child_added = {}, - child_removed = {}, - }, - }, LanguageTree) + _callbacks = {}, + _callbacks_rec = {}, + } + + setmetatable(self, LanguageTree) + + if vim.g.__ts_debug and type(vim.g.__ts_debug) == 'number' then + self:_set_logger() + self:_log('START') + end + + for _, name in pairs(TSCallbackNames) do + self._callbacks[name] = {} + self._callbacks_rec[name] = {} + end return self end +--- @private +function LanguageTree:_set_logger() + local source = self:source() + source = type(source) == 'string' and 'text' or tostring(source) + + local lang = self:lang() + + vim.fn.mkdir(vim.fn.stdpath('log'), 'p') + local logfilename = vim.fs.joinpath(vim.fn.stdpath('log'), 'treesitter.log') + + local logfile, openerr = io.open(logfilename, 'a+') + + if not logfile or openerr then + error(string.format('Could not open file (%s) for logging: %s', logfilename, openerr)) + return + end + + self._logfile = logfile + + self._logger = function(logtype, msg) + self._logfile:write(string.format('%s:%s:(%s) %s\n', source, lang, logtype, msg)) + self._logfile:flush() + end + + local log_lex = vim.g.__ts_debug >= 3 + local log_parse = vim.g.__ts_debug >= 2 + self._parser:_set_logger(log_lex, log_parse, self._logger) +end + +---Measure execution time of a function +---@generic R1, R2, R3 +---@param f fun(): R1, R2, R2 +---@return number, R1, R2, R3 +local function tcall(f, ...) + local start = vim.uv.hrtime() + ---@diagnostic disable-next-line + local r = { f(...) } + --- @type number + local duration = (vim.uv.hrtime() - start) / 1000000 + return duration, unpack(r) +end + +---@private +---@vararg any +function LanguageTree:_log(...) + if not self._logger then + return + end + + if not vim.g.__ts_debug or vim.g.__ts_debug < 1 then + return + end + + local args = { ... } + if type(args[1]) == 'function' then + args = { args[1]() } + end + + local info = debug.getinfo(2, 'nl') + local nregions = vim.tbl_count(self:included_regions()) + local prefix = + string.format('%s:%d: (#regions=%d) ', info.name or '???', info.currentline or 0, nregions) + + local msg = { prefix } + for _, x in ipairs(args) do + if type(x) == 'string' then + msg[#msg + 1] = x + else + msg[#msg + 1] = vim.inspect(x, { newline = ' ', indent = '' }) + end + end + self._logger('nvim', table.concat(msg, ' ')) +end + --- Invalidates this parser and all its children +---@param reload boolean|nil function LanguageTree:invalidate(reload) self._valid = false -- buffer was reloaded, reparse all trees if reload then + for _, t in pairs(self._trees) do + self:_do_callback('changedtree', t:included_ranges(true), t) + end self._trees = {} end - for _, child in ipairs(self._children) do + for _, child in pairs(self._children) do child:invalidate(reload) end end ---- Returns all trees this language tree contains. +--- Returns all trees of the regions parsed by this parser. --- Does not include child languages. +--- The result is list-like if +--- * this LanguageTree is the root, in which case the result is empty or a singleton list; or +--- * the root LanguageTree is fully parsed. +--- +---@return table<integer, TSTree> function LanguageTree:trees() return self._trees end @@ -89,11 +261,39 @@ function LanguageTree:lang() return self._lang end ---- Determines whether this tree is valid. ---- If the tree is invalid, call `parse()`. ---- This will return the updated tree. -function LanguageTree:is_valid() - return self._valid +--- Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| reflects the latest +--- state of the source. If invalid, user should call |LanguageTree:parse()|. +---@param exclude_children boolean|nil whether to ignore the validity of children (default `false`) +---@return boolean +function LanguageTree:is_valid(exclude_children) + local valid = self._valid + + if type(valid) == 'table' then + for i, _ in pairs(self:included_regions()) do + if not valid[i] then + return false + end + end + end + + if not exclude_children then + if not self._injections_processed then + return false + end + + for _, child in pairs(self._children) do + if not child:is_valid(exclude_children) then + return false + end + end + end + + if type(valid) == 'boolean' then + return valid + end + + self._valid = true + return true end --- Returns a map of language to child tree. @@ -106,50 +306,77 @@ function LanguageTree:source() return self._source end ---- Parses all defined regions using a treesitter parser ---- for the language this tree represents. ---- This will run the injection query for this language to ---- determine if any child languages should be created. ---- ----@return userdata[] Table of parsed |tstree| ----@return table Change list -function LanguageTree:parse() - if self._valid then - return self._trees +--- @param region Range6[] +--- @param range? boolean|Range +--- @return boolean +local function intercepts_region(region, range) + if #region == 0 then + return true + end + + if range == nil then + return false + end + + if type(range) == 'boolean' then + return range end - local parser = self._parser + for _, r in ipairs(region) do + if Range.intercepts(r, range) then + return true + end + end + + return false +end + +--- @private +--- @param range boolean|Range? +--- @return Range6[] changes +--- @return integer no_regions_parsed +--- @return number total_parse_time +function LanguageTree:_parse_regions(range) local changes = {} + local no_regions_parsed = 0 + local total_parse_time = 0 - local old_trees = self._trees - self._trees = {} + if type(self._valid) ~= 'table' then + self._valid = {} + end -- If there are no ranges, set to an empty list -- so the included ranges in the parser are cleared. - if self._regions and #self._regions > 0 then - for i, ranges in ipairs(self._regions) do - local old_tree = old_trees[i] - parser:set_included_ranges(ranges) + for i, ranges in pairs(self:included_regions()) do + if not self._valid[i] and intercepts_region(ranges, range) then + self._parser:set_included_ranges(ranges) + local parse_time, tree, tree_changes = + tcall(self._parser.parse, self._parser, self._trees[i], self._source, true) - local tree, tree_changes = parser:parse(old_tree, self._source) - self:_do_callback('changedtree', tree_changes, tree) + -- Pass ranges if this is an initial parse + local cb_changes = self._trees[i] and tree_changes or tree:included_ranges(true) - table.insert(self._trees, tree) + self:_do_callback('changedtree', cb_changes, tree) + self._trees[i] = tree vim.list_extend(changes, tree_changes) - end - else - local tree, tree_changes = parser:parse(old_trees[1], self._source) - self:_do_callback('changedtree', tree_changes, tree) - table.insert(self._trees, tree) - vim.list_extend(changes, tree_changes) + total_parse_time = total_parse_time + parse_time + no_regions_parsed = no_regions_parsed + 1 + self._valid[i] = true + end end - local injections_by_lang = self:_get_injections() - local seen_langs = {} + return changes, no_regions_parsed, total_parse_time +end + +--- @private +--- @return number +function LanguageTree:_add_injections() + local seen_langs = {} ---@type table<string,boolean> - for lang, injection_ranges in pairs(injections_by_lang) do - local has_lang = language.require_language(lang, nil, true) + local query_time, injections_by_lang = tcall(self._get_injections, self) + for lang, injection_regions in pairs(injections_by_lang) do + local has_lang = pcall(language.add, lang) -- Child language trees should just be ignored if not found, since -- they can depend on the text of a node. Intermediate strings @@ -161,16 +388,7 @@ function LanguageTree:parse() child = self:add_child(lang) end - child:set_included_regions(injection_ranges) - - local _, child_changes = child:parse() - - -- Propagate any child changes so they are included in the - -- the change list for the callback. - if child_changes then - vim.list_extend(changes, child_changes) - end - + child:set_included_regions(injection_regions) seen_langs[lang] = true end end @@ -181,16 +399,71 @@ function LanguageTree:parse() end end - self._valid = true + return query_time +end + +--- Recursively parse all regions in the language tree using |treesitter-parsers| +--- for the corresponding languages and run injection queries on the parsed trees +--- to determine whether child trees should be created and parsed. +--- +--- Any region with empty range (`{}`, typically only the root tree) is always parsed; +--- otherwise (typically injections) only if it intersects {range} (or if {range} is `true`). +--- +--- @param range boolean|Range|nil: Parse this range in the parser's source. +--- Set to `true` to run a complete parse of the source (Note: Can be slow!) +--- Set to `false|nil` to only parse regions with empty ranges (typically +--- only the root tree without injections). +--- @return table<integer, TSTree> +function LanguageTree:parse(range) + if self:is_valid() then + self:_log('valid') + return self._trees + end - return self._trees, changes + local changes --- @type Range6[]? + + -- Collect some stats + local no_regions_parsed = 0 + local query_time = 0 + local total_parse_time = 0 + + --- At least 1 region is invalid + if not self:is_valid(true) then + changes, no_regions_parsed, total_parse_time = self:_parse_regions(range) + -- Need to run injections when we parsed something + if no_regions_parsed > 0 then + self._injections_processed = false + end + end + + if not self._injections_processed and range ~= false and range ~= nil then + query_time = self:_add_injections() + self._injections_processed = true + end + + self:_log({ + changes = changes and #changes > 0 and changes or nil, + regions_parsed = no_regions_parsed, + parse_time = total_parse_time, + query_time = query_time, + range = range, + }) + + for _, child in pairs(self._children) do + child:parse(range) + end + + return self._trees end +---@deprecated Misleading name. Use `LanguageTree:children()` (non-recursive) instead, +--- add recursion yourself if needed. --- Invokes the callback for each |LanguageTree| and its children recursively --- ----@param fn function(tree: LanguageTree, lang: string) ----@param include_self boolean Whether to include the invoking tree in the results +---@param fn fun(tree: LanguageTree, lang: string) +---@param include_self boolean|nil Whether to include the invoking tree in the results function LanguageTree:for_each_child(fn, include_self) + vim.deprecate('LanguageTree:for_each_child()', 'LanguageTree:children()', '0.11') if include_self then fn(self, self._lang) end @@ -204,9 +477,9 @@ end --- --- Note: This includes the invoking tree's child trees as well. --- ----@param fn function(tree: TSTree, languageTree: LanguageTree) +---@param fn fun(tree: TSTree, ltree: LanguageTree) function LanguageTree:for_each_tree(fn) - for _, tree in ipairs(self._trees) do + for _, tree in pairs(self._trees) do fn(tree, self) end @@ -221,15 +494,20 @@ end --- ---@private ---@param lang string Language to add. ----@return LanguageTree Injected |LanguageTree| +---@return LanguageTree injected function LanguageTree:add_child(lang) if self._children[lang] then self:remove_child(lang) end - self._children[lang] = LanguageTree.new(self._source, lang, self._opts) + local child = LanguageTree.new(self._source, lang, self._opts, self:lang()) - self:invalidate() + -- Inherit recursive callbacks + for nm, cb in pairs(self._callbacks_rec) do + vim.list_extend(child._callbacks_rec[nm], cb) + end + + self._children[lang] = child self:_do_callback('child_added', self._children[lang]) return self._children[lang] @@ -245,7 +523,6 @@ function LanguageTree:remove_child(lang) if child then self._children[lang] = nil child:destroy() - self:invalidate() self:_do_callback('child_removed', child) end end @@ -258,11 +535,60 @@ end --- `remove_child` must be called on the parent to remove it. function LanguageTree:destroy() -- Cleanup here - for _, child in ipairs(self._children) do + for _, child in pairs(self._children) do child:destroy() end end +---@param region Range6[] +local function region_tostr(region) + if #region == 0 then + return '[]' + end + local srow, scol = region[1][1], region[1][2] + local erow, ecol = region[#region][4], region[#region][5] + return string.format('[%d:%d-%d:%d]', srow, scol, erow, ecol) +end + +---@private +---Iterate through all the regions. fn returns a boolean to indicate if the +---region is valid or not. +---@param fn fun(index: integer, region: Range6[]): boolean +function LanguageTree:_iter_regions(fn) + if not self._valid then + return + end + + local was_valid = type(self._valid) ~= 'table' + + if was_valid then + self:_log('was valid', self._valid) + self._valid = {} + end + + local all_valid = true + + for i, region in pairs(self:included_regions()) do + if was_valid or self._valid[i] then + self._valid[i] = fn(i, region) + if not self._valid[i] then + self:_log(function() + return 'invalidating region', i, region_tostr(region) + end) + end + end + + if not self._valid[i] then + all_valid = false + end + end + + -- Compress the valid value to 'true' if there are no invalid regions + if all_valid then + self._valid = all_valid + end +end + --- Sets the included regions that should be parsed by this |LanguageTree|. --- A region is a set of nodes and/or ranges that will be parsed in the same context. --- @@ -277,151 +603,253 @@ end --- This allows for embedded languages to be parsed together across different --- nodes, which is useful for templating languages like ERB and EJS. --- ---- Note: This call invalidates the tree and requires it to be parsed again. ---- ---@private ----@param regions table List of regions this tree should manage and parse. -function LanguageTree:set_included_regions(regions) +---@param new_regions (Range4|Range6|TSNode)[][] List of regions this tree should manage and parse. +function LanguageTree:set_included_regions(new_regions) + self._has_regions = true + -- Transform the tables from 4 element long to 6 element long (with byte offset) - for _, region in ipairs(regions) do + for _, region in ipairs(new_regions) do for i, range in ipairs(region) do if type(range) == 'table' and #range == 4 then - local start_row, start_col, end_row, end_col = unpack(range) - local start_byte = 0 - local end_byte = 0 - -- TODO(vigoux): proper byte computation here, and account for EOL ? - if type(self._source) == 'number' then - -- Easy case, this is a buffer parser - start_byte = a.nvim_buf_get_offset(self._source, start_row) + start_col - end_byte = a.nvim_buf_get_offset(self._source, end_row) + end_col - elseif type(self._source) == 'string' then - -- string parser, single `\n` delimited string - start_byte = vim.fn.byteidx(self._source, start_col) - end_byte = vim.fn.byteidx(self._source, end_col) - end - - region[i] = { start_row, start_col, start_byte, end_row, end_col, end_byte } + region[i] = Range.add_bytes(self._source, range --[[@as Range4]]) + elseif type(range) == 'userdata' then + region[i] = { range:range(true) } end end end - self._regions = regions - -- Trees are no longer valid now that we have changed regions. - -- TODO(vigoux,steelsojka): Look into doing this smarter so we can use some of the - -- old trees for incremental parsing. Currently, this only - -- affects injected languages. - self._trees = {} - self:invalidate() + -- included_regions is not guaranteed to be list-like, but this is still sound, i.e. if + -- new_regions is different from included_regions, then outdated regions in included_regions are + -- invalidated. For example, if included_regions = new_regions ++ hole ++ outdated_regions, then + -- outdated_regions is invalidated by _iter_regions in else branch. + if #self:included_regions() ~= #new_regions then + -- TODO(lewis6991): inefficient; invalidate trees incrementally + for _, t in pairs(self._trees) do + self:_do_callback('changedtree', t:included_ranges(true), t) + end + self._trees = {} + self:invalidate() + else + self:_iter_regions(function(i, region) + return vim.deep_equal(new_regions[i], region) + end) + end + + self._regions = new_regions end ---- Gets the set of included regions +---Gets the set of included regions managed by this LanguageTree. This can be different from the +---regions set by injection query, because a partial |LanguageTree:parse()| drops the regions +---outside the requested range. +---@return table<integer, Range6[]> function LanguageTree:included_regions() - return self._regions + if self._regions then + return self._regions + end + + if not self._has_regions then + -- treesitter.c will default empty ranges to { -1, -1, -1, -1, -1, -1} (the full range) + return { {} } + end + + local regions = {} ---@type Range6[][] + for i, _ in pairs(self._trees) do + regions[i] = self._trees[i]:included_ranges(true) + end + + self._regions = regions + return regions +end + +---@param node TSNode +---@param source string|integer +---@param metadata TSMetadata +---@param include_children boolean +---@return Range6[] +local function get_node_ranges(node, source, metadata, include_children) + local range = vim.treesitter.get_range(node, source, metadata) + local child_count = node:named_child_count() + + if include_children or child_count == 0 then + return { range } + end + + local ranges = {} ---@type Range6[] + + local srow, scol, sbyte, erow, ecol, ebyte = Range.unpack6(range) + + -- We are excluding children so we need to mask out their ranges + for i = 0, child_count - 1 do + local child = assert(node:named_child(i)) + local c_srow, c_scol, c_sbyte, c_erow, c_ecol, c_ebyte = child:range(true) + if c_srow > srow or c_scol > scol then + ranges[#ranges + 1] = { srow, scol, sbyte, c_srow, c_scol, c_sbyte } + end + srow = c_erow + scol = c_ecol + sbyte = c_ebyte + end + + if erow > srow or ecol > scol then + ranges[#ranges + 1] = Range.add_bytes(source, { srow, scol, sbyte, erow, ecol, ebyte }) + end + + return ranges +end + +---@class TSInjectionElem +---@field combined boolean +---@field regions Range6[][] + +---@alias TSInjection table<string,table<integer,TSInjectionElem>> + +---@param t table<integer,TSInjection> +---@param tree_index integer +---@param pattern integer +---@param lang string +---@param combined boolean +---@param ranges Range6[] +local function add_injection(t, tree_index, pattern, lang, combined, ranges) + if #ranges == 0 then + -- Make sure not to add an empty range set as this is interpreted to mean the whole buffer. + return + end + + -- Each tree index should be isolated from the other nodes. + if not t[tree_index] then + t[tree_index] = {} + end + + if not t[tree_index][lang] then + t[tree_index][lang] = {} + end + + -- Key this by pattern. If combined is set to true all captures of this pattern + -- will be parsed by treesitter as the same "source". + -- If combined is false, each "region" will be parsed as a single source. + if not t[tree_index][lang][pattern] then + t[tree_index][lang][pattern] = { combined = combined, regions = {} } + end + + table.insert(t[tree_index][lang][pattern].regions, ranges) +end + +-- TODO(clason): replace by refactored `ts.has_parser` API (without registering) +--- The result of this function is cached to prevent nvim_get_runtime_file from being +--- called too often +--- @param lang string parser name +--- @return boolean # true if parser for {lang} exists on rtp +local has_parser = vim.func._memoize(1, function(lang) + return vim._ts_has_language(lang) + or #vim.api.nvim_get_runtime_file('parser/' .. lang .. '.*', false) > 0 +end) + +--- Return parser name for language (if exists) or filetype (if registered and exists). +--- Also attempts with the input lower-cased. +--- +---@param alias string language or filetype name +---@return string? # resolved parser name +local function resolve_lang(alias) + if has_parser(alias) then + return alias + end + + if has_parser(alias:lower()) then + return alias:lower() + end + + local lang = vim.treesitter.language.get_lang(alias) + if lang and has_parser(lang) then + return lang + end + + lang = vim.treesitter.language.get_lang(alias:lower()) + if lang and has_parser(lang) then + return lang + end end ---@private -local function get_range_from_metadata(node, id, metadata) - if metadata[id] and metadata[id].range then - return metadata[id].range +--- Extract injections according to: +--- https://tree-sitter.github.io/tree-sitter/syntax-highlighting#language-injection +---@param match table<integer,TSNode> +---@param metadata TSMetadata +---@return string?, boolean, Range6[] +function LanguageTree:_get_injection(match, metadata) + local ranges = {} ---@type Range6[] + local combined = metadata['injection.combined'] ~= nil + local injection_lang = metadata['injection.language'] --[[@as string?]] + local lang = metadata['injection.self'] ~= nil and self:lang() + or metadata['injection.parent'] ~= nil and self._parent_lang + or (injection_lang and resolve_lang(injection_lang)) + local include_children = metadata['injection.include-children'] ~= nil + + for id, node in pairs(match) do + local name = self._injection_query.captures[id] + -- Lang should override any other language tag + if name == 'injection.language' then + local text = vim.treesitter.get_node_text(node, self._source, { metadata = metadata[id] }) + lang = resolve_lang(text) + elseif name == 'injection.content' then + ranges = get_node_ranges(node, self._source, metadata[id], include_children) + end end - return { node:range() } + + return lang, combined, ranges end ---- Gets language injection points by language. +--- Can't use vim.tbl_flatten since a range is just a table. +---@param regions Range6[][] +---@return Range6[] +local function combine_regions(regions) + local result = {} ---@type Range6[] + for _, region in ipairs(regions) do + for _, range in ipairs(region) do + result[#result + 1] = range + end + end + return result +end + +--- Gets language injection regions by language. --- --- This is where most of the injection processing occurs. --- --- TODO: Allow for an offset predicate to tailor the injection range --- instead of using the entire nodes range. ----@private +--- @private +--- @return table<string, Range6[][]> function LanguageTree:_get_injections() if not self._injection_query then return {} end + ---@type table<integer,TSInjection> local injections = {} - for tree_index, tree in ipairs(self._trees) do + for index, tree in pairs(self._trees) do local root_node = tree:root() local start_line, _, end_line, _ = root_node:range() for pattern, match, metadata in self._injection_query:iter_matches(root_node, self._source, start_line, end_line + 1) do - local lang = nil - local ranges = {} - local combined = metadata.combined - - -- Directives can configure how injections are captured as well as actual node captures. - -- This allows more advanced processing for determining ranges and language resolution. - if metadata.content then - local content = metadata.content - - -- Allow for captured nodes to be used - if type(content) == 'number' then - content = { match[content]:range() } - end - - if type(content) == 'table' and #content >= 4 then - vim.list_extend(ranges, content) - end + local lang, combined, ranges = self:_get_injection(match, metadata) + if lang then + add_injection(injections, index, pattern, lang, combined, ranges) + else + self:_log('match from injection query failed for pattern', pattern) end - - if metadata.language then - lang = metadata.language - end - - -- You can specify the content and language together - -- using a tag with the language, for example - -- @javascript - for id, node in pairs(match) do - local name = self._injection_query.captures[id] - - -- Lang should override any other language tag - if name == 'language' and not lang then - lang = query.get_node_text(node, self._source) - elseif name == 'combined' then - combined = true - elseif name == 'content' and #ranges == 0 then - table.insert(ranges, get_range_from_metadata(node, id, metadata)) - -- Ignore any tags that start with "_" - -- Allows for other tags to be used in matches - elseif string.sub(name, 1, 1) ~= '_' then - if not lang then - lang = name - end - - if #ranges == 0 then - table.insert(ranges, get_range_from_metadata(node, id, metadata)) - end - end - end - - -- Each tree index should be isolated from the other nodes. - if not injections[tree_index] then - injections[tree_index] = {} - end - - if not injections[tree_index][lang] then - injections[tree_index][lang] = {} - end - - -- Key this by pattern. If combined is set to true all captures of this pattern - -- will be parsed by treesitter as the same "source". - -- If combined is false, each "region" will be parsed as a single source. - if not injections[tree_index][lang][pattern] then - injections[tree_index][lang][pattern] = { combined = combined, regions = {} } - end - - table.insert(injections[tree_index][lang][pattern].regions, ranges) end end + ---@type table<string,Range6[][]> local result = {} -- Generate a map by lang of node lists. -- Each list is a set of ranges that should be parsed together. - for _, lang_map in ipairs(injections) do + for _, lang_map in pairs(injections) do for lang, patterns in pairs(lang_map) do if not result[lang] then result[lang] = {} @@ -429,12 +857,9 @@ function LanguageTree:_get_injections() for _, entry in pairs(patterns) do if entry.combined then - local regions = vim.tbl_map(function(e) - return vim.tbl_flatten(e) - end, entry.regions) - table.insert(result[lang], regions) + table.insert(result[lang], combine_regions(entry.regions)) else - for _, ranges in ipairs(entry.regions) do + for _, ranges in pairs(entry.regions) do table.insert(result[lang], ranges) end end @@ -446,13 +871,94 @@ function LanguageTree:_get_injections() end ---@private +---@param cb_name TSCallbackName function LanguageTree:_do_callback(cb_name, ...) for _, cb in ipairs(self._callbacks[cb_name]) do cb(...) end + for _, cb in ipairs(self._callbacks_rec[cb_name]) do + cb(...) + end end ----@private +---@package +function LanguageTree:_edit( + start_byte, + end_byte_old, + end_byte_new, + start_row, + start_col, + end_row_old, + end_col_old, + end_row_new, + end_col_new +) + for _, tree in pairs(self._trees) do + tree:edit( + start_byte, + end_byte_old, + end_byte_new, + start_row, + start_col, + end_row_old, + end_col_old, + end_row_new, + end_col_new + ) + end + + self._regions = nil + + local changed_range = { + start_row, + start_col, + start_byte, + end_row_old, + end_col_old, + end_byte_old, + } + + -- Validate regions after editing the tree + self:_iter_regions(function(_, region) + if #region == 0 then + -- empty region, use the full source + return false + end + for _, r in ipairs(region) do + if Range.intercepts(r, changed_range) then + return false + end + end + return true + end) + + for _, child in pairs(self._children) do + child:_edit( + start_byte, + end_byte_old, + end_byte_new, + start_row, + start_col, + end_row_old, + end_col_old, + end_row_new, + end_col_new + ) + end +end + +---@package +---@param bufnr integer +---@param changed_tick integer +---@param start_row integer +---@param start_col integer +---@param start_byte integer +---@param old_row integer +---@param old_col integer +---@param old_byte integer +---@param new_row integer +---@param new_col integer +---@param new_byte integer function LanguageTree:_on_bytes( bufnr, changed_tick, @@ -466,26 +972,36 @@ function LanguageTree:_on_bytes( new_col, new_byte ) - self:invalidate() - local old_end_col = old_col + ((old_row == 0) and start_col or 0) local new_end_col = new_col + ((new_row == 0) and start_col or 0) - -- Edit all trees recursively, together BEFORE emitting a bytes callback. - -- In most cases this callback should only be called from the root tree. - self:for_each_tree(function(tree) - tree:edit( - start_byte, - start_byte + old_byte, - start_byte + new_byte, - start_row, - start_col, - start_row + old_row, - old_end_col, - start_row + new_row, - new_end_col - ) - end) + self:_log( + 'on_bytes', + bufnr, + changed_tick, + start_row, + start_col, + start_byte, + old_row, + old_col, + old_byte, + new_row, + new_col, + new_byte + ) + + -- Edit trees together BEFORE emitting a bytes callback. + self:_edit( + start_byte, + start_byte + old_byte, + start_byte + new_byte, + start_row, + start_col, + start_row + old_row, + old_end_col, + start_row + new_row, + new_end_col + ) self:_do_callback( 'bytes', @@ -503,63 +1019,65 @@ function LanguageTree:_on_bytes( ) end ----@private +---@package function LanguageTree:_on_reload() self:invalidate(true) end ----@private +---@package function LanguageTree:_on_detach(...) self:invalidate(true) self:_do_callback('detach', ...) + if self._logfile then + self._logger('nvim', 'detaching') + self._logger = nil + self._logfile:close() + end end --- Registers callbacks for the |LanguageTree|. ---@param cbs table An |nvim_buf_attach()|-like table argument with the following handlers: --- - `on_bytes` : see |nvim_buf_attach()|, but this will be called _after_ the parsers callback. --- - `on_changedtree` : a callback that will be called every time the tree has syntactical changes. ---- It will only be passed one argument, which is a table of the ranges (as node ranges) that ---- changed. +--- It will be passed two arguments: a table of the ranges (as node ranges) that +--- changed and the changed tree. --- - `on_child_added` : emitted when a child is added to the tree. --- - `on_child_removed` : emitted when a child is removed from the tree. -function LanguageTree:register_cbs(cbs) +--- - `on_detach` : emitted when the buffer is detached, see |nvim_buf_detach_event|. +--- Takes one argument, the number of the buffer. +--- @param recursive? boolean Apply callbacks recursively for all children. Any new children will +--- also inherit the callbacks. +function LanguageTree:register_cbs(cbs, recursive) + ---@cast cbs table<TSCallbackNameOn,function> if not cbs then return end - if cbs.on_changedtree then - table.insert(self._callbacks.changedtree, cbs.on_changedtree) - end - - if cbs.on_bytes then - table.insert(self._callbacks.bytes, cbs.on_bytes) - end + local callbacks = recursive and self._callbacks_rec or self._callbacks - if cbs.on_detach then - table.insert(self._callbacks.detach, cbs.on_detach) - end - - if cbs.on_child_added then - table.insert(self._callbacks.child_added, cbs.on_child_added) + for name, cbname in pairs(TSCallbackNames) do + if cbs[name] then + table.insert(callbacks[cbname], cbs[name]) + end end - if cbs.on_child_removed then - table.insert(self._callbacks.child_removed, cbs.on_child_removed) + if recursive then + for _, child in pairs(self._children) do + child:register_cbs(cbs, true) + end end end ----@private +---@param tree TSTree +---@param range Range +---@return boolean local function tree_contains(tree, range) - local start_row, start_col, end_row, end_col = tree:root():range() - local start_fits = start_row < range[1] or (start_row == range[1] and start_col <= range[2]) - local end_fits = end_row > range[3] or (end_row == range[3] and end_col >= range[4]) - - return start_fits and end_fits + return Range.contains({ tree:root():range() }, range) end --- Determines whether {range} is contained in the |LanguageTree|. --- ----@param range table `{ start_line, start_col, end_line, end_col }` +---@param range Range4 `{ start_line, start_col, end_line, end_col }` ---@return boolean function LanguageTree:contains(range) for _, tree in pairs(self._trees) do @@ -573,20 +1091,19 @@ end --- Gets the tree that contains {range}. --- ----@param range table `{ start_line, start_col, end_line, end_col }` +---@param range Range4 `{ start_line, start_col, end_line, end_col }` ---@param opts table|nil Optional keyword arguments: --- - ignore_injections boolean Ignore injected languages (default true) ----@return userdata|nil Contained |tstree| +---@return TSTree|nil function LanguageTree:tree_for_range(range, opts) opts = opts or {} local ignore = vim.F.if_nil(opts.ignore_injections, true) if not ignore then for _, child in pairs(self._children) do - for _, tree in pairs(child:trees()) do - if tree_contains(tree, range) then - return tree - end + local tree = child:tree_for_range(range, opts) + if tree then + return tree end end end @@ -602,10 +1119,10 @@ end --- Gets the smallest named node that contains {range}. --- ----@param range table `{ start_line, start_col, end_line, end_col }` +---@param range Range4 `{ start_line, start_col, end_line, end_col }` ---@param opts table|nil Optional keyword arguments: --- - ignore_injections boolean Ignore injected languages (default true) ----@return userdata|nil Found |tsnode| +---@return TSNode | nil Found node function LanguageTree:named_node_for_range(range, opts) local tree = self:tree_for_range(range, opts) if tree then @@ -615,7 +1132,7 @@ end --- Gets the appropriate language that contains {range}. --- ----@param range table `{ start_line, start_col, end_line, end_col }` +---@param range Range4 `{ start_line, start_col, end_line, end_col }` ---@return LanguageTree Managing {range} function LanguageTree:language_for_range(range) for _, child in pairs(self._children) do diff --git a/runtime/lua/vim/treesitter/playground.lua b/runtime/lua/vim/treesitter/playground.lua deleted file mode 100644 index bb073290c6..0000000000 --- a/runtime/lua/vim/treesitter/playground.lua +++ /dev/null @@ -1,186 +0,0 @@ -local api = vim.api - -local M = {} - ----@class Playground ----@field ns number API namespace ----@field opts table Options table with the following keys: ---- - anon (boolean): If true, display anonymous nodes ---- - lang (boolean): If true, display the language alongside each node ---- ----@class Node ----@field id number Node id ----@field text string Node text ----@field named boolean True if this is a named (non-anonymous) node ----@field depth number Depth of the node within the tree ----@field lnum number Beginning line number of this node in the source buffer ----@field col number Beginning column number of this node in the source buffer ----@field end_lnum number Final line number of this node in the source buffer ----@field end_col number Final column number of this node in the source buffer ----@field lang string Source language of this node - ---- Traverse all child nodes starting at {node}. ---- ---- This is a recursive function. The {depth} parameter indicates the current recursion level. ---- {lang} is a string indicating the language of the tree currently being traversed. Each traversed ---- node is added to {tree}. When recursion completes, {tree} is an array of all nodes in the order ---- they were visited. ---- ---- {injections} is a table mapping node ids from the primary tree to language tree injections. Each ---- injected language has a series of trees nested within the primary language's tree, and the root ---- node of each of these trees is contained within a node in the primary tree. The {injections} ---- table maps nodes in the primary tree to root nodes of injected trees. ---- ----@param node userdata Starting node to begin traversal |tsnode| ----@param depth number Current recursion depth ----@param lang string Language of the tree currently being traversed ----@param injections table Mapping of node ids to root nodes of injected language trees (see ---- explanation above) ----@param tree Node[] Output table containing a list of tables each representing a node in the tree ----@private -local function traverse(node, depth, lang, injections, tree) - local injection = injections[node:id()] - if injection then - traverse(injection.root, depth, injection.lang, injections, tree) - end - - for child, field in node:iter_children() do - local type = child:type() - local lnum, col, end_lnum, end_col = child:range() - local named = child:named() - local text - if named then - if field then - text = string.format('%s: (%s)', field, type) - else - text = string.format('(%s)', type) - end - else - text = string.format('"%s"', type:gsub('\n', '\\n')) - end - - table.insert(tree, { - id = child:id(), - text = text, - named = named, - depth = depth, - lnum = lnum, - col = col, - end_lnum = end_lnum, - end_col = end_col, - lang = lang, - }) - - traverse(child, depth + 1, lang, injections, tree) - end - - return tree -end - ---- Create a new Playground object. ---- ----@param bufnr number Source buffer number ----@param lang string|nil Language of source buffer ---- ----@return Playground|nil ----@return string|nil Error message, if any ---- ----@private -function M.new(self, bufnr, lang) - local ok, parser = pcall(vim.treesitter.get_parser, bufnr or 0, lang) - if not ok then - return nil, 'No parser available for the given buffer' - end - - -- For each child tree (injected language), find the root of the tree and locate the node within - -- the primary tree that contains that root. Add a mapping from the node in the primary tree to - -- the root in the child tree to the {injections} table. - local root = parser:parse()[1]:root() - local injections = {} - parser:for_each_child(function(child, lang_) - child:for_each_tree(function(tree) - local r = tree:root() - local node = root:named_descendant_for_range(r:range()) - if node then - injections[node:id()] = { - lang = lang_, - root = r, - } - end - end) - end) - - local nodes = traverse(root, 0, parser:lang(), injections, {}) - - local named = {} - for _, v in ipairs(nodes) do - if v.named then - named[#named + 1] = v - end - end - - local t = { - ns = api.nvim_create_namespace(''), - nodes = nodes, - named = named, - opts = { - anon = false, - lang = false, - }, - } - - setmetatable(t, self) - self.__index = self - return t -end - ---- Write the contents of this Playground into {bufnr}. ---- ----@param bufnr number Buffer number to write into. ----@private -function M.draw(self, bufnr) - vim.bo[bufnr].modifiable = true - local lines = {} - for _, item in self:iter() do - lines[#lines + 1] = table.concat({ - string.rep(' ', item.depth), - item.text, - item.lnum == item.end_lnum - and string.format(' [%d:%d-%d]', item.lnum + 1, item.col + 1, item.end_col) - or string.format( - ' [%d:%d-%d:%d]', - item.lnum + 1, - item.col + 1, - item.end_lnum + 1, - item.end_col - ), - self.opts.lang and string.format(' %s', item.lang) or '', - }) - end - api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) - vim.bo[bufnr].modifiable = false -end - ---- Get node {i} from this Playground object. ---- ---- The node number is dependent on whether or not anonymous nodes are displayed. ---- ----@param i number Node number to get ----@return Node ----@private -function M.get(self, i) - local t = self.opts.anon and self.nodes or self.named - return t[i] -end - ---- Iterate over all of the nodes in this Playground object. ---- ----@return function Iterator over all nodes in this Playground ----@return table ----@return number ----@private -function M.iter(self) - return ipairs(self.opts.anon and self.nodes or self.named) -end - -return M diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua index dbf134573d..8cbbffcd60 100644 --- a/runtime/lua/vim/treesitter/query.lua +++ b/runtime/lua/vim/treesitter/query.lua @@ -1,21 +1,25 @@ -local a = vim.api +local api = vim.api local language = require('vim.treesitter.language') --- query: pattern matching on trees --- predicate matching is implemented in lua --- ---@class Query ---@field captures string[] List of captures used in query ----@field info table Contains used queries, predicates, directives +---@field info TSQueryInfo Contains used queries, predicates, directives ---@field query userdata Parsed query local Query = {} Query.__index = Query +---@class TSQueryInfo +---@field captures table +---@field patterns table<string,any[][]> + +---@class TSQueryModule local M = {} ----@private +---@param files string[] +---@return string[] local function dedupe_files(files) local result = {} + ---@type table<string,boolean> local seen = {} for _, path in ipairs(files) do @@ -28,7 +32,6 @@ local function dedupe_files(files) return result end ----@private local function safe_read(filename, read_quantifier) local file, err = io.open(filename, 'r') if not file then @@ -39,7 +42,6 @@ local function safe_read(filename, read_quantifier) return content end ----@private --- Adds {ilang} to {base_langs}, only if {ilang} is different than {lang} --- ---@return boolean true If lang == ilang @@ -51,24 +53,34 @@ local function add_included_lang(base_langs, lang, ilang) return false end +---@deprecated +function M.get_query_files(...) + vim.deprecate( + 'vim.treesitter.query.get_query_files()', + 'vim.treesitter.query.get_files()', + '0.10' + ) + return M.get_files(...) +end + --- Gets the list of files used to make up a query --- ---@param lang string Language to get query for ---@param query_name string Name of the query to load (e.g., "highlights") ---@param is_included (boolean|nil) Internal parameter, most of the time left as `nil` ---@return string[] query_files List of files to load for given query and language -function M.get_query_files(lang, query_name, is_included) +function M.get_files(lang, query_name, is_included) local query_path = string.format('queries/%s/%s.scm', lang, query_name) - local lang_files = dedupe_files(a.nvim_get_runtime_file(query_path, true)) + local lang_files = dedupe_files(api.nvim_get_runtime_file(query_path, true)) if #lang_files == 0 then return {} end - local base_query = nil + local base_query = nil ---@type string? local extensions = {} - local base_langs = {} + local base_langs = {} ---@type string[] -- Now get the base languages by looking at the first line of every file -- The syntax is the following : @@ -87,6 +99,7 @@ function M.get_query_files(lang, query_name, is_included) local extension = false for modeline in + ---@return string function() return file:read('*l') end @@ -97,6 +110,7 @@ function M.get_query_files(lang, query_name, is_included) local langlist = modeline:match(MODELINE_FORMAT) if langlist then + ---@diagnostic disable-next-line:param-type-mismatch for _, incllang in ipairs(vim.split(langlist, ',', true)) do local is_optional = incllang:match('%(.*%)') @@ -127,7 +141,7 @@ function M.get_query_files(lang, query_name, is_included) local query_files = {} for _, base_lang in ipairs(base_langs) do - local base_files = M.get_query_files(base_lang, query_name, true) + local base_files = M.get_files(base_lang, query_name, true) vim.list_extend(query_files, base_files) end vim.list_extend(query_files, { base_query }) @@ -136,7 +150,8 @@ function M.get_query_files(lang, query_name, is_included) return query_files end ----@private +---@param filenames string[] +---@return string local function read_query_files(filenames) local contents = {} @@ -147,7 +162,8 @@ local function read_query_files(filenames) return table.concat(contents, '') end ---- The explicitly set queries from |vim.treesitter.query.set_query()| +-- The explicitly set queries from |vim.treesitter.query.set()| +---@type table<string,table<string,Query>> local explicit_queries = setmetatable({}, { __index = function(t, k) local lang_queries = {} @@ -157,6 +173,12 @@ local explicit_queries = setmetatable({}, { end, }) +---@deprecated +function M.set_query(...) + vim.deprecate('vim.treesitter.query.set_query()', 'vim.treesitter.query.set()', '0.10') + M.set(...) +end + --- Sets the runtime query named {query_name} for {lang} --- --- This allows users to override any runtime files and/or configuration @@ -165,8 +187,14 @@ local explicit_queries = setmetatable({}, { ---@param lang string Language to use for the query ---@param query_name string Name of the query (e.g., "highlights") ---@param text string Query text (unparsed). -function M.set_query(lang, query_name, text) - explicit_queries[lang][query_name] = M.parse_query(lang, text) +function M.set(lang, query_name, text) + explicit_queries[lang][query_name] = M.parse(lang, text) +end + +---@deprecated +function M.get_query(...) + vim.deprecate('vim.treesitter.query.get_query()', 'vim.treesitter.query.get()', '0.10') + return M.get(...) end --- Returns the runtime query {query_name} for {lang}. @@ -174,24 +202,28 @@ end ---@param lang string Language to use for the query ---@param query_name string Name of the query (e.g. "highlights") --- ----@return Query Parsed query -function M.get_query(lang, query_name) +---@return Query|nil Parsed query +M.get = vim.func._memoize('concat-2', function(lang, query_name) if explicit_queries[lang][query_name] then return explicit_queries[lang][query_name] end - local query_files = M.get_query_files(lang, query_name) + local query_files = M.get_files(lang, query_name) local query_string = read_query_files(query_files) - if #query_string > 0 then - return M.parse_query(lang, query_string) + if #query_string == 0 then + return nil end -end -local query_cache = vim.defaulttable(function() - return setmetatable({}, { __mode = 'v' }) + return M.parse(lang, query_string) end) +---@deprecated +function M.parse_query(...) + vim.deprecate('vim.treesitter.query.parse_query()', 'vim.treesitter.query.parse()', '0.10') + return M.parse(...) +end + --- Parse {query} as a string. (If the query is in a file, the caller --- should read the contents into a string before calling). --- @@ -209,81 +241,50 @@ end) ---@param query string Query in s-expr syntax --- ---@return Query Parsed query -function M.parse_query(lang, query) - language.require_language(lang) - local cached = query_cache[lang][query] - if cached then - return cached - else - local self = setmetatable({}, Query) - self.query = vim._ts_parse_query(lang, query) - self.info = self.query:inspect() - self.captures = self.info.captures - query_cache[lang][query] = self - return self - end -end +M.parse = vim.func._memoize('concat-2', function(lang, query) + language.add(lang) + + local self = setmetatable({}, Query) + self.query = vim._ts_parse_query(lang, query) + self.info = self.query:inspect() + self.captures = self.info.captures + return self +end) ---- Gets the text corresponding to a given node ---- ----@param node userdata |tsnode| ----@param source (number|string) Buffer or string from which the {node} is extracted ----@param opts (table|nil) Optional parameters. ---- - concat: (boolean) Concatenate result in a string (default true) ----@return (string[]|string) -function M.get_node_text(node, source, opts) - opts = opts or {} - local concat = vim.F.if_nil(opts.concat, true) - - local start_row, start_col, start_byte = node:start() - local end_row, end_col, end_byte = node:end_() - - if type(source) == 'number' then - local lines - local eof_row = a.nvim_buf_line_count(source) - if start_row >= eof_row then - return nil - end +---@deprecated +function M.get_range(...) + vim.deprecate('vim.treesitter.query.get_range()', 'vim.treesitter.get_range()', '0.10') + return vim.treesitter.get_range(...) +end - if end_col == 0 then - lines = a.nvim_buf_get_lines(source, start_row, end_row, true) - end_col = -1 - else - lines = a.nvim_buf_get_lines(source, start_row, end_row + 1, true) - end +---@deprecated +function M.get_node_text(...) + vim.deprecate('vim.treesitter.query.get_node_text()', 'vim.treesitter.get_node_text()', '0.10') + return vim.treesitter.get_node_text(...) +end - if #lines > 0 then - if #lines == 1 then - lines[1] = string.sub(lines[1], start_col + 1, end_col) - else - lines[1] = string.sub(lines[1], start_col + 1) - lines[#lines] = string.sub(lines[#lines], 1, end_col) - end - end +---@alias TSMatch table<integer,TSNode> - return concat and table.concat(lines, '\n') or lines - elseif type(source) == 'string' then - return source:sub(start_byte + 1, end_byte) - end -end +---@alias TSPredicate fun(match: TSMatch, _, _, predicate: any[]): boolean -- Predicate handler receive the following arguments -- (match, pattern, bufnr, predicate) +---@type table<string,TSPredicate> local predicate_handlers = { ['eq?'] = function(match, _, source, predicate) local node = match[predicate[2]] if not node then return true end - local node_text = M.get_node_text(node, source) + local node_text = vim.treesitter.get_node_text(node, source) - local str + local str ---@type string if type(predicate[3]) == 'string' then -- (#eq? @aa "foo") str = predicate[3] else -- (#eq? @aa @bb) - str = M.get_node_text(match[predicate[3]], source) + str = vim.treesitter.get_node_text(match[predicate[3]], source) end if node_text ~= str or str == nil then @@ -299,12 +300,11 @@ local predicate_handlers = { return true end local regex = predicate[3] - return string.find(M.get_node_text(node, source), regex) + return string.find(vim.treesitter.get_node_text(node, source), regex) ~= nil end, ['match?'] = (function() local magic_prefixes = { ['\\v'] = true, ['\\m'] = true, ['\\M'] = true, ['\\V'] = true } - ---@private local function check_magic(str) if string.len(str) < 2 or magic_prefixes[string.sub(str, 1, 2)] then return str @@ -321,12 +321,14 @@ local predicate_handlers = { }) return function(match, _, source, pred) + ---@cast match TSMatch local node = match[pred[2]] if not node then return true end + ---@diagnostic disable-next-line no-unknown local regex = compiled_vim_regexes[pred[3]] - return regex:match_str(M.get_node_text(node, source)) + return regex:match_str(vim.treesitter.get_node_text(node, source)) end end)(), @@ -335,7 +337,7 @@ local predicate_handlers = { if not node then return true end - local node_text = M.get_node_text(node, source) + local node_text = vim.treesitter.get_node_text(node, source) for i = 3, #predicate do if string.find(node_text, predicate[i], 1, true) then @@ -351,7 +353,7 @@ local predicate_handlers = { if not node then return true end - local node_text = M.get_node_text(node, source) + local node_text = vim.treesitter.get_node_text(node, source) -- Since 'predicate' will not be used by callers of this function, use it -- to store a string set built from the list of words to check against. @@ -359,6 +361,7 @@ local predicate_handlers = { if not string_set then string_set = {} for i = 3, #predicate do + ---@diagnostic disable-next-line:no-unknown string_set[predicate[i]] = true end predicate['string_set'] = string_set @@ -366,36 +369,85 @@ local predicate_handlers = { return string_set[node_text] end, + + ['has-ancestor?'] = function(match, _, _, predicate) + local node = match[predicate[2]] + if not node then + return true + end + + local ancestor_types = {} + for _, type in ipairs({ unpack(predicate, 3) }) do + ancestor_types[type] = true + end + + node = node:parent() + while node do + if ancestor_types[node:type()] then + return true + end + node = node:parent() + end + return false + end, + + ['has-parent?'] = function(match, _, _, predicate) + local node = match[predicate[2]] + if not node then + return true + end + + if vim.list_contains({ unpack(predicate, 3) }, node:parent():type()) then + return true + end + return false + end, } -- As we provide lua-match? also expose vim-match? predicate_handlers['vim-match?'] = predicate_handlers['match?'] +---@class TSMetadata +---@field range? Range +---@field conceal? string +---@field [integer] TSMetadata +---@field [string] integer|string + +---@alias TSDirective fun(match: TSMatch, _, _, predicate: (string|integer)[], metadata: TSMetadata) + +-- Predicate handler receive the following arguments +-- (match, pattern, bufnr, predicate) + -- Directives store metadata or perform side effects against a match. -- Directives should always end with a `!`. -- Directive handler receive the following arguments -- (match, pattern, bufnr, predicate, metadata) +---@type table<string,TSDirective> local directive_handlers = { ['set!'] = function(_, _, _, pred, metadata) - if #pred == 4 then - -- (#set! @capture "key" "value") - local _, capture_id, key, value = unpack(pred) + if #pred >= 3 and type(pred[2]) == 'number' then + -- (#set! @capture key value) + local capture_id, key, value = pred[2], pred[3], pred[4] if not metadata[capture_id] then metadata[capture_id] = {} end metadata[capture_id][key] = value else - local _, key, value = unpack(pred) - -- (#set! "key" "value") - metadata[key] = value + -- (#set! key value) + local key, value = pred[2], pred[3] + metadata[key] = value or true end end, -- Shifts the range of a node. -- Example: (#offset! @_node 0 1 0 -1) ['offset!'] = function(match, _, _, pred, metadata) + ---@cast pred integer[] local capture_id = pred[2] - local offset_node = match[capture_id] - local range = { offset_node:range() } + if not metadata[capture_id] then + metadata[capture_id] = {} + end + + local range = metadata[capture_id].range or { match[capture_id]:range() } local start_row_offset = pred[3] or 0 local start_col_offset = pred[4] or 0 local end_row_offset = pred[5] or 0 @@ -408,19 +460,74 @@ local directive_handlers = { -- If this produces an invalid range, we just skip it. if range[1] < range[3] or (range[1] == range[3] and range[2] <= range[4]) then - if not metadata[capture_id] then - metadata[capture_id] = {} - end metadata[capture_id].range = range end end, + -- Transform the content of the node + -- Example: (#gsub! @_node ".*%.(.*)" "%1") + ['gsub!'] = function(match, _, bufnr, pred, metadata) + assert(#pred == 4) + + local id = pred[2] + assert(type(id) == 'number') + + local node = match[id] + local text = vim.treesitter.get_node_text(node, bufnr, { metadata = metadata[id] }) or '' + + if not metadata[id] then + metadata[id] = {} + end + + local pattern, replacement = pred[3], pred[4] + assert(type(pattern) == 'string') + assert(type(replacement) == 'string') + + metadata[id].text = text:gsub(pattern, replacement) + end, + -- Trim blank lines from end of the node + -- Example: (#trim! @fold) + -- TODO(clason): generalize to arbitrary whitespace removal + ['trim!'] = function(match, _, bufnr, pred, metadata) + local capture_id = pred[2] + assert(type(capture_id) == 'number') + + local node = match[capture_id] + if not node then + return + end + + local start_row, start_col, end_row, end_col = node:range() + + -- Don't trim if region ends in middle of a line + if end_col ~= 0 then + return + end + + while end_row >= start_row do + -- As we only care when end_col == 0, always inspect one line above end_row. + local end_line = api.nvim_buf_get_lines(bufnr, end_row - 1, end_row, true)[1] + + if end_line ~= '' then + break + end + + end_row = end_row - 1 + end + + -- If this produces an invalid range, we just skip it. + if start_row < end_row or (start_row == end_row and start_col <= end_col) then + metadata[capture_id] = metadata[capture_id] or {} + metadata[capture_id].range = { start_row, start_col, end_row, end_col } + end + end, } --- Adds a new predicate to be used in queries --- ---@param name string Name of the predicate, without leading # ----@param handler function(match:table, pattern:string, bufnr:number, predicate:string[]) +---@param handler function(match:table<string,TSNode>, pattern:string, bufnr:integer, predicate:string[]) --- - see |vim.treesitter.query.add_directive()| for argument meanings +---@param force boolean|nil function M.add_predicate(name, handler, force) if predicate_handlers[name] and not force then error(string.format('Overriding %s', name)) @@ -437,12 +544,13 @@ end --- metadata table `metadata[capture_id].key = value` --- ---@param name string Name of the directive, without leading # ----@param handler function(match:table, pattern:string, bufnr:number, predicate:string[], metadata:table) +---@param handler function(match:table<string,TSNode>, pattern:string, bufnr:integer, predicate:string[], metadata:table) --- - match: see |treesitter-query| --- - node-level data are accessible via `match[capture_id]` --- - pattern: see |treesitter-query| --- - predicate: list of strings containing the full directive being called, e.g. --- `(node (#set! conceal "-"))` would get the predicate `{ "#set!", "conceal", "-" }` +---@param force boolean|nil function M.add_directive(name, handler, force) if directive_handlers[name] and not force then error(string.format('Overriding %s', name)) @@ -463,17 +571,18 @@ function M.list_predicates() return vim.tbl_keys(predicate_handlers) end ----@private local function xor(x, y) return (x or y) and not (x and y) end ----@private local function is_directive(name) return string.sub(name, -1) == '!' end ---@private +---@param match TSMatch +---@param pattern string +---@param source integer|string function Query:match_preds(match, pattern, source) local preds = self.info.patterns[pattern] @@ -482,8 +591,9 @@ function Query:match_preds(match, pattern, source) -- continue on the other case. This way unknown predicates will not be considered, -- which allows some testing and easier user extensibility (#12173). -- Also, tree-sitter strips the leading # from predicates for us. - local pred_name - local is_not + local pred_name ---@type string + + local is_not ---@type boolean -- Skip over directives... they will get processed after all the predicates. if not is_directive(pred[1]) then @@ -513,6 +623,8 @@ function Query:match_preds(match, pattern, source) end ---@private +---@param match TSMatch +---@param metadata TSMetadata function Query:apply_directives(match, pattern, source, metadata) local preds = self.info.patterns[pattern] @@ -533,7 +645,10 @@ end --- Returns the start and stop value if set else the node's range. -- When the node's range is used, the stop is incremented by 1 -- to make the search inclusive. ----@private +---@param start integer +---@param stop integer +---@param node TSNode +---@return integer, integer local function value_or_node_range(start, stop, node) if start == nil and stop == nil then local node_start, _, node_stop, _ = node:range() @@ -547,42 +662,41 @@ end --- --- {source} is needed if the query contains predicates; then the caller --- must ensure to use a freshly parsed tree consistent with the current ---- text of the buffer (if relevant). {start_row} and {end_row} can be used to limit +--- text of the buffer (if relevant). {start} and {stop} can be used to limit --- matches inside a row range (this is typically used with root node --- as the {node}, i.e., to get syntax highlight matches in the current ---- viewport). When omitted, the {start} and {end} row values are used from the given node. +--- viewport). When omitted, the {start} and {stop} row values are used from the given node. --- --- The iterator returns three values: a numeric id identifying the capture, --- the captured node, and metadata from any directives processing the match. --- The following example shows how to get captures by name: ---- <pre>lua +--- +--- ```lua --- for id, node, metadata in query:iter_captures(tree:root(), bufnr, first, last) do --- local name = query.captures[id] -- name of the capture in the query --- -- typically useful info about the node: --- local type = node:type() -- type of the captured node --- local row1, col1, row2, col2 = node:range() -- range of the capture ---- ... use the info here ... +--- -- ... use the info here ... --- end ---- </pre> +--- ``` --- ----@param node userdata |tsnode| under which the search will occur ----@param source (number|string) Source buffer or string to extract text from ----@param start number Starting line for the search ----@param stop number Stopping line for the search (end-exclusive) +---@param node TSNode under which the search will occur +---@param source (integer|string) Source buffer or string to extract text from +---@param start integer Starting line for the search +---@param stop integer Stopping line for the search (end-exclusive) --- ----@return number capture Matching capture id ----@return table capture_node Capture for {node} ----@return table metadata for the {capture} +---@return (fun(end_line: integer|nil): integer, TSNode, TSMetadata): +--- capture id, capture node, metadata function Query:iter_captures(node, source, start, stop) if type(source) == 'number' and source == 0 then - source = vim.api.nvim_get_current_buf() + source = api.nvim_get_current_buf() end start, stop = value_or_node_range(start, stop, node) local raw_iter = node:_rawquery(self.query, true, start, stop) - ---@private - local function iter() + local function iter(end_line) local capture, captured_node, match = raw_iter() local metadata = {} @@ -590,7 +704,10 @@ function Query:iter_captures(node, source, start, stop) local active = self:match_preds(match, match.pattern, source) match.active = active if not active then - return iter() -- tail call: try next match + if end_line and captured_node:range() > end_line then + return nil, captured_node, nil + end + return iter(end_line) -- tail call: try next match end self:apply_directives(match, match.pattern, source, metadata) @@ -609,7 +726,8 @@ end --- If the query has more than one pattern, the capture table might be sparse --- and e.g. `pairs()` method should be used over `ipairs`. --- Here is an example iterating over all captures in every match: ---- <pre>lua +--- +--- ```lua --- for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do --- for id, node in pairs(match) do --- local name = query.captures[id] @@ -617,27 +735,30 @@ end --- --- local node_data = metadata[id] -- Node level metadata --- ---- ... use the info here ... +--- -- ... use the info here ... --- end --- end ---- </pre> +--- ``` --- ----@param node userdata |tsnode| under which the search will occur ----@param source (number|string) Source buffer or string to search ----@param start number Starting line for the search ----@param stop number Stopping line for the search (end-exclusive) +---@param node TSNode under which the search will occur +---@param source (integer|string) Source buffer or string to search +---@param start integer Starting line for the search +---@param stop integer Stopping line for the search (end-exclusive) +---@param opts table|nil Options: +--- - max_start_depth (integer) if non-zero, sets the maximum start depth +--- for each match. This is used to prevent traversing too deep into a tree. +--- Requires treesitter >= 0.20.9. --- ----@return number pattern id ----@return table match ----@return table metadata -function Query:iter_matches(node, source, start, stop) +---@return (fun(): integer, table<integer,TSNode>, table): pattern id, match, metadata +function Query:iter_matches(node, source, start, stop, opts) if type(source) == 'number' and source == 0 then - source = vim.api.nvim_get_current_buf() + source = api.nvim_get_current_buf() end start, stop = value_or_node_range(start, stop, node) - local raw_iter = node:_rawquery(self.query, false, start, stop) + local raw_iter = node:_rawquery(self.query, false, start, stop, opts) + ---@cast raw_iter fun(): string, any local function iter() local pattern, match = raw_iter() local metadata = {} @@ -655,4 +776,58 @@ function Query:iter_matches(node, source, start, stop) return iter end +---@class QueryLinterOpts +---@field langs (string|string[]|nil) +---@field clear (boolean) + +--- Lint treesitter queries using installed parser, or clear lint errors. +--- +--- Use |treesitter-parsers| in runtimepath to check the query file in {buf} for errors: +--- +--- - verify that used nodes are valid identifiers in the grammar. +--- - verify that predicates and directives are valid. +--- - verify that top-level s-expressions are valid. +--- +--- The found diagnostics are reported using |diagnostic-api|. +--- By default, the parser used for verification is determined by the containing folder +--- of the query file, e.g., if the path ends in `/lua/highlights.scm`, the parser for the +--- `lua` language will be used. +---@param buf (integer) Buffer handle +---@param opts (QueryLinterOpts|nil) Optional keyword arguments: +--- - langs (string|string[]|nil) Language(s) to use for checking the query. +--- If multiple languages are specified, queries are validated for all of them +--- - clear (boolean) if `true`, just clear current lint errors +function M.lint(buf, opts) + if opts and opts.clear then + require('vim.treesitter._query_linter').clear(buf) + else + require('vim.treesitter._query_linter').lint(buf, opts) + end +end + +--- Omnifunc for completing node names and predicates in treesitter queries. +--- +--- Use via +--- +--- ```lua +--- vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc' +--- ``` +--- +function M.omnifunc(findstart, base) + return require('vim.treesitter._query_linter').omnifunc(findstart, base) +end + +--- Opens a live editor to query the buffer you started from. +--- +--- Can also be shown with *:EditQuery*. +--- +--- If you move the cursor to a capture name ("@foo"), text matching the capture is highlighted in +--- the source buffer. The query editor is a scratch buffer, use `:write` to save it. You can find +--- example queries at `$VIMRUNTIME/queries/`. +--- +--- @param lang? string language to open the query editor for. If omitted, inferred from the current buffer's filetype. +function M.edit(lang) + require('vim.treesitter.dev').edit_query(lang) +end + return M diff --git a/runtime/lua/vim/ui.lua b/runtime/lua/vim/ui.lua index 8f5be15221..b6ddf337ce 100644 --- a/runtime/lua/vim/ui.lua +++ b/runtime/lua/vim/ui.lua @@ -1,6 +1,24 @@ local M = {} ---- Prompts the user to pick a single item from a collection of entries +--- Prompts the user to pick from a list of items, allowing arbitrary (potentially asynchronous) +--- work until `on_choice`. +--- +--- Example: +--- +--- ```lua +--- vim.ui.select({ 'tabs', 'spaces' }, { +--- prompt = 'Select tabs or spaces:', +--- format_item = function(item) +--- return "I'd like to choose " .. item +--- end, +--- }, function(choice) +--- if choice == 'spaces' then +--- vim.o.expandtab = true +--- else +--- vim.o.expandtab = false +--- end +--- end) +--- ``` --- ---@param items table Arbitrary items ---@param opts table Additional options @@ -18,24 +36,6 @@ local M = {} --- Called once the user made a choice. --- `idx` is the 1-based index of `item` within `items`. --- `nil` if the user aborted the dialog. ---- ---- ---- Example: ---- <pre>lua ---- vim.ui.select({ 'tabs', 'spaces' }, { ---- prompt = 'Select tabs or spaces:', ---- format_item = function(item) ---- return "I'd like to choose " .. item ---- end, ---- }, function(choice) ---- if choice == 'spaces' then ---- vim.o.expandtab = true ---- else ---- vim.o.expandtab = false ---- end ---- end) ---- </pre> - function M.select(items, opts, on_choice) vim.validate({ items = { items, 'table', false }, @@ -55,7 +55,16 @@ function M.select(items, opts, on_choice) end end ---- Prompts the user for input +--- Prompts the user for input, allowing arbitrary (potentially asynchronous) work until +--- `on_confirm`. +--- +--- Example: +--- +--- ```lua +--- vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) +--- vim.o.shiftwidth = tonumber(input) +--- end) +--- ``` --- ---@param opts table Additional options. See |input()| --- - prompt (string|nil) @@ -76,13 +85,6 @@ end --- `input` is what the user typed (it might be --- an empty string if nothing was entered), or --- `nil` if the user aborted the dialog. ---- ---- Example: ---- <pre>lua ---- vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) ---- vim.o.shiftwidth = tonumber(input) ---- end) ---- </pre> function M.input(opts, on_confirm) vim.validate({ on_confirm = { on_confirm, 'function', false }, @@ -103,4 +105,59 @@ function M.input(opts, on_confirm) end end +--- Opens `path` with the system default handler (macOS `open`, Windows `explorer.exe`, Linux +--- `xdg-open`, …), or returns (but does not show) an error message on failure. +--- +--- Expands "~/" and environment variables in filesystem paths. +--- +--- Examples: +--- +--- ```lua +--- vim.ui.open("https://neovim.io/") +--- vim.ui.open("~/path/to/file") +--- vim.ui.open("$VIMRUNTIME") +--- ``` +--- +---@param path string Path or URL to open +--- +---@return vim.SystemCompleted|nil # Command result, or nil if not found. +---@return string|nil # Error message on failure +--- +---@see |vim.system()| +function M.open(path) + vim.validate({ + path = { path, 'string' }, + }) + local is_uri = path:match('%w+:') + if not is_uri then + path = vim.fn.expand(path) + end + + local cmd + + if vim.fn.has('mac') == 1 then + cmd = { 'open', path } + elseif vim.fn.has('win32') == 1 then + if vim.fn.executable('rundll32') == 1 then + cmd = { 'rundll32', 'url.dll,FileProtocolHandler', path } + else + return nil, 'vim.ui.open: rundll32 not found' + end + elseif vim.fn.executable('wslview') == 1 then + cmd = { 'wslview', path } + elseif vim.fn.executable('xdg-open') == 1 then + cmd = { 'xdg-open', path } + else + return nil, 'vim.ui.open: no handler found (tried: wslview, xdg-open)' + end + + local rv = vim.system(cmd, { text = true, detach = true }):wait() + if rv.code ~= 0 then + local msg = ('vim.ui.open: command failed (%d): %s'):format(rv.code, vim.inspect(cmd)) + return rv, msg + end + + return rv, nil +end + return M diff --git a/runtime/lua/vim/ui/clipboard/osc52.lua b/runtime/lua/vim/ui/clipboard/osc52.lua new file mode 100644 index 0000000000..6483f0387d --- /dev/null +++ b/runtime/lua/vim/ui/clipboard/osc52.lua @@ -0,0 +1,75 @@ +local M = {} + +--- Return the OSC 52 escape sequence +--- +--- @param clipboard string The clipboard to read from or write to +--- @param contents string The Base64 encoded contents to write to the clipboard, or '?' to read +--- from the clipboard +local function osc52(clipboard, contents) + return string.format('\027]52;%s;%s\027\\', clipboard, contents) +end + +function M.copy(reg) + local clipboard = reg == '+' and 'c' or 'p' + return function(lines) + local s = table.concat(lines, '\n') + io.stdout:write(osc52(clipboard, vim.base64.encode(s))) + end +end + +function M.paste(reg) + local clipboard = reg == '+' and 'c' or 'p' + return function() + local contents = nil + local id = vim.api.nvim_create_autocmd('TermResponse', { + callback = function(args) + local resp = args.data ---@type string + local encoded = resp:match('\027%]52;%w?;([A-Za-z0-9+/=]*)') + if encoded then + contents = vim.base64.decode(encoded) + return true + end + end, + }) + + io.stdout:write(osc52(clipboard, '?')) + + local ok, res + + -- Wait 1s first for terminals that respond quickly + ok, res = vim.wait(1000, function() + return contents ~= nil + end) + + if res == -1 then + -- If no response was received after 1s, print a message and keep waiting + vim.api.nvim_echo( + { { 'Waiting for OSC 52 response from the terminal. Press Ctrl-C to interrupt...' } }, + false, + {} + ) + ok, res = vim.wait(9000, function() + return contents ~= nil + end) + end + + if not ok then + vim.api.nvim_del_autocmd(id) + if res == -1 then + vim.notify( + 'Timed out waiting for a clipboard response from the terminal', + vim.log.levels.WARN + ) + elseif res == -2 then + -- Clear message area + vim.api.nvim_echo({ { '' } }, false, {}) + end + return 0 + end + + -- If we get here, contents should be non-nil + return vim.split(assert(contents), '\n') + end +end + +return M diff --git a/runtime/lua/vim/uri.lua b/runtime/lua/vim/uri.lua index d6b0b7410e..2dc817c5c1 100644 --- a/runtime/lua/vim/uri.lua +++ b/runtime/lua/vim/uri.lua @@ -1,72 +1,71 @@ ---- TODO: This is implemented only for files now. +---TODO: This is implemented only for files currently. -- https://tools.ietf.org/html/rfc3986 -- https://tools.ietf.org/html/rfc2732 -- https://tools.ietf.org/html/rfc2396 -local uri_decode -do - local schar = string.char +local M = {} +local sbyte = string.byte +local schar = string.char +local tohex = require('bit').tohex +local URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):.*' +local WINDOWS_URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):[a-zA-Z]:.*' +local PATTERNS = { + ---RFC 2396 + ---https://tools.ietf.org/html/rfc2396#section-2.2 + rfc2396 = "^A-Za-z0-9%-_.!~*'()", + ---RFC 2732 + ---https://tools.ietf.org/html/rfc2732 + rfc2732 = "^A-Za-z0-9%-_.!~*'()[]", + ---RFC 3986 + ---https://tools.ietf.org/html/rfc3986#section-2.2 + rfc3986 = "^A-Za-z0-9%-._~!$&'()*+,;=:@/", +} - --- Convert hex to char - ---@private - local function hex_to_char(hex) - return schar(tonumber(hex, 16)) - end - uri_decode = function(str) - return str:gsub('%%([a-fA-F0-9][a-fA-F0-9])', hex_to_char) - end +---Converts hex to char +---@param hex string +---@return string +local function hex_to_char(hex) + return schar(tonumber(hex, 16)) end -local uri_encode -do - local PATTERNS = { - --- RFC 2396 - -- https://tools.ietf.org/html/rfc2396#section-2.2 - rfc2396 = "^A-Za-z0-9%-_.!~*'()", - --- RFC 2732 - -- https://tools.ietf.org/html/rfc2732 - rfc2732 = "^A-Za-z0-9%-_.!~*'()[]", - --- RFC 3986 - -- https://tools.ietf.org/html/rfc3986#section-2.2 - rfc3986 = "^A-Za-z0-9%-._~!$&'()*+,;=:@/", - } - local sbyte, tohex = string.byte - if jit then - tohex = require('bit').tohex - else - tohex = function(b) - return string.format('%02x', b) - end - end - - ---@private - local function percent_encode_char(char) - return '%' .. tohex(sbyte(char), 2) - end - uri_encode = function(text, rfc) - if not text then - return - end - local pattern = PATTERNS[rfc] or PATTERNS.rfc3986 - return text:gsub('([' .. pattern .. '])', percent_encode_char) - end +---@param char string +---@return string +local function percent_encode_char(char) + return '%' .. tohex(sbyte(char), 2) end ----@private +---@param uri string +---@return boolean local function is_windows_file_uri(uri) return uri:match('^file:/+[a-zA-Z]:') ~= nil end ---- Get a URI from a file path. +---URI-encodes a string using percent escapes. +---@param str string string to encode +---@param rfc "rfc2396" | "rfc2732" | "rfc3986" | nil +---@return string encoded string +function M.uri_encode(str, rfc) + local pattern = PATTERNS[rfc] or PATTERNS.rfc3986 + return (str:gsub('([' .. pattern .. '])', percent_encode_char)) -- clamped to 1 retval with () +end + +---URI-decodes a string containing percent escapes. +---@param str string string to decode +---@return string decoded string +function M.uri_decode(str) + return (str:gsub('%%([a-fA-F0-9][a-fA-F0-9])', hex_to_char)) -- clamped to 1 retval with () +end + +---Gets a URI from a file path. ---@param path string Path to file ---@return string URI -local function uri_from_fname(path) - local volume_path, fname = path:match('^([a-zA-Z]:)(.*)') +function M.uri_from_fname(path) + local volume_path, fname = path:match('^([a-zA-Z]:)(.*)') ---@type string? local is_windows = volume_path ~= nil if is_windows then - path = volume_path .. uri_encode(fname:gsub('\\', '/')) + path = volume_path .. M.uri_encode(fname:gsub('\\', '/')) else - path = uri_encode(path) + path = M.uri_encode(path) end local uri_parts = { 'file://' } if is_windows then @@ -76,17 +75,14 @@ local function uri_from_fname(path) return table.concat(uri_parts) end -local URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):.*' -local WINDOWS_URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):[a-zA-Z]:.*' - ---- Get a URI from a bufnr ----@param bufnr number +---Gets a URI from a bufnr. +---@param bufnr integer ---@return string URI -local function uri_from_bufnr(bufnr) +function M.uri_from_bufnr(bufnr) local fname = vim.api.nvim_buf_get_name(bufnr) local volume_path = fname:match('^([a-zA-Z]:).*') local is_windows = volume_path ~= nil - local scheme + local scheme ---@type string? if is_windows then fname = fname:gsub('\\', '/') scheme = fname:match(WINDOWS_URI_SCHEME_PATTERN) @@ -96,42 +92,35 @@ local function uri_from_bufnr(bufnr) if scheme then return fname else - return uri_from_fname(fname) + return M.uri_from_fname(fname) end end ---- Get a filename from a URI +---Gets a filename from a URI. ---@param uri string ---@return string filename or unchanged URI for non-file URIs -local function uri_to_fname(uri) +function M.uri_to_fname(uri) local scheme = assert(uri:match(URI_SCHEME_PATTERN), 'URI must contain a scheme: ' .. uri) if scheme ~= 'file' then return uri end - uri = uri_decode(uri) - -- TODO improve this. + uri = M.uri_decode(uri) + --TODO improve this. if is_windows_file_uri(uri) then - uri = uri:gsub('^file:/+', '') - uri = uri:gsub('/', '\\') + uri = uri:gsub('^file:/+', ''):gsub('/', '\\') else - uri = uri:gsub('^file:/+', '/') + uri = uri:gsub('^file:/+', '/') ---@type string end return uri end ---- Get the buffer for a uri. ---- Creates a new unloaded buffer if no buffer for the uri already exists. +---Gets the buffer for a uri. +---Creates a new unloaded buffer if no buffer for the uri already exists. -- ---@param uri string ----@return number bufnr -local function uri_to_bufnr(uri) - return vim.fn.bufadd(uri_to_fname(uri)) +---@return integer bufnr +function M.uri_to_bufnr(uri) + return vim.fn.bufadd(M.uri_to_fname(uri)) end -return { - uri_from_fname = uri_from_fname, - uri_from_bufnr = uri_from_bufnr, - uri_to_fname = uri_to_fname, - uri_to_bufnr = uri_to_bufnr, -} --- vim:sw=2 ts=2 et +return M diff --git a/runtime/lua/vim/version.lua b/runtime/lua/vim/version.lua new file mode 100644 index 0000000000..306eef90d3 --- /dev/null +++ b/runtime/lua/vim/version.lua @@ -0,0 +1,437 @@ +--- @defgroup vim.version +--- +--- @brief The \`vim.version\` module provides functions for comparing versions and ranges +--- conforming to the https://semver.org spec. Plugins, and plugin managers, can use this to check +--- available tools and dependencies on the current system. +--- +--- Example: +--- +--- ```lua +--- local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false}) +--- if vim.version.gt(v, {3, 2, 0}) then +--- -- ... +--- end +--- ``` +--- +--- \*vim.version()\* returns the version of the current Nvim process. +--- +--- VERSION RANGE SPEC \*version-range\* +--- +--- A version "range spec" defines a semantic version range which can be tested against a version, +--- using |vim.version.range()|. +--- +--- Supported range specs are shown in the following table. +--- Note: suffixed versions (1.2.3-rc1) are not matched. +--- +--- ``` +--- 1.2.3 is 1.2.3 +--- =1.2.3 is 1.2.3 +--- >1.2.3 greater than 1.2.3 +--- <1.2.3 before 1.2.3 +--- >=1.2.3 at least 1.2.3 +--- ~1.2.3 is >=1.2.3 <1.3.0 "reasonably close to 1.2.3" +--- ^1.2.3 is >=1.2.3 <2.0.0 "compatible with 1.2.3" +--- ^0.2.3 is >=0.2.3 <0.3.0 (0.x.x is special) +--- ^0.0.1 is =0.0.1 (0.0.x is special) +--- ^1.2 is >=1.2.0 <2.0.0 (like ^1.2.0) +--- ~1.2 is >=1.2.0 <1.3.0 (like ~1.2.0) +--- ^1 is >=1.0.0 <2.0.0 "compatible with 1" +--- ~1 same "reasonably close to 1" +--- 1.x same +--- 1.* same +--- 1 same +--- * any version +--- x same +--- +--- 1.2.3 - 2.3.4 is >=1.2.3 <=2.3.4 +--- +--- Partial right: missing pieces treated as x (2.3 => 2.3.x). +--- 1.2.3 - 2.3 is >=1.2.3 <2.4.0 +--- 1.2.3 - 2 is >=1.2.3 <3.0.0 +--- +--- Partial left: missing pieces treated as 0 (1.2 => 1.2.0). +--- 1.2 - 2.3.0 is 1.2.0 - 2.3.0 +--- ``` + +local M = {} + +---@class Version +---@field [1] number +---@field [2] number +---@field [3] number +---@field major number +---@field minor number +---@field patch number +---@field prerelease? string +---@field build? string +local Version = {} +Version.__index = Version + +--- Compares prerelease strings: per semver, number parts must be must be treated as numbers: +--- "pre1.10" is greater than "pre1.2". https://semver.org/#spec-item-11 +local function cmp_prerel(prerel1, prerel2) + if not prerel1 or not prerel2 then + return prerel1 and -1 or (prerel2 and 1 or 0) + end + -- TODO(justinmk): not fully spec-compliant; this treats non-dot-delimited digit sequences as + -- numbers. Maybe better: "(.-)(%.%d*)". + local iter1 = prerel1:gmatch('([^0-9]*)(%d*)') + local iter2 = prerel2:gmatch('([^0-9]*)(%d*)') + while true do + local word1, n1 = iter1() + local word2, n2 = iter2() + if word1 == nil and word2 == nil then -- Done iterating. + return 0 + end + word1, n1, word2, n2 = + word1 or '', n1 and tonumber(n1) or 0, word2 or '', n2 and tonumber(n2) or 0 + if word1 ~= word2 then + return word1 < word2 and -1 or 1 + end + if n1 ~= n2 then + return n1 < n2 and -1 or 1 + end + end +end + +function Version:__index(key) + return type(key) == 'number' and ({ self.major, self.minor, self.patch })[key] or Version[key] +end + +function Version:__newindex(key, value) + if key == 1 then + self.major = value + elseif key == 2 then + self.minor = value + elseif key == 3 then + self.patch = value + else + rawset(self, key, value) + end +end + +---@param other Version +function Version:__eq(other) + for i = 1, 3 do + if self[i] ~= other[i] then + return false + end + end + return 0 == cmp_prerel(self.prerelease, other.prerelease) +end + +function Version:__tostring() + local ret = table.concat({ self.major, self.minor, self.patch }, '.') + if self.prerelease then + ret = ret .. '-' .. self.prerelease + end + if self.build and self.build ~= vim.NIL then + ret = ret .. '+' .. self.build + end + return ret +end + +---@param other Version +function Version:__lt(other) + for i = 1, 3 do + if self[i] > other[i] then + return false + elseif self[i] < other[i] then + return true + end + end + return -1 == cmp_prerel(self.prerelease, other.prerelease) +end + +---@param other Version +function Version:__le(other) + return self < other or self == other +end + +--- @private +--- +--- Creates a new Version object, or returns `nil` if `version` is invalid. +--- +--- @param version string|number[]|Version +--- @param strict? boolean Reject "1.0", "0-x", "3.2a" or other non-conforming version strings +--- @return Version? +function M._version(version, strict) -- Adapted from https://github.com/folke/lazy.nvim + if type(version) == 'table' then + if version.major then + return setmetatable(vim.deepcopy(version), Version) + end + return setmetatable({ + major = version[1] or 0, + minor = version[2] or 0, + patch = version[3] or 0, + }, Version) + end + + if not strict then -- TODO: add more "scrubbing". + version = version:match('%d[^ ]*') + end + + local prerel = version:match('%-([^+]*)') + local prerel_strict = version:match('%-([0-9A-Za-z-]*)') + if + strict + and prerel + and (prerel_strict == nil or prerel_strict == '' or not vim.startswith(prerel, prerel_strict)) + then + return nil -- Invalid prerelease. + end + local build = prerel and version:match('%-[^+]*%+(.*)$') or version:match('%+(.*)$') + local major, minor, patch = + version:match('^v?(%d+)%.?(%d*)%.?(%d*)' .. (strict and (prerel and '%-' or '$') or '')) + + if + (not strict and major) + or (major and minor and patch and major ~= '' and minor ~= '' and patch ~= '') + then + return setmetatable({ + major = tonumber(major), + minor = minor == '' and 0 or tonumber(minor), + patch = patch == '' and 0 or tonumber(patch), + prerelease = prerel ~= '' and prerel or nil, + build = build ~= '' and build or nil, + }, Version) + end + return nil -- Invalid version string. +end + +---TODO: generalize this, move to func.lua +--- +---@generic T: Version +---@param versions T[] +---@return T? +function M.last(versions) + local last = versions[1] + for i = 2, #versions do + if versions[i] > last then + last = versions[i] + end + end + return last +end + +---@class VersionRange +---@field from Version +---@field to? Version +local VersionRange = {} + +--- @private +--- +---@param version string|Version +function VersionRange:has(version) + if type(version) == 'string' then + ---@diagnostic disable-next-line: cast-local-type + version = M.parse(version) + elseif getmetatable(version) ~= Version then + -- Need metatable to compare versions. + version = setmetatable(vim.deepcopy(version), Version) + end + if version then + if version.prerelease ~= self.from.prerelease then + return false + end + return version >= self.from and (self.to == nil or version < self.to) + end +end + +--- Parses a semver |version-range| "spec" and returns a range object: +--- +--- ``` +--- { +--- from: Version +--- to: Version +--- has(v: string|Version) +--- } +--- ``` +--- +--- `:has()` checks if a version is in the range (inclusive `from`, exclusive `to`). +--- +--- Example: +--- +--- ```lua +--- local r = vim.version.range('1.0.0 - 2.0.0') +--- print(r:has('1.9.9')) -- true +--- print(r:has('2.0.0')) -- false +--- print(r:has(vim.version())) -- check against current Nvim version +--- ``` +--- +--- Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly: +--- +--- ```lua +--- local r = vim.version.range('1.0.0 - 2.0.0') +--- print(vim.version.gt({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to)) +--- ``` +--- +--- @see # https://github.com/npm/node-semver#ranges +--- +--- @param spec string Version range "spec" +function M.range(spec) -- Adapted from https://github.com/folke/lazy.nvim + if spec == '*' or spec == '' then + return setmetatable({ from = M.parse('0.0.0') }, { __index = VersionRange }) + end + + ---@type number? + local hyphen = spec:find(' - ', 1, true) + if hyphen then + local a = spec:sub(1, hyphen - 1) + local b = spec:sub(hyphen + 3) + local parts = vim.split(b, '.', { plain = true }) + local ra = M.range(a) + local rb = M.range(b) + return setmetatable({ + from = ra and ra.from, + to = rb and (#parts == 3 and rb.from or rb.to), + }, { __index = VersionRange }) + end + ---@type string, string + local mods, version = spec:lower():match('^([%^=<>~]*)(.*)$') + version = version:gsub('%.[%*x]', '') + local parts = vim.split(version:gsub('%-.*', ''), '.', { plain = true }) + if #parts < 3 and mods == '' then + mods = '~' + end + + local semver = M.parse(version) + if semver then + local from = semver + local to = vim.deepcopy(semver) + if mods == '' or mods == '=' then + to.patch = to.patch + 1 + elseif mods == '<' then + from = M._version({}) + elseif mods == '<=' then + from = M._version({}) + to.patch = to.patch + 1 + elseif mods == '>' then + from.patch = from.patch + 1 + to = nil ---@diagnostic disable-line: cast-local-type + elseif mods == '>=' then + to = nil ---@diagnostic disable-line: cast-local-type + elseif mods == '~' then + if #parts >= 2 then + to[2] = to[2] + 1 + to[3] = 0 + else + to[1] = to[1] + 1 + to[2] = 0 + to[3] = 0 + end + elseif mods == '^' then + for i = 1, 3 do + if to[i] ~= 0 then + to[i] = to[i] + 1 + for j = i + 1, 3 do + to[j] = 0 + end + break + end + end + end + return setmetatable({ from = from, to = to }, { __index = VersionRange }) + end +end + +---@param v string|Version +---@return string +local function create_err_msg(v) + if type(v) == 'string' then + return string.format('invalid version: "%s"', tostring(v)) + elseif type(v) == 'table' and v.major then + return string.format('invalid version: %s', vim.inspect(v)) + end + return string.format('invalid version: %s (%s)', tostring(v), type(v)) +end + +--- Parses and compares two version objects (the result of |vim.version.parse()|, or +--- specified literally as a `{major, minor, patch}` tuple, e.g. `{1, 0, 3}`). +--- +--- Example: +--- +--- ```lua +--- if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then +--- -- ... +--- end +--- local v1 = vim.version.parse('1.0.3-pre') +--- local v2 = vim.version.parse('0.2.1') +--- if vim.version.cmp(v1, v2) == 0 then +--- -- ... +--- end +--- ``` +--- +--- @note Per semver, build metadata is ignored when comparing two otherwise-equivalent versions. +--- +---@param v1 Version|number[] Version object. +---@param v2 Version|number[] Version to compare with `v1`. +---@return integer -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`. +function M.cmp(v1, v2) + local v1_parsed = assert(M._version(v1), create_err_msg(v1)) + local v2_parsed = assert(M._version(v2), create_err_msg(v1)) + if v1_parsed == v2_parsed then + return 0 + end + if v1_parsed > v2_parsed then + return 1 + end + return -1 +end + +---Returns `true` if the given versions are equal. See |vim.version.cmp()| for usage. +---@param v1 Version|number[] +---@param v2 Version|number[] +---@return boolean +function M.eq(v1, v2) + return M.cmp(v1, v2) == 0 +end + +---Returns `true` if `v1 < v2`. See |vim.version.cmp()| for usage. +---@param v1 Version|number[] +---@param v2 Version|number[] +---@return boolean +function M.lt(v1, v2) + return M.cmp(v1, v2) == -1 +end + +---Returns `true` if `v1 > v2`. See |vim.version.cmp()| for usage. +---@param v1 Version|number[] +---@param v2 Version|number[] +---@return boolean +function M.gt(v1, v2) + return M.cmp(v1, v2) == 1 +end + +--- Parses a semantic version string and returns a version object which can be used with other +--- `vim.version` functions. For example "1.0.1-rc1+build.2" returns: +--- +--- ``` +--- { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" } +--- ``` +--- +--- @see # https://semver.org/spec/v2.0.0.html +--- +---@param version string Version string to parse. +---@param opts table|nil Optional keyword arguments: +--- - strict (boolean): Default false. If `true`, no coercion is attempted on +--- input not conforming to semver v2.0.0. If `false`, `parse()` attempts to +--- coerce input such as "1.0", "0-x", "tmux 3.2a" into valid versions. +---@return table|nil parsed_version Version object or `nil` if input is invalid. +function M.parse(version, opts) + assert(type(version) == 'string', create_err_msg(version)) + opts = opts or { strict = false } + return M._version(version, opts.strict) +end + +setmetatable(M, { + --- Returns the current Nvim version. + __call = function() + local version = vim.fn.api_info().version + -- Workaround: vim.fn.api_info().version reports "prerelease" as a boolean. + version.prerelease = version.prerelease and 'dev' or nil + return setmetatable(version, Version) + end, +}) + +return M diff --git a/runtime/lua/vim/vimhelp.lua b/runtime/lua/vim/vimhelp.lua new file mode 100644 index 0000000000..a4d6a50b12 --- /dev/null +++ b/runtime/lua/vim/vimhelp.lua @@ -0,0 +1,31 @@ +-- Extra functionality for displaying Vim help. + +local M = {} + +-- Called when editing the doc/syntax.txt file +function M.highlight_groups() + local save_cursor = vim.fn.getcurpos() + + local start_lnum = vim.fn.search([[\*highlight-groups\*]], 'c') + if start_lnum == 0 then + return + end + local end_lnum = vim.fn.search('^======') + if end_lnum == 0 then + return + end + + local ns = vim.api.nvim_create_namespace('vimhelp') + vim.api.nvim_buf_clear_namespace(0, ns, 0, -1) + + for lnum = start_lnum, end_lnum do + local word = vim.api.nvim_buf_get_lines(0, lnum - 1, lnum, true)[1]:match('^(%w+)\t') + if vim.fn.hlexists(word) ~= 0 then + vim.api.nvim_buf_set_extmark(0, ns, lnum - 1, 0, { end_col = #word, hl_group = word }) + end + end + + vim.fn.setpos('.', save_cursor) +end + +return M |