docs: replace <pre> with ``` (#25136)

This commit is contained in:
Gregory Anders
2023-09-14 08:23:01 -05:00
committed by GitHub
parent 9fc321c976
commit 2e92065686
43 changed files with 1350 additions and 1245 deletions

View File

@@ -2041,10 +2041,14 @@ whether a buffer is loaded.
nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()* nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()*
Activates buffer-update events on a channel, or as Lua callbacks. Activates buffer-update events on a channel, or as Lua callbacks.
Example (Lua): capture buffer updates in a global `events` variable (use "vim.print(events)" to see its contents): >lua Example (Lua): capture buffer updates in a global `events` variable (use
"vim.print(events)" to see its contents): >lua
events = {} events = {}
vim.api.nvim_buf_attach(0, false, { vim.api.nvim_buf_attach(0, false, {
on_lines=function(...) table.insert(events, {...}) end}) on_lines = function(...)
table.insert(events, {...})
end,
})
< <
Parameters: ~ Parameters: ~
@@ -3062,6 +3066,7 @@ nvim_open_win({buffer}, {enter}, {*config}) *nvim_open_win()*
Example (Lua): buffer-relative float (travels as buffer is scrolled) >lua Example (Lua): buffer-relative float (travels as buffer is scrolled) >lua
vim.api.nvim_open_win(0, false, vim.api.nvim_open_win(0, false,
{relative='win', width=12, height=3, bufpos={100,10}}) {relative='win', width=12, height=3, bufpos={100,10}})
})
< <
Attributes: ~ Attributes: ~
@@ -3340,8 +3345,8 @@ nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()*
}) })
< <
Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|),
"$HOME" and "~" must be expanded explicitly: >lua thus names like "$HOME" and "~" must be expanded explicitly: >lua
pattern = vim.fn.expand("~") .. "/some/path/*.py" pattern = vim.fn.expand("~") .. "/some/path/*.py"
< <

View File

@@ -238,7 +238,7 @@ Docstring format:
`---@see`, `---@param`, `---@returns` `---@see`, `---@param`, `---@returns`
- Limited markdown is supported. - Limited markdown is supported.
- List-items start with `-` (useful to nest or "indent") - List-items start with `-` (useful to nest or "indent")
- Use `<pre>` for code samples. - Use ``` for code samples.
Code samples can be annotated as `vim` or `lua` Code samples can be annotated as `vim` or `lua`
- Use `@nodoc` to prevent documentation generation. - Use `@nodoc` to prevent documentation generation.
- Files which has `@meta` are only used for typing and documentation. - Files which has `@meta` are only used for typing and documentation.
@@ -250,12 +250,13 @@ vim.paste in runtime/lua/vim/_editor.lua like this: >
--- (such as the |TUI|) pastes text into the editor. --- (such as the |TUI|) pastes text into the editor.
--- ---
--- Example: To remove ANSI color codes when pasting: --- Example: To remove ANSI color codes when pasting:
--- <pre>lua ---
--- ```lua
--- vim.paste = (function() --- vim.paste = (function()
--- local overridden = vim.paste --- local overridden = vim.paste
--- ... --- ...
--- end)() --- end)()
--- </pre> --- ```
--- ---
---@see |paste| ---@see |paste|
--- ---

View File

@@ -359,12 +359,10 @@ config({opts}, {namespace}) *vim.diagnostic.config()*
followed by namespace configuration, and finally global configuration. followed by namespace configuration, and finally global configuration.
For example, if a user enables virtual text globally with >lua For example, if a user enables virtual text globally with >lua
vim.diagnostic.config({ virtual_text = true }) vim.diagnostic.config({ virtual_text = true })
< <
and a diagnostic producer sets diagnostics with >lua and a diagnostic producer sets diagnostics with >lua
vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false })
< <
@@ -608,12 +606,10 @@ match({str}, {pat}, {groups}, {severity_map}, {defaults})
Parse a diagnostic from a string. Parse a diagnostic from a string.
For example, consider a line of output from a linter: > For example, consider a line of output from a linter: >
WARNING filename:27:3: Variable 'foo' does not exist WARNING filename:27:3: Variable 'foo' does not exist
< <
This can be parsed into a diagnostic |diagnostic-structure| with: >lua This can be parsed into a diagnostic |diagnostic-structure| with: >lua
local s = "WARNING filename:27:3: Variable 'foo' does not exist" local s = "WARNING filename:27:3: Variable 'foo' does not exist"
local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$"
local groups = { "severity", "lnum", "col", "message" } local groups = { "severity", "lnum", "col", "message" }

View File

@@ -901,7 +901,6 @@ start({config}, {opts}) *vim.lsp.start()*
the current buffer to the client. the current buffer to the client.
Example: >lua Example: >lua
vim.lsp.start({ vim.lsp.start({
name = 'my-server-name', name = 'my-server-name',
cmd = {'name-of-language-server-executable'}, cmd = {'name-of-language-server-executable'},
@@ -1078,8 +1077,8 @@ status() *vim.lsp.status()*
stop_client({client_id}, {force}) *vim.lsp.stop_client()* stop_client({client_id}, {force}) *vim.lsp.stop_client()*
Stops a client(s). Stops a client(s).
You can also use the `stop()` function on a |vim.lsp.client| object. To stop all clients: >lua You can also use the `stop()` function on a |vim.lsp.client| object. To
stop all clients: >lua
vim.lsp.stop_client(vim.lsp.get_clients()) vim.lsp.stop_client(vim.lsp.get_clients())
< <
@@ -1196,7 +1195,7 @@ definition({options}) *vim.lsp.buf.definition()*
document_highlight() *vim.lsp.buf.document_highlight()* document_highlight() *vim.lsp.buf.document_highlight()*
Send request to the server to resolve document highlights for the current 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 text document position. This request can be triggered by a key mapping or
by events such as `CursorHold` , e.g.: >vim by events such as `CursorHold`, e.g.: >vim
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorHoldI <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() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
@@ -1242,7 +1241,7 @@ format({options}) *vim.lsp.buf.format()*
buffer (0). buffer (0).
• filter (function|nil): Predicate used to filter clients. • filter (function|nil): Predicate used to filter clients.
Receives a client as argument and must return a boolean. Receives a client as argument and must return a boolean.
Clients matching the predicate are included. Example: >lua Clients matching the predicate are included. Example: >lua
-- Never request typescript-language-server for formatting -- Never request typescript-language-server for formatting
vim.lsp.buf.format { vim.lsp.buf.format {
@@ -1366,7 +1365,6 @@ on_diagnostic({_}, {result}, {ctx}, {config})
See |vim.diagnostic.config()| for configuration options. Handler-specific See |vim.diagnostic.config()| for configuration options. Handler-specific
configuration can be set using |vim.lsp.with()|: >lua configuration can be set using |vim.lsp.with()|: >lua
vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with( vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with(
vim.lsp.diagnostic.on_diagnostic, { vim.lsp.diagnostic.on_diagnostic, {
-- Enable underline, use default values -- Enable underline, use default values
@@ -1395,7 +1393,6 @@ on_publish_diagnostics({_}, {result}, {ctx}, {config})
See |vim.diagnostic.config()| for configuration options. Handler-specific See |vim.diagnostic.config()| for configuration options. Handler-specific
configuration can be set using |vim.lsp.with()|: >lua configuration can be set using |vim.lsp.with()|: >lua
vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
vim.lsp.diagnostic.on_publish_diagnostics, { vim.lsp.diagnostic.on_publish_diagnostics, {
-- Enable underline, use default values -- Enable underline, use default values
@@ -1534,7 +1531,6 @@ start({bufnr}, {client_id}, {opts}) *vim.lsp.semantic_tokens.start()*
server that supports it, you can delete the semanticTokensProvider table server that supports it, you can delete the semanticTokensProvider table
from the {server_capabilities} of your client in your |LspAttach| callback from the {server_capabilities} of your client in your |LspAttach| callback
or your configuration's `on_attach` callback: >lua or your configuration's `on_attach` callback: >lua
client.server_capabilities.semanticTokensProvider = nil client.server_capabilities.semanticTokensProvider = nil
< <
@@ -1565,7 +1561,6 @@ Lua module: vim.lsp.handlers *lsp-handlers*
hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()* hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()*
|lsp-handler| for the method "textDocument/hover" >lua |lsp-handler| for the method "textDocument/hover" >lua
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(
vim.lsp.handlers.hover, { vim.lsp.handlers.hover, {
-- Use a sharp border with `FloatBorder` highlights -- Use a sharp border with `FloatBorder` highlights
@@ -1585,9 +1580,9 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()*
*vim.lsp.handlers.signature_help()* *vim.lsp.handlers.signature_help()*
signature_help({_}, {result}, {ctx}, {config}) signature_help({_}, {result}, {ctx}, {config})
|lsp-handler| for the method "textDocument/signatureHelp". The active |lsp-handler| for the method "textDocument/signatureHelp".
parameter is highlighted with |hl-LspSignatureActiveParameter|. >lua
The active parameter is highlighted with |hl-LspSignatureActiveParameter|. >lua
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(
vim.lsp.handlers.signature_help, { vim.lsp.handlers.signature_help, {
-- Use a sharp border with `FloatBorder` highlights -- Use a sharp border with `FloatBorder` highlights
@@ -1597,6 +1592,8 @@ signature_help({_}, {result}, {ctx}, {config})
< <
Parameters: ~ Parameters: ~
• {result} (table) Response from the language server
• {ctx} (table) Client context
• {config} (table) Configuration table. • {config} (table) Configuration table.
• border: (default=nil) • border: (default=nil)
• Add borders to the floating window • Add borders to the floating window

View File

@@ -582,17 +582,20 @@ VIM.HIGHLIGHT *vim.highlight*
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` : >vim To enable it, add the following to your `init.vim`: >vim
au TextYankPost * silent! lua vim.highlight.on_yank() au TextYankPost * silent! lua vim.highlight.on_yank()
< <
You can customize the highlight group and the duration of the highlight You can customize the highlight group and the duration of the highlight
via: >vim via: >vim
au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} 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 If you want to exclude visual selections from highlighting on yank, use: >vim
au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
< <
vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
@@ -688,10 +691,9 @@ vim.diff({a}, {b}, {opts}) *vim.diff()*
either directly or via callback arguments, are 1-based. either directly or via callback arguments, are 1-based.
Examples: >lua Examples: >lua
vim.diff('a\n', 'b\nc\n') vim.diff('a\n', 'b\nc\n')
-- => -- =>
-- @ -1 +1,2 @ -- @@ -1 +1,2 @@
-- -a -- -a
-- +b -- +b
-- +c -- +c
@@ -781,16 +783,18 @@ vim.json.decode({str}, {opts}) *vim.json.decode()*
• Decodes empty array as `{}` (empty Lua table). • Decodes empty array as `{}` (empty Lua table).
Example: >lua Example: >lua
vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
:lua vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}')) -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
--> { bar = {}, foo = vim.empty_dict(), zub = vim.NIL } <
< 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` .
Parameters: ~ Parameters: ~
• {str} (string) • {str} (string) Stringified JSON data.
• {opts} table<string,|nil any> • {opts} table<string,any>|nil 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: ~ Return: ~
any any
@@ -817,7 +821,6 @@ vim.spell.check({str}) *vim.spell.check()*
the buffer. Consider calling this with |nvim_buf_call()|. the buffer. Consider calling this with |nvim_buf_call()|.
Example: >lua Example: >lua
vim.spell.check("the quik brown fox") vim.spell.check("the quik brown fox")
-- => -- =>
-- { -- {
@@ -978,7 +981,6 @@ vim.str_utf_end({str}, {index}) *vim.str_utf_end()*
(character) that {index} points to. (character) that {index} points to.
Examples: >lua Examples: >lua
-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8) -- 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 -- Returns 0 because the index is pointing at the last byte of a character
@@ -1015,7 +1017,6 @@ vim.str_utf_start({str}, {index}) *vim.str_utf_start()*
character. character.
Examples: >lua Examples: >lua
-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8) -- 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 -- Returns 0 because the index is pointing at the first byte of a character
@@ -1080,7 +1081,6 @@ vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
likewise experimental). likewise experimental).
Example (stub for a |ui-popupmenu| implementation): >lua Example (stub for a |ui-popupmenu| implementation): >lua
ns = vim.api.nvim_create_namespace('my_fancy_pum') ns = vim.api.nvim_create_namespace('my_fancy_pum')
vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...) vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
@@ -1116,7 +1116,6 @@ vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()*
time. time.
Examples: >lua Examples: >lua
--- ---
-- Wait for 100 ms, allowing other events to process -- Wait for 100 ms, allowing other events to process
vim.wait(100, function() end) vim.wait(100, function() end)
@@ -1171,6 +1170,7 @@ Lua list: >lua
local list = { 1, 2, 3 } local list = { 1, 2, 3 }
vim.fn.remove(list, 0) vim.fn.remove(list, 0)
vim.print(list) --> "{ 1, 2, 3 }" vim.print(list) --> "{ 1, 2, 3 }"
< <
vim.call({func}, {...}) *vim.call()* vim.call({func}, {...}) *vim.call()*
@@ -1430,13 +1430,12 @@ vim.bo *vim.bo*
print(vim.bo.baz) -- error: invalid key print(vim.bo.baz) -- error: invalid key
< <
Parameters: ~
• {bufnr} (integer|nil)
vim.env *vim.env* vim.env *vim.env*
Environment variables defined in the editor session. See |expand-env| and Environment variables defined in the editor session. See |expand-env| and
|:let-environment| for the Vimscript behavior. Invalid or unset key |:let-environment| for the Vimscript behavior. Invalid or unset key
returns `nil` . Example: >lua returns `nil`.
Example: >lua
vim.env.FOO = 'bar' vim.env.FOO = 'bar'
print(vim.env.TERM) print(vim.env.TERM)
< <
@@ -1497,7 +1496,6 @@ vim.cmd *vim.cmd()*
callable function to the command. callable function to the command.
Example: >lua Example: >lua
vim.cmd('echo 42') vim.cmd('echo 42')
vim.cmd([[ vim.cmd([[
augroup My_group augroup My_group
@@ -1579,7 +1577,6 @@ vim.keycode({str}) *vim.keycode()*
Translate keycodes. Translate keycodes.
Example: >lua Example: >lua
local k = vim.keycode local k = vim.keycode
vim.g.mapleader = k'<bs>' vim.g.mapleader = k'<bs>'
< <
@@ -1653,7 +1650,6 @@ vim.paste({lines}, {phase}) *vim.paste()*
|TUI|) pastes text into the editor. |TUI|) pastes text into the editor.
Example: To remove ANSI color codes when pasting: >lua Example: To remove ANSI color codes when pasting: >lua
vim.paste = (function(overridden) vim.paste = (function(overridden)
return function(lines, phase) return function(lines, phase)
for i,line in ipairs(lines) do for i,line in ipairs(lines) do
@@ -1684,7 +1680,6 @@ vim.print({...}) *vim.print()*
"Pretty prints" the given arguments and returns them unmodified. "Pretty prints" the given arguments and returns them unmodified.
Example: >lua Example: >lua
local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true)) local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
< <
@@ -1737,7 +1732,6 @@ vim.system({cmd}, {opts}, {on_exit}) *vim.system()*
Run a system command Run a system command
Examples: >lua Examples: >lua
local on_exit = function(obj) local on_exit = function(obj)
print(obj.code) print(obj.code)
print(obj.signal) print(obj.signal)
@@ -1894,10 +1888,7 @@ vim.defaulttable({create}) *vim.defaulttable()*
If {create} is `nil`, this will create a defaulttable whose constructor If {create} is `nil`, this will create a defaulttable whose constructor
function is this function, effectively allowing to create nested tables on function is this function, effectively allowing to create nested tables on
the fly: the fly: >lua
>lua
local a = vim.defaulttable() local a = vim.defaulttable()
a.b.c = 1 a.b.c = 1
< <
@@ -1924,7 +1915,6 @@ vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()*
in "lazy" fashion (as opposed to |vim.split()| which is "eager"). in "lazy" fashion (as opposed to |vim.split()| which is "eager").
Example: >lua Example: >lua
for s in vim.gsplit(':aa::b:', ':', {plain=true}) do for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
print(s) print(s)
end end
@@ -1932,9 +1922,8 @@ vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()*
If you want to also inspect the separator itself (instead of discarding If you want to also inspect the separator itself (instead of discarding
it), use |string.gmatch()|. Example: >lua it), use |string.gmatch()|. Example: >lua
for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
for word, num in ('foo111bar222'):gmatch('([^0-9]*)(d*)') do print(('word: %s num: %s'):format(word, num))
print(('word: s num: s'):format(word, num))
end end
< <
@@ -2021,9 +2010,7 @@ vim.pesc({s}) *vim.pesc()*
vim.ringbuf({size}) *vim.ringbuf()* vim.ringbuf({size}) *vim.ringbuf()*
Create a ring buffer limited to a maximal number of items. Once the buffer Create a ring buffer limited to a maximal number of items. Once the buffer
is full, adding a new entry overrides the oldest entry. is full, adding a new entry overrides the oldest entry. >lua
>
local ringbuf = vim.ringbuf(4) local ringbuf = vim.ringbuf(4)
ringbuf:push("a") ringbuf:push("a")
ringbuf:push("b") ringbuf:push("b")
@@ -2090,7 +2077,6 @@ vim.split({s}, {sep}, {opts}) *vim.split()*
a table (unlike |vim.gsplit()|). a table (unlike |vim.gsplit()|).
Examples: >lua Examples: >lua
split(":aa::b:", ":") --> {'','aa','','b',''} split(":aa::b:", ":") --> {'','aa','','b',''}
split("axaby", "ab?") --> {'','x','y'} split("axaby", "ab?") --> {'','x','y'}
split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
@@ -2137,7 +2123,6 @@ vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()*
a predicate that is checked for each value. a predicate that is checked for each value.
Example: >lua Example: >lua
vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v) vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
return vim.deep_equal(v, { 'b', 'c' }) return vim.deep_equal(v, { 'b', 'c' })
end, { predicate = true }) end, { predicate = true })
@@ -2158,10 +2143,7 @@ vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()*
• |vim.list_contains()| for checking values in list-like tables • |vim.list_contains()| for checking values in list-like tables
vim.tbl_count({t}) *vim.tbl_count()* vim.tbl_count({t}) *vim.tbl_count()*
Counts the number of non-nil values in table `t`. Counts the number of non-nil values in table `t`. >lua
>lua
vim.tbl_count({ a=1, b=2 }) --> 2 vim.tbl_count({ a=1, b=2 }) --> 2
vim.tbl_count({ 1, 2 }) --> 2 vim.tbl_count({ 1, 2 }) --> 2
< <
@@ -2237,7 +2219,6 @@ vim.tbl_get({o}, {...}) *vim.tbl_get()*
arguments. Return `nil` if the key does not exist. arguments. Return `nil` if the key does not exist.
Examples: >lua Examples: >lua
vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
< <
@@ -2340,7 +2321,6 @@ vim.validate({opt}) *vim.validate()*
Validates a parameter specification (types and values). Validates a parameter specification (types and values).
Usage example: >lua Usage example: >lua
function user.new(name, age, hobbies) function user.new(name, age, hobbies)
vim.validate{ vim.validate{
name={name, 'string'}, name={name, 'string'},
@@ -2352,7 +2332,6 @@ vim.validate({opt}) *vim.validate()*
< <
Examples with explicit argument values (can be run directly): >lua Examples with explicit argument values (can be run directly): >lua
vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
--> NOP (success) --> NOP (success)
@@ -2364,12 +2343,11 @@ vim.validate({opt}) *vim.validate()*
< <
If multiple types are valid they can be given as a list. >lua If multiple types are valid they can be given as a list. >lua
vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
--> NOP (success) -- NOP (success)
vim.validate{arg1={1, {'string', 'table'}}} vim.validate{arg1={1, {'string', 'table'}}}
--> error('arg1: expected string|table, got number') -- error('arg1: expected string|table, got number')
< <
Parameters: ~ Parameters: ~
@@ -2506,7 +2484,6 @@ vim.ui.input({opts}, {on_confirm}) *vim.ui.input()*
work until `on_confirm`. work until `on_confirm`.
Example: >lua Example: >lua
vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input) vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
vim.o.shiftwidth = tonumber(input) vim.o.shiftwidth = tonumber(input)
end) end)
@@ -2535,7 +2512,6 @@ vim.ui.open({path}) *vim.ui.open()*
Expands "~/" and environment variables in filesystem paths. Expands "~/" and environment variables in filesystem paths.
Examples: >lua Examples: >lua
vim.ui.open("https://neovim.io/") vim.ui.open("https://neovim.io/")
vim.ui.open("~/path/to/file") vim.ui.open("~/path/to/file")
vim.ui.open("$VIMRUNTIME") vim.ui.open("$VIMRUNTIME")
@@ -2556,7 +2532,6 @@ vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()*
(potentially asynchronous) work until `on_choice`. (potentially asynchronous) work until `on_choice`.
Example: >lua Example: >lua
vim.ui.select({ 'tabs', 'spaces' }, { vim.ui.select({ 'tabs', 'spaces' }, {
prompt = 'Select tabs or spaces:', prompt = 'Select tabs or spaces:',
format_item = function(item) format_item = function(item)
@@ -2620,7 +2595,6 @@ vim.filetype.add({filetypes}) *vim.filetype.add()*
See $VIMRUNTIME/lua/vim/filetype.lua for more examples. See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
Example: >lua Example: >lua
vim.filetype.add({ vim.filetype.add({
extension = { extension = {
foo = 'fooscript', foo = 'fooscript',
@@ -2639,12 +2613,12 @@ vim.filetype.add({filetypes}) *vim.filetype.add()*
['/etc/foo/config'] = 'toml', ['/etc/foo/config'] = 'toml',
}, },
pattern = { pattern = {
['.*/etc/foo/.*'] = 'fooscript', ['.*&zwj;/etc/foo/.*'] = 'fooscript',
-- Using an optional priority -- Using an optional priority
['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } }, ['.*&zwj;/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
-- A pattern containing an environment variable -- A pattern containing an environment variable
['${XDG_CONFIG_HOME}/foo/git'] = 'git', ['${XDG_CONFIG_HOME}/foo/git'] = 'git',
['README.(a+)$'] = function(path, bufnr, ext) ['README.(%a+)$'] = function(path, bufnr, ext)
if ext == 'md' then if ext == 'md' then
return 'markdown' return 'markdown'
elseif ext == 'rst' then elseif ext == 'rst' then
@@ -2656,16 +2630,15 @@ vim.filetype.add({filetypes}) *vim.filetype.add()*
< <
To add a fallback match on contents, use >lua To add a fallback match on contents, use >lua
vim.filetype.add { vim.filetype.add {
pattern = { pattern = {
['.*'] = { ['.*'] = {
priority = -math.huge, priority = -math.huge,
function(path, bufnr) function(path, bufnr)
local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or '' local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or ''
if vim.regex([[^#!.*\<mine\>]]):match_str(content) ~= nil then if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then
return 'mine' return 'mine'
elseif vim.regex([[\<drawing\>]]):match_str(content) ~= nil then elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then
return 'drawing' return 'drawing'
end end
end, end,
@@ -2687,7 +2660,6 @@ vim.filetype.get_option({filetype}, {option})
files. files.
Example: >lua Example: >lua
vim.filetype.get_option('vim', 'commentstring') vim.filetype.get_option('vim', 'commentstring')
< <
@@ -2717,10 +2689,7 @@ vim.filetype.match({args}) *vim.filetype.match()*
the filetype. the filetype.
Each of the three options is specified using a key to the single argument Each of the three options is specified using a key to the single argument
of this function. Example: of this function. Example: >lua
>lua
-- Using a buffer number -- Using a buffer number
vim.filetype.match({ buf = 42 }) vim.filetype.match({ buf = 42 })
@@ -2762,7 +2731,6 @@ Lua module: vim.keymap *vim.keymap*
vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()* vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()*
Remove an existing mapping. Examples: >lua Remove an existing mapping. Examples: >lua
vim.keymap.del('n', 'lhs') vim.keymap.del('n', 'lhs')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
@@ -2778,7 +2746,6 @@ vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()*
vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()* vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
Adds a new |mapping|. Examples: >lua Adds a new |mapping|. Examples: >lua
-- Map to a Lua function: -- Map to a Lua function:
vim.keymap.set('n', 'lhs', function() print("real lua function") end) vim.keymap.set('n', 'lhs', function() print("real lua function") end)
-- Map to multiple modes: -- Map to multiple modes:
@@ -2790,7 +2757,7 @@ vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>" return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
end, { expr = true }) end, { expr = true })
-- <Plug> mapping: -- <Plug> mapping:
vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)') vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
< <
Parameters: ~ Parameters: ~
@@ -2871,7 +2838,6 @@ vim.fs.find({names}, {opts}) *vim.fs.find()*
narrow the search to find only that type. narrow the search to find only that type.
Examples: >lua Examples: >lua
-- location of Cargo.toml from the current buffer's path -- location of Cargo.toml from the current buffer's path
local cargo = vim.fs.find('Cargo.toml', { local cargo = vim.fs.find('Cargo.toml', {
upward = true, upward = true,
@@ -2887,7 +2853,7 @@ vim.fs.find({names}, {opts}) *vim.fs.find()*
-- get all files ending with .cpp or .hpp inside lib/ -- get all files ending with .cpp or .hpp inside lib/
local cpp_hpp = vim.fs.find(function(name, path) local cpp_hpp = vim.fs.find(function(name, path)
return name:match('.*%.[ch]pp$') and path:match('[/\\]lib$') return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$')
end, {limit = math.huge, type = 'file'}) end, {limit = math.huge, type = 'file'})
< <
@@ -2934,15 +2900,14 @@ vim.fs.normalize({path}, {opts}) *vim.fs.normalize()*
variables are also expanded. variables are also expanded.
Examples: >lua Examples: >lua
vim.fs.normalize('C:\\\\Users\\\\jdoe')
vim.fs.normalize('C:\\Users\\jdoe') -- 'C:/Users/jdoe'
--> 'C:/Users/jdoe'
vim.fs.normalize('~/src/neovim') vim.fs.normalize('~/src/neovim')
--> '/home/jdoe/src/neovim' -- '/home/jdoe/src/neovim'
vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
--> '/Users/jdoe/.config/nvim/init.vim' -- '/Users/jdoe/.config/nvim/init.vim'
< <
Parameters: ~ Parameters: ~
@@ -2958,7 +2923,6 @@ vim.fs.parents({start}) *vim.fs.parents()*
Iterate over all the parents of the given path. Iterate over all the parents of the given path.
Example: >lua Example: >lua
local root_dir local root_dir
for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
if vim.fn.isdirectory(dir .. "/.git") == 1 then if vim.fn.isdirectory(dir .. "/.git") == 1 then
@@ -3033,7 +2997,6 @@ spec. Plugins, and plugin managers, can use this to check available tools
and dependencies on the current system. and dependencies on the current system.
Example: >lua Example: >lua
local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false}) local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
if vim.version.gt(v, {3, 2, 0}) then if vim.version.gt(v, {3, 2, 0}) then
-- ... -- ...
@@ -3050,7 +3013,6 @@ tested against a version, using |vim.version.range()|.
Supported range specs are shown in the following table. Note: suffixed Supported range specs are shown in the following table. Note: suffixed
versions (1.2.3-rc1) are not matched. > versions (1.2.3-rc1) are not matched. >
1.2.3 is 1.2.3 1.2.3 is 1.2.3
=1.2.3 is 1.2.3 =1.2.3 is 1.2.3
>1.2.3 greater than 1.2.3 >1.2.3 greater than 1.2.3
@@ -3087,7 +3049,6 @@ vim.version.cmp({v1}, {v2}) *vim.version.cmp()*
tuple, e.g. `{1, 0, 3}`). tuple, e.g. `{1, 0, 3}`).
Example: >lua Example: >lua
if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
-- ... -- ...
end end
@@ -3150,8 +3111,8 @@ vim.version.lt({v1}, {v2}) *vim.version.lt()*
vim.version.parse({version}, {opts}) *vim.version.parse()* vim.version.parse({version}, {opts}) *vim.version.parse()*
Parses a semantic version string and returns a version object which can be 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: > used with other `vim.version` functions. For example "1.0.1-rc1+build.2"
returns: >
{ major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" } { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
< <
@@ -3171,7 +3132,6 @@ vim.version.parse({version}, {opts}) *vim.version.parse()*
vim.version.range({spec}) *vim.version.range()* vim.version.range({spec}) *vim.version.range()*
Parses a semver |version-range| "spec" and returns a range object: > Parses a semver |version-range| "spec" and returns a range object: >
{ {
from: Version from: Version
to: Version to: Version
@@ -3183,7 +3143,6 @@ vim.version.range({spec}) *vim.version.range()*
`to`). `to`).
Example: >lua Example: >lua
local r = vim.version.range('1.0.0 - 2.0.0') local r = vim.version.range('1.0.0 - 2.0.0')
print(r:has('1.9.9')) -- true print(r:has('1.9.9')) -- true
print(r:has('2.0.0')) -- false print(r:has('2.0.0')) -- false
@@ -3191,7 +3150,6 @@ vim.version.range({spec}) *vim.version.range()*
< <
Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly: >lua Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly: >lua
local r = vim.version.range('1.0.0 - 2.0.0') 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)) print(vim.version.gt({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
< <
@@ -3228,7 +3186,6 @@ iterator runs out of values (for function iterators, this means that the
first value returned by the function is nil). first value returned by the function is nil).
Examples: >lua Examples: >lua
local it = vim.iter({ 1, 2, 3, 4, 5 }) local it = vim.iter({ 1, 2, 3, 4, 5 })
it:map(function(v) it:map(function(v)
return v * 3 return v * 3
@@ -3275,7 +3232,6 @@ filter({f}, {src}, {...}) *vim.iter.filter()*
Filter a table or iterator. Filter a table or iterator.
This is a convenience function that performs: >lua This is a convenience function that performs: >lua
vim.iter(src):filter(f):totable() vim.iter(src):filter(f):totable()
< <
@@ -3325,19 +3281,16 @@ Iter:enumerate() *Iter:enumerate()*
the iterator value. the iterator value.
For list tables, prefer >lua For list tables, prefer >lua
vim.iter(ipairs(t)) vim.iter(ipairs(t))
< <
over >lua over >lua
vim.iter(t):enumerate() vim.iter(t):enumerate()
< <
as the former is faster. as the former is faster.
Example: >lua Example: >lua
local it = vim.iter(vim.gsplit('abc', '')):enumerate() local it = vim.iter(vim.gsplit('abc', '')):enumerate()
it:next() it:next()
-- 1 'a' -- 1 'a'
@@ -3354,7 +3307,6 @@ Iter:filter({f}) *Iter:filter()*
Add a filter step to the iterator pipeline. Add a filter step to the iterator pipeline.
Example: >lua Example: >lua
local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded) local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
< <
@@ -3373,7 +3325,6 @@ Iter:find({f}) *Iter:find()*
found. found.
Examples: >lua Examples: >lua
local it = vim.iter({ 3, 6, 9, 12 }) local it = vim.iter({ 3, 6, 9, 12 })
it:find(12) it:find(12)
-- 12 -- 12
@@ -3394,7 +3345,6 @@ Iter:fold({init}, {f}) *Iter:fold()*
Fold ("reduce") an iterator or table into a single value. Fold ("reduce") an iterator or table into a single value.
Examples: >lua Examples: >lua
-- Create a new table with only even values -- Create a new table with only even values
local t = { a = 1, b = 2, c = 3, d = 4 } local t = { a = 1, b = 2, c = 3, d = 4 }
local it = vim.iter(t) local it = vim.iter(t)
@@ -3419,7 +3369,6 @@ Iter:last() *Iter:last()*
Drains the iterator. Drains the iterator.
Example: >lua Example: >lua
local it = vim.iter(vim.gsplit('abcdefg', '')) local it = vim.iter(vim.gsplit('abcdefg', ''))
it:last() it:last()
-- 'g' -- 'g'
@@ -3438,7 +3387,6 @@ Iter:map({f}) *Iter:map()*
If the map function returns nil, the value is filtered from the iterator. If the map function returns nil, the value is filtered from the iterator.
Example: >lua Example: >lua
local it = vim.iter({ 1, 2, 3, 4 }):map(function(v) local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
if v % 2 == 0 then if v % 2 == 0 then
return v * 3 return v * 3
@@ -3461,7 +3409,6 @@ Iter:next() *Iter:next()*
Return the next value from the iterator. Return the next value from the iterator.
Example: >lua Example: >lua
local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber) local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
it:next() it:next()
-- 1 -- 1
@@ -3480,7 +3427,6 @@ Iter:nextback() *Iter:nextback()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Example: >lua Example: >lua
local it = vim.iter({1, 2, 3, 4}) local it = vim.iter({1, 2, 3, 4})
it:nextback() it:nextback()
-- 4 -- 4
@@ -3497,7 +3443,6 @@ Iter:nth({n}) *Iter:nth()*
This function advances the iterator. This function advances the iterator.
Example: >lua Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }) local it = vim.iter({ 3, 6, 9, 12 })
it:nth(2) it:nth(2)
-- 6 -- 6
@@ -3519,7 +3464,6 @@ Iter:nthback({n}) *Iter:nthback()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Example: >lua Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }) local it = vim.iter({ 3, 6, 9, 12 })
it:nthback(2) it:nthback(2)
-- 9 -- 9
@@ -3539,7 +3483,6 @@ Iter:peek() *Iter:peek()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Example: >lua Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }) local it = vim.iter({ 3, 6, 9, 12 })
it:peek() it:peek()
-- 3 -- 3
@@ -3558,7 +3501,6 @@ Iter:peekback() *Iter:peekback()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Example: >lua Example: >lua
local it = vim.iter({1, 2, 3, 4}) local it = vim.iter({1, 2, 3, 4})
it:peekback() it:peekback()
-- 4 -- 4
@@ -3577,7 +3519,6 @@ Iter:rev() *Iter:rev()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Example: >lua Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }):rev() local it = vim.iter({ 3, 6, 9, 12 }):rev()
it:totable() it:totable()
-- { 12, 9, 6, 3 } -- { 12, 9, 6, 3 }
@@ -3596,7 +3537,6 @@ Iter:rfind({f}) *Iter:rfind()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Examples: >lua Examples: >lua
local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate() local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
it:rfind(1) it:rfind(1)
-- 5 1 -- 5 1
@@ -3614,7 +3554,6 @@ Iter:skip({n}) *Iter:skip()*
Skip values in the iterator. Skip values in the iterator.
Example: >lua Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }):skip(2) local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
it:next() it:next()
-- 9 -- 9
@@ -3632,7 +3571,6 @@ Iter:skipback({n}) *Iter:skipback()*
Only supported for iterators on list-like tables. Only supported for iterators on list-like tables.
Example: >lua Example: >lua
local it = vim.iter({ 1, 2, 3, 4, 5 }):skipback(2) local it = vim.iter({ 1, 2, 3, 4, 5 }):skipback(2)
it:next() it:next()
-- 1 -- 1
@@ -3669,7 +3607,6 @@ Iter:totable() *Iter:totable()*
the iterator pipeline, each value will be included in a table. the iterator pipeline, each value will be included in a table.
Examples: >lua Examples: >lua
vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable() vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
-- { 100, 20, 50 } -- { 100, 20, 50 }
@@ -3691,7 +3628,6 @@ map({f}, {src}, {...}) *vim.iter.map()*
Map and filter a table or iterator. Map and filter a table or iterator.
This is a convenience function that performs: >lua This is a convenience function that performs: >lua
vim.iter(src):map(f):totable() vim.iter(src):map(f):totable()
< <
@@ -3711,7 +3647,6 @@ totable({f}, {...}) *vim.iter.totable()*
Collect an iterator into a table. Collect an iterator into a table.
This is a convenience function that performs: >lua This is a convenience function that performs: >lua
vim.iter(f):totable() vim.iter(f):totable()
< <

View File

@@ -945,7 +945,7 @@ A jump table for the options with a short description can be found at |Q_op|.
backups if you don't care about losing the file. backups if you don't care about losing the file.
Note that environment variables are not expanded. If you want to use Note that environment variables are not expanded. If you want to use
$HOME you must expand it explicitly, e.g.: > $HOME you must expand it explicitly, e.g.: >vim
:let &backupskip = escape(expand('$HOME'), '\') .. '/tmp/*' :let &backupskip = escape(expand('$HOME'), '\') .. '/tmp/*'
< Note that the default also makes sure that "crontab -e" works (when a < Note that the default also makes sure that "crontab -e" works (when a

View File

@@ -551,7 +551,6 @@ Lua module: vim.treesitter *lua-treesitter-core*
foldexpr({lnum}) *vim.treesitter.foldexpr()* foldexpr({lnum}) *vim.treesitter.foldexpr()*
Returns the fold level for {lnum} in the current buffer. Can be set Returns the fold level for {lnum} in the current buffer. Can be set
directly to 'foldexpr': >lua directly to 'foldexpr': >lua
vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()' vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
< <
@@ -746,7 +745,6 @@ start({bufnr}, {lang}) *vim.treesitter.start()*
the call to `start`. the call to `start`.
Example: >lua Example: >lua
vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
callback = function(args) callback = function(args)
vim.treesitter.start(args.buf, 'latex') vim.treesitter.start(args.buf, 'latex')
@@ -958,7 +956,6 @@ Query:iter_captures({node}, {source}, {start}, {stop})
The iterator returns three values: a numeric id identifying the capture, The iterator returns three values: a numeric id identifying the capture,
the captured node, and metadata from any directives processing the match. the captured node, and metadata from any directives processing the match.
The following example shows how to get captures by name: >lua The following example shows how to get captures by name: >lua
for id, node, metadata in query:iter_captures(tree:root(), bufnr, first, last) do 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 local name = query.captures[id] -- name of the capture in the query
-- typically useful info about the node: -- typically useful info about the node:
@@ -988,8 +985,8 @@ Query:iter_matches({node}, {source}, {start}, {stop}, {opts})
(1-based) index of the pattern in the query, a table mapping capture (1-based) index of the pattern in the query, a table mapping capture
indices to nodes, and metadata from any directives processing the match. indices to nodes, and metadata from any directives processing the match.
If the query has more than one pattern, the capture table might be sparse 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: >lua and e.g. `pairs()` method should be used over `ipairs`. Here is an example
iterating over all captures in every match: >lua
for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do
for id, node in pairs(match) do for id, node in pairs(match) do
local name = query.captures[id] local name = query.captures[id]
@@ -1039,10 +1036,7 @@ inject other languages, recursively. For example a Lua buffer containing
some Vimscript commands needs multiple parsers to fully understand its some Vimscript commands needs multiple parsers to fully understand its
contents. contents.
To create a LanguageTree (parser object) for a given buffer and language, use: To create a LanguageTree (parser object) for a given buffer and language, use: >lua
>lua
local parser = vim.treesitter.get_parser(bufnr, lang) local parser = vim.treesitter.get_parser(bufnr, lang)
< <
@@ -1052,10 +1046,7 @@ Note: currently the parser is retained for the lifetime of a buffer but
this may change; a plugin should keep a reference to the parser object if this may change; a plugin should keep a reference to the parser object if
it wants incremental updates. it wants incremental updates.
Whenever you need to access the current syntax tree, parse the buffer: Whenever you need to access the current syntax tree, parse the buffer: >lua
>lua
local tree = parser:parse({ start_row, end_row }) local tree = parser:parse({ start_row, end_row })
< <

View File

@@ -5,13 +5,14 @@ local F = {}
--- If all arguments are nil, returns nil. --- If all arguments are nil, returns nil.
--- ---
--- Examples: --- Examples:
--- <pre> ---
--- ```lua
--- local a = nil --- local a = nil
--- local b = nil --- local b = nil
--- local c = 42 --- local c = 42
--- local d = true --- local d = true
--- assert(vim.F.if_nil(a, b, c, d) == 42) --- assert(vim.F.if_nil(a, b, c, d) == 42)
--- </pre> --- ```
--- ---
---@param ... any ---@param ... any
---@return any ---@return any

View File

@@ -70,7 +70,8 @@ vim.log = {
--- Run a system command --- Run a system command
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- ---
--- local on_exit = function(obj) --- local on_exit = function(obj)
--- print(obj.code) --- print(obj.code)
@@ -86,7 +87,7 @@ vim.log = {
--- local obj = vim.system({'echo', 'hello'}, { text = true }):wait() --- local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
--- -- { code = 0, signal = 0, stdout = 'hello', stderr = '' } --- -- { code = 0, signal = 0, stdout = 'hello', stderr = '' }
--- ---
--- </pre> --- ```
--- ---
--- See |uv.spawn()| for more details. --- See |uv.spawn()| for more details.
--- ---
@@ -200,7 +201,8 @@ do
--- (such as the |TUI|) pastes text into the editor. --- (such as the |TUI|) pastes text into the editor.
--- ---
--- Example: To remove ANSI color codes when pasting: --- Example: To remove ANSI color codes when pasting:
--- <pre>lua ---
--- ```lua
--- vim.paste = (function(overridden) --- vim.paste = (function(overridden)
--- return function(lines, phase) --- return function(lines, phase)
--- for i,line in ipairs(lines) do --- for i,line in ipairs(lines) do
@@ -210,7 +212,7 @@ do
--- overridden(lines, phase) --- overridden(lines, phase)
--- end --- end
--- end)(vim.paste) --- end)(vim.paste)
--- </pre> --- ```
--- ---
---@see |paste| ---@see |paste|
---@alias paste_phase -1 | 1 | 2 | 3 ---@alias paste_phase -1 | 1 | 2 | 3
@@ -361,7 +363,8 @@ local VIM_CMD_ARG_MAX = 20
--- command. --- command.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.cmd('echo 42') --- vim.cmd('echo 42')
--- vim.cmd([[ --- vim.cmd([[
--- augroup My_group --- augroup My_group
@@ -386,7 +389,7 @@ local VIM_CMD_ARG_MAX = 20
--- -- Ex command :colorscheme blue --- -- Ex command :colorscheme blue
--- vim.cmd('colorscheme blue') --- vim.cmd('colorscheme blue')
--- vim.cmd.colorscheme('blue') --- vim.cmd.colorscheme('blue')
--- </pre> --- ```
--- ---
---@param command string|table Command(s) to execute. ---@param command string|table Command(s) to execute.
--- If a string, executes multiple lines of Vim script at once. In this --- 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. --- "Pretty prints" the given arguments and returns them unmodified.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true)) --- local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
--- </pre> --- ```
--- ---
--- @see |vim.inspect()| --- @see |vim.inspect()|
--- @see |:=| --- @see |:=|
@@ -900,10 +904,12 @@ end
--- Translate keycodes. --- Translate keycodes.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- local k = vim.keycode --- local k = vim.keycode
--- vim.g.mapleader = k'<bs>' --- vim.g.mapleader = k'<bs>'
--- </pre> --- ```
---
--- @param str string String to be converted. --- @param str string String to be converted.
--- @return string --- @return string
--- @see |nvim_replace_termcodes()| --- @see |nvim_replace_termcodes()|

View File

@@ -127,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 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. --- 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 --- ```lua
--- events = {} --- events = {}
--- vim.api.nvim_buf_attach(0, false, { --- vim.api.nvim_buf_attach(0, false, {
--- on_lines=function(...) table.insert(events, {...}) end}) --- on_lines = function(...)
--- table.insert(events, {...})
--- end,
--- })
--- ``` --- ```
--- ---
--- @param buffer integer Buffer handle, or 0 for current buffer --- @param buffer integer Buffer handle, or 0 for current buffer
@@ -314,16 +319,19 @@ 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 --- 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) --- positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1)
--- respectively, thus the following are equivalent: --- respectively, thus the following are equivalent:
---
--- ```lua --- ```lua
--- vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -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}, {}) --- vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {})
--- ``` --- ```
---
--- If `end` is less than `start`, traversal works backwards. (Useful with --- If `end` is less than `start`, traversal works backwards. (Useful with
--- `limit`, to get the first marks prior to a given position.) --- `limit`, to get the first marks prior to a given position.)
--- Note: when using extmark ranges (marks with a end_row/end_col 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 --- the `overlap` option might be useful. Otherwise only the start position of
--- an extmark will be considered. --- an extmark will be considered.
--- Example: --- Example:
---
--- ```lua --- ```lua
--- local api = vim.api --- local api = vim.api
--- local pos = api.nvim_win_get_cursor(0) --- local pos = api.nvim_win_get_cursor(0)
@@ -775,6 +783,7 @@ function vim.api.nvim_command_output(command) end
--- Create or get an autocommand group `autocmd-groups`. --- Create or get an autocommand group `autocmd-groups`.
--- To get an existing group id, do: --- To get an existing group id, do:
---
--- ```lua --- ```lua
--- local id = vim.api.nvim_create_augroup("MyGroup", { --- local id = vim.api.nvim_create_augroup("MyGroup", {
--- clear = false --- clear = false
@@ -790,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). --- Creates an `autocommand` event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string).
--- Example using Lua callback: --- Example using Lua callback:
---
--- ```lua --- ```lua
--- vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { --- vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
--- pattern = {"*.c", "*.h"}, --- pattern = {"*.c", "*.h"},
@@ -798,15 +808,19 @@ function vim.api.nvim_create_augroup(name, opts) end
--- end --- end
--- }) --- })
--- ``` --- ```
---
--- Example using an Ex command as the handler: --- Example using an Ex command as the handler:
---
--- ```lua --- ```lua
--- vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { --- vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
--- pattern = {"*.c", "*.h"}, --- pattern = {"*.c", "*.h"},
--- command = "echo 'Entering a C or C++ file'", --- 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 --- ```lua
--- pattern = vim.fn.expand("~") .. "/some/path/*.py" --- pattern = vim.fn.expand("~") .. "/some/path/*.py"
--- ``` --- ```
@@ -870,6 +884,7 @@ function vim.api.nvim_create_namespace(name) end
--- Creates a global `user-commands` command. --- Creates a global `user-commands` command.
--- For Lua usage see `lua-guide-commands-create`. --- For Lua usage see `lua-guide-commands-create`.
--- Example: --- Example:
---
--- ```vim --- ```vim
--- :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true}) --- :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true})
--- :SayHello --- :SayHello
@@ -1084,6 +1099,7 @@ function vim.api.nvim_execute_lua(code, args) end
--- with escape_ks=false) to replace `keycodes`, then pass the result to --- with escape_ks=false) to replace `keycodes`, then pass the result to
--- nvim_feedkeys(). --- nvim_feedkeys().
--- Example: --- Example:
---
--- ```vim --- ```vim
--- :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) --- :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true)
--- :call nvim_feedkeys(key, 'n', v:false) --- :call nvim_feedkeys(key, 'n', v:false)
@@ -1111,6 +1127,7 @@ function vim.api.nvim_get_api_info() end
--- Get all autocommands that match the corresponding {opts}. --- Get all autocommands that match the corresponding {opts}.
--- These examples will get autocommands matching ALL the given criteria: --- These examples will get autocommands matching ALL the given criteria:
---
--- ```lua --- ```lua
--- -- Matches all criteria --- -- Matches all criteria
--- autocommands = vim.api.nvim_get_autocmds({ --- autocommands = vim.api.nvim_get_autocmds({
@@ -1124,6 +1141,7 @@ function vim.api.nvim_get_api_info() end
--- group = "MyGroup", --- group = "MyGroup",
--- }) --- })
--- ``` --- ```
---
--- NOTE: When multiple patterns or events are provided, it will find all the --- NOTE: When multiple patterns or events are provided, it will find all the
--- autocommands that match any combination of them. --- autocommands that match any combination of them.
--- ---
@@ -1149,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 --- Returns the 24-bit RGB value of a `nvim_get_color_map()` color name or
--- "#rrggbb" hexadecimal string. --- "#rrggbb" hexadecimal string.
--- Example: --- Example:
---
--- ```vim --- ```vim
--- :echo nvim_get_color_by_name("Pink") --- :echo nvim_get_color_by_name("Pink")
--- :echo nvim_get_color_by_name("#cbcbcb") --- :echo nvim_get_color_by_name("#cbcbcb")
@@ -1471,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 --- could let floats hover outside of the main window like a tooltip, but this
--- should not be used to specify arbitrary WM screen positions. --- should not be used to specify arbitrary WM screen positions.
--- Example (Lua): window-relative float --- Example (Lua): window-relative float
---
--- ```lua --- ```lua
--- vim.api.nvim_open_win(0, false, --- vim.api.nvim_open_win(0, false,
--- {relative='win', row=3, col=3, width=12, height=3}) --- {relative='win', row=3, col=3, width=12, height=3})
--- ``` --- ```
---
--- Example (Lua): buffer-relative float (travels as buffer is scrolled) --- Example (Lua): buffer-relative float (travels as buffer is scrolled)
---
--- ```lua --- ```lua
--- vim.api.nvim_open_win(0, false, --- vim.api.nvim_open_win(0, false,
--- {relative='win', width=12, height=3, bufpos={100,10}}) --- {relative='win', width=12, height=3, bufpos={100,10}})
--- })
--- ``` --- ```
--- ---
--- @param buffer integer Buffer to display, or 0 for current buffer --- @param buffer integer Buffer to display, or 0 for current buffer
@@ -1856,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 --- Unlike `:map`, leading/trailing whitespace is accepted as part of the
--- {lhs} or {rhs}. Empty {rhs} is `<Nop>`. `keycodes` are replaced as usual. --- {lhs} or {rhs}. Empty {rhs} is `<Nop>`. `keycodes` are replaced as usual.
--- Example: --- Example:
---
--- ```vim --- ```vim
--- call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) --- call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true})
--- ``` --- ```
---
--- is equivalent to: --- is equivalent to:
---
--- ```vim --- ```vim
--- nmap <nowait> <Space><NL> <Nop> --- nmap <nowait> <Space><NL> <Nop>
--- ``` --- ```

View File

@@ -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. --- The result can be added to {index} to get the starting byte of a character.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8) --- -- 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 --- -- 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 --- -- Returns -1 because the index is pointing at the second byte of a character
--- vim.str_utf_start('æ', 2) --- vim.str_utf_start('æ', 2)
--- </pre> --- ```
--- ---
--- @param str string --- @param str string
--- @param index number --- @param index number
@@ -150,7 +151,8 @@ function vim.str_utf_start(str, index) end
--- to. --- to.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- -- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8) --- -- 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 --- -- 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 --- -- Returns 1 because the index is pointing at the penultimate byte of a character
--- vim.str_utf_end('æ', 1) --- vim.str_utf_end('æ', 1)
--- </pre> --- ```
--- ---
--- @param str string --- @param str string
--- @param index number --- @param index number
@@ -204,7 +206,8 @@ function vim.schedule(callback) end
--- this time. --- this time.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- ---
--- --- --- ---
--- -- Wait for 100 ms, allowing other events to process --- -- 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 --- if vim.wait(10000, function() return vim.g.timer_result end) then
--- print('Only waiting a little bit of time!') --- print('Only waiting a little bit of time!')
--- end --- end
--- </pre> --- ```
--- ---
--- @param time integer Number of milliseconds to wait --- @param time integer Number of milliseconds to wait
--- @param callback? fun(): boolean Optional callback. Waits until {callback} returns true --- @param callback? fun(): boolean Optional callback. Waits until {callback} returns true
@@ -258,8 +261,8 @@ function vim.wait(time, callback, interval, fast_only) end
--- likewise experimental). --- likewise experimental).
--- ---
--- Example (stub for a |ui-popupmenu| implementation): --- Example (stub for a |ui-popupmenu| implementation):
--- <pre>lua
--- ---
--- ```lua
--- ns = vim.api.nvim_create_namespace('my_fancy_pum') --- ns = vim.api.nvim_create_namespace('my_fancy_pum')
--- ---
--- vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...) --- vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
@@ -273,7 +276,8 @@ function vim.wait(time, callback, interval, fast_only) end
--- print("FIN") --- print("FIN")
--- end --- end
--- end) --- end)
--- </pre> --- ```
---
--- @param ns integer --- @param ns integer
--- @param options table<string, any> --- @param options table<string, any>
--- @param callback fun() --- @param callback fun()

View File

@@ -6,24 +6,25 @@
--- either directly or via callback arguments, are 1-based. --- either directly or via callback arguments, are 1-based.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- vim.diff('a\\n', 'b\\nc\\n') --- ```lua
--- vim.diff('a\n', 'b\nc\n')
--- -- => --- -- =>
--- -- @@ -1 +1,2 @@ --- -- @@ -1 +1,2 @@
--- -- -a --- -- -a
--- -- +b --- -- +b
--- -- +c --- -- +c
--- ---
--- vim.diff('a\\n', 'b\\nc\\n', {result_type = 'indices'}) --- vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
--- -- => --- -- =>
--- -- { --- -- {
--- -- {1, 1, 1, 2} --- -- {1, 1, 1, 2}
--- -- } --- -- }
--- </pre> --- ```
--- ---
--- @param a string First string to compare ---@param a string First string to compare
--- @param b string Second string to compare ---@param b string Second string to compare
--- @param opts table<string,any> Optional parameters: ---@param opts table<string,any> Optional parameters:
--- - `on_hunk` (callback): --- - `on_hunk` (callback):
--- Invoked for each hunk in the diff. Return a negative number --- Invoked for each hunk in the diff. Return a negative number
--- to cancel the callback for any remaining hunks. --- to cancel the callback for any remaining hunks.
@@ -64,6 +65,6 @@
--- Use the indent heuristic for the internal --- Use the indent heuristic for the internal
--- diff library. --- diff library.
--- ---
--- @return string|table|nil ---@return string|table|nil
--- See {opts.result_type}. `nil` if {opts.on_hunk} is given. --- See {opts.result_type}. `nil` if {opts.on_hunk} is given.
function vim.diff(a, b, opts) end function vim.diff(a, b, opts) end

View File

@@ -1,8 +1,8 @@
--- @meta ---@meta
-- luacheck: no unused args -- luacheck: no unused args
--- @defgroup vim.json ---@defgroup vim.json
--- ---
--- This module provides encoding and decoding of Lua objects to and --- This module provides encoding and decoding of Lua objects to and
--- from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|. --- from JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
@@ -14,24 +14,23 @@
--- - Decodes empty array as `{}` (empty Lua table). --- - Decodes empty array as `{}` (empty Lua table).
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- :lua vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}')) --- ```lua
--- --> { bar = {}, foo = vim.empty_dict(), zub = vim.NIL } --- vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
--- </pre> --- -- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
--- Parameters: ~ --- ```
--- • {str} Stringified JSON data. ---
--- • {opts} Options map keys: ---@param str string Stringified JSON data.
--- • luanil: { object: bool, array: bool } ---@param opts? table<string,any> Options table with keys:
--- • `luanil.object=true` converts `null` in JSON objects to --- - luanil: (table) Table with keys:
--- Lua `nil` instead of `vim.NIL`. --- * object: (boolean) When true, converts `null` in JSON objects
--- • `luanil.array=true` converts `null` in JSON arrays to Lua --- to Lua `nil` instead of |vim.NIL|.
--- `nil` instead of `vim.NIL`. --- * array: (boolean) When true, converts `null` in JSON arrays
--- @param str string --- to Lua `nil` instead of |vim.NIL|.
--- @param opts? table<string, any> ---@return any
--- @return any
function vim.json.decode(str, opts) end function vim.json.decode(str, opts) end
--- Encodes (or "packs") Lua object {obj} as JSON in a Lua string. --- Encodes (or "packs") Lua object {obj} as JSON in a Lua string.
--- @param obj any ---@param obj any
--- @return string ---@return string
function vim.json.encode(obj) end function vim.json.encode(obj) end

View File

@@ -5,9 +5,11 @@
--- Invokes |vim-function| or |user-function| {func} with arguments {...}. --- Invokes |vim-function| or |user-function| {func} with arguments {...}.
--- See also |vim.fn|. --- See also |vim.fn|.
--- Equivalent to: --- Equivalent to:
--- <pre>lua ---
--- ```lua
--- vim.fn[func]({...}) --- vim.fn[func]({...})
--- </pre> --- ```
---
--- @param func fun() --- @param func fun()
--- @param ... any --- @param ... any
function vim.call(func, ...) end function vim.call(func, ...) end

View File

@@ -141,6 +141,7 @@ vim.bo.ai = vim.bo.autoindent
--- :set autoread< --- :set autoread<
--- ``` --- ```
--- ---
---
--- @type boolean --- @type boolean
vim.o.autoread = true vim.o.autoread = true
vim.o.ar = vim.o.autoread 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 --- :set bdir=c:\\tmp,\ dir\\,with\\,commas,\\\ dir\ with\ spaces
--- ``` --- ```
---
--- See also 'backup' and 'writebackup' options. --- See also 'backup' and 'writebackup' options.
--- If you want to hide your backup files on Unix, consider this value: --- 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 --- Note that environment variables are not expanded. If you want to use
--- $HOME you must expand it explicitly, e.g.: --- $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 --- 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 --- 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 --- set cinscopedecls+=signals,public\ slots,private\ slots
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.cinscopedecls = "public,protected,private" vim.o.cinscopedecls = "public,protected,private"
vim.o.cinsd = vim.o.cinscopedecls 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 --- The screen column can be an absolute number, or a number preceded with
--- '+' or '-', which is added to or subtracted from 'textwidth'. --- '+' or '-', which is added to or subtracted from 'textwidth'.
--- ``` --- ```
---
--- :set cc=+1 " highlight column after 'textwidth' --- :set cc=+1 " highlight column after 'textwidth'
--- :set cc=+1,+2,+3 " highlight three columns after 'textwidth' --- :set cc=+1,+2,+3 " highlight three columns after 'textwidth'
--- :hi ColorColumn ctermbg=lightgrey guibg=lightgrey --- :hi ColorColumn ctermbg=lightgrey guibg=lightgrey
--- ``` --- ```
---
--- When 'textwidth' is zero then the items with '-' and '+' are not used. --- When 'textwidth' is zero then the items with '-' and '+' are not used.
--- A maximum of 256 columns are highlighted. --- A maximum of 256 columns are highlighted.
--- ---
@@ -1418,6 +1421,7 @@ vim.wo.crb = vim.wo.cursorbind
--- au WinEnter * set cursorline cursorcolumn --- au WinEnter * set cursorline cursorcolumn
--- ``` --- ```
--- ---
---
--- @type boolean --- @type boolean
vim.o.cursorcolumn = false vim.o.cursorcolumn = false
vim.o.cuc = vim.o.cursorcolumn 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(' --- let &l:define = '^\s*\ze\k\+\s*=\s*function('
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.define = "" vim.o.define = ""
vim.o.def = 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 --- :set diffopt-=internal " do NOT use the internal diff parser
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.diffopt = "internal,filler,closeoff" vim.o.diffopt = "internal,filler,closeoff"
vim.o.dip = vim.o.diffopt 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 --- :set dir=c:\\tmp,\ dir\\,with\\,commas,\\\ dir\ with\ spaces
--- ``` --- ```
---
--- Editing the same file twice will result in a warning. Using "/tmp" on --- 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 --- is discouraged: if the system crashes you lose the swap file. And
--- others on the computer may be able to see the files. --- 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 --- :set ei=WinEnter,WinLeave
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.eventignore = "" vim.o.eventignore = ""
vim.o.ei = 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: --- To disable cursor-styling, reset the option:
--- ``` --- ```
--- :set guicursor= --- :set guicursor=
---
--- ``` --- ```
--- To enable mode shapes, "Cursor" highlight, and blinking: --- To enable mode shapes, "Cursor" highlight, and blinking:
--- ``` --- ```
--- :set guicursor=n-v-c:block,i-ci-ve:ver25,r-cr:hor20,o:hor50 --- :set guicursor=n-v-c:block,i-ci-ve:ver25,r-cr:hor20,o:hor50
--- \,a:blinkwait700-blinkoff400-blinkon250-Cursor/lCursor --- \,a:blinkwait700-blinkoff400-blinkon250-Cursor/lCursor
--- \,sm:block-blinkwait175-blinkoff150-blinkon175 --- \,sm:block-blinkwait175-blinkoff150-blinkon175
---
--- ``` --- ```
--- The option is a comma-separated list of parts. Each part consists of a --- The option is a comma-separated list of parts. Each part consists of a
--- mode-list and an argument-list: --- mode-list and an argument-list:
@@ -2719,6 +2725,7 @@ vim.go.gp = vim.go.grepprg
--- :highlight Cursor gui=NONE guifg=bg guibg=fg --- :highlight Cursor gui=NONE guifg=bg guibg=fg
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.guicursor = "n-v-c-sm:block,i-ci-ve:ver25,r-cr-o:hor20" vim.o.guicursor = "n-v-c-sm:block,i-ci-ve:ver25,r-cr-o:hor20"
vim.o.gcr = vim.o.guicursor vim.o.gcr = vim.o.guicursor
@@ -2790,6 +2797,7 @@ vim.go.gcr = vim.go.guicursor
--- :set guifont=Andale_Mono:h7.5:w4.5 --- :set guifont=Andale_Mono:h7.5:w4.5
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.guifont = "" vim.o.guifont = ""
vim.o.gfn = 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" --- :let &guitabtooltip = "line one\nline two"
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.guitabtooltip = "" vim.o.guitabtooltip = ""
vim.o.gtt = vim.o.guitabtooltip vim.o.gtt = vim.o.guitabtooltip
@@ -3206,6 +3215,7 @@ vim.go.inc = vim.go.include
--- ``` --- ```
--- :setlocal includeexpr=tr(v:fname,'.','/') --- :setlocal includeexpr=tr(v:fname,'.','/')
--- ``` --- ```
---
--- Also used for the `gf` command if an unmodified file name can't be --- 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. --- found. Allows doing "gf" on the name after an 'include' statement.
--- Also used for `<cfile>`. --- Also used for `<cfile>`.
@@ -3258,6 +3268,7 @@ vim.bo.inex = vim.bo.includeexpr
--- autocmd CmdlineLeave /,\? :set nohlsearch --- autocmd CmdlineLeave /,\? :set nohlsearch
--- augroup END --- augroup END
--- ``` --- ```
---
--- CTRL-L can be used to add one character from after the current match --- 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 --- to the command line. If 'ignorecase' and 'smartcase' are set and the
--- command line has no uppercase characters, the added character is --- 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 --- :set langmap=zy,yz,ZY,YZ
--- ``` --- ```
---
--- The 'langmap' option is a list of parts, separated with commas. Each --- The 'langmap' option is a list of parts, separated with commas. Each
--- part can be in one of two forms: --- part can be in one of two forms:
--- 1. A list of pairs. Each pair is a "from" character immediately --- 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:\ \ --- :set list lcs=tab:\ \
--- ``` --- ```
---
--- Note that list mode will also affect formatting (set with 'textwidth' --- Note that list mode will also affect formatting (set with 'textwidth'
--- or 'wrapmargin') when 'cpoptions' includes 'L'. See 'listchars' for --- or 'wrapmargin') when 'cpoptions' includes 'L'. See 'listchars' for
--- changing the way tabs are displayed. --- changing the way tabs are displayed.
@@ -3790,6 +3803,7 @@ vim.wo.list = vim.o.list
--- >-- --- >--
--- etc. --- etc.
--- ``` --- ```
---
--- tab:xyz The 'z' is always used, then 'x' is prepended, and --- tab:xyz The 'z' is always used, then 'x' is prepended, and
--- then 'y' is used as many times as will fit. Thus --- then 'y' is used as many times as will fit. Thus
--- "tab:<->" displays: --- "tab:<->" displays:
@@ -3801,6 +3815,7 @@ vim.wo.list = vim.o.list
--- <--> --- <-->
--- etc. --- etc.
--- ``` --- ```
---
--- When "tab:" is omitted, a tab is shown as ^I. --- When "tab:" is omitted, a tab is shown as ^I.
--- *lcs-space* --- *lcs-space*
--- space:c Character to show for a space. When omitted, spaces --- space:c Character to show for a space. When omitted, spaces
@@ -3816,6 +3831,7 @@ vim.wo.list = vim.o.list
--- ``` --- ```
--- ---+---+-- --- ---+---+--
--- ``` --- ```
---
--- *lcs-lead* --- *lcs-lead*
--- lead:c Character to show for leading spaces. When omitted, --- lead:c Character to show for leading spaces. When omitted,
--- leading spaces are blank. Overrides the "space" and --- leading spaces are blank. Overrides the "space" and
@@ -3824,6 +3840,7 @@ vim.wo.list = vim.o.list
--- ``` --- ```
--- :set listchars+=tab:>-,lead:. --- :set listchars+=tab:>-,lead:.
--- ``` --- ```
---
--- *lcs-leadmultispace* --- *lcs-leadmultispace*
--- leadmultispace:c... --- leadmultispace:c...
--- Like the `lcs-multispace` value, but for leading --- Like the `lcs-multispace` value, but for leading
@@ -3834,6 +3851,7 @@ vim.wo.list = vim.o.list
--- ``` --- ```
--- ---+---+--XXX --- ---+---+--XXX
--- ``` --- ```
---
--- Where "XXX" denotes the first non-blank characters in --- Where "XXX" denotes the first non-blank characters in
--- the line. --- the line.
--- *lcs-trail* --- *lcs-trail*
@@ -3941,6 +3959,7 @@ vim.go.mef = vim.go.makeef
--- :set makeencoding=char " system locale is used --- :set makeencoding=char " system locale is used
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.makeencoding = "" vim.o.makeencoding = ""
vim.o.menc = vim.o.makeencoding vim.o.menc = vim.o.makeencoding
@@ -3986,13 +4005,11 @@ vim.go.mp = vim.go.makeprg
--- '>' (for HTML): --- '>' (for HTML):
--- ``` --- ```
--- :set mps+=<:> --- :set mps+=<:>
---
--- ``` --- ```
--- A more exotic example, to jump between the '=' and ';' in an --- A more exotic example, to jump between the '=' and ';' in an
--- assignment, useful for languages like C and Java: --- assignment, useful for languages like C and Java:
--- ``` --- ```
--- :au FileType c,cpp,java set mps+==:; --- :au FileType c,cpp,java set mps+==:;
---
--- ``` --- ```
--- For a more advanced way of using "%", see the matchit.vim plugin in --- For a more advanced way of using "%", see the matchit.vim plugin in
--- the $VIMRUNTIME/plugin directory. `add-local-help` --- the $VIMRUNTIME/plugin directory. `add-local-help`
@@ -4078,6 +4095,7 @@ vim.go.mis = vim.go.menuitems
--- ``` --- ```
--- {start},{inc},{added} --- {start},{inc},{added}
--- ``` --- ```
---
--- For most languages the uncompressed word tree fits in memory. {start} --- For most languages the uncompressed word tree fits in memory. {start}
--- gives the amount of memory in Kbyte that can be used before any --- 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 --- 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 --- :set mouse=nv
--- ``` --- ```
---
--- To temporarily disable mouse support, hold the shift key while using --- To temporarily disable mouse support, hold the shift key while using
--- the mouse. --- the mouse.
--- ---
@@ -4299,6 +4318,7 @@ vim.go.mh = vim.go.mousehide
--- :map <4-S-LeftDrag> <4-RightDrag> --- :map <4-S-LeftDrag> <4-RightDrag>
--- :map <4-S-LeftRelease> <4-RightRelease> --- :map <4-S-LeftRelease> <4-RightRelease>
--- ``` --- ```
---
--- Mouse commands requiring the CTRL modifier can be simulated by typing --- Mouse commands requiring the CTRL modifier can be simulated by typing
--- the "g" key before using the mouse: --- the "g" key before using the mouse:
--- "g<LeftMouse>" is "<C-LeftMouse> (jump to tag under mouse click) --- "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 --- |there | 4 there | 1 there | 1 there
--- ``` --- ```
--- ---
---
--- @type boolean --- @type boolean
vim.o.number = false vim.o.number = false
vim.o.nu = vim.o.number 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 --- the popupmenu using `highlight-blend`. For instance, to enable
--- transparency but force the current selected element to be fully opaque: --- transparency but force the current selected element to be fully opaque:
--- ``` --- ```
---
--- :set pumblend=15 --- :set pumblend=15
--- :hi PmenuSel blend=0 --- :hi PmenuSel blend=0
--- ``` --- ```
---
--- UI-dependent. Works best with RGB colors. 'termguicolors' --- UI-dependent. Works best with RGB colors. 'termguicolors'
--- ---
--- @type integer --- @type integer
@@ -4986,6 +5007,7 @@ vim.go.ru = vim.go.ruler
--- :set rulerformat=%15(%c%V\ %p%%%) --- :set rulerformat=%15(%c%V\ %p%%%)
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.rulerformat = "" vim.o.rulerformat = ""
vim.o.ruf = 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 --- :set shada='50,<1000,s100,:0,n~/nvim/shada
--- ``` --- ```
---
--- '50 Marks will be remembered for the last 50 files you --- '50 Marks will be remembered for the last 50 files you
--- edited. --- edited.
--- <1000 Contents of registers (up to 1000 lines each) will be --- <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 &shellredir = '2>&1 | %%{ "$_" } | Out-File %s; exit $LastExitCode'
--- let &shellpipe = '2>&1 | %%{ "$_" } | tee %s; exit $LastExitCode' --- let &shellpipe = '2>&1 | %%{ "$_" } | tee %s; exit $LastExitCode'
--- set shellquote= shellxquote= --- set shellquote= shellxquote=
---
--- ``` --- ```
--- This option cannot be set from a `modeline` or in the `sandbox`, for --- This option cannot be set from a `modeline` or in the `sandbox`, for
--- security reasons. --- security reasons.
@@ -5726,6 +5748,7 @@ vim.go.shm = vim.go.shortmess
--- :setlocal showbreak=NONE --- :setlocal showbreak=NONE
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.showbreak = "" vim.o.showbreak = ""
vim.o.sbr = vim.o.showbreak vim.o.sbr = vim.o.showbreak
@@ -5858,15 +5881,16 @@ vim.go.ss = vim.go.sidescroll
--- setlocal sidescrolloff< --- setlocal sidescrolloff<
--- setlocal sidescrolloff=-1 --- setlocal sidescrolloff=-1
--- ``` --- ```
---
--- Example: Try this together with 'sidescroll' and 'listchars' as --- Example: Try this together with 'sidescroll' and 'listchars' as
--- in the following example to never allow the cursor to move --- in the following example to never allow the cursor to move
--- onto the "extends" character: --- onto the "extends" character:
--- ``` --- ```
---
--- :set nowrap sidescroll=1 listchars=extends:>,precedes:< --- :set nowrap sidescroll=1 listchars=extends:>,precedes:<
--- :set sidescrolloff=1 --- :set sidescrolloff=1
--- ``` --- ```
--- ---
---
--- @type integer --- @type integer
vim.o.sidescrolloff = 0 vim.o.sidescrolloff = 0
vim.o.siso = vim.o.sidescrolloff 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() --- :set sps=file:~/.config/nvim/sugg,best,expr:MySuggest()
--- ``` --- ```
---
--- This option cannot be set from a `modeline` or in the `sandbox`, for --- This option cannot be set from a `modeline` or in the `sandbox`, for
--- security reasons. --- security reasons.
--- ---
@@ -6263,6 +6288,7 @@ vim.go.sol = vim.go.startofline
--- handler should be written with this in mind. --- handler should be written with this in mind.
--- ---
--- Examples: --- Examples:
---
--- ```vim --- ```vim
--- " Relative number with bar separator and click handlers: --- " Relative number with bar separator and click handlers:
--- :set statuscolumn=%@SignCb@%s%=%T%@NumCb@%r│%T --- :set statuscolumn=%@SignCb@%s%=%T%@NumCb@%r│%T
@@ -6282,7 +6308,6 @@ vim.go.sol = vim.go.startofline
--- :let &stc='%#NonText#%{&nu?v:lnum:""}' . --- :let &stc='%#NonText#%{&nu?v:lnum:""}' .
--- '%=%{&rnu&&(v:lnum%2)?"\ ".v:relnum:""}' . --- '%=%{&rnu&&(v:lnum%2)?"\ ".v:relnum:""}' .
--- '%#LineNr#%{&rnu&&!(v:lnum%2)?"\ ".v:relnum:""}' --- '%#LineNr#%{&rnu&&!(v:lnum%2)?"\ ".v:relnum:""}'
---
--- ``` --- ```
--- WARNING: this expression is evaluated for each screen line so defining --- WARNING: this expression is evaluated for each screen line so defining
--- an expensive expression can negatively affect render performance. --- an expensive expression can negatively affect render performance.
@@ -6522,6 +6547,7 @@ vim.wo.stc = vim.wo.statuscolumn
--- :endfunction --- :endfunction
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.statusline = "" vim.o.statusline = ""
vim.o.stl = vim.o.statusline vim.o.stl = vim.o.statusline
@@ -6553,6 +6579,7 @@ vim.go.su = vim.go.suffixes
--- :set suffixesadd=.java --- :set suffixesadd=.java
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.suffixesadd = "" vim.o.suffixesadd = ""
vim.o.sua = vim.o.suffixesadd vim.o.sua = vim.o.suffixesadd
@@ -7445,6 +7472,7 @@ vim.go.ww = vim.go.whichwrap
--- :set wc=<Tab> --- :set wc=<Tab>
--- ``` --- ```
--- ---
---
--- @type integer --- @type integer
vim.o.wildchar = 9 vim.o.wildchar = 9
vim.o.wc = vim.o.wildchar vim.o.wc = vim.o.wildchar
@@ -7533,6 +7561,7 @@ vim.go.wic = vim.go.wildignorecase
--- :cnoremap <Left> <Space><BS><Left> --- :cnoremap <Left> <Space><BS><Left>
--- :cnoremap <Right> <Space><BS><Right> --- :cnoremap <Right> <Space><BS><Right>
--- ``` --- ```
---
--- `hl-WildMenu` highlights the current match. --- `hl-WildMenu` highlights the current match.
--- ---
--- @type boolean --- @type boolean
@@ -7762,6 +7791,7 @@ vim.go.wh = vim.go.winheight
--- set winhighlight=Normal:MyNormal,NormalNC:MyNormalNC --- set winhighlight=Normal:MyNormal,NormalNC:MyNormalNC
--- ``` --- ```
--- ---
---
--- @type string --- @type string
vim.o.winhighlight = "" vim.o.winhighlight = ""
vim.o.winhl = vim.o.winhighlight vim.o.winhl = vim.o.winhighlight

View File

@@ -10,13 +10,14 @@
--- the buffer. Consider calling this with |nvim_buf_call()|. --- the buffer. Consider calling this with |nvim_buf_call()|.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.spell.check("the quik brown fox") --- vim.spell.check("the quik brown fox")
--- -- => --- -- =>
--- -- { --- -- {
--- -- {'quik', 'bad', 5} --- -- {'quik', 'bad', 5}
--- -- } --- -- }
--- </pre> --- ```
--- ---
--- @param str string --- @param str string
--- @return {[1]: string, [2]: string, [3]: string}[] --- @return {[1]: string, [2]: string, [3]: string}[]

View File

@@ -7,11 +7,12 @@
---"references". |lua-guide-variables| For example, using \`vim.fn.remove()\` on ---"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 ---a Lua list copies the list object to Vimscript and does NOT modify the Lua
---list: ---list:
---<pre>lua ---
--- ```lua
--- local list = { 1, 2, 3 } --- local list = { 1, 2, 3 }
--- vim.fn.remove(list, 0) --- vim.fn.remove(list, 0)
--- vim.print(list) --> "{ 1, 2, 3 }" --- vim.print(list) --> "{ 1, 2, 3 }"
---</pre> --- ```
---@addtogroup lua-vimscript ---@addtogroup lua-vimscript
---@brief <pre>help ---@brief <pre>help
@@ -131,13 +132,17 @@ local function get_options_info(name)
return info return info
end end
---Environment variables defined in the editor session. --- Environment variables defined in the editor session.
---See |expand-env| and |:let-environment| for the Vimscript behavior. --- See |expand-env| and |:let-environment| for the Vimscript behavior.
---Invalid or unset key returns `nil`. --- Invalid or unset key returns `nil`.
---Example: <pre>lua ---
--- Example:
---
--- ```lua
--- vim.env.FOO = 'bar' --- vim.env.FOO = 'bar'
--- print(vim.env.TERM) --- print(vim.env.TERM)
---</pre> --- ```
---
---@param var string ---@param var string
vim.env = setmetatable({}, { vim.env = setmetatable({}, {
__index = function(_, k) __index = function(_, k)
@@ -226,16 +231,18 @@ end
---global value of a |global-local| option, see |:setglobal|. ---global value of a |global-local| option, see |:setglobal|.
---</pre> ---</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 --- Note: this works on both buffer-scoped and window-scoped options using the
---current buffer and window. --- current buffer and window.
--- ---
---Example: <pre>lua --- Example:
---
--- ```lua
--- vim.o.cmdheight = 4 --- vim.o.cmdheight = 4
--- print(vim.o.columns) --- print(vim.o.columns)
--- print(vim.o.foo) -- error: invalid key --- print(vim.o.foo) -- error: invalid key
---</pre> --- ```
vim.o = setmetatable({}, { vim.o = setmetatable({}, {
__index = function(_, k) __index = function(_, k)
return api.nvim_get_option_value(k, {}) return api.nvim_get_option_value(k, {})
@@ -245,18 +252,20 @@ vim.o = setmetatable({}, {
end, end,
}) })
---Get or set global |options|. Like `:setglobal`. Invalid key is --- Get or set global |options|. Like `:setglobal`. Invalid key is
---an error. --- an error.
--- ---
---Note: this is different from |vim.o| because this accesses the global --- Note: this is different from |vim.o| because this accesses the global
---option value and thus is mostly useful for use with |global-local| --- option value and thus is mostly useful for use with |global-local|
---options. --- options.
--- ---
---Example: <pre>lua --- Example:
---
--- ```lua
--- vim.go.cmdheight = 4 --- vim.go.cmdheight = 4
--- print(vim.go.columns) --- print(vim.go.columns)
--- print(vim.go.bar) -- error: invalid key --- print(vim.go.bar) -- error: invalid key
---</pre> --- ```
vim.go = setmetatable({}, { vim.go = setmetatable({}, {
__index = function(_, k) __index = function(_, k)
return api.nvim_get_option_value(k, { scope = 'global' }) return api.nvim_get_option_value(k, { scope = 'global' })
@@ -266,37 +275,39 @@ vim.go = setmetatable({}, {
end, end,
}) })
---Get or set buffer-scoped |options| for the buffer with number {bufnr}. --- Get or set buffer-scoped |options| for the buffer with number {bufnr}.
---Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current --- Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
---buffer is used. Invalid {bufnr} or key is an error. --- 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 --- Example:
---
--- ```lua
--- local bufnr = vim.api.nvim_get_current_buf() --- local bufnr = vim.api.nvim_get_current_buf()
--- vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true --- vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
--- print(vim.bo.comments) --- print(vim.bo.comments)
--- print(vim.bo.baz) -- error: invalid key --- print(vim.bo.baz) -- error: invalid key
---</pre> --- ```
---@param bufnr integer|nil
vim.bo = new_buf_opt_accessor() vim.bo = new_buf_opt_accessor()
---Get or set window-scoped |options| for the window with handle {winid} and --- Get or set window-scoped |options| for the window with handle {winid} and
---buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like --- buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like
---`:set` otherwise. If [{winid}] is omitted then the current window is --- `:set` otherwise. If [{winid}] is omitted then the current window is
---used. Invalid {winid}, {bufnr} or key is an error. --- used. Invalid {winid}, {bufnr} or key is an error.
--- ---
---Note: only {bufnr} with value `0` (the current buffer in the window) is --- Note: only {bufnr} with value `0` (the current buffer in the window) is
---supported. --- supported.
--- ---
---Example: <pre>lua --- Example:
---
--- ```lua
--- local winid = vim.api.nvim_get_current_win() --- local winid = vim.api.nvim_get_current_win()
--- vim.wo[winid].number = true -- same as vim.wo.number = true --- vim.wo[winid].number = true -- same as vim.wo.number = true
--- print(vim.wo.foldmarker) --- print(vim.wo.foldmarker)
--- print(vim.wo.quux) -- error: invalid key --- print(vim.wo.quux) -- error: invalid key
--- vim.wo[winid][0].spell = false -- like ':setlocal nospell' --- vim.wo[winid][0].spell = false -- like ':setlocal nospell'
--- --- ```
---</pre>
vim.wo = new_win_opt_accessor() vim.wo = new_win_opt_accessor()
---@brief [[ ---@brief [[
@@ -795,11 +806,13 @@ end
--- @diagnostic disable-next-line:unused-local used for gen_vimdoc --- @diagnostic disable-next-line:unused-local used for gen_vimdoc
local Option = {} -- luacheck: no unused local Option = {} -- luacheck: no unused
---Returns a Lua-representation of the option. Boolean, number and string --- Returns a Lua-representation of the option. Boolean, number and string
---values will be returned in exactly the same fashion. --- values will be returned in exactly the same fashion.
--- ---
---For values that are comma-separated lists, an array will be returned with --- For values that are comma-separated lists, an array will be returned with
---the values as entries in the array: <pre>lua --- the values as entries in the array:
---
--- ```lua
--- vim.cmd [[set wildignore=*.pyc,*.o]] --- vim.cmd [[set wildignore=*.pyc,*.o]]
--- ---
--- vim.print(vim.opt.wildignore:get()) --- vim.print(vim.opt.wildignore:get())
@@ -810,10 +823,12 @@ local Option = {} -- luacheck: no unused
--- end --- end
--- -- Will ignore: *.pyc --- -- Will ignore: *.pyc
--- -- Will ignore: *.o --- -- Will ignore: *.o
---</pre> --- ```
--- ---
---For values that are comma-separated maps, a table will be returned with --- For values that are comma-separated maps, a table will be returned with
---the names as keys and the values as entries: <pre>lua --- the names as keys and the values as entries:
---
--- ```lua
--- vim.cmd [[set listchars=space:_,tab:>~]] --- vim.cmd [[set listchars=space:_,tab:>~]]
--- ---
--- vim.print(vim.opt.listchars:get()) --- vim.print(vim.opt.listchars:get())
@@ -822,10 +837,12 @@ local Option = {} -- luacheck: no unused
--- for char, representation in pairs(vim.opt.listchars:get()) do --- for char, representation in pairs(vim.opt.listchars:get()) do
--- print(char, "=>", representation) --- print(char, "=>", representation)
--- end --- end
---</pre> --- ```
--- ---
---For values that are lists of flags, a set will be returned with the flags --- For values that are lists of flags, a set will be returned with the flags
---as keys and `true` as entries. <pre>lua --- as keys and `true` as entries.
---
--- ```lua
--- vim.cmd [[set formatoptions=njtcroql]] --- vim.cmd [[set formatoptions=njtcroql]]
--- ---
--- vim.print(vim.opt.formatoptions:get()) --- vim.print(vim.opt.formatoptions:get())
@@ -835,37 +852,47 @@ local Option = {} -- luacheck: no unused
--- if format_opts.j then --- if format_opts.j then
--- print("J is enabled!") --- print("J is enabled!")
--- end --- end
---</pre> --- ```
---
---@return string|integer|boolean|nil value of option ---@return string|integer|boolean|nil value of option
---@diagnostic disable-next-line:unused-local used for gen_vimdoc ---@diagnostic disable-next-line:unused-local used for gen_vimdoc
function Option:get() end 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: <pre>lua --- These are equivalent:
---
--- ```lua
--- vim.opt.formatoptions:append('j') --- vim.opt.formatoptions:append('j')
--- vim.opt.formatoptions = vim.opt.formatoptions + 'j' --- vim.opt.formatoptions = vim.opt.formatoptions + 'j'
---</pre> --- ```
---
---@param value string Value to append ---@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 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: <pre>lua --- These are equivalent:
---
--- ```lua
--- vim.opt.wildignore:prepend('*.o') --- vim.opt.wildignore:prepend('*.o')
--- vim.opt.wildignore = vim.opt.wildignore ^ '*.o' --- vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
---</pre> --- ```
---
---@param value string Value to prepend ---@param value string Value to prepend
---@diagnostic disable-next-line:unused-local used for gen_vimdoc ---@diagnostic disable-next-line:unused-local used for gen_vimdoc
function Option:prepend(value) end -- luacheck: no unused 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: <pre>lua --- These are equivalent:
---
--- ```lua
--- vim.opt.wildignore:remove('*.pyc') --- vim.opt.wildignore:remove('*.pyc')
--- vim.opt.wildignore = vim.opt.wildignore - '*.pyc' --- vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
---</pre> --- ```
---
---@param value string Value to remove ---@param value string Value to remove
---@diagnostic disable-next-line:unused-local used for gen_vimdoc ---@diagnostic disable-next-line:unused-local used for gen_vimdoc
function Option:remove(value) end -- luacheck: no unused function Option:remove(value) end -- luacheck: no unused

View File

@@ -553,14 +553,16 @@ end
--- followed by namespace configuration, and finally global configuration. --- followed by namespace configuration, and finally global configuration.
--- ---
--- For example, if a user enables virtual text globally with --- For example, if a user enables virtual text globally with
--- <pre>lua ---
--- ```lua
--- vim.diagnostic.config({ virtual_text = true }) --- vim.diagnostic.config({ virtual_text = true })
--- </pre> --- ```
--- ---
--- and a diagnostic producer sets diagnostics with --- and a diagnostic producer sets diagnostics with
--- <pre>lua ---
--- ```lua
--- vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false }) --- vim.diagnostic.set(ns, 0, diagnostics, { virtual_text = false })
--- </pre> --- ```
--- ---
--- then virtual text will not be enabled for those diagnostics. --- then virtual text will not be enabled for those diagnostics.
--- ---
@@ -1601,18 +1603,20 @@ end
--- Parse a diagnostic from a string. --- Parse a diagnostic from a string.
--- ---
--- For example, consider a line of output from a linter: --- For example, consider a line of output from a linter:
--- <pre> ---
--- ```
--- WARNING filename:27:3: Variable 'foo' does not exist --- WARNING filename:27:3: Variable 'foo' does not exist
--- </pre> --- ```
--- ---
--- This can be parsed into a diagnostic |diagnostic-structure| --- This can be parsed into a diagnostic |diagnostic-structure|
--- with: --- with:
--- <pre>lua ---
--- ```lua
--- local s = "WARNING filename:27:3: Variable 'foo' does not exist" --- local s = "WARNING filename:27:3: Variable 'foo' does not exist"
--- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$" --- local pattern = "^(%w+) %w+:(%d+):(%d+): (.+)$"
--- local groups = { "severity", "lnum", "col", "message" } --- local groups = { "severity", "lnum", "col", "message" }
--- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN }) --- vim.diagnostic.match(s, pattern, groups, { WARNING = vim.diagnostic.WARN })
--- </pre> --- ```
--- ---
---@param str string String to parse diagnostics from. ---@param str string String to parse diagnostics from.
---@param pat string Lua pattern with capture groups. ---@param pat string Lua pattern with capture groups.

View File

@@ -2081,7 +2081,8 @@ end
--- See $VIMRUNTIME/lua/vim/filetype.lua for more examples. --- See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.filetype.add({ --- vim.filetype.add({
--- extension = { --- extension = {
--- foo = 'fooscript', --- foo = 'fooscript',
@@ -2114,10 +2115,11 @@ end
--- end, --- end,
--- }, --- },
--- }) --- })
--- </pre> --- ```
--- ---
--- To add a fallback match on contents, use --- To add a fallback match on contents, use
--- <pre>lua ---
--- ```lua
--- vim.filetype.add { --- vim.filetype.add {
--- pattern = { --- pattern = {
--- ['.*'] = { --- ['.*'] = {
@@ -2133,7 +2135,7 @@ end
--- }, --- },
--- }, --- },
--- } --- }
--- </pre> --- ```
--- ---
---@param filetypes vim.filetype.add.filetypes A table containing new filetype maps (see example). ---@param filetypes vim.filetype.add.filetypes A table containing new filetype maps (see example).
function M.add(filetypes) function M.add(filetypes)
@@ -2256,7 +2258,7 @@ end
--- Each of the three options is specified using a key to the single argument of this function. --- Each of the three options is specified using a key to the single argument of this function.
--- Example: --- Example:
--- ---
--- <pre>lua --- ```lua
--- -- Using a buffer number --- -- Using a buffer number
--- vim.filetype.match({ buf = 42 }) --- vim.filetype.match({ buf = 42 })
--- ---
@@ -2268,7 +2270,7 @@ end
--- ---
--- -- Using file contents --- -- Using file contents
--- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) --- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
--- </pre> --- ```
--- ---
---@param args vim.filetype.match.args Table specifying which matching strategy to use. ---@param args vim.filetype.match.args Table specifying which matching strategy to use.
--- Accepted keys are: --- Accepted keys are:
@@ -2404,9 +2406,10 @@ end
--- is set, meaning it should respect all FileType autocmds and ftplugin files. --- is set, meaning it should respect all FileType autocmds and ftplugin files.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.filetype.get_option('vim', 'commentstring') --- vim.filetype.get_option('vim', 'commentstring')
--- </pre> --- ```
--- ---
--- Note: this uses |nvim_get_option_value()| but caches the result. --- Note: this uses |nvim_get_option_value()| but caches the result.
--- This means |ftplugin| and |FileType| autocommands are only --- This means |ftplugin| and |FileType| autocommands are only

View File

@@ -5,7 +5,8 @@ local iswin = vim.uv.os_uname().sysname == 'Windows_NT'
--- Iterate over all the parents of the given path. --- Iterate over all the parents of the given path.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- local root_dir --- local root_dir
--- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do --- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
--- if vim.fn.isdirectory(dir .. "/.git") == 1 then --- 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 --- if root_dir then
--- print("Found git repository at", root_dir) --- print("Found git repository at", root_dir)
--- end --- end
--- </pre> --- ```
--- ---
---@param start (string) Initial path. ---@param start (string) Initial path.
---@return fun(_, dir: string): string? # Iterator ---@return fun(_, dir: string): string? # Iterator
@@ -165,7 +166,8 @@ end
--- to narrow the search to find only that type. --- to narrow the search to find only that type.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- -- location of Cargo.toml from the current buffer's path --- -- location of Cargo.toml from the current buffer's path
--- local cargo = vim.fs.find('Cargo.toml', { --- local cargo = vim.fs.find('Cargo.toml', {
--- upward = true, --- upward = true,
@@ -183,7 +185,7 @@ end
--- local cpp_hpp = vim.fs.find(function(name, path) --- local cpp_hpp = vim.fs.find(function(name, path)
--- return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$') --- return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$')
--- end, {limit = math.huge, type = 'file'}) --- end, {limit = math.huge, type = 'file'})
--- </pre> --- ```
--- ---
---@param names (string|string[]|fun(name: string, path: string): boolean) Names of the items to find. ---@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. --- 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. --- variables are also expanded.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- vim.fs.normalize('C:\\\\Users\\\\jdoe') --- vim.fs.normalize('C:\\\\Users\\\\jdoe')
--- --> 'C:/Users/jdoe' --- -- 'C:/Users/jdoe'
--- ---
--- vim.fs.normalize('~/src/neovim') --- vim.fs.normalize('~/src/neovim')
--- --> '/home/jdoe/src/neovim' --- -- '/home/jdoe/src/neovim'
--- ---
--- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim') --- vim.fs.normalize('$XDG_CONFIG_HOME/nvim/init.vim')
--- --> '/Users/jdoe/.config/nvim/init.vim' --- -- '/Users/jdoe/.config/nvim/init.vim'
--- </pre> --- ```
--- ---
---@param path (string) Path to normalize ---@param path (string) Path to normalize
---@param opts table|nil Options: ---@param opts table|nil Options:

View File

@@ -1,23 +1,24 @@
---@defgroup vim.highlight ---@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`: --- To enable it, add the following to your `init.vim`:
---<pre>vim ---
--- ```vim
--- au TextYankPost * silent! lua vim.highlight.on_yank() --- au TextYankPost * silent! lua vim.highlight.on_yank()
---</pre> --- ```
--- ---
---You can customize the highlight group and the duration of --- You can customize the highlight group and the duration of the highlight via:
---the highlight via: ---
---<pre>vim --- ```vim
--- au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150} --- au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=150}
---</pre> --- ```
--- ---
---If you want to exclude visual selections from highlighting on yank, use: --- If you want to exclude visual selections from highlighting on yank, use:
---<pre>vim ---
--- ```vim
--- au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} --- au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
---</pre> --- ```
local api = vim.api local api = vim.api

View File

@@ -2,7 +2,8 @@ local keymap = {}
--- Adds a new |mapping|. --- Adds a new |mapping|.
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- -- Map to a Lua function: --- -- Map to a Lua function:
--- vim.keymap.set('n', 'lhs', function() print("real lua function") end) --- vim.keymap.set('n', 'lhs', function() print("real lua function") end)
--- -- Map to multiple modes: --- -- Map to multiple modes:
@@ -15,7 +16,7 @@ local keymap = {}
--- end, { expr = true }) --- end, { expr = true })
--- -- <Plug> mapping: --- -- <Plug> mapping:
--- vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)') --- vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
--- </pre> --- ```
--- ---
---@param mode string|table Mode short-name, see |nvim_set_keymap()|. ---@param mode string|table Mode short-name, see |nvim_set_keymap()|.
--- Can also be list of modes to create mapping on multiple modes. --- Can also be list of modes to create mapping on multiple modes.
@@ -80,11 +81,13 @@ end
--- Remove an existing mapping. --- Remove an existing mapping.
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- vim.keymap.del('n', 'lhs') --- vim.keymap.del('n', 'lhs')
--- ---
--- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 }) --- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
--- </pre> --- ```
---
---@param opts table|nil A table of optional arguments: ---@param opts table|nil A table of optional arguments:
--- - "buffer": (number|boolean) Remove a mapping from the given buffer. --- - "buffer": (number|boolean) Remove a mapping from the given buffer.
--- When `0` or `true`, use the current buffer. --- When `0` or `true`, use the current buffer.

View File

@@ -809,13 +809,14 @@ end
--- Attaches the current buffer to the client. --- Attaches the current buffer to the client.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.lsp.start({ --- vim.lsp.start({
--- name = 'my-server-name', --- name = 'my-server-name',
--- cmd = {'name-of-language-server-executable'}, --- cmd = {'name-of-language-server-executable'},
--- root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]), --- 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: --- See |vim.lsp.start_client()| for all available options. The most important are:
--- ---
@@ -1988,9 +1989,10 @@ end
--- ---
--- You can also use the `stop()` function on a |vim.lsp.client| object. --- You can also use the `stop()` function on a |vim.lsp.client| object.
--- To stop all clients: --- To stop all clients:
--- <pre>lua ---
--- ```lua
--- vim.lsp.stop_client(vim.lsp.get_clients()) --- vim.lsp.stop_client(vim.lsp.get_clients())
--- </pre> --- ```
--- ---
--- By default asks the server to shutdown, unless stop was requested --- By default asks the server to shutdown, unless stop was requested
--- already for this client, then force-shutdown is attempted. --- already for this client, then force-shutdown is attempted.
@@ -2502,12 +2504,7 @@ end
---@param bufnr integer Buffer number ---@param bufnr integer Buffer number
---@param fn function Function to run on each client attached to buffer ---@param fn function Function to run on each client attached to buffer
--- {bufnr}. The function takes the client, client ID, and --- {bufnr}. The function takes the client, client ID, and
--- buffer number as arguments. Example: --- buffer number as arguments.
--- <pre>lua
--- vim.lsp.for_each_buffer_client(0, function(client, client_id, bufnr)
--- vim.print(client)
--- end)
--- </pre>
---@deprecated use lsp.get_clients({ bufnr = bufnr }) with regular loop ---@deprecated use lsp.get_clients({ bufnr = bufnr }) with regular loop
function lsp.for_each_buffer_client(bufnr, fn) function lsp.for_each_buffer_client(bufnr, fn)
return for_each_buffer_client(bufnr, fn) return for_each_buffer_client(bufnr, fn)

View File

@@ -168,9 +168,7 @@ end
--- ---
--- - filter (function|nil): --- - filter (function|nil):
--- Predicate used to filter clients. Receives a client as argument and must return a --- Predicate used to filter clients. Receives a client as argument and must return a
--- boolean. Clients matching the predicate are included. Example: --- boolean. Clients matching the predicate are included. Example: <pre>lua
---
--- <pre>lua
--- -- Never request typescript-language-server for formatting --- -- Never request typescript-language-server for formatting
--- vim.lsp.buf.format { --- vim.lsp.buf.format {
--- filter = function(client) return client.name ~= "tsserver" end --- filter = function(client) return client.name ~= "tsserver" end
@@ -555,11 +553,12 @@ end
--- Send request to the server to resolve document highlights for the current --- 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 --- text document position. This request can be triggered by a key mapping or
--- by events such as `CursorHold`, e.g.: --- by events such as `CursorHold`, e.g.:
--- <pre>vim ---
--- ```vim
--- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() --- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
--- autocmd CursorHoldI <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() --- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
--- </pre> --- ```
--- ---
--- Note: Usage of |vim.lsp.buf.document_highlight()| requires the following highlight groups --- 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. --- to be defined or you won't be able to see the actual highlights.

View File

@@ -255,10 +255,10 @@ end
--- It is recommended to trigger this using an autocmd or via keymap. --- It is recommended to trigger this using an autocmd or via keymap.
--- ---
--- Example: --- 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() function M.refresh()
local params = { local params = {
textDocument = util.make_text_document_params(), textDocument = util.make_text_document_params(),

View File

@@ -203,7 +203,8 @@ end
--- ---
--- See |vim.diagnostic.config()| for configuration options. Handler-specific --- See |vim.diagnostic.config()| for configuration options. Handler-specific
--- configuration can be set using |vim.lsp.with()|: --- configuration can be set using |vim.lsp.with()|:
--- <pre>lua ---
--- ```lua
--- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with( --- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
--- vim.lsp.diagnostic.on_publish_diagnostics, { --- vim.lsp.diagnostic.on_publish_diagnostics, {
--- -- Enable underline, use default values --- -- Enable underline, use default values
@@ -221,7 +222,7 @@ end
--- update_in_insert = false, --- update_in_insert = false,
--- } --- }
--- ) --- )
--- </pre> --- ```
--- ---
---@param config table Configuration table (see |vim.diagnostic.config()|). ---@param config table Configuration table (see |vim.diagnostic.config()|).
function M.on_publish_diagnostics(_, result, ctx, config) function M.on_publish_diagnostics(_, result, ctx, config)
@@ -263,7 +264,8 @@ end
--- ---
--- See |vim.diagnostic.config()| for configuration options. Handler-specific --- See |vim.diagnostic.config()| for configuration options. Handler-specific
--- configuration can be set using |vim.lsp.with()|: --- configuration can be set using |vim.lsp.with()|:
--- <pre>lua ---
--- ```lua
--- vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with( --- vim.lsp.handlers["textDocument/diagnostic"] = vim.lsp.with(
--- vim.lsp.diagnostic.on_diagnostic, { --- vim.lsp.diagnostic.on_diagnostic, {
--- -- Enable underline, use default values --- -- Enable underline, use default values
@@ -281,7 +283,7 @@ end
--- update_in_insert = false, --- update_in_insert = false,
--- } --- }
--- ) --- )
--- </pre> --- ```
--- ---
---@param config table Configuration table (see |vim.diagnostic.config()|). ---@param config table Configuration table (see |vim.diagnostic.config()|).
function M.on_diagnostic(_, result, ctx, config) function M.on_diagnostic(_, result, ctx, config)

View File

@@ -342,7 +342,8 @@ M[ms.textDocument_completion] = function(_, result, _, _)
end end
--- |lsp-handler| for the method "textDocument/hover" --- |lsp-handler| for the method "textDocument/hover"
--- <pre>lua ---
--- ```lua
--- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with( --- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(
--- vim.lsp.handlers.hover, { --- vim.lsp.handlers.hover, {
--- -- Use a sharp border with `FloatBorder` highlights --- -- Use a sharp border with `FloatBorder` highlights
@@ -351,7 +352,8 @@ end
--- title = "hover" --- title = "hover"
--- } --- }
--- ) --- )
--- </pre> --- ```
---
---@param config table Configuration table. ---@param config table Configuration table.
--- - border: (default=nil) --- - border: (default=nil)
--- - Add borders to the floating window --- - Add borders to the floating window
@@ -430,15 +432,20 @@ M[ms.textDocument_typeDefinition] = location_handler
M[ms.textDocument_implementation] = location_handler M[ms.textDocument_implementation] = location_handler
--- |lsp-handler| for the method "textDocument/signatureHelp". --- |lsp-handler| for the method "textDocument/signatureHelp".
---
--- The active parameter is highlighted with |hl-LspSignatureActiveParameter|. --- The active parameter is highlighted with |hl-LspSignatureActiveParameter|.
--- <pre>lua ---
--- ```lua
--- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with( --- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(
--- vim.lsp.handlers.signature_help, { --- vim.lsp.handlers.signature_help, {
--- -- Use a sharp border with `FloatBorder` highlights --- -- Use a sharp border with `FloatBorder` highlights
--- border = "single" --- border = "single"
--- } --- }
--- ) --- )
--- </pre> --- ```
---
---@param result table Response from the language server
---@param ctx table Client context
---@param config table Configuration table. ---@param config table Configuration table.
--- - border: (default=nil) --- - border: (default=nil)
--- - Add borders to the floating window --- - Add borders to the floating window

View File

@@ -555,9 +555,10 @@ local M = {}
--- delete the semanticTokensProvider table from the {server_capabilities} of --- delete the semanticTokensProvider table from the {server_capabilities} of
--- your client in your |LspAttach| callback or your configuration's --- your client in your |LspAttach| callback or your configuration's
--- `on_attach` callback: --- `on_attach` callback:
--- <pre>lua ---
--- ```lua
--- client.server_capabilities.semanticTokensProvider = nil --- client.server_capabilities.semanticTokensProvider = nil
--- </pre> --- ```
--- ---
---@param bufnr integer ---@param bufnr integer
---@param client_id integer ---@param client_id integer

View File

@@ -65,19 +65,21 @@ end
--- (as opposed to |vim.split()| which is "eager"). --- (as opposed to |vim.split()| which is "eager").
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- for s in vim.gsplit(':aa::b:', ':', {plain=true}) do --- for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
--- print(s) --- print(s)
--- end --- end
--- </pre> --- ```
--- ---
--- If you want to also inspect the separator itself (instead of discarding it), use --- If you want to also inspect the separator itself (instead of discarding it), use
--- |string.gmatch()|. Example: --- |string.gmatch()|. Example:
--- <pre>lua ---
--- ```lua
--- for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do --- for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
--- print(('word: %s num: %s'):format(word, num)) --- print(('word: %s num: %s'):format(word, num))
--- end --- end
--- </pre> --- ```
--- ---
--- @see |string.gmatch()| --- @see |string.gmatch()|
--- @see |vim.split()| --- @see |vim.split()|
@@ -165,12 +167,13 @@ end
--- |vim.gsplit()|). --- |vim.gsplit()|).
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- split(":aa::b:", ":") --> {'','aa','','b',''} --- split(":aa::b:", ":") --> {'','aa','','b',''}
--- split("axaby", "ab?") --> {'','x','y'} --- split("axaby", "ab?") --> {'','x','y'}
--- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'} --- split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
--- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'} --- split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
--- </pre> --- ```
--- ---
---@see |vim.gsplit()| ---@see |vim.gsplit()|
---@see |string.gmatch()| ---@see |string.gmatch()|
@@ -259,12 +262,13 @@ end
--- a predicate that is checked for each value. --- a predicate that is checked for each value.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v) --- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
--- return vim.deep_equal(v, { 'b', 'c' }) --- return vim.deep_equal(v, { 'b', 'c' })
--- end, { predicate = true }) --- end, { predicate = true })
--- -- true --- -- true
--- </pre> --- ```
--- ---
---@see |vim.list_contains()| for checking values in list-like tables ---@see |vim.list_contains()| for checking values in list-like tables
--- ---
@@ -455,10 +459,11 @@ end
--- Return `nil` if the key does not exist. --- Return `nil` if the key does not exist.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true --- vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
--- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil --- vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
--- </pre> --- ```
--- ---
---@param o table Table to index ---@param o table Table to index
---@param ... any Optional keys (0 or more, variadic) via which to index the table ---@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`. --- Counts the number of non-nil values in table `t`.
--- ---
--- <pre>lua --- ```lua
--- vim.tbl_count({ a=1, b=2 }) --> 2 --- vim.tbl_count({ a=1, b=2 }) --> 2
--- vim.tbl_count({ 1, 2 }) --> 2 --- vim.tbl_count({ 1, 2 }) --> 2
--- </pre> --- ```
--- ---
---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua ---@see https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
---@param t table Table ---@param t table Table
@@ -703,7 +708,8 @@ end
--- Validates a parameter specification (types and values). --- Validates a parameter specification (types and values).
--- ---
--- Usage example: --- Usage example:
--- <pre>lua ---
--- ```lua
--- function user.new(name, age, hobbies) --- function user.new(name, age, hobbies)
--- vim.validate{ --- vim.validate{
--- name={name, 'string'}, --- name={name, 'string'},
@@ -712,10 +718,11 @@ end
--- } --- }
--- ... --- ...
--- end --- end
--- </pre> --- ```
--- ---
--- Examples with explicit argument values (can be run directly): --- Examples with explicit argument values (can be run directly):
--- <pre>lua ---
--- ```lua
--- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}} --- vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
--- --> NOP (success) --- --> NOP (success)
--- ---
@@ -724,17 +731,18 @@ end
--- ---
--- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}} --- vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
--- --> error('arg1: expected even number, got 3') --- --> error('arg1: expected even number, got 3')
--- </pre> --- ```
--- ---
--- If multiple types are valid they can be given as a list. --- If multiple types are valid they can be given as a list.
--- <pre>lua ---
--- ```lua
--- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}} --- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
--- --> NOP (success) --- -- NOP (success)
--- ---
--- vim.validate{arg1={1, {'string', 'table'}}} --- vim.validate{arg1={1, {'string', 'table'}}}
--- --> error('arg1: expected string|table, got number') --- -- error('arg1: expected string|table, got number')
--- ---
--- </pre> --- ```
--- ---
---@param opt table Names of parameters to validate. Each key is a parameter ---@param opt table Names of parameters to validate. Each key is a parameter
--- name; each value is a tuple in one of these forms: --- 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 --- If {create} is `nil`, this will create a defaulttable whose constructor function is
--- this function, effectively allowing to create nested tables on the fly: --- this function, effectively allowing to create nested tables on the fly:
--- ---
--- <pre>lua --- ```lua
--- local a = vim.defaulttable() --- local a = vim.defaulttable()
--- a.b.c = 1 --- a.b.c = 1
--- </pre> --- ```
--- ---
---@param create function?(key:any):any The function called to create a missing value. ---@param create function?(key:any):any The function called to create a missing value.
---@return table Empty table with metamethod ---@return table Empty table with metamethod
@@ -938,7 +946,7 @@ do
--- Create a ring buffer limited to a maximal number of items. --- Create a ring buffer limited to a maximal number of items.
--- Once the buffer is full, adding a new entry overrides the oldest entry. --- Once the buffer is full, adding a new entry overrides the oldest entry.
--- ---
--- <pre> --- ```lua
--- local ringbuf = vim.ringbuf(4) --- local ringbuf = vim.ringbuf(4)
--- ringbuf:push("a") --- ringbuf:push("a")
--- ringbuf:push("b") --- ringbuf:push("b")
@@ -952,7 +960,7 @@ do
--- for val in ringbuf do --- for val in ringbuf do
--- print(val) --- print(val)
--- end --- end
--- </pre> --- ```
--- ---
--- Returns a Ringbuf instance with the following methods: --- Returns a Ringbuf instance with the following methods:
--- ---

View File

@@ -441,14 +441,15 @@ end
--- In this case, add ``vim.bo.syntax = 'on'`` after the call to `start`. --- In this case, add ``vim.bo.syntax = 'on'`` after the call to `start`.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', --- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
--- callback = function(args) --- callback = function(args)
--- vim.treesitter.start(args.buf, 'latex') --- vim.treesitter.start(args.buf, 'latex')
--- vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed --- vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed
--- end --- end
--- }) --- })
--- </pre> --- ```
--- ---
---@param bufnr (integer|nil) Buffer to be highlighted (default: current buffer) ---@param bufnr (integer|nil) Buffer to be highlighted (default: current buffer)
---@param lang (string|nil) Language of the parser (default: buffer filetype) ---@param lang (string|nil) Language of the parser (default: buffer filetype)
@@ -502,9 +503,11 @@ function M.preview_query()
end end
--- Returns the fold level for {lnum} in the current buffer. Can be set directly to 'foldexpr': --- 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()' --- vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
--- </pre> --- ```
---
---@param lnum integer|nil Line number to calculate fold level for ---@param lnum integer|nil Line number to calculate fold level for
---@return string ---@return string
function M.foldexpr(lnum) function M.foldexpr(lnum)

View File

@@ -7,9 +7,9 @@
--- ---
--- To create a LanguageTree (parser object) for a given buffer and language, use: --- To create a LanguageTree (parser object) for a given buffer and language, use:
--- ---
--- <pre>lua --- ```lua
--- local parser = vim.treesitter.get_parser(bufnr, lang) --- local parser = vim.treesitter.get_parser(bufnr, lang)
--- </pre> --- ```
--- ---
--- (where `bufnr=0` means current buffer). `lang` defaults to 'filetype'. --- (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; --- 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: --- Whenever you need to access the current syntax tree, parse the buffer:
--- ---
--- <pre>lua --- ```lua
--- local tree = parser:parse({ start_row, end_row }) --- local tree = parser:parse({ start_row, end_row })
--- </pre> --- ```
--- ---
--- This returns a table of immutable |treesitter-tree| objects representing the current state of --- 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 --- the buffer. When the plugin wants to access the state after a (possible) edit it must call

View File

@@ -692,7 +692,8 @@ end
--- The iterator returns three values: a numeric id identifying the capture, --- The iterator returns three values: a numeric id identifying the capture,
--- the captured node, and metadata from any directives processing the match. --- the captured node, and metadata from any directives processing the match.
--- The following example shows how to get captures by name: --- 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 --- 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 --- local name = query.captures[id] -- name of the capture in the query
--- -- typically useful info about the node: --- -- typically useful info about the node:
@@ -700,7 +701,7 @@ end
--- local row1, col1, row2, col2 = node:range() -- range of the capture --- local row1, col1, row2, col2 = node:range() -- range of the capture
--- -- ... use the info here ... --- -- ... use the info here ...
--- end --- end
--- </pre> --- ```
--- ---
---@param node TSNode under which the search will occur ---@param node TSNode under which the search will occur
---@param source (integer|string) Source buffer or string to extract text from ---@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 --- If the query has more than one pattern, the capture table might be sparse
--- and e.g. `pairs()` method should be used over `ipairs`. --- and e.g. `pairs()` method should be used over `ipairs`.
--- Here is an example iterating over all captures in every match: --- 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 pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do
--- for id, node in pairs(match) do --- for id, node in pairs(match) do
--- local name = query.captures[id] --- local name = query.captures[id]
@@ -754,7 +756,7 @@ end
--- -- ... use the info here ... --- -- ... use the info here ...
--- end --- end
--- end --- end
--- </pre> --- ```
--- ---
---@param node TSNode under which the search will occur ---@param node TSNode under which the search will occur
---@param source (integer|string) Source buffer or string to search ---@param source (integer|string) Source buffer or string to search
@@ -824,9 +826,11 @@ end
--- Omnifunc for completing node names and predicates in treesitter queries. --- Omnifunc for completing node names and predicates in treesitter queries.
--- ---
--- Use via --- Use via
--- <pre>lua ---
--- ```lua
--- vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc' --- vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc'
--- </pre> --- ```
---
function M.omnifunc(findstart, base) function M.omnifunc(findstart, base)
return require('vim.treesitter._query_linter').omnifunc(findstart, base) return require('vim.treesitter._query_linter').omnifunc(findstart, base)
end end

View File

@@ -3,6 +3,23 @@ local M = {}
--- Prompts the user to pick from a list of items, allowing arbitrary (potentially asynchronous) --- Prompts the user to pick from a list of items, allowing arbitrary (potentially asynchronous)
--- work until `on_choice`. --- 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 items table Arbitrary items
---@param opts table Additional options ---@param opts table Additional options
--- - prompt (string|nil) --- - prompt (string|nil)
@@ -19,23 +36,6 @@ local M = {}
--- Called once the user made a choice. --- Called once the user made a choice.
--- `idx` is the 1-based index of `item` within `items`. --- `idx` is the 1-based index of `item` within `items`.
--- `nil` if the user aborted the dialog. --- `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) function M.select(items, opts, on_choice)
vim.validate({ vim.validate({
items = { items, 'table', false }, items = { items, 'table', false },
@@ -58,6 +58,14 @@ end
--- Prompts the user for input, allowing arbitrary (potentially asynchronous) work until --- Prompts the user for input, allowing arbitrary (potentially asynchronous) work until
--- `on_confirm`. --- `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()| ---@param opts table Additional options. See |input()|
--- - prompt (string|nil) --- - prompt (string|nil)
--- Text of the prompt --- Text of the prompt
@@ -77,13 +85,6 @@ end
--- `input` is what the user typed (it might be --- `input` is what the user typed (it might be
--- an empty string if nothing was entered), or --- an empty string if nothing was entered), or
--- `nil` if the user aborted the dialog. --- `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) function M.input(opts, on_confirm)
vim.validate({ vim.validate({
on_confirm = { on_confirm, 'function', false }, on_confirm = { on_confirm, 'function', false },
@@ -110,11 +111,12 @@ end
--- Expands "~/" and environment variables in filesystem paths. --- Expands "~/" and environment variables in filesystem paths.
--- ---
--- Examples: --- Examples:
--- <pre>lua ---
--- ```lua
--- vim.ui.open("https://neovim.io/") --- vim.ui.open("https://neovim.io/")
--- vim.ui.open("~/path/to/file") --- vim.ui.open("~/path/to/file")
--- vim.ui.open("$VIMRUNTIME") --- vim.ui.open("$VIMRUNTIME")
--- </pre> --- ```
--- ---
---@param path string Path or URL to open ---@param path string Path or URL to open
--- ---

View File

@@ -5,12 +5,13 @@
--- available tools and dependencies on the current system. --- available tools and dependencies on the current system.
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false}) --- local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
--- if vim.version.gt(v, {3, 2, 0}) then --- if vim.version.gt(v, {3, 2, 0}) then
--- -- ... --- -- ...
--- end --- end
--- </pre> --- ```
--- ---
--- \*vim.version()\* returns the version of the current Nvim process. --- \*vim.version()\* returns the version of the current Nvim process.
--- ---
@@ -21,7 +22,8 @@
--- ---
--- Supported range specs are shown in the following table. --- Supported range specs are shown in the following table.
--- Note: suffixed versions (1.2.3-rc1) are not matched. --- 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 is 1.2.3 --- =1.2.3 is 1.2.3
--- >1.2.3 greater than 1.2.3 --- >1.2.3 greater than 1.2.3
@@ -49,7 +51,7 @@
--- ---
--- Partial left: missing pieces treated as 0 (1.2 => 1.2.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 --- 1.2 - 2.3.0 is 1.2.0 - 2.3.0
--- </pre> --- ```
local M = {} local M = {}
@@ -237,29 +239,32 @@ function VersionRange:has(version)
end end
--- Parses a semver |version-range| "spec" and returns a range object: --- Parses a semver |version-range| "spec" and returns a range object:
--- <pre> ---
--- ```
--- { --- {
--- from: Version --- from: Version
--- to: Version --- to: Version
--- has(v: string|Version) --- has(v: string|Version)
--- } --- }
--- </pre> --- ```
--- ---
--- `:has()` checks if a version is in the range (inclusive `from`, exclusive `to`). --- `:has()` checks if a version is in the range (inclusive `from`, exclusive `to`).
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- local r = vim.version.range('1.0.0 - 2.0.0') --- local r = vim.version.range('1.0.0 - 2.0.0')
--- print(r:has('1.9.9')) -- true --- print(r:has('1.9.9')) -- true
--- print(r:has('2.0.0')) -- false --- print(r:has('2.0.0')) -- false
--- print(r:has(vim.version())) -- check against current Nvim version --- print(r:has(vim.version())) -- check against current Nvim version
--- </pre> --- ```
--- ---
--- Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly: --- Or use cmp(), eq(), lt(), and gt() to compare `.to` and `.from` directly:
--- <pre>lua ---
--- ```lua
--- local r = vim.version.range('1.0.0 - 2.0.0') --- 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)) --- print(vim.version.gt({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
--- </pre> --- ```
--- ---
--- @see # https://github.com/npm/node-semver#ranges --- @see # https://github.com/npm/node-semver#ranges
--- ---
@@ -345,7 +350,8 @@ end
--- specified literally as a `{major, minor, patch}` tuple, e.g. `{1, 0, 3}`). --- specified literally as a `{major, minor, patch}` tuple, e.g. `{1, 0, 3}`).
--- ---
--- Example: --- Example:
--- <pre>lua ---
--- ```lua
--- if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then --- if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
--- -- ... --- -- ...
--- end --- end
@@ -354,7 +360,7 @@ end
--- if vim.version.cmp(v1, v2) == 0 then --- if vim.version.cmp(v1, v2) == 0 then
--- -- ... --- -- ...
--- end --- end
--- </pre> --- ```
--- ---
--- @note Per semver, build metadata is ignored when comparing two otherwise-equivalent versions. --- @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 --- 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: --- `vim.version` functions. For example "1.0.1-rc1+build.2" returns:
--- <pre> ---
--- ```
--- { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" } --- { major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
--- </pre> --- ```
--- ---
--- @see # https://semver.org/spec/v2.0.0.html --- @see # https://semver.org/spec/v2.0.0.html
--- ---

View File

@@ -213,17 +213,20 @@ end
--- Convert vimdoc references to markdown literals --- Convert vimdoc references to markdown literals
--- Convert vimdoc codeblocks to markdown codeblocks --- Convert vimdoc codeblocks to markdown codeblocks
---
--- Ensure code blocks have one empty line before the start fence and after the closing fence.
---
--- @param x string --- @param x string
--- @return string --- @return string
local function norm_text(x) local function norm_text(x)
return ( return (
x:gsub('|([^ ]+)|', '`%1`') x:gsub('|([^ ]+)|', '`%1`')
:gsub('>lua', '\n```lua') :gsub('\n*>lua', '\n\n```lua')
:gsub('>vim', '\n```vim') :gsub('\n*>vim', '\n\n```vim')
:gsub('\n<$', '\n```') :gsub('\n+<$', '\n```')
:gsub('\n<\n', '\n```\n') :gsub('\n+<\n+', '\n```\n\n')
:gsub('%s+>\n', '\n```\n') :gsub('%s+>\n+', '\n```\n')
:gsub('\n<%s+\n?', '\n```\n') :gsub('\n+<%s+\n?', '\n```\n')
) )
end end

View File

@@ -585,13 +585,12 @@ def render_node(n, text, prefix='', indent='', width=text_width - indentation,
text += '>{}{}\n<'.format(ensure_nl, o) text += '>{}{}\n<'.format(ensure_nl, o)
elif n.nodeName == 'programlisting': # codeblock (```) elif n.nodeName == 'programlisting': # codeblock (```)
o = get_text(n) o = get_text(n)
filename = n.attributes['filename'].value
if filename:
text += '>{}'.format(filename.lstrip('.'))
else:
text += '>' text += '>'
if 'filename' in n.attributes:
filename = n.attributes['filename'].value
text += filename.lstrip('.')
text += '\n\n{}\n<'.format(textwrap.indent(o, ' ' * 4)) text += '\n{}\n<'.format(textwrap.indent(o, ' ' * 4))
elif is_inline(n): elif is_inline(n):
text = doc_wrap(get_text(n), prefix=prefix, indent=indent, width=width) text = doc_wrap(get_text(n), prefix=prefix, indent=indent, width=width)
elif n.nodeName == 'verbatim': elif n.nodeName == 'verbatim':
@@ -768,6 +767,27 @@ def para_as_map(parent, indent='', width=text_width - indentation, fmt_vimhelp=F
return chunks, xrefs return chunks, xrefs
def is_program_listing(para):
"""
Return True if `para` contains a "programlisting" (i.e. a Markdown code
block ```).
Sometimes a <para> element will have only a single "programlisting" child
node, but othertimes it will have extra whitespace around the
"programlisting" node.
@param para XML <para> node
@return True if <para> is a programlisting
"""
# Remove any child text nodes that are only whitespace
children = [
n for n in para.childNodes
if n.nodeType != n.TEXT_NODE or n.data.strip() != ''
]
return len(children) == 1 and children[0].nodeName == 'programlisting'
def fmt_node_as_vimhelp(parent: Element, width=text_width - indentation, indent='', def fmt_node_as_vimhelp(parent: Element, width=text_width - indentation, indent='',
fmt_vimhelp=False): fmt_vimhelp=False):
"""Renders (nested) Doxygen <para> nodes as Vim :help text. """Renders (nested) Doxygen <para> nodes as Vim :help text.
@@ -799,10 +819,7 @@ def fmt_node_as_vimhelp(parent: Element, width=text_width - indentation, indent=
# 'programlisting' blocks are Markdown code blocks. Do not include # 'programlisting' blocks are Markdown code blocks. Do not include
# these as a separate paragraph, but append to the last non-empty line # these as a separate paragraph, but append to the last non-empty line
# in the text # in the text
if ( if is_program_listing(child):
len(child.childNodes) == 1
and child.childNodes[0].nodeName == 'programlisting'
):
while rendered_blocks and rendered_blocks[-1] == '': while rendered_blocks and rendered_blocks[-1] == '':
rendered_blocks.pop() rendered_blocks.pop()
rendered_blocks[-1] += ' ' + para['text'] rendered_blocks[-1] += ' ' + para['text']

View File

@@ -49,7 +49,8 @@ static int64_t next_autocmd_id = 1;
/// Get all autocommands that match the corresponding {opts}. /// Get all autocommands that match the corresponding {opts}.
/// ///
/// These examples will get autocommands matching ALL the given criteria: /// These examples will get autocommands matching ALL the given criteria:
/// <pre>lua ///
/// ```lua
/// -- Matches all criteria /// -- Matches all criteria
/// autocommands = vim.api.nvim_get_autocmds({ /// autocommands = vim.api.nvim_get_autocmds({
/// group = "MyGroup", /// group = "MyGroup",
@@ -61,7 +62,7 @@ static int64_t next_autocmd_id = 1;
/// autocommands = vim.api.nvim_get_autocmds({ /// autocommands = vim.api.nvim_get_autocmds({
/// group = "MyGroup", /// group = "MyGroup",
/// }) /// })
/// </pre> /// ```
/// ///
/// NOTE: When multiple patterns or events are provided, it will find all the autocommands that /// NOTE: When multiple patterns or events are provided, it will find all the autocommands that
/// match any combination of them. /// match any combination of them.
@@ -344,28 +345,31 @@ cleanup:
/// function _name_ string) or `command` (Ex command string). /// function _name_ string) or `command` (Ex command string).
/// ///
/// Example using Lua callback: /// Example using Lua callback:
/// <pre>lua ///
/// ```lua
/// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { /// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
/// pattern = {"*.c", "*.h"}, /// pattern = {"*.c", "*.h"},
/// callback = function(ev) /// callback = function(ev)
/// print(string.format('event fired: \%s', vim.inspect(ev))) /// print(string.format('event fired: %s', vim.inspect(ev)))
/// end /// end
/// }) /// })
/// </pre> /// ```
/// ///
/// Example using an Ex command as the handler: /// Example using an Ex command as the handler:
/// <pre>lua ///
/// ```lua
/// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { /// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
/// pattern = {"*.c", "*.h"}, /// pattern = {"*.c", "*.h"},
/// command = "echo 'Entering a C or C++ file'", /// command = "echo 'Entering a C or C++ file'",
/// }) /// })
/// </pre> /// ```
/// ///
/// Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like "$HOME" /// Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like "$HOME"
/// and "~" must be expanded explicitly: /// and "~" must be expanded explicitly:
/// <pre>lua ///
/// ```lua
/// pattern = vim.fn.expand("~") .. "/some/path/*.py" /// pattern = vim.fn.expand("~") .. "/some/path/*.py"
/// </pre> /// ```
/// ///
/// @param event (string|array) Event(s) that will trigger the handler (`callback` or `command`). /// @param event (string|array) Event(s) that will trigger the handler (`callback` or `command`).
/// @param opts Options dict: /// @param opts Options dict:
@@ -619,11 +623,12 @@ cleanup:
/// Create or get an autocommand group |autocmd-groups|. /// Create or get an autocommand group |autocmd-groups|.
/// ///
/// To get an existing group id, do: /// To get an existing group id, do:
/// <pre>lua ///
/// ```lua
/// local id = vim.api.nvim_create_augroup("MyGroup", { /// local id = vim.api.nvim_create_augroup("MyGroup", {
/// clear = false /// clear = false
/// }) /// })
/// </pre> /// ```
/// ///
/// @param name String: The name of the group /// @param name String: The name of the group
/// @param opts Dictionary Parameters /// @param opts Dictionary Parameters

View File

@@ -85,11 +85,15 @@ Integer nvim_buf_line_count(Buffer buffer, Error *err)
/// ///
/// Example (Lua): capture buffer updates in a global `events` variable /// Example (Lua): capture buffer updates in a global `events` variable
/// (use "vim.print(events)" to see its contents): /// (use "vim.print(events)" to see its contents):
/// <pre>lua ///
/// ```lua
/// events = {} /// events = {}
/// vim.api.nvim_buf_attach(0, false, { /// vim.api.nvim_buf_attach(0, false, {
/// on_lines=function(...) table.insert(events, {...}) end}) /// on_lines = function(...)
/// </pre> /// table.insert(events, {...})
/// end,
/// })
/// ```
/// ///
/// @see |nvim_buf_detach()| /// @see |nvim_buf_detach()|
/// @see |api-buffer-updates-lua| /// @see |api-buffer-updates-lua|

View File

@@ -860,11 +860,12 @@ static void build_cmdline_str(char **cmdlinep, exarg_T *eap, CmdParseInfo *cmdin
/// For Lua usage see |lua-guide-commands-create|. /// For Lua usage see |lua-guide-commands-create|.
/// ///
/// Example: /// Example:
/// <pre>vim ///
/// ```vim
/// :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true}) /// :call nvim_create_user_command('SayHello', 'echo "Hello world!"', {'bang': v:true})
/// :SayHello /// :SayHello
/// Hello world! /// Hello world!
/// </pre> /// ```
/// ///
/// @param name Name of the new user command. Must begin with an uppercase letter. /// @param name Name of the new user command. Must begin with an uppercase letter.
/// @param command Replacement command to execute when this user command is executed. When called /// @param command Replacement command to execute when this user command is executed. When called

View File

@@ -300,10 +300,11 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id,
/// Region can be given as (row,col) tuples, or valid extmark ids (whose /// 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) /// positions define the bounds). 0 and -1 are understood as (0,0) and (-1,-1)
/// respectively, thus the following are equivalent: /// respectively, thus the following are equivalent:
/// <pre>lua ///
/// ```lua
/// vim.api.nvim_buf_get_extmarks(0, my_ns, 0, -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}, {}) /// vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {})
/// </pre> /// ```
/// ///
/// If `end` is less than `start`, traversal works backwards. (Useful /// If `end` is less than `start`, traversal works backwards. (Useful
/// with `limit`, to get the first marks prior to a given position.) /// with `limit`, to get the first marks prior to a given position.)
@@ -313,7 +314,8 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id,
/// of an extmark will be considered. /// of an extmark will be considered.
/// ///
/// Example: /// Example:
/// <pre>lua ///
/// ```lua
/// local api = vim.api /// local api = vim.api
/// local pos = api.nvim_win_get_cursor(0) /// local pos = api.nvim_win_get_cursor(0)
/// local ns = api.nvim_create_namespace('my-plugin') /// local ns = api.nvim_create_namespace('my-plugin')
@@ -326,7 +328,7 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id,
/// -- Get all marks in this buffer + namespace. /// -- Get all marks in this buffer + namespace.
/// local all = api.nvim_buf_get_extmarks(0, ns, 0, -1, {}) /// local all = api.nvim_buf_get_extmarks(0, ns, 0, -1, {})
/// vim.print(ms) /// vim.print(ms)
/// </pre> /// ```
/// ///
/// @param buffer Buffer handle, or 0 for current buffer /// @param buffer Buffer handle, or 0 for current buffer
/// @param ns_id Namespace id from |nvim_create_namespace()| or -1 for all namespaces /// @param ns_id Namespace id from |nvim_create_namespace()| or -1 for all namespaces

View File

@@ -212,10 +212,11 @@ void nvim_set_hl_ns_fast(Integer ns_id, Error *err)
/// nvim_feedkeys(). /// nvim_feedkeys().
/// ///
/// Example: /// Example:
/// <pre>vim ///
/// ```vim
/// :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true) /// :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true)
/// :call nvim_feedkeys(key, 'n', v:false) /// :call nvim_feedkeys(key, 'n', v:false)
/// </pre> /// ```
/// ///
/// @param keys to be typed /// @param keys to be typed
/// @param mode behavior flags, see |feedkeys()| /// @param mode behavior flags, see |feedkeys()|
@@ -1280,10 +1281,11 @@ void nvim_unsubscribe(uint64_t channel_id, String event)
/// "#rrggbb" hexadecimal string. /// "#rrggbb" hexadecimal string.
/// ///
/// Example: /// Example:
/// <pre>vim ///
/// ```vim
/// :echo nvim_get_color_by_name("Pink") /// :echo nvim_get_color_by_name("Pink")
/// :echo nvim_get_color_by_name("#cbcbcb") /// :echo nvim_get_color_by_name("#cbcbcb")
/// </pre> /// ```
/// ///
/// @param name Color name or "#rrggbb" string /// @param name Color name or "#rrggbb" string
/// @return 24-bit RGB value, or -1 for invalid argument. /// @return 24-bit RGB value, or -1 for invalid argument.
@@ -1420,14 +1422,16 @@ ArrayOf(Dictionary) nvim_get_keymap(String mode)
/// Empty {rhs} is |<Nop>|. |keycodes| are replaced as usual. /// Empty {rhs} is |<Nop>|. |keycodes| are replaced as usual.
/// ///
/// Example: /// Example:
/// <pre>vim ///
/// ```vim
/// call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true}) /// call nvim_set_keymap('n', ' <NL>', '', {'nowait': v:true})
/// </pre> /// ```
/// ///
/// is equivalent to: /// is equivalent to:
/// <pre>vim ///
/// ```vim
/// nmap <nowait> <Space><NL> <Nop> /// nmap <nowait> <Space><NL> <Nop>
/// </pre> /// ```
/// ///
/// @param channel_id /// @param channel_id
/// @param mode Mode short-name (map command prefix: "n", "i", "v", "x", …) /// @param mode Mode short-name (map command prefix: "n", "i", "v", "x", …)

View File

@@ -56,16 +56,19 @@
/// this should not be used to specify arbitrary WM screen positions. /// this should not be used to specify arbitrary WM screen positions.
/// ///
/// Example (Lua): window-relative float /// Example (Lua): window-relative float
/// <pre>lua ///
/// ```lua
/// vim.api.nvim_open_win(0, false, /// vim.api.nvim_open_win(0, false,
/// {relative='win', row=3, col=3, width=12, height=3}) /// {relative='win', row=3, col=3, width=12, height=3})
/// </pre> /// ```
/// ///
/// Example (Lua): buffer-relative float (travels as buffer is scrolled) /// Example (Lua): buffer-relative float (travels as buffer is scrolled)
/// <pre>lua ///
/// ```lua
/// vim.api.nvim_open_win(0, false, /// vim.api.nvim_open_win(0, false,
/// {relative='win', width=12, height=3, bufpos={100,10}}) /// {relative='win', width=12, height=3, bufpos={100,10}})
/// </pre> /// })
/// ```
/// ///
/// @param buffer Buffer to display, or 0 for current buffer /// @param buffer Buffer to display, or 0 for current buffer
/// @param enter Enter the window (make it the current window) /// @param enter Enter the window (make it the current window)

View File

@@ -566,7 +566,7 @@ return {
backups if you don't care about losing the file. backups if you don't care about losing the file.
Note that environment variables are not expanded. If you want to use Note that environment variables are not expanded. If you want to use
$HOME you must expand it explicitly, e.g.: > $HOME you must expand it explicitly, e.g.: >vim
:let &backupskip = escape(expand('$HOME'), '\') .. '/tmp/*' :let &backupskip = escape(expand('$HOME'), '\') .. '/tmp/*'
< Note that the default also makes sure that "crontab -e" works (when a < Note that the default also makes sure that "crontab -e" works (when a