aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/lua/vim')
-rw-r--r--runtime/lua/vim/F.lua5
-rw-r--r--runtime/lua/vim/_editor.lua98
-rw-r--r--runtime/lua/vim/_meta/api.lua121
-rw-r--r--runtime/lua/vim/_meta/api_keysets.lua8
-rw-r--r--runtime/lua/vim/_meta/builtin.lua48
-rw-r--r--runtime/lua/vim/_meta/diff.lua35
-rw-r--r--runtime/lua/vim/_meta/json.lua37
-rw-r--r--runtime/lua/vim/_meta/misc.lua8
-rw-r--r--runtime/lua/vim/_meta/options.lua58
-rw-r--r--runtime/lua/vim/_meta/regex.lua2
-rw-r--r--runtime/lua/vim/_meta/spell.lua15
-rw-r--r--runtime/lua/vim/_meta/vimfn.lua2
-rw-r--r--runtime/lua/vim/_options.lua231
-rw-r--r--runtime/lua/vim/diagnostic.lua32
-rw-r--r--runtime/lua/vim/filetype.lua103
-rw-r--r--runtime/lua/vim/fs.lua27
-rw-r--r--runtime/lua/vim/highlight.lua34
-rw-r--r--runtime/lua/vim/iter.lua187
-rw-r--r--runtime/lua/vim/keymap.lua39
-rw-r--r--runtime/lua/vim/lsp.lua19
-rw-r--r--runtime/lua/vim/lsp/buf.lua23
-rw-r--r--runtime/lua/vim/lsp/codelens.lua6
-rw-r--r--runtime/lua/vim/lsp/diagnostic.lua10
-rw-r--r--runtime/lua/vim/lsp/handlers.lua47
-rw-r--r--runtime/lua/vim/lsp/semantic_tokens.lua7
-rw-r--r--runtime/lua/vim/lsp/util.lua66
-rw-r--r--runtime/lua/vim/shared.lua120
-rw-r--r--runtime/lua/vim/treesitter.lua20
-rw-r--r--runtime/lua/vim/treesitter/_fold.lua4
-rw-r--r--runtime/lua/vim/treesitter/_query_linter.lua177
-rw-r--r--runtime/lua/vim/treesitter/dev.lua56
-rw-r--r--runtime/lua/vim/treesitter/highlighter.lua2
-rw-r--r--runtime/lua/vim/treesitter/language.lua4
-rw-r--r--runtime/lua/vim/treesitter/languagetree.lua62
-rw-r--r--runtime/lua/vim/treesitter/query.lua27
-rw-r--r--runtime/lua/vim/ui.lua54
-rw-r--r--runtime/lua/vim/version.lua131
37 files changed, 1018 insertions, 907 deletions
diff --git a/runtime/lua/vim/F.lua b/runtime/lua/vim/F.lua
index 16c834b371..5ed60ca8ab 100644
--- a/runtime/lua/vim/F.lua
+++ b/runtime/lua/vim/F.lua
@@ -5,13 +5,14 @@ local F = {}
--- If all arguments are nil, returns nil.
---
--- Examples:
---- <pre>
+---
+--- ```lua
--- local a = nil
--- local b = nil
--- local c = 42
--- local d = true
--- assert(vim.F.if_nil(a, b, c, d) == 42)
---- </pre>
+--- ```
---
---@param ... any
---@return any
diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua
index 68992a16bb..0215cae0cb 100644
--- a/runtime/lua/vim/_editor.lua
+++ b/runtime/lua/vim/_editor.lua
@@ -70,23 +70,24 @@ vim.log = {
--- Run a system command
---
--- Examples:
---- <pre>lua
---
---- local on_exit = function(obj)
---- print(obj.code)
---- print(obj.signal)
---- print(obj.stdout)
---- print(obj.stderr)
---- end
+--- ```lua
---
---- -- Run asynchronously
---- vim.system({'echo', 'hello'}, { text = true }, on_exit)
+--- local on_exit = function(obj)
+--- print(obj.code)
+--- print(obj.signal)
+--- print(obj.stdout)
+--- print(obj.stderr)
+--- end
---
---- -- Run synchronously
---- local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
---- -- { code = 0, signal = 0, stdout = 'hello', stderr = '' }
+--- -- Run asynchronously
+--- vim.system({'echo', 'hello'}, { text = true }, on_exit)
---
---- </pre>
+--- -- Run synchronously
+--- local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
+--- -- { code = 0, signal = 0, stdout = 'hello', stderr = '' }
+---
+--- ```
---
--- See |uv.spawn()| for more details.
---
@@ -104,7 +105,7 @@ vim.log = {
--- 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 stdout. When passed as a function must have the signature `fun(err: string, data: string)`.
+--- 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
@@ -200,7 +201,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
@@ -210,7 +212,7 @@ do
--- overridden(lines, phase)
--- end
--- end)(vim.paste)
- --- </pre>
+ --- ```
---
---@see |paste|
---@alias paste_phase -1 | 1 | 2 | 3
@@ -361,32 +363,33 @@ local VIM_CMD_ARG_MAX = 20
--- 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"')
+--- ```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 :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>
+--- -- 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
@@ -871,9 +874,10 @@ end
--- "Pretty prints" the given arguments and returns them unmodified.
---
--- Example:
---- <pre>lua
---- local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
---- </pre>
+---
+--- ```lua
+--- local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
+--- ```
---
--- @see |vim.inspect()|
--- @see |:=|
@@ -900,10 +904,12 @@ end
--- Translate keycodes.
---
--- Example:
---- <pre>lua
---- local k = vim.keycode
---- vim.g.mapleader = k'<bs>'
---- </pre>
+---
+--- ```lua
+--- local k = vim.keycode
+--- vim.g.mapleader = k'<bs>'
+--- ```
+---
--- @param str string String to be converted.
--- @return string
--- @see |nvim_replace_termcodes()|
diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua
index dd67fdb38b..6573c68493 100644
--- a/runtime/lua/vim/_meta/api.lua
+++ b/runtime/lua/vim/_meta/api.lua
@@ -7,6 +7,13 @@ 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
@@ -120,11 +127,16 @@ function vim.api.nvim__unpack(str) end
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):
+--- 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})
+--- 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
@@ -307,26 +319,32 @@ function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end
--- 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}, {})
+--- 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)
+--- 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
@@ -337,11 +355,13 @@ function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end
--- @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 table<string,any> Optional parameters. Keys:
+--- @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[]
@@ -457,6 +477,10 @@ function vim.api.nvim_buf_line_count(buffer) end
--- 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()`
@@ -621,6 +645,7 @@ function vim.api.nvim_buf_set_option(buffer, name, value) end
--- 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
@@ -758,6 +783,7 @@ 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
@@ -773,6 +799,7 @@ 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"},
@@ -781,17 +808,21 @@ function vim.api.nvim_create_augroup(name, opts) end
--- 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:
+---
+--- 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"
+--- pattern = vim.fn.expand("~") .. "/some/path/*.py"
--- ```
---
--- @param event any (string|array) Event(s) that will trigger the handler
@@ -853,10 +884,11 @@ 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!
+--- :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
@@ -1067,6 +1099,7 @@ function vim.api.nvim_execute_lua(code, args) end
--- 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)
@@ -1094,19 +1127,21 @@ function vim.api.nvim_get_api_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",
---- })
+--- -- 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.
---
@@ -1132,6 +1167,7 @@ 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")
@@ -1193,6 +1229,8 @@ function vim.api.nvim_get_current_win() end
--- • 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
@@ -1452,14 +1490,18 @@ function vim.api.nvim_open_term(buffer, opts) end
--- 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
@@ -1774,7 +1816,9 @@ function vim.api.nvim_set_current_win(window) end
--- • on_buf: called for each buffer being redrawn (before window
--- callbacks) ["buf", bufnr, tick]
--- • on_win: called when starting to redraw a specific window.
---- ["win", winid, bufnr, topline, botline_guess]
+--- 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]
@@ -1835,10 +1879,13 @@ function vim.api.nvim_set_hl_ns_fast(ns_id) end
--- 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>
--- ```
diff --git a/runtime/lua/vim/_meta/api_keysets.lua b/runtime/lua/vim/_meta/api_keysets.lua
index 08c29ebe7a..4d08563ce2 100644
--- a/runtime/lua/vim/_meta/api_keysets.lua
+++ b/runtime/lua/vim/_meta/api_keysets.lua
@@ -122,10 +122,18 @@ error('Cannot require a meta file')
--- @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.highlight
--- @field bold? boolean
diff --git a/runtime/lua/vim/_meta/builtin.lua b/runtime/lua/vim/_meta/builtin.lua
index d7b76a803c..0a6dd3e151 100644
--- a/runtime/lua/vim/_meta/builtin.lua
+++ b/runtime/lua/vim/_meta/builtin.lua
@@ -131,7 +131,8 @@ function vim.str_utf_pos(str) end
--- The result can be added to {index} to get the starting byte of a character.
---
--- Examples:
---- <pre>lua
+---
+--- ```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
@@ -139,7 +140,7 @@ function vim.str_utf_pos(str) end
---
--- -- Returns -1 because the index is pointing at the second byte of a character
--- vim.str_utf_start('æ', 2)
---- </pre>
+--- ```
---
--- @param str string
--- @param index number
@@ -150,7 +151,8 @@ function vim.str_utf_start(str, index) end
--- to.
---
--- Examples:
---- <pre>lua
+---
+--- ```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
@@ -158,7 +160,7 @@ function vim.str_utf_start(str, index) end
---
--- -- Returns 1 because the index is pointing at the penultimate byte of a character
--- vim.str_utf_end('æ', 1)
---- </pre>
+--- ```
---
--- @param str string
--- @param index number
@@ -204,7 +206,8 @@ function vim.schedule(callback) end
--- this time.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
---
--- ---
--- -- Wait for 100 ms, allowing other events to process
@@ -226,7 +229,7 @@ function vim.schedule(callback) end
--- if vim.wait(10000, function() return vim.g.timer_result end) then
--- print('Only waiting a little bit of time!')
--- end
---- </pre>
+--- ```
---
--- @param time integer Number of milliseconds to wait
--- @param callback? fun(): boolean Optional callback. Waits until {callback} returns true
@@ -258,22 +261,23 @@ function vim.wait(time, callback, interval, fast_only) end
--- likewise experimental).
---
--- Example (stub for a |ui-popupmenu| implementation):
---- <pre>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)
---- </pre>
+---
+--- ```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()
diff --git a/runtime/lua/vim/_meta/diff.lua b/runtime/lua/vim/_meta/diff.lua
index 246ac0c75a..f265139448 100644
--- a/runtime/lua/vim/_meta/diff.lua
+++ b/runtime/lua/vim/_meta/diff.lua
@@ -6,24 +6,25 @@
--- either directly or via callback arguments, are 1-based.
---
--- Examples:
---- <pre>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}
---- -- }
---- </pre>
+--- ```lua
+--- vim.diff('a\n', 'b\nc\n')
+--- -- =>
+--- -- @@ -1 +1,2 @@
+--- -- -a
+--- -- +b
+--- -- +c
---
---- @param a string First string to compare
---- @param b string Second string to compare
---- @param opts table<string,any> Optional parameters:
+--- 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.
@@ -64,6 +65,6 @@
--- Use the indent heuristic for the internal
--- diff library.
---
---- @return string|table|nil
+---@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
index 76a6c7b733..edf905c7c6 100644
--- a/runtime/lua/vim/_meta/json.lua
+++ b/runtime/lua/vim/_meta/json.lua
@@ -1,8 +1,8 @@
---- @meta
+---@meta
-- luacheck: no unused args
---- @defgroup vim.json
+---@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()|.
@@ -14,24 +14,23 @@
--- - Decodes empty array as `{}` (empty Lua table).
---
--- Example:
---- <pre>lua
---- :lua vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
---- --> { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
---- </pre>
---- Parameters: ~
---- • {str} Stringified JSON data.
---- • {opts} Options map keys:
---- • luanil: { object: bool, array: bool }
---- • `luanil.object=true` converts `null` in JSON objects to
---- Lua `nil` instead of `vim.NIL`.
---- • `luanil.array=true` converts `null` in JSON arrays to Lua
---- `nil` instead of `vim.NIL`.
---- @param str string
---- @param opts? table<string, any>
---- @return any
+---
+--- ```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
+---@param obj any
+---@return string
function vim.json.encode(obj) end
diff --git a/runtime/lua/vim/_meta/misc.lua b/runtime/lua/vim/_meta/misc.lua
index 8a76755962..0d70e16314 100644
--- a/runtime/lua/vim/_meta/misc.lua
+++ b/runtime/lua/vim/_meta/misc.lua
@@ -5,9 +5,11 @@
--- Invokes |vim-function| or |user-function| {func} with arguments {...}.
--- See also |vim.fn|.
--- Equivalent to:
---- <pre>lua
---- vim.fn[func]({...})
---- </pre>
+---
+--- ```lua
+--- vim.fn[func]({...})
+--- ```
+---
--- @param func fun()
--- @param ... any
function vim.call(func, ...) end
diff --git a/runtime/lua/vim/_meta/options.lua b/runtime/lua/vim/_meta/options.lua
index 4fb3141df0..af676fa961 100644
--- a/runtime/lua/vim/_meta/options.lua
+++ b/runtime/lua/vim/_meta/options.lua
@@ -141,6 +141,7 @@ vim.bo.ai = vim.bo.autoindent
--- :set autoread<
--- ```
---
+---
--- @type boolean
vim.o.autoread = true
vim.o.ar = vim.o.autoread
@@ -354,6 +355,7 @@ vim.go.bkc = vim.go.backupcopy
--- ```
--- :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:
--- ```
@@ -409,9 +411,9 @@ vim.go.bex = vim.go.backupext
---
--- Note that environment variables are not expanded. If you want to use
--- $HOME you must expand it explicitly, e.g.:
---- ```
---- :let &backupskip = escape(expand('$HOME'), '\') .. '/tmp/*'
---
+--- ```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
@@ -833,6 +835,7 @@ vim.bo.cino = vim.bo.cinoptions
--- set cinscopedecls+=signals,public\ slots,private\ slots
--- ```
---
+---
--- @type string
vim.o.cinscopedecls = "public,protected,private"
vim.o.cinsd = vim.o.cinscopedecls
@@ -916,11 +919,11 @@ vim.go.cwh = vim.go.cmdwinheight
--- 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.
---
@@ -1418,6 +1421,7 @@ vim.wo.crb = vim.wo.cursorbind
--- au WinEnter * set cursorline cursorcolumn
--- ```
---
+---
--- @type boolean
vim.o.cursorcolumn = false
vim.o.cuc = vim.o.cursorcolumn
@@ -1499,6 +1503,7 @@ vim.go.debug = vim.o.debug
--- let &l:define = '^\s*\ze\k\+\s*=\s*function('
--- ```
---
+---
--- @type string
vim.o.define = ""
vim.o.def = vim.o.define
@@ -1679,6 +1684,7 @@ vim.go.dex = vim.go.diffexpr
--- :set diffopt-=internal " do NOT use the internal diff parser
--- ```
---
+---
--- @type string
vim.o.diffopt = "internal,filler,closeoff"
vim.o.dip = vim.o.diffopt
@@ -1729,6 +1735,7 @@ vim.go.dg = vim.go.digraph
--- ```
--- :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.
@@ -1917,6 +1924,7 @@ vim.go.efm = vim.go.errorformat
--- :set ei=WinEnter,WinLeave
--- ```
---
+---
--- @type string
vim.o.eventignore = ""
vim.o.ei = vim.o.eventignore
@@ -2634,14 +2642,12 @@ vim.go.gp = vim.go.grepprg
--- 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:
@@ -2697,10 +2703,10 @@ vim.go.gp = vim.go.grepprg
--- 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-likes modes, use
+--- terminal. In Insert-like modes, use
--- a vertical bar cursor with colors from
---- "Cursor" highlight group. In Replace-likes
---- modes, use a underline cursor with
+--- "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
@@ -2719,6 +2725,7 @@ vim.go.gp = vim.go.grepprg
--- :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
@@ -2790,6 +2797,7 @@ vim.go.gcr = vim.go.guicursor
--- :set guifont=Andale_Mono:h7.5:w4.5
--- ```
---
+---
--- @type string
vim.o.guifont = ""
vim.o.gfn = vim.o.guifont
@@ -2944,6 +2952,7 @@ vim.go.gtl = vim.go.guitablabel
--- :let &guitabtooltip = "line one\nline two"
--- ```
---
+---
--- @type string
vim.o.guitabtooltip = ""
vim.o.gtt = vim.o.guitabtooltip
@@ -3206,6 +3215,7 @@ vim.go.inc = vim.go.include
--- ```
--- :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>`.
@@ -3258,6 +3268,7 @@ vim.bo.inex = vim.bo.includeexpr
--- 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
@@ -3565,6 +3576,7 @@ vim.go.kp = vim.go.keywordprg
--- ```
--- :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
@@ -3762,6 +3774,7 @@ vim.go.lw = vim.go.lispwords
--- ```
--- :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.
@@ -3790,6 +3803,7 @@ vim.wo.list = vim.o.list
--- >--
--- 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:
@@ -3801,6 +3815,7 @@ vim.wo.list = vim.o.list
--- <-->
--- etc.
--- ```
+---
--- When "tab:" is omitted, a tab is shown as ^I.
--- *lcs-space*
--- space:c Character to show for a space. When omitted, spaces
@@ -3816,6 +3831,7 @@ vim.wo.list = vim.o.list
--- ```
--- ---+---+--
--- ```
+---
--- *lcs-lead*
--- lead:c Character to show for leading spaces. When omitted,
--- leading spaces are blank. Overrides the "space" and
@@ -3824,6 +3840,7 @@ vim.wo.list = vim.o.list
--- ```
--- :set listchars+=tab:>-,lead:.
--- ```
+---
--- *lcs-leadmultispace*
--- leadmultispace:c...
--- Like the `lcs-multispace` value, but for leading
@@ -3834,6 +3851,7 @@ vim.wo.list = vim.o.list
--- ```
--- ---+---+--XXX
--- ```
+---
--- Where "XXX" denotes the first non-blank characters in
--- the line.
--- *lcs-trail*
@@ -3941,6 +3959,7 @@ vim.go.mef = vim.go.makeef
--- :set makeencoding=char " system locale is used
--- ```
---
+---
--- @type string
vim.o.makeencoding = ""
vim.o.menc = vim.o.makeencoding
@@ -3986,13 +4005,11 @@ vim.go.mp = vim.go.makeprg
--- '>' (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`
@@ -4078,6 +4095,7 @@ vim.go.mis = vim.go.menuitems
--- ```
--- {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
@@ -4196,6 +4214,7 @@ vim.go.more = vim.o.more
--- ```
--- :set mouse=nv
--- ```
+---
--- To temporarily disable mouse support, hold the shift key while using
--- the mouse.
---
@@ -4299,6 +4318,7 @@ vim.go.mh = vim.go.mousehide
--- :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)
@@ -4477,6 +4497,7 @@ vim.bo.nf = vim.bo.nrformats
--- |there | 4 there | 1 there | 1 there
--- ```
---
+---
--- @type boolean
vim.o.number = false
vim.o.nu = vim.o.number
@@ -4710,10 +4731,10 @@ vim.wo.pvw = vim.wo.previewwindow
--- 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
@@ -4986,6 +5007,7 @@ vim.go.ru = vim.go.ruler
--- :set rulerformat=%15(%c%V\ %p%%%)
--- ```
---
+---
--- @type string
vim.o.rulerformat = ""
vim.o.ruf = vim.o.rulerformat
@@ -5363,6 +5385,7 @@ vim.go.ssop = vim.go.sessionoptions
--- ```
--- :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
@@ -5449,7 +5472,6 @@ vim.go.sdf = vim.go.shadafile
--- 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.
@@ -5726,6 +5748,7 @@ vim.go.shm = vim.go.shortmess
--- :setlocal showbreak=NONE
--- ```
---
+---
--- @type string
vim.o.showbreak = ""
vim.o.sbr = vim.o.showbreak
@@ -5858,15 +5881,16 @@ vim.go.ss = vim.go.sidescroll
--- 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
@@ -6171,6 +6195,7 @@ vim.bo.spo = vim.bo.spelloptions
--- ```
--- :set sps=file:~/.config/nvim/sugg,best,expr:MySuggest()
--- ```
+---
--- This option cannot be set from a `modeline` or in the `sandbox`, for
--- security reasons.
---
@@ -6263,6 +6288,7 @@ vim.go.sol = vim.go.startofline
--- 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
@@ -6282,7 +6308,6 @@ vim.go.sol = vim.go.startofline
--- :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.
@@ -6522,6 +6547,7 @@ vim.wo.stc = vim.wo.statuscolumn
--- :endfunction
--- ```
---
+---
--- @type string
vim.o.statusline = ""
vim.o.stl = vim.o.statusline
@@ -6553,6 +6579,7 @@ vim.go.su = vim.go.suffixes
--- :set suffixesadd=.java
--- ```
---
+---
--- @type string
vim.o.suffixesadd = ""
vim.o.sua = vim.o.suffixesadd
@@ -7445,6 +7472,7 @@ vim.go.ww = vim.go.whichwrap
--- :set wc=<Tab>
--- ```
---
+---
--- @type integer
vim.o.wildchar = 9
vim.o.wc = vim.o.wildchar
@@ -7533,6 +7561,7 @@ vim.go.wic = vim.go.wildignorecase
--- :cnoremap <Left> <Space><BS><Left>
--- :cnoremap <Right> <Space><BS><Right>
--- ```
+---
--- `hl-WildMenu` highlights the current match.
---
--- @type boolean
@@ -7762,6 +7791,7 @@ vim.go.wh = vim.go.winheight
--- set winhighlight=Normal:MyNormal,NormalNC:MyNormalNC
--- ```
---
+---
--- @type string
vim.o.winhighlight = ""
vim.o.winhl = vim.o.winhighlight
diff --git a/runtime/lua/vim/_meta/regex.lua b/runtime/lua/vim/_meta/regex.lua
index ab4f46d43f..58aa2be8c2 100644
--- a/runtime/lua/vim/_meta/regex.lua
+++ b/runtime/lua/vim/_meta/regex.lua
@@ -21,7 +21,7 @@ local regex = {} -- luacheck: no unused
--- 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()` can be directly used as a condition in an if-statement.
+--- `regex:match_str()` can be directly used as a condition in an if-statement.
--- @param str string
function regex:match_str(str) end
diff --git a/runtime/lua/vim/_meta/spell.lua b/runtime/lua/vim/_meta/spell.lua
index d55867f769..57f2180895 100644
--- a/runtime/lua/vim/_meta/spell.lua
+++ b/runtime/lua/vim/_meta/spell.lua
@@ -10,13 +10,14 @@
--- the buffer. Consider calling this with |nvim_buf_call()|.
---
--- Example:
---- <pre>lua
---- vim.spell.check("the quik brown fox")
---- -- =>
---- -- {
---- -- {'quik', 'bad', 5}
---- -- }
---- </pre>
+---
+--- ```lua
+--- vim.spell.check("the quik brown fox")
+--- -- =>
+--- -- {
+--- -- {'quik', 'bad', 5}
+--- -- }
+--- ```
---
--- @param str string
--- @return {[1]: string, [2]: string, [3]: string}[]
diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua
index 6209ce0c73..efb779ad41 100644
--- a/runtime/lua/vim/_meta/vimfn.lua
+++ b/runtime/lua/vim/_meta/vimfn.lua
@@ -6194,7 +6194,7 @@ function vim.fn.prevnonblank(lnum) end
--- *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 accomodate translations
+--- corresponding message in English. To accommodate translations
--- having a different word order, positional arguments may be
--- used to indicate this. For instance: >vim
---
diff --git a/runtime/lua/vim/_options.lua b/runtime/lua/vim/_options.lua
index e1c125baf2..7b44f6b35f 100644
--- a/runtime/lua/vim/_options.lua
+++ b/runtime/lua/vim/_options.lua
@@ -7,11 +7,12 @@
---"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:
----<pre>lua
---- local list = { 1, 2, 3 }
---- vim.fn.remove(list, 0)
---- vim.print(list) --> "{ 1, 2, 3 }"
----</pre>
+---
+--- ```lua
+--- local list = { 1, 2, 3 }
+--- vim.fn.remove(list, 0)
+--- vim.print(list) --> "{ 1, 2, 3 }"
+--- ```
---@addtogroup lua-vimscript
---@brief <pre>help
@@ -131,13 +132,17 @@ local function get_options_info(name)
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: <pre>lua
---- vim.env.FOO = 'bar'
---- print(vim.env.TERM)
----</pre>
+--- 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)
@@ -226,16 +231,18 @@ end
---global value of a |global-local| option, see |:setglobal|.
---</pre>
----Get or set |options|. Like `:set`. Invalid key is an error.
+--- 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.
+--- Note: this works on both buffer-scoped and window-scoped options using the
+--- current buffer and window.
---
----Example: <pre>lua
---- vim.o.cmdheight = 4
---- print(vim.o.columns)
---- print(vim.o.foo) -- error: invalid key
----</pre>
+--- 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, {})
@@ -245,18 +252,20 @@ vim.o = setmetatable({}, {
end,
})
----Get or set global |options|. Like `:setglobal`. Invalid key is
----an error.
+--- 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.
+--- 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: <pre>lua
---- vim.go.cmdheight = 4
---- print(vim.go.columns)
---- print(vim.go.bar) -- error: invalid key
----</pre>
+--- 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' })
@@ -266,37 +275,39 @@ vim.go = setmetatable({}, {
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.
+--- 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`.
+--- Note: this is equivalent to both `:set` and `:setlocal`.
---
----Example: <pre>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
----</pre>
----@param bufnr integer|nil
+--- 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.
+--- 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.
+--- Note: only {bufnr} with value `0` (the current buffer in the window) is
+--- supported.
---
----Example: <pre>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'
+--- Example:
---
----</pre>
+--- ```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 [[
@@ -795,77 +806,93 @@ end
--- @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.
+--- 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: <pre>lua
---- vim.cmd [[set wildignore=*.pyc,*.o]]
+--- For values that are comma-separated lists, an array will be returned with
+--- the values as entries in the array:
---
---- vim.print(vim.opt.wildignore:get())
---- -- { "*.pyc", "*.o", }
+--- ```lua
+--- vim.cmd [[set wildignore=*.pyc,*.o]]
---
---- for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
---- print("Will ignore:", ignore_pattern)
---- end
---- -- Will ignore: *.pyc
---- -- Will ignore: *.o
----</pre>
+--- vim.print(vim.opt.wildignore:get())
+--- -- { "*.pyc", "*.o", }
---
----For values that are comma-separated maps, a table will be returned with
----the names as keys and the values as entries: <pre>lua
---- vim.cmd [[set listchars=space:_,tab:>~]]
+--- for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
+--- print("Will ignore:", ignore_pattern)
+--- end
+--- -- Will ignore: *.pyc
+--- -- Will ignore: *.o
+--- ```
---
---- vim.print(vim.opt.listchars:get())
---- -- { space = "_", tab = ">~", }
+--- For values that are comma-separated maps, a table will be returned with
+--- the names as keys and the values as entries:
---
---- for char, representation in pairs(vim.opt.listchars:get()) do
---- print(char, "=>", representation)
---- end
----</pre>
+--- ```lua
+--- vim.cmd [[set listchars=space:_,tab:>~]]
---
----For values that are lists of flags, a set will be returned with the flags
----as keys and `true` as entries. <pre>lua
---- vim.cmd [[set formatoptions=njtcroql]]
+--- vim.print(vim.opt.listchars:get())
+--- -- { space = "_", tab = ">~", }
---
---- vim.print(vim.opt.formatoptions:get())
---- -- { n = true, j = true, c = true, ... }
+--- 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
+--- ```
---
---- local format_opts = vim.opt.formatoptions:get()
---- if format_opts.j then
---- print("J is enabled!")
---- end
----</pre>
---@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+=|
+--- 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'
+--- ```
---
----These are equivalent: <pre>lua
---- vim.opt.formatoptions:append('j')
---- vim.opt.formatoptions = vim.opt.formatoptions + 'j'
----</pre>
---@param value string Value to append
---- @diagnostic disable-next-line:unused-local used for gen_vimdoc
+---@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^=|
+--- 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'
+--- ```
---
----These are equivalent: <pre>lua
---- vim.opt.wildignore:prepend('*.o')
---- vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
----</pre>
---@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-=|
+--- 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'
+--- ```
---
----These are equivalent: <pre>lua
---- vim.opt.wildignore:remove('*.pyc')
---- vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
----</pre>
---@param value string Value to remove
---@diagnostic disable-next-line:unused-local used for gen_vimdoc
function Option:remove(value) end -- luacheck: no unused
diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua
index a1f3020c88..b8d3906b7f 100644
--- a/runtime/lua/vim/diagnostic.lua
+++ b/runtime/lua/vim/diagnostic.lua
@@ -553,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.
---
@@ -1601,18 +1603,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.
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua
index 0e8ecf1b07..d847c28f5c 100644
--- a/runtime/lua/vim/filetype.lua
+++ b/runtime/lua/vim/filetype.lua
@@ -669,6 +669,8 @@ local extension = {
m2 = 'modula2',
mi = 'modula2',
lm3 = 'modula3',
+ mojo = 'mojo',
+ ['🔥'] = 'mojo', -- 🙄
ssc = 'monk',
monk = 'monk',
tsc = 'monk',
@@ -2079,43 +2081,45 @@ 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 = {
--- ['.*'] = {
@@ -2131,7 +2135,7 @@ end
--- },
--- },
--- }
---- </pre>
+--- ```
---
---@param filetypes vim.filetype.add.filetypes A table containing new filetype maps (see example).
function M.add(filetypes)
@@ -2254,19 +2258,19 @@ 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 vim.filetype.match.args Table specifying which matching strategy to use.
--- Accepted keys are:
@@ -2402,9 +2406,10 @@ end
--- is set, meaning it should respect all FileType autocmds and ftplugin files.
---
--- Example:
---- <pre>lua
---- vim.filetype.get_option('vim', 'commentstring')
---- </pre>
+---
+--- ```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
diff --git a/runtime/lua/vim/fs.lua b/runtime/lua/vim/fs.lua
index 7cd9e3cf04..22612a7255 100644
--- a/runtime/lua/vim/fs.lua
+++ b/runtime/lua/vim/fs.lua
@@ -5,7 +5,8 @@ local iswin = vim.uv.os_uname().sysname == 'Windows_NT'
--- 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,7 +18,7 @@ local iswin = vim.uv.os_uname().sysname == 'Windows_NT'
--- if root_dir then
--- print("Found git repository at", root_dir)
--- end
---- </pre>
+--- ```
---
---@param start (string) Initial path.
---@return fun(_, dir: string): string? # Iterator
@@ -165,7 +166,8 @@ end
--- to narrow the search to find only that type.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
--- -- location of Cargo.toml from the current buffer's path
--- local cargo = vim.fs.find('Cargo.toml', {
--- upward = true,
@@ -183,7 +185,7 @@ end
--- local cpp_hpp = vim.fs.find(function(name, path)
--- return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$')
--- end, {limit = math.huge, type = 'file'})
---- </pre>
+--- ```
---
---@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.
@@ -322,16 +324,17 @@ 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('~/src/neovim')
+--- -- '/home/jdoe/src/neovim'
---
---- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
---- --> '/Users/jdoe/.config/nvim/init.vim'
---- </pre>
+--- 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:
diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua
index 14b0e71312..fc2fd43c97 100644
--- a/runtime/lua/vim/highlight.lua
+++ b/runtime/lua/vim/highlight.lua
@@ -1,23 +1,24 @@
---@defgroup vim.highlight
---
----@brief
----Nvim includes a function for highlighting a selection on yank.
+--- Nvim includes a function for highlighting a selection on yank.
---
----To enable it, add the following to your `init.vim`:
----<pre>vim
---- au TextYankPost * silent! lua vim.highlight.on_yank()
----</pre>
+--- To enable it, add the following to your `init.vim`:
---
----You can customize the highlight group and the duration of
----the highlight via:
----<pre>vim
---- au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150}
----</pre>
+--- ```vim
+--- au TextYankPost * silent! lua vim.highlight.on_yank()
+--- ```
---
----If you want to exclude visual selections from highlighting on yank, use:
----<pre>vim
---- au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
----</pre>
+--- 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
@@ -55,6 +56,9 @@ function M.range(bufnr, ns, higroup, start, finish, opts)
local inclusive = opts.inclusive or false
local priority = opts.priority or M.priorities.user
+ -- 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
diff --git a/runtime/lua/vim/iter.lua b/runtime/lua/vim/iter.lua
index 56c130dd0c..595baa7019 100644
--- a/runtime/lua/vim/iter.lua
+++ b/runtime/lua/vim/iter.lua
@@ -15,44 +15,45 @@
--- (for function iterators, this means that the first value returned by the function is nil).
---
--- Examples:
---- <pre>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" }
---- </pre>
+---
+--- ```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()|.
@@ -140,9 +141,10 @@ end
--- Add a filter step to the iterator pipeline.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
--- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
---- </pre>
+--- ```
---
---@param f function(...):bool Takes all values returned from the previous stage
--- in the pipeline and returns false or nil if the
@@ -176,7 +178,8 @@ end
--- If the map function returns nil, the value is filtered from the iterator.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
--- local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
--- if v % 2 == 0 then
--- return v * 3
@@ -184,7 +187,7 @@ end
--- end)
--- it:totable()
--- -- { 6, 12 }
---- </pre>
+--- ```
---
---@param f function(...):any Mapping function. Takes all values returned from
--- the previous stage in the pipeline as arguments
@@ -288,7 +291,8 @@ end
--- pipeline, each value will be included in a table.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
--- vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
--- -- { 100, 20, 50 }
---
@@ -297,7 +301,7 @@ end
---
--- vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
--- -- { { 'a', 1 }, { 'c', 3 } }
---- </pre>
+--- ```
---
--- The generated table is a list-like table with consecutive, numeric indices.
--- To create a map-like table with arbitrary keys, use |Iter:fold()|.
@@ -352,7 +356,8 @@ end
--- Fold ("reduce") an iterator or table into a single value.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
--- -- Create a new table with only even values
--- local t = { a = 1, b = 2, c = 3, d = 4 }
--- local it = vim.iter(t)
@@ -362,7 +367,7 @@ end
--- return t
--- end)
--- -- { b = 2, d = 4 }
---- </pre>
+--- ```
---
---@generic A
---
@@ -398,7 +403,8 @@ end
--- Return the next value from the iterator.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
--- it:next()
@@ -408,7 +414,7 @@ end
--- it:next()
--- -- 3
---
---- </pre>
+--- ```
---
---@return any
function Iter.next(self) -- luacheck: no unused args
@@ -431,13 +437,14 @@ end
--- Only supported for iterators on list-like tables.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 3, 6, 9, 12 }):rev()
--- it:totable()
--- -- { 12, 9, 6, 3 }
---
---- </pre>
+--- ```
---
---@return Iter
function Iter.rev(self)
@@ -457,7 +464,8 @@ end
--- Only supported for iterators on list-like tables.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 3, 6, 9, 12 })
--- it:peek()
@@ -467,7 +475,7 @@ end
--- it:next()
--- -- 3
---
---- </pre>
+--- ```
---
---@return any
function Iter.peek(self) -- luacheck: no unused args
@@ -486,7 +494,8 @@ end
--- Advances the iterator. Returns nil and drains the iterator if no value is found.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 3, 6, 9, 12 })
--- it:find(12)
@@ -500,7 +509,7 @@ end
--- it:find(function(v) return v % 4 == 0 end)
--- -- 12
---
---- </pre>
+--- ```
---
---@return any
function Iter.find(self, f)
@@ -536,7 +545,8 @@ end
--- Only supported for iterators on list-like tables.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
--- it:rfind(1)
@@ -544,7 +554,7 @@ end
--- it:rfind(1)
--- -- 1 1
---
---- </pre>
+--- ```
---
---@see Iter.find
---
@@ -578,13 +588,14 @@ end
--- Only supported for iterators on list-like tables.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
--- local it = vim.iter({1, 2, 3, 4})
--- it:nextback()
--- -- 4
--- it:nextback()
--- -- 3
---- </pre>
+--- ```
---
---@return any
function Iter.nextback(self) -- luacheck: no unused args
@@ -604,7 +615,8 @@ end
--- Only supported for iterators on list-like tables.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
--- local it = vim.iter({1, 2, 3, 4})
--- it:peekback()
--- -- 4
@@ -612,7 +624,7 @@ end
--- -- 4
--- it:nextback()
--- -- 4
---- </pre>
+--- ```
---
---@return any
function Iter.peekback(self) -- luacheck: no unused args
@@ -629,13 +641,14 @@ end
--- Skip values in the iterator.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
--- it:next()
--- -- 9
---
---- </pre>
+--- ```
---
---@param n number Number of values to skip.
---@return Iter
@@ -661,13 +674,14 @@ end
--- Only supported for iterators on list-like tables.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
--- local it = vim.iter({ 1, 2, 3, 4, 5 }):skipback(2)
--- it:next()
--- -- 1
--- it:nextback()
--- -- 3
---- </pre>
+--- ```
---
---@param n number Number of values to skip.
---@return Iter
@@ -691,7 +705,8 @@ end
--- This function advances the iterator.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 3, 6, 9, 12 })
--- it:nth(2)
@@ -699,7 +714,7 @@ end
--- it:nth(2)
--- -- 12
---
---- </pre>
+--- ```
---
---@param n number The index of the value to return.
---@return any
@@ -716,7 +731,8 @@ end
--- Only supported for iterators on list-like tables.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter({ 3, 6, 9, 12 })
--- it:nthback(2)
@@ -724,7 +740,7 @@ end
--- it:nthback(2)
--- -- 3
---
---- </pre>
+--- ```
---
---@param n number The index of the value to return.
---@return any
@@ -805,7 +821,8 @@ end
--- Drains the iterator.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter(vim.gsplit('abcdefg', ''))
--- it:last()
@@ -815,7 +832,7 @@ end
--- it:last()
--- -- 15
---
---- </pre>
+--- ```
---
---@return any
function Iter.last(self)
@@ -839,19 +856,22 @@ end
--- Add an iterator stage that returns the current iterator count as well as the iterator value.
---
--- For list tables, prefer
---- <pre>lua
+---
+--- ```lua
--- vim.iter(ipairs(t))
---- </pre>
+--- ```
---
--- over
---- <pre>lua
+---
+--- ```lua
--- vim.iter(t):enumerate()
---- </pre>
+--- ```
---
--- as the former is faster.
---
--- Example:
---- <pre>lua
+---
+--- ```lua
---
--- local it = vim.iter(vim.gsplit('abc', '')):enumerate()
--- it:next()
@@ -861,7 +881,7 @@ end
--- it:next()
--- -- 3 'c'
---
---- </pre>
+--- ```
---
---@return Iter
function Iter.enumerate(self)
@@ -959,9 +979,10 @@ end
--- Collect an iterator into a table.
---
--- This is a convenience function that performs:
---- <pre>lua
+---
+--- ```lua
--- vim.iter(f):totable()
---- </pre>
+--- ```
---
---@param f function Iterator function
---@return table
@@ -972,9 +993,10 @@ end
--- Filter a table or iterator.
---
--- This is a convenience function that performs:
---- <pre>lua
+---
+--- ```lua
--- vim.iter(src):filter(f):totable()
---- </pre>
+--- ```
---
---@see |Iter:filter()|
---
@@ -990,9 +1012,10 @@ end
--- Map and filter a table or iterator.
---
--- This is a convenience function that performs:
---- <pre>lua
+---
+--- ```lua
--- vim.iter(src):map(f):totable()
---- </pre>
+--- ```
---
---@see |Iter:map()|
---
diff --git a/runtime/lua/vim/keymap.lua b/runtime/lua/vim/keymap.lua
index 2b55ddc787..df593be097 100644
--- a/runtime/lua/vim/keymap.lua
+++ b/runtime/lua/vim/keymap.lua
@@ -2,20 +2,21 @@ local keymap = {}
--- Adds a new |mapping|.
--- Examples:
---- <pre>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)')
---- </pre>
+---
+--- ```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)')
+--- ```
---
---@param mode string|table Mode short-name, see |nvim_set_keymap()|.
--- Can also be list of modes to create mapping on multiple modes.
@@ -80,11 +81,13 @@ 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|boolean) Remove a mapping from the given buffer.
--- When `0` or `true`, use the current buffer.
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua
index b0caf5af35..f68ca7e88c 100644
--- a/runtime/lua/vim/lsp.lua
+++ b/runtime/lua/vim/lsp.lua
@@ -809,13 +809,14 @@ end
--- 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:
---
@@ -1955,8 +1956,6 @@ function lsp.buf_detach_client(bufnr, 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.
@@ -1990,9 +1989,10 @@ end
---
--- You can also use the `stop()` function on a |vim.lsp.client| object.
--- To stop all clients:
---- <pre>lua
+---
+--- ```lua
--- vim.lsp.stop_client(vim.lsp.get_clients())
---- </pre>
+--- ```
---
--- By default asks the server to shutdown, unless stop was requested
--- already for this client, then force-shutdown is attempted.
@@ -2504,12 +2504,7 @@ end
---@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)
---- vim.print(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)
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua
index 6cd0aa1e95..8a29fac2b5 100644
--- a/runtime/lua/vim/lsp/buf.lua
+++ b/runtime/lua/vim/lsp/buf.lua
@@ -168,13 +168,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
@@ -555,11 +553,12 @@ 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.
diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua
index d581eb985f..384d09ee48 100644
--- a/runtime/lua/vim/lsp/codelens.lua
+++ b/runtime/lua/vim/lsp/codelens.lua
@@ -255,10 +255,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(),
diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua
index 2a77992c4d..73ffa1a46c 100644
--- a/runtime/lua/vim/lsp/diagnostic.lua
+++ b/runtime/lua/vim/lsp/diagnostic.lua
@@ -203,7 +203,8 @@ end
---
--- 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
@@ -221,7 +222,7 @@ end
--- update_in_insert = false,
--- }
--- )
---- </pre>
+--- ```
---
---@param config table Configuration table (see |vim.diagnostic.config()|).
function M.on_publish_diagnostics(_, result, ctx, config)
@@ -263,7 +264,8 @@ end
---
--- See |vim.diagnostic.config()| for configuration options. Handler-specific
--- configuration can be set using |vim.lsp.with()|:
---- <pre>lua
+---
+--- ```lua
--- vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with(
--- vim.lsp.diagnostic.on_diagnostic, {
--- -- Enable underline, use default values
@@ -281,7 +283,7 @@ end
--- update_in_insert = false,
--- }
--- )
---- </pre>
+--- ```
---
---@param config table Configuration table (see |vim.diagnostic.config()|).
function M.on_diagnostic(_, result, ctx, config)
diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua
index a6b70ac911..4ea3dde81c 100644
--- a/runtime/lua/vim/lsp/handlers.lua
+++ b/runtime/lua/vim/lsp/handlers.lua
@@ -342,20 +342,22 @@ M[ms.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
@@ -430,19 +432,24 @@ M[ms.textDocument_typeDefinition] = 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
diff --git a/runtime/lua/vim/lsp/semantic_tokens.lua b/runtime/lua/vim/lsp/semantic_tokens.lua
index 5b20344bd3..a5831c0beb 100644
--- a/runtime/lua/vim/lsp/semantic_tokens.lua
+++ b/runtime/lua/vim/lsp/semantic_tokens.lua
@@ -555,9 +555,10 @@ 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>
+---
+--- ```lua
+--- client.server_capabilities.semanticTokensProvider = nil
+--- ```
---
---@param bufnr integer
---@param client_id integer
diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua
index a6d17afa1b..54721865b7 100644
--- a/runtime/lua/vim/lsp/util.lua
+++ b/runtime/lua/vim/lsp/util.lua
@@ -454,23 +454,6 @@ 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 or bufnr == 0
- local cursor = (function()
- if not is_current_buf then
- return {
- row = -1,
- col = -1,
- }
- end
- local cursor = api.nvim_win_get_cursor(0)
- return {
- row = cursor[1] - 1,
- col = cursor[2],
- }
- end)()
-
-- 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
@@ -480,7 +463,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
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
@@ -527,20 +509,6 @@ 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
@@ -560,16 +528,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
end
end
- -- 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, cursor.row) or '')
- if is_valid_cursor then
- api.nvim_win_set_cursor(0, { cursor.row + 1, cursor.col })
- end
- end
-
-- Remove final line if needed
local fix_eol = has_eol_text_edit
fix_eol = fix_eol and (vim.bo[bufnr].eol or (vim.bo[bufnr].fixeol and not vim.bo[bufnr].binary))
@@ -1087,6 +1045,12 @@ end
--- - focusable (string or table) override `focusable`
--- - zindex (string or table) override `zindex`, defaults to 50
--- - relative ("mouse"|"cursor") defaults to "cursor"
+--- - 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({
@@ -1105,7 +1069,20 @@ 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
+
+ if anchor_below then
anchor = anchor .. 'N'
height = math.min(lines_below, height)
row = 1
@@ -1635,7 +1612,8 @@ 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()|)
+---@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
diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua
index 422d49d746..0c38fa955a 100644
--- a/runtime/lua/vim/shared.lua
+++ b/runtime/lua/vim/shared.lua
@@ -65,19 +65,21 @@ end
--- (as opposed to |vim.split()| which is "eager").
---
--- Example:
---- <pre>lua
---- for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
---- print(s)
---- end
---- </pre>
+---
+--- ```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:
---- <pre>lua
---- for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
---- print(('word: %s num: %s'):format(word, num))
---- end
---- </pre>
+---
+--- ```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()|
@@ -165,12 +167,13 @@ end
--- |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()|
@@ -259,12 +262,13 @@ end
--- a predicate that is checked for each value.
---
--- Example:
---- <pre>lua
---- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
---- return vim.deep_equal(v, { 'b', 'c' })
---- end, { predicate = true })
---- -- true
---- </pre>
+---
+--- ```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
---
@@ -455,10 +459,11 @@ 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 ... any Optional keys (0 or more, variadic) via which to index the table
@@ -626,10 +631,10 @@ 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
@@ -703,38 +708,41 @@ 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>
+---
+--- ```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):
---- <pre>lua
---- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
---- --> NOP (success)
---
---- vim.validate{arg1={1, 'table'}}
---- --> error('arg1: expected table, got number')
+--- ```lua
+--- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
+--- --> NOP (success)
---
---- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
---- --> error('arg1: expected even number, got 3')
---- </pre>
+--- 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.
---- <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')
+--- ```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:
@@ -866,10 +874,10 @@ end
--- If {create} is `nil`, this will create a defaulttable whose constructor function is
--- this function, effectively allowing to create nested tables on the fly:
---
---- <pre>lua
+--- ```lua
--- local a = vim.defaulttable()
--- a.b.c = 1
---- </pre>
+--- ```
---
---@param create function?(key:any):any The function called to create a missing value.
---@return table Empty table with metamethod
@@ -938,7 +946,7 @@ do
--- Create a ring buffer limited to a maximal number of items.
--- Once the buffer is full, adding a new entry overrides the oldest entry.
---
- --- <pre>
+ --- ```lua
--- local ringbuf = vim.ringbuf(4)
--- ringbuf:push("a")
--- ringbuf:push("b")
@@ -952,7 +960,7 @@ do
--- for val in ringbuf do
--- print(val)
--- end
- --- </pre>
+ --- ```
---
--- Returns a Ringbuf instance with the following methods:
---
diff --git a/runtime/lua/vim/treesitter.lua b/runtime/lua/vim/treesitter.lua
index 4f84fc2e0f..cc8be72670 100644
--- a/runtime/lua/vim/treesitter.lua
+++ b/runtime/lua/vim/treesitter.lua
@@ -441,14 +441,15 @@ 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 (integer|nil) Buffer to be highlighted (default: current buffer)
---@param lang (string|nil) Language of the parser (default: buffer filetype)
@@ -472,7 +473,7 @@ 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, "o" to toggle the query previewer, and press
+--- 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*
@@ -494,17 +495,12 @@ function M.inspect_tree(opts)
require('vim.treesitter.dev').inspect_tree(opts)
end
---- Open a window for live editing of a treesitter query.
----
---- Can also be shown with `:PreviewQuery`. *:PreviewQuery*
-function M.preview_query()
- require('vim.treesitter.dev').preview_query()
-end
-
--- Returns the fold level for {lnum} in the current buffer. Can be set directly to 'foldexpr':
---- <pre>lua
+---
+--- ```lua
--- vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
---- </pre>
+--- ```
+---
---@param lnum integer|nil Line number to calculate fold level for
---@return string
function M.foldexpr(lnum)
diff --git a/runtime/lua/vim/treesitter/_fold.lua b/runtime/lua/vim/treesitter/_fold.lua
index d82e04a5a8..8bc08c9c2e 100644
--- a/runtime/lua/vim/treesitter/_fold.lua
+++ b/runtime/lua/vim/treesitter/_fold.lua
@@ -299,7 +299,9 @@ local function on_changedtree(bufnr, foldinfo, tree_changes)
local srow, _, erow = Range.unpack4(change)
get_folds_levels(bufnr, foldinfo, srow, erow)
end
- foldupdate(bufnr)
+ if #tree_changes > 0 then
+ foldupdate(bufnr)
+ end
end)
end
diff --git a/runtime/lua/vim/treesitter/_query_linter.lua b/runtime/lua/vim/treesitter/_query_linter.lua
index 3dd0177a81..abf0bf345d 100644
--- a/runtime/lua/vim/treesitter/_query_linter.lua
+++ b/runtime/lua/vim/treesitter/_query_linter.lua
@@ -1,8 +1,6 @@
local api = vim.api
local namespace = api.nvim_create_namespace('vim.treesitter.query_linter')
--- those node names exist for every language
-local BUILT_IN_NODE_NAMES = { '_', 'ERROR' }
local M = {}
@@ -10,11 +8,13 @@ local M = {}
--- @field langs string[]
--- @field clear boolean
+--- @alias vim.treesitter.ParseError {msg: string, range: Range4}
+
--- @private
--- Caches parse results for queries for each language.
--- Entries of parse_cache[lang][query_text] will either be true for successful parse or contain the
---- error message of the parse
---- @type table<string,table<string,string|true>>
+--- message and range of the parse error.
+--- @type table<string,table<string,vim.treesitter.ParseError|true>>
local parse_cache = {}
--- Contains language dependent context for the query linter
@@ -26,20 +26,16 @@ local parse_cache = {}
--- @private
--- Adds a diagnostic for node in the query buffer
--- @param diagnostics Diagnostic[]
---- @param node TSNode
---- @param buf integer
+--- @param range Range4
--- @param lint string
--- @param lang string?
-local function add_lint_for_node(diagnostics, node, buf, lint, lang)
- local node_text = vim.treesitter.get_node_text(node, buf):gsub('\n', ' ')
- --- @type string
- local message = lint .. ': ' .. node_text
- local error_range = { node:range() }
+local function add_lint_for_node(diagnostics, range, lint, lang)
+ local message = lint:gsub('\n', ' ')
diagnostics[#diagnostics + 1] = {
- lnum = error_range[1],
- end_lnum = error_range[3],
- col = error_range[2],
- end_col = error_range[4],
+ lnum = range[1],
+ end_lnum = range[3],
+ col = range[2],
+ end_col = range[4],
severity = vim.diagnostic.ERROR,
message = message,
source = lang,
@@ -92,6 +88,31 @@ local lint_query = [[;; query
]]
--- @private
+--- @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
+
+--- @private
--- @param node TSNode
--- @param buf integer
--- @param lang string
@@ -106,104 +127,19 @@ local function check_toplevel(node, buf, lang, diagnostics)
local lang_cache = parse_cache[lang]
if lang_cache[query_text] == nil then
- local ok, err = pcall(vim.treesitter.query.parse, lang, query_text)
+ local cache_val, err = pcall(vim.treesitter.query.parse, lang, query_text) ---@type boolean|vim.treesitter.ParseError, string|Query
- if not ok and type(err) == 'string' then
- err = err:match('.-:%d+: (.+)')
+ if not cache_val and type(err) == 'string' then
+ cache_val = get_error_entry(err, node)
end
- lang_cache[query_text] = ok or err
+ lang_cache[query_text] = cache_val
end
local cache_entry = lang_cache[query_text]
- if type(cache_entry) == 'string' then
- add_lint_for_node(diagnostics, node, buf, cache_entry, lang)
- end
-end
-
---- @private
---- @param node TSNode
---- @param buf integer
---- @param lang string
---- @param parser_info table
---- @param diagnostics Diagnostic[]
-local function check_field(node, buf, lang, parser_info, diagnostics)
- local field_name = vim.treesitter.get_node_text(node, buf)
- if not vim.tbl_contains(parser_info.fields, field_name) then
- add_lint_for_node(diagnostics, node, buf, 'Invalid field', lang)
- end
-end
-
---- @private
---- @param node TSNode
---- @param buf integer
---- @param lang string
---- @param parser_info (table)
---- @param diagnostics Diagnostic[]
-local function check_node(node, buf, lang, parser_info, diagnostics)
- local node_type = vim.treesitter.get_node_text(node, buf)
- local is_named = node_type:sub(1, 1) ~= '"'
-
- if not is_named then
- node_type = node_type:gsub('"(.*)".*$', '%1'):gsub('\\(.)', '%1')
- end
-
- local found = vim.tbl_contains(BUILT_IN_NODE_NAMES, node_type)
- or vim.tbl_contains(parser_info.symbols, function(s)
- return vim.deep_equal(s, { node_type, is_named })
- end, { predicate = true })
-
- if not found then
- add_lint_for_node(diagnostics, node, buf, 'Invalid node type', lang)
- end
-end
-
---- @private
---- @param node TSNode
---- @param buf integer
---- @param is_predicate boolean
---- @return string
-local function get_predicate_name(node, buf, is_predicate)
- local name = vim.treesitter.get_node_text(node, buf)
- if is_predicate then
- if vim.startswith(name, 'not-') then
- --- @type string
- name = name:sub(string.len('not-') + 1)
- end
- return name .. '?'
- end
- return name .. '!'
-end
-
---- @private
---- @param predicate_node TSNode
---- @param predicate_type_node TSNode
---- @param buf integer
---- @param lang string?
---- @param diagnostics Diagnostic[]
-local function check_predicate(predicate_node, predicate_type_node, buf, lang, diagnostics)
- local type_string = vim.treesitter.get_node_text(predicate_type_node, buf)
-
- -- Quirk of the query grammar that directives are also predicates!
- if type_string == '?' then
- if
- not vim.tbl_contains(
- vim.treesitter.query.list_predicates(),
- get_predicate_name(predicate_node, buf, true)
- )
- then
- add_lint_for_node(diagnostics, predicate_node, buf, 'Unknown predicate', lang)
- end
- elseif type_string == '!' then
- if
- not vim.tbl_contains(
- vim.treesitter.query.list_directives(),
- get_predicate_name(predicate_node, buf, false)
- )
- then
- add_lint_for_node(diagnostics, predicate_node, buf, 'Unknown directive', lang)
- end
+ if type(cache_entry) ~= 'boolean' then
+ add_lint_for_node(diagnostics, cache_entry.range, cache_entry.msg, lang)
end
end
@@ -214,8 +150,6 @@ end
--- @param lang_context QueryLinterLanguageContext
--- @param diagnostics Diagnostic[]
local function lint_match(buf, match, query, lang_context, diagnostics)
- local predicate --- @type TSNode
- local predicate_type --- @type TSNode
local lang = lang_context.lang
local parser_info = lang_context.parser_info
@@ -223,31 +157,16 @@ local function lint_match(buf, match, query, lang_context, diagnostics)
local cap_id = query.captures[id]
-- perform language-independent checks only for first lang
- if lang_context.is_first_lang then
- if cap_id == 'error' then
- add_lint_for_node(diagnostics, node, buf, 'Syntax error')
- elseif cap_id == 'predicate.name' then
- predicate = node
- elseif cap_id == 'predicate.type' then
- predicate_type = node
- end
+ 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 then
- if cap_id == 'toplevel' then
- check_toplevel(node, buf, lang, diagnostics)
- elseif cap_id == 'field' then
- check_field(node, buf, lang, parser_info, diagnostics)
- elseif cap_id == 'node.named' or cap_id == 'node.anonymous' then
- check_node(node, buf, lang, parser_info, diagnostics)
- end
+ if lang and parser_info and cap_id == 'toplevel' then
+ check_toplevel(node, buf, lang, diagnostics)
end
end
-
- if predicate and predicate_type then
- check_predicate(predicate, predicate_type, buf, lang, diagnostics)
- end
end
--- @private
@@ -339,7 +258,7 @@ function M.omnifunc(findstart, base)
end
end
for _, s in pairs(parser_info.symbols) do
- local text = s[2] and s[1] or '"' .. s[1]:gsub([[\]], [[\\]]) .. '"'
+ 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
diff --git a/runtime/lua/vim/treesitter/dev.lua b/runtime/lua/vim/treesitter/dev.lua
index 72b6e3db4a..bc54853103 100644
--- a/runtime/lua/vim/treesitter/dev.lua
+++ b/runtime/lua/vim/treesitter/dev.lua
@@ -101,18 +101,18 @@ function TSTreeView:new(bufnr, lang)
-- the root in the child tree to the {injections} table.
local root = parser:parse(true)[1]:root()
local injections = {} ---@type table<integer,table>
- parser:for_each_child(function(child, lang_)
- child:for_each_tree(function(tree)
+ for _, child in pairs(parser:children()) do
+ child:for_each_tree(function(tree, ltree)
local r = tree:root()
local node = root:named_descendant_for_range(r:range())
if node then
injections[node:id()] = {
- lang = lang_,
+ lang = ltree:lang(),
root = r,
}
end
end)
- end)
+ end
local nodes = traverse(root, 0, parser:lang(), injections, {})
@@ -351,11 +351,11 @@ function M.inspect_tree(opts)
end,
})
api.nvim_buf_set_keymap(b, 'n', 'o', '', {
- desc = 'Toggle query previewer',
+ desc = 'Toggle query editor',
callback = function()
- local preview_w = vim.b[buf].dev_preview
- if not preview_w or not close_win(preview_w) then
- M.preview_query()
+ local edit_w = vim.b[buf].dev_edit
+ if not edit_w or not close_win(edit_w) then
+ M.edit_query()
end
end,
})
@@ -464,16 +464,16 @@ function M.inspect_tree(opts)
})
end
-local preview_ns = api.nvim_create_namespace('treesitter/dev-preview')
+local edit_ns = api.nvim_create_namespace('treesitter/dev-edit')
---@param query_win integer
---@param base_win integer
-local function update_preview_highlights(query_win, base_win)
+local function update_editor_highlights(query_win, base_win)
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)
local lang = parser:lang()
- api.nvim_buf_clear_namespace(base_buf, preview_ns, 0, -1)
+ 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)
@@ -493,7 +493,7 @@ local function update_preview_highlights(query_win, base_win)
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, preview_ns, lnum, col, {
+ api.nvim_buf_set_extmark(base_buf, edit_ns, lnum, col, {
end_row = end_lnum,
end_col = end_col,
hl_group = 'Visual',
@@ -506,17 +506,17 @@ local function update_preview_highlights(query_win, base_win)
end
--- @private
-function M.preview_query()
+function M.edit_query()
local buf = api.nvim_get_current_buf()
local win = api.nvim_get_current_win()
- -- Close any existing previewer window
- if vim.b[buf].dev_preview then
- close_win(vim.b[buf].dev_preview)
+ -- 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 previewer above it.
+ -- 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
@@ -537,20 +537,20 @@ function M.preview_query()
local query_win = api.nvim_get_current_win()
local query_buf = api.nvim_win_get_buf(query_win)
- vim.b[buf].dev_preview = 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_previewer.scm', lang))
+ api.nvim_buf_set_name(query_buf, string.format('%s/query_editor.scm', lang))
- local group = api.nvim_create_augroup('treesitter/dev-preview', {})
+ local group = api.nvim_create_augroup('treesitter/dev-edit', {})
api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, {
group = group,
buffer = query_buf,
- desc = 'Update query previewer diagnostics when the query changes',
+ desc = 'Update query editor diagnostics when the query changes',
callback = function()
vim.treesitter.query.lint(query_buf, { langs = lang, clear = false })
end,
@@ -558,37 +558,37 @@ function M.preview_query()
api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave', 'CursorMoved', 'BufEnter' }, {
group = group,
buffer = query_buf,
- desc = 'Update query previewer highlights when the cursor moves',
+ desc = 'Update query editor highlights when the cursor moves',
callback = function()
if api.nvim_win_is_valid(win) then
- update_preview_highlights(query_win, win)
+ update_editor_highlights(query_win, win)
end
end,
})
api.nvim_create_autocmd('BufLeave', {
group = group,
buffer = query_buf,
- desc = 'Clear the query previewer highlights when leaving the previewer',
+ desc = 'Clear highlights when leaving the query editor',
callback = function()
- api.nvim_buf_clear_namespace(buf, preview_ns, 0, -1)
+ api.nvim_buf_clear_namespace(buf, edit_ns, 0, -1)
end,
})
api.nvim_create_autocmd('BufLeave', {
group = group,
buffer = buf,
- desc = 'Clear the query previewer highlights when leaving the source buffer',
+ 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, preview_ns, 0, -1)
+ api.nvim_buf_clear_namespace(query_buf, edit_ns, 0, -1)
end,
})
api.nvim_create_autocmd('BufHidden', {
group = group,
buffer = buf,
- desc = 'Close the previewer window when the source buffer is hidden',
+ desc = 'Close the editor window when the source buffer is hidden',
once = true,
callback = function()
close_win(query_win)
diff --git a/runtime/lua/vim/treesitter/highlighter.lua b/runtime/lua/vim/treesitter/highlighter.lua
index 56b075b723..8d4d6a9337 100644
--- a/runtime/lua/vim/treesitter/highlighter.lua
+++ b/runtime/lua/vim/treesitter/highlighter.lua
@@ -322,7 +322,7 @@ function TSHighlighter._on_win(_, _win, buf, topline, botline)
if not self then
return false
end
- self.tree:parse({ topline, botline })
+ self.tree:parse({ topline, botline + 1 })
self:reset_highlight_state()
self.redraw_count = self.redraw_count + 1
return true
diff --git a/runtime/lua/vim/treesitter/language.lua b/runtime/lua/vim/treesitter/language.lua
index 9695e2c41c..15bf666a1e 100644
--- a/runtime/lua/vim/treesitter/language.lua
+++ b/runtime/lua/vim/treesitter/language.lua
@@ -82,9 +82,8 @@ function M.add(lang, opts)
filetype = { filetype, { 'string', 'table' }, true },
})
- M.register(lang, filetype)
-
if vim._ts_has_language(lang) then
+ M.register(lang, filetype)
return
end
@@ -102,6 +101,7 @@ function M.add(lang, opts)
end
vim._ts_add_language(path, lang, symbol_name)
+ M.register(lang, filetype)
end
--- @param x string|string[]
diff --git a/runtime/lua/vim/treesitter/languagetree.lua b/runtime/lua/vim/treesitter/languagetree.lua
index e81778b269..79f36a27fd 100644
--- a/runtime/lua/vim/treesitter/languagetree.lua
+++ b/runtime/lua/vim/treesitter/languagetree.lua
@@ -7,9 +7,9 @@
---
--- To create a LanguageTree (parser object) for a given buffer and language, use:
---
---- <pre>lua
---- local parser = vim.treesitter.get_parser(bufnr, lang)
---- </pre>
+--- ```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;
@@ -17,9 +17,9 @@
---
--- Whenever you need to access the current syntax tree, parse the buffer:
---
---- <pre>lua
---- local tree = parser:parse({ start_row, end_row })
---- </pre>
+--- ```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
@@ -444,18 +444,21 @@ function LanguageTree:parse(range)
range = range,
})
- self:for_each_child(function(child)
+ for _, child in pairs(self._children) do
child:parse(range)
- end)
+ 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 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
@@ -897,6 +900,20 @@ function LanguageTree:_edit(
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
@@ -943,20 +960,17 @@ function LanguageTree:_on_bytes(
)
-- Edit trees together BEFORE emitting a bytes callback.
- ---@private
- self:for_each_child(function(child)
- child:_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, true)
+ 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',
@@ -1017,9 +1031,9 @@ function LanguageTree:register_cbs(cbs, recursive)
end
if recursive then
- self:for_each_child(function(child)
+ for _, child in pairs(self._children) do
child:register_cbs(cbs, true)
- end)
+ end
end
end
diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua
index 3093657313..d7973cc48f 100644
--- a/runtime/lua/vim/treesitter/query.lua
+++ b/runtime/lua/vim/treesitter/query.lua
@@ -692,7 +692,8 @@ end
--- 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:
@@ -700,7 +701,7 @@ end
--- local row1, col1, row2, col2 = node:range() -- range of the capture
--- -- ... use the info here ...
--- end
---- </pre>
+--- ```
---
---@param node TSNode under which the search will occur
---@param source (integer|string) Source buffer or string to extract text from
@@ -743,7 +744,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]
@@ -754,7 +756,7 @@ end
--- -- ... use the info here ...
--- end
--- end
---- </pre>
+--- ```
---
---@param node TSNode under which the search will occur
---@param source (integer|string) Source buffer or string to search
@@ -824,11 +826,22 @@ end
--- Omnifunc for completing node names and predicates in treesitter queries.
---
--- Use via
---- <pre>lua
---- vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc'
---- </pre>
+---
+--- ```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
+--- Open a window for live editing of a treesitter query.
+---
+--- Can also be shown with `:EditQuery`. *:EditQuery*
+---
+--- Note that the editor opens a scratch buffer, and so queries aren't persisted on disk.
+function M.edit()
+ require('vim.treesitter.dev').edit_query()
+end
+
return M
diff --git a/runtime/lua/vim/ui.lua b/runtime/lua/vim/ui.lua
index cd90886489..b6ddf337ce 100644
--- a/runtime/lua/vim/ui.lua
+++ b/runtime/lua/vim/ui.lua
@@ -3,6 +3,23 @@ local M = {}
--- 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
--- - prompt (string|nil)
@@ -19,23 +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 },
@@ -58,6 +58,14 @@ end
--- 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)
--- Text of the prompt
@@ -77,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 },
@@ -110,11 +111,12 @@ end
--- Expands "~/" and environment variables in filesystem paths.
---
--- Examples:
---- <pre>lua
+---
+--- ```lua
--- vim.ui.open("https://neovim.io/")
--- vim.ui.open("~/path/to/file")
--- vim.ui.open("$VIMRUNTIME")
---- </pre>
+--- ```
---
---@param path string Path or URL to open
---
diff --git a/runtime/lua/vim/version.lua b/runtime/lua/vim/version.lua
index 056e1678ff..306eef90d3 100644
--- a/runtime/lua/vim/version.lua
+++ b/runtime/lua/vim/version.lua
@@ -5,12 +5,13 @@
--- available tools and dependencies on the current system.
---
--- Example:
---- <pre>lua
---- local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
---- if vim.version.gt(v, {3, 2, 0}) then
---- -- ...
---- end
---- </pre>
+---
+--- ```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.
---
@@ -21,35 +22,36 @@
---
--- Supported range specs are shown in the following table.
--- Note: suffixed versions (1.2.3-rc1) are not matched.
---- <pre>
---- 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
+--- ```
+--- 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 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
---- </pre>
+--- 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 = {}
@@ -237,29 +239,32 @@ function VersionRange:has(version)
end
--- Parses a semver |version-range| "spec" and returns a range object:
---- <pre>
---- {
---- from: Version
---- to: Version
---- has(v: string|Version)
---- }
---- </pre>
+---
+--- ```
+--- {
+--- from: Version
+--- to: Version
+--- has(v: string|Version)
+--- }
+--- ```
---
--- `:has()` checks if a version is in the range (inclusive `from`, exclusive `to`).
---
--- Example:
---- <pre>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
---- </pre>
+---
+--- ```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:
---- <pre>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))
---- </pre>
+---
+--- ```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
---
@@ -345,16 +350,17 @@ end
--- specified literally as a `{major, minor, patch}` tuple, e.g. `{1, 0, 3}`).
---
--- Example:
---- <pre>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
---- </pre>
+---
+--- ```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.
---
@@ -399,9 +405,10 @@ 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:
---- <pre>
---- { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
---- </pre>
+---
+--- ```
+--- { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
+--- ```
---
--- @see # https://semver.org/spec/v2.0.0.html
---