docs(lua): more improvements (#24387)

* docs(lua): teach lua2dox how to table

* docs(lua): teach gen_vimdoc.py about local functions

No more need to mark local functions with @private

* docs(lua): mention @nodoc and @meta in dev-lua-doc

* fixup!

Co-authored-by: Justin M. Keyes <justinkz@gmail.com>

---------

Co-authored-by: Justin M. Keyes <justinkz@gmail.com>
This commit is contained in:
Lewis Russell 2023-07-18 15:42:30 +01:00 committed by GitHub
parent d0ae529861
commit be74807eef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 322 additions and 511 deletions

View File

@ -233,6 +233,8 @@ Docstring format:
- List-items start with `-` (useful to nest or "indent") - List-items start with `-` (useful to nest or "indent")
- Use `<pre>` for code samples. - Use `<pre>` 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.
- Files which has `@meta` are only used for typing and documentation.
Example: the help for |vim.paste()| is generated from a docstring decorating Example: the help for |vim.paste()| is generated from a docstring decorating
vim.paste in runtime/lua/vim/_editor.lua like this: > vim.paste in runtime/lua/vim/_editor.lua like this: >

View File

@ -758,6 +758,24 @@ client_is_stopped({client_id}) *vim.lsp.client_is_stopped()*
Return: ~ Return: ~
(boolean) stopped true if client is stopped, false otherwise. (boolean) stopped true if client is stopped, false otherwise.
commands *vim.lsp.commands*
Registry for client side commands. This is an extension point for plugins
to handle custom commands which are not part of the core language server
protocol specification.
The registry is a table where the key is a unique command name, and the
value is a function which is called if any LSP action (code action, code
lenses, ...) triggers the command.
If a LSP response contains a command for which no matching entry is
available in this registry, the command will be executed via the LSP
server using `workspace/executeCommand`.
The first argument to the function will be the `Command`: Command title:
String command: String arguments?: any[]
The second argument is the `ctx` of |lsp-handler|
formatexpr({opts}) *vim.lsp.formatexpr()* formatexpr({opts}) *vim.lsp.formatexpr()*
Provides an interface between the built-in client and a `formatexpr` Provides an interface between the built-in client and a `formatexpr`
function. function.

View File

@ -591,16 +591,6 @@ 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.priorities *vim.highlight.priorities*
Table with default priorities used for highlighting:
• `syntax`: `50`, used for standard syntax highlighting
• `treesitter`: `100`, used for tree-sitter-based highlighting
• `semantic_tokens`: `125`, used for LSP semantic token highlighting
• `diagnostics`: `150`, used for code analysis such as diagnostics
• `user`: `200`, used for user-triggered highlights such as LSP document
symbols or `on_yank` autocommands
vim.highlight.on_yank({opts}) *vim.highlight.on_yank()* vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
Highlight the yanked text Highlight the yanked text
@ -616,6 +606,15 @@ vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
• priority integer priority (default • priority integer priority (default
|vim.highlight.priorities|`.user`) |vim.highlight.priorities|`.user`)
vim.highlight.priorities *vim.highlight.priorities*
Table with default priorities used for highlighting:
• `syntax`: `50`, used for standard syntax highlighting
• `treesitter`: `100`, used for tree-sitter-based highlighting
• `semantic_tokens`: `125`, used for LSP semantic token highlighting
• `diagnostics`: `150`, used for code analysis such as diagnostics
• `user`: `200`, used for user-triggered highlights such as LSP document
symbols or `on_yank` autocommands
*vim.highlight.range()* *vim.highlight.range()*
vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts}) vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts})
Apply highlight group to range of text. Apply highlight group to range of text.
@ -1189,15 +1188,6 @@ vim.v *vim.v*
|v:| variables. |v:| variables.
Invalid or unset key returns `nil`. Invalid or unset key returns `nil`.
vim.env *vim.env*
Environment variables defined in the editor session.
See |expand-env| and |:let-environment| for the Vimscript behavior.
Invalid or unset key returns `nil`.
Example: >lua
vim.env.FOO = 'bar'
print(vim.env.TERM)
<
` ` *lua-options* ` ` *lua-options*
*lua-vim-options* *lua-vim-options*
*lua-vim-set* *lua-vim-set*
@ -1221,62 +1211,6 @@ window-scoped options. Note that this must NOT be confused with
|local-options| and |:setlocal|. There is also |vim.go| that only accesses the |local-options| and |:setlocal|. There is also |vim.go| that only accesses the
global value of a |global-local| option, see |:setglobal|. global value of a |global-local| option, see |:setglobal|.
vim.o *vim.o*
Get or set |options|. Like `:set`. Invalid key is an error.
Note: this works on both buffer-scoped and window-scoped options using the
current buffer and window.
Example: >lua
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
<
vim.go *vim.go*
Get or set global |options|. Like `:setglobal`. Invalid key is
an error.
Note: this is different from |vim.o| because this accesses the global
option value and thus is mostly useful for use with |global-local|
options.
Example: >lua
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
<
vim.bo[{bufnr}] *vim.bo*
Get or set buffer-scoped |options| for the buffer with number {bufnr}.
Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
buffer is used. Invalid {bufnr} or key is an error.
Note: this is equivalent to both `:set` and `:setlocal`.
Example: >lua
local bufnr = vim.api.nvim_get_current_buf()
vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
print(vim.bo.comments)
print(vim.bo.baz) -- error: invalid key
vim.wo[{winid}][{bufnr}] *vim.wo*
Get or set window-scoped |options| for the window with handle {winid} and
buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like
`:set` otherwise. If [{winid}] is omitted then the current window is
used. Invalid {winid}, {bufnr} or key is an error.
Note: only {bufnr} with value `0` (the current buffer in the window) is
supported.
Example: >lua
local winid = vim.api.nvim_get_current_win()
vim.wo[winid].number = true -- same as vim.wo.number = true
print(vim.wo.foldmarker)
print(vim.wo.quux) -- error: invalid key
vim.wo[winid][0].spell = false -- like ':setlocal nospell'
<
` ` *vim.opt_local* ` ` *vim.opt_local*
*vim.opt_global* *vim.opt_global*
*vim.opt* *vim.opt*
@ -1419,11 +1353,81 @@ Option:remove({value}) *vim.opt:remove()*
Parameters: ~ Parameters: ~
• {value} (string) Value to remove • {value} (string) Value to remove
vim.bo *vim.bo*
Get or set buffer-scoped |options| for the buffer with number {bufnr}.
Like `:set` and `:setlocal`. If [{bufnr}] is omitted then the current
buffer is used. Invalid {bufnr} or key is an error.
Note: this is equivalent to both `:set` and `:setlocal`.
Example: >lua
local bufnr = vim.api.nvim_get_current_buf()
vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
print(vim.bo.comments)
print(vim.bo.baz) -- error: invalid key
<
Parameters: ~
• {bufnr} (integer|nil)
vim.env *vim.env*
Environment variables defined in the editor session. See |expand-env| and
|:let-environment| for the Vimscript behavior. Invalid or unset key
returns `nil` . Example: >lua
vim.env.FOO = 'bar'
print(vim.env.TERM)
<
Parameters: ~
• {var} (string)
vim.go *vim.go*
Get or set global |options|. Like `:setglobal`. Invalid key is an error.
Note: this is different from |vim.o| because this accesses the global
option value and thus is mostly useful for use with |global-local|
options.
Example: >lua
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
<
vim.o *vim.o*
Get or set |options|. Like `:set`. Invalid key is an error.
Note: this works on both buffer-scoped and window-scoped options using the
current buffer and window.
Example: >lua
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
<
vim.wo *vim.wo*
Get or set window-scoped |options| for the window with handle {winid} and
buffer with number {bufnr}. Like `:setlocal` if {bufnr} is provided, like
`:set` otherwise. If [{winid}] is omitted then the current window is used.
Invalid {winid}, {bufnr} or key is an error.
Note: only {bufnr} with value `0` (the current buffer in the window) is
supported.
Example: >lua
local winid = vim.api.nvim_get_current_win()
vim.wo[winid].number = true -- same as vim.wo.number = true
print(vim.wo.foldmarker)
print(vim.wo.quux) -- error: invalid key
vim.wo[winid][0].spell = false -- like ':setlocal nospell'
<
============================================================================== ==============================================================================
Lua module: vim *lua-vim* Lua module: vim *lua-vim*
vim.cmd({command}) *vim.cmd()* vim.cmd *vim.cmd()*
Execute Vim script commands. Execute Vim script commands.
Note that `vim.cmd` can be indexed with a command name to return a Note that `vim.cmd` can be indexed with a command name to return a
@ -1468,10 +1472,6 @@ vim.cmd({command}) *vim.cmd()*
See also: ~ See also: ~
• |ex-cmd-index| • |ex-cmd-index|
*vim.connection_failure_errmsg()*
vim.connection_failure_errmsg({consequence})
TODO: Documentation
vim.defer_fn({fn}, {timeout}) *vim.defer_fn()* vim.defer_fn({fn}, {timeout}) *vim.defer_fn()*
Defers calling {fn} until {timeout} ms passes. Defers calling {fn} until {timeout} ms passes.
@ -1501,7 +1501,7 @@ vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
Return: ~ Return: ~
(string|nil) # Deprecated message, or nil if no message was shown. (string|nil) # Deprecated message, or nil if no message was shown.
vim.inspect({object}, {options}) *vim.inspect()* vim.inspect *vim.inspect()*
Gets a human-readable representation of the given object. Gets a human-readable representation of the given object.
See also: ~ See also: ~

View File

@ -54,6 +54,7 @@ vim._extra = {
inspect_pos = true, inspect_pos = true,
} }
--- @private
vim.log = { vim.log = {
levels = { levels = {
TRACE = 0, TRACE = 0,
@ -187,9 +188,7 @@ end
---@see |vim.print()| ---@see |vim.print()|
---@see https://github.com/kikito/inspect.lua ---@see https://github.com/kikito/inspect.lua
---@see https://github.com/mpeterv/vinspect ---@see https://github.com/mpeterv/vinspect
local function inspect(object, options) -- luacheck: no unused vim.inspect = vim.inspect
error(object, options) -- Stub for gen_vimdoc.py
end
do do
local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false
@ -328,6 +327,7 @@ function vim.schedule_wrap(cb)
end end
-- vim.fn.{func}(...) -- vim.fn.{func}(...)
---@private
vim.fn = setmetatable({}, { vim.fn = setmetatable({}, {
__index = function(t, key) __index = function(t, key)
local _fn local _fn
@ -345,10 +345,13 @@ vim.fn = setmetatable({}, {
end, end,
}) })
--- @private
vim.funcref = function(viml_func_name) vim.funcref = function(viml_func_name)
return vim.fn[viml_func_name] return vim.fn[viml_func_name]
end end
local VIM_CMD_ARG_MAX = 20
--- Execute Vim script commands. --- Execute Vim script commands.
--- ---
--- Note that `vim.cmd` can be indexed with a command name to return a callable function to the --- Note that `vim.cmd` can be indexed with a command name to return a callable function to the
@ -389,12 +392,6 @@ end
--- If a table, executes a single command. In this case, it is an alias --- If a table, executes a single command. In this case, it is an alias
--- to |nvim_cmd()| where `opts` is empty. --- to |nvim_cmd()| where `opts` is empty.
---@see |ex-cmd-index| ---@see |ex-cmd-index|
function vim.cmd(command) -- luacheck: no unused
error(command) -- Stub for gen_vimdoc.py
end
local VIM_CMD_ARG_MAX = 20
vim.cmd = setmetatable({}, { vim.cmd = setmetatable({}, {
__call = function(_, command) __call = function(_, command)
if type(command) == 'table' then if type(command) == 'table' then
@ -435,7 +432,6 @@ vim.cmd = setmetatable({}, {
do do
local validate = vim.validate local validate = vim.validate
---@private
local function make_dict_accessor(scope, handle) local function make_dict_accessor(scope, handle)
validate({ validate({
scope = { scope, 's' }, scope = { scope, 's' },
@ -745,7 +741,6 @@ function vim._expand_pat(pat, env)
end end
local keys = {} local keys = {}
---@private
local function insert_keys(obj) local function insert_keys(obj)
for k, _ in pairs(obj) do for k, _ in pairs(obj) do
if type(k) == 'string' and string.sub(k, 1, string.len(match_part)) == match_part then if type(k) == 'string' and string.sub(k, 1, string.len(match_part)) == match_part then
@ -1008,7 +1003,6 @@ end
function vim._init_default_mappings() function vim._init_default_mappings()
-- mappings -- mappings
---@private
local function region_chunks(region) local function region_chunks(region)
local chunks = {} local chunks = {}
local maxcol = vim.v.maxcol local maxcol = vim.v.maxcol
@ -1020,7 +1014,6 @@ function vim._init_default_mappings()
return chunks return chunks
end end
---@private
local function _visual_search(cmd) local function _visual_search(cmd)
assert(cmd == '/' or cmd == '?') assert(cmd == '/' or cmd == '?')
vim.api.nvim_feedkeys('\27', 'nx', true) -- Escape visual mode. vim.api.nvim_feedkeys('\27', 'nx', true) -- Escape visual mode.
@ -1037,7 +1030,6 @@ function vim._init_default_mappings()
vim.api.nvim_feedkeys(search_cmd, 'nx', true) vim.api.nvim_feedkeys(search_cmd, 'nx', true)
end end
---@private
local function map(mode, lhs, rhs) local function map(mode, lhs, rhs)
vim.keymap.set(mode, lhs, rhs, { desc = 'Nvim builtin' }) vim.keymap.set(mode, lhs, rhs, { desc = 'Nvim builtin' })
end end

View File

@ -56,7 +56,6 @@ function vim.inspect_pos(bufnr, row, col, filter)
} }
-- resolve hl links -- resolve hl links
---@private
local function resolve_hl(data) local function resolve_hl(data)
if data.hl_group then if data.hl_group then
local hlid = vim.api.nvim_get_hl_id_by_name(data.hl_group) local hlid = vim.api.nvim_get_hl_id_by_name(data.hl_group)
@ -91,7 +90,6 @@ function vim.inspect_pos(bufnr, row, col, filter)
end end
--- Convert an extmark tuple into a table --- Convert an extmark tuple into a table
--- @private
local function to_map(extmark) local function to_map(extmark)
extmark = { extmark = {
id = extmark[1], id = extmark[1],
@ -107,7 +105,6 @@ function vim.inspect_pos(bufnr, row, col, filter)
end end
--- Check if an extmark overlaps this position --- Check if an extmark overlaps this position
--- @private
local function is_here(extmark) local function is_here(extmark)
return (row >= extmark.row and row <= extmark.end_row) -- within the rows of the extmark return (row >= extmark.row and row <= extmark.end_row) -- within the rows of the extmark
and (row > extmark.row or col >= extmark.col) -- either not the first row, or in range of the col and (row > extmark.row or col >= extmark.col) -- either not the first row, or in range of the col
@ -148,17 +145,14 @@ function vim.show_pos(bufnr, row, col, filter)
local lines = { {} } local lines = { {} }
---@private
local function append(str, hl) local function append(str, hl)
table.insert(lines[#lines], { str, hl }) table.insert(lines[#lines], { str, hl })
end end
---@private
local function nl() local function nl()
table.insert(lines, {}) table.insert(lines, {})
end end
---@private
local function item(data, comment) local function item(data, comment)
append(' - ') append(' - ')
append(data.hl_group, data.hl_group) append(data.hl_group, data.hl_group)

View File

@ -92,15 +92,6 @@
---vim.v *vim.v* ---vim.v *vim.v*
--- |v:| variables. --- |v:| variables.
--- Invalid or unset key returns `nil`. --- Invalid or unset key returns `nil`.
---
---vim.env *vim.env*
--- Environment variables defined in the editor session.
--- See |expand-env| and |:let-environment| for the Vimscript behavior.
--- Invalid or unset key returns `nil`.
--- Example: >lua
--- vim.env.FOO = 'bar'
--- print(vim.env.TERM)
---<
---</pre> ---</pre>
local api = vim.api local api = vim.api
@ -118,7 +109,6 @@ local key_value_options = {
--- Convert a vimoption_T style dictionary to the correct OptionType associated with it. --- Convert a vimoption_T style dictionary to the correct OptionType associated with it.
---@return string ---@return string
---@private
local function get_option_metatype(name, info) local function get_option_metatype(name, info)
if info.type == 'string' then if info.type == 'string' then
if info.flaglist then if info.flaglist then
@ -143,6 +133,14 @@ local options_info = setmetatable({}, {
end, end,
}) })
---Environment variables defined in the editor session.
---See |expand-env| and |:let-environment| for the Vimscript behavior.
---Invalid or unset key returns `nil`.
---Example: <pre>lua
--- vim.env.FOO = 'bar'
--- print(vim.env.TERM)
---</pre>
---@param var string
vim.env = setmetatable({}, { vim.env = setmetatable({}, {
__index = function(_, k) __index = function(_, k)
local v = vim.fn.getenv(k) local v = vim.fn.getenv(k)
@ -157,7 +155,6 @@ vim.env = setmetatable({}, {
end, end,
}) })
---@private
local function opt_validate(option_name, target_scope) local function opt_validate(option_name, target_scope)
local scope = options_info[option_name].scope local scope = options_info[option_name].scope
if scope ~= target_scope then if scope ~= target_scope then
@ -174,7 +171,6 @@ local function opt_validate(option_name, target_scope)
end end
end end
---@private
local function new_buf_opt_accessor(bufnr) local function new_buf_opt_accessor(bufnr)
return setmetatable({}, { return setmetatable({}, {
__index = function(_, k) __index = function(_, k)
@ -192,7 +188,6 @@ local function new_buf_opt_accessor(bufnr)
}) })
end end
---@private
local function new_win_opt_accessor(winid, bufnr) local function new_win_opt_accessor(winid, bufnr)
return setmetatable({}, { return setmetatable({}, {
__index = function(_, k) __index = function(_, k)
@ -253,19 +248,15 @@ end
---global value of a |global-local| option, see |:setglobal|. ---global value of a |global-local| option, see |:setglobal|.
---</pre> ---</pre>
---@addtogroup lua-vimscript
---@brief <pre>help
---vim.o *vim.o*
---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: >lua ---Example: <pre>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> ---</pre>
vim.o = setmetatable({}, { vim.o = setmetatable({}, {
__index = function(_, k) __index = function(_, k)
@ -276,9 +267,6 @@ vim.o = setmetatable({}, {
end, end,
}) })
---@addtogroup lua-vimscript
---@brief <pre>help
---vim.go *vim.go*
---Get or set global |options|. Like `:setglobal`. Invalid key is ---Get or set global |options|. Like `:setglobal`. Invalid key is
---an error. ---an error.
--- ---
@ -286,11 +274,10 @@ vim.o = setmetatable({}, {
---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: >lua ---Example: <pre>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> ---</pre>
vim.go = setmetatable({}, { vim.go = setmetatable({}, {
__index = function(_, k) __index = function(_, k)
@ -301,26 +288,21 @@ vim.go = setmetatable({}, {
end, end,
}) })
---@addtogroup lua-vimscript
---@brief <pre>help
---vim.bo[{bufnr}] *vim.bo*
---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: >lua ---Example: <pre>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> ---</pre>
---@param bufnr integer|nil
vim.bo = new_buf_opt_accessor() vim.bo = new_buf_opt_accessor()
---@addtogroup lua-vimscript
---@brief <pre>help
---vim.wo[{winid}][{bufnr}] *vim.wo*
---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
@ -329,13 +311,13 @@ vim.bo = new_buf_opt_accessor()
---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: >lua ---Example: <pre>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> ---</pre>
vim.wo = new_win_opt_accessor() vim.wo = new_win_opt_accessor()
@ -348,7 +330,6 @@ vim.wo = new_win_opt_accessor()
---@brief ]] ---@brief ]]
--- Preserves the order and does not mutate the original list --- Preserves the order and does not mutate the original list
--- @private
local function remove_duplicate_values(t) local function remove_duplicate_values(t)
local result, seen = {}, {} local result, seen = {}, {}
for _, v in ipairs(t) do for _, v in ipairs(t) do
@ -364,7 +345,6 @@ end
-- Check whether the OptionTypes is allowed for vim.opt -- Check whether the OptionTypes is allowed for vim.opt
-- If it does not match, throw an error which indicates which option causes the error. -- If it does not match, throw an error which indicates which option causes the error.
--- @private
local function assert_valid_value(name, value, types) local function assert_valid_value(name, value, types)
local type_of_value = type(value) local type_of_value = type(value)
for _, valid_type in ipairs(types) do for _, valid_type in ipairs(types) do
@ -383,17 +363,14 @@ local function assert_valid_value(name, value, types)
) )
end end
--- @private
local function passthrough(_, x) local function passthrough(_, x)
return x return x
end end
--- @private
local function tbl_merge(left, right) local function tbl_merge(left, right)
return vim.tbl_extend('force', left, right) return vim.tbl_extend('force', left, right)
end end
--- @private
local function tbl_remove(t, value) local function tbl_remove(t, value)
if type(value) == 'string' then if type(value) == 'string' then
t[value] = nil t[value] = nil
@ -475,7 +452,6 @@ local to_vim_value = {
} }
--- Convert a Lua value to a vimoption_T value --- Convert a Lua value to a vimoption_T value
--- @private
local function convert_value_to_vim(name, info, value) local function convert_value_to_vim(name, info, value)
if value == nil then if value == nil then
return vim.NIL return vim.NIL
@ -591,7 +567,6 @@ local to_lua_value = {
} }
--- Converts a vimoption_T style value to a Lua value --- Converts a vimoption_T style value to a Lua value
--- @private
local function convert_value_to_lua(info, option_value) local function convert_value_to_lua(info, option_value)
return to_lua_value[info.metatype](info, option_value) return to_lua_value[info.metatype](info, option_value)
end end
@ -618,7 +593,6 @@ local prepend_methods = {
} }
--- Handles the '^' operator --- Handles the '^' operator
--- @private
local function prepend_value(info, current, new) local function prepend_value(info, current, new)
return prepend_methods[info.metatype]( return prepend_methods[info.metatype](
convert_value_to_lua(info, current), convert_value_to_lua(info, current),
@ -648,7 +622,6 @@ local add_methods = {
} }
--- Handles the '+' operator --- Handles the '+' operator
--- @private
local function add_value(info, current, new) local function add_value(info, current, new)
return add_methods[info.metatype]( return add_methods[info.metatype](
convert_value_to_lua(info, current), convert_value_to_lua(info, current),
@ -656,7 +629,6 @@ local function add_value(info, current, new)
) )
end end
--- @private
local function remove_one_item(t, val) local function remove_one_item(t, val)
if vim.tbl_islist(t) then if vim.tbl_islist(t) then
local remove_index = nil local remove_index = nil
@ -700,16 +672,13 @@ local remove_methods = {
} }
--- Handles the '-' operator --- Handles the '-' operator
--- @private
local function remove_value(info, current, new) local function remove_value(info, current, new)
return remove_methods[info.metatype](convert_value_to_lua(info, current), new) return remove_methods[info.metatype](convert_value_to_lua(info, current), new)
end end
--- @private
local function create_option_accessor(scope) local function create_option_accessor(scope)
local option_mt local option_mt
--- @private
local function make_option(name, value) local function make_option(name, value)
local info = assert(options_info[name], 'Not a valid option name: ' .. name) local info = assert(options_info[name], 'Not a valid option name: ' .. name)
@ -923,6 +892,11 @@ function Option:prepend(value) end -- luacheck: no unused
---@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
---@private
vim.opt = create_option_accessor() vim.opt = create_option_accessor()
---@private
vim.opt_local = create_option_accessor('local') vim.opt_local = create_option_accessor('local')
---@private
vim.opt_global = create_option_accessor('global') vim.opt_global = create_option_accessor('global')

View File

@ -30,7 +30,6 @@ local uv = vim.uv
--- @field cmd string[] --- @field cmd string[]
--- @field result? SystemCompleted --- @field result? SystemCompleted
---@private
---@param state SystemState ---@param state SystemState
local function close_handles(state) local function close_handles(state)
for _, handle in pairs({ state.handle, state.stdin, state.stdout, state.stderr }) do for _, handle in pairs({ state.handle, state.stdin, state.stdout, state.stderr }) do
@ -128,7 +127,6 @@ function SystemObj:is_closing()
return handle == nil or handle:is_closing() return handle == nil or handle:is_closing()
end end
---@private
---@param output function|'false' ---@param output function|'false'
---@return uv_stream_t? ---@return uv_stream_t?
---@return function? Handler ---@return function? Handler
@ -145,7 +143,6 @@ local function setup_output(output)
return nil, nil return nil, nil
end end
---@private
---@param input string|string[]|true|nil ---@param input string|string[]|true|nil
---@return uv_stream_t? ---@return uv_stream_t?
---@return string|string[]? ---@return string|string[]?

View File

@ -7,7 +7,6 @@ M.FileChangeType = vim.tbl_add_reverse_lookup({
Deleted = 3, Deleted = 3,
}) })
---@private
--- Joins filepath elements by static '/' separator --- Joins filepath elements by static '/' separator
--- ---
---@param ... (string) The path elements. ---@param ... (string) The path elements.
@ -16,7 +15,6 @@ local function filepath_join(...)
return table.concat({ ... }, '/') return table.concat({ ... }, '/')
end end
---@private
--- Stops and closes a libuv |uv_fs_event_t| or |uv_fs_poll_t| handle --- Stops and closes a libuv |uv_fs_event_t| or |uv_fs_poll_t| handle
--- ---
---@param handle (uv_fs_event_t|uv_fs_poll_t) The handle to stop ---@param handle (uv_fs_event_t|uv_fs_poll_t) The handle to stop
@ -88,7 +86,6 @@ local default_poll_interval_ms = 2000
--- @field include_pattern? userdata --- @field include_pattern? userdata
--- @field exclude_pattern? userdata --- @field exclude_pattern? userdata
---@private
--- Implementation for poll, hiding internally-used parameters. --- Implementation for poll, hiding internally-used parameters.
--- ---
---@param path string ---@param path string

View File

@ -72,7 +72,6 @@ local bufs_waiting_to_update = setmetatable({}, bufnr_and_namespace_cacher_mt)
local all_namespaces = {} local all_namespaces = {}
---@private
local function to_severity(severity) local function to_severity(severity)
if type(severity) == 'string' then if type(severity) == 'string' then
return assert( return assert(
@ -83,7 +82,6 @@ local function to_severity(severity)
return severity return severity
end end
---@private
local function filter_by_severity(severity, diagnostics) local function filter_by_severity(severity, diagnostics)
if not severity then if not severity then
return diagnostics return diagnostics
@ -104,7 +102,6 @@ local function filter_by_severity(severity, diagnostics)
end, diagnostics) end, diagnostics)
end end
---@private
local function count_sources(bufnr) local function count_sources(bufnr)
local seen = {} local seen = {}
local count = 0 local count = 0
@ -119,7 +116,6 @@ local function count_sources(bufnr)
return count return count
end end
---@private
local function prefix_source(diagnostics) local function prefix_source(diagnostics)
return vim.tbl_map(function(d) return vim.tbl_map(function(d)
if not d.source then if not d.source then
@ -132,7 +128,6 @@ local function prefix_source(diagnostics)
end, diagnostics) end, diagnostics)
end end
---@private
local function reformat_diagnostics(format, diagnostics) local function reformat_diagnostics(format, diagnostics)
vim.validate({ vim.validate({
format = { format, 'f' }, format = { format, 'f' },
@ -146,7 +141,6 @@ local function reformat_diagnostics(format, diagnostics)
return formatted return formatted
end end
---@private
local function enabled_value(option, namespace) local function enabled_value(option, namespace)
local ns = namespace and M.get_namespace(namespace) or {} local ns = namespace and M.get_namespace(namespace) or {}
if ns.opts and type(ns.opts[option]) == 'table' then if ns.opts and type(ns.opts[option]) == 'table' then
@ -160,7 +154,6 @@ local function enabled_value(option, namespace)
return {} return {}
end end
---@private
local function resolve_optional_value(option, value, namespace, bufnr) local function resolve_optional_value(option, value, namespace, bufnr)
if not value then if not value then
return false return false
@ -180,7 +173,6 @@ local function resolve_optional_value(option, value, namespace, bufnr)
end end
end end
---@private
local function get_resolved_options(opts, namespace, bufnr) local function get_resolved_options(opts, namespace, bufnr)
local ns = namespace and M.get_namespace(namespace) or {} local ns = namespace and M.get_namespace(namespace) or {}
-- Do not use tbl_deep_extend so that an empty table can be used to reset to default values -- Do not use tbl_deep_extend so that an empty table can be used to reset to default values
@ -202,7 +194,6 @@ local diagnostic_severities = {
} }
-- Make a map from DiagnosticSeverity -> Highlight Name -- Make a map from DiagnosticSeverity -> Highlight Name
---@private
local function make_highlight_map(base_name) local function make_highlight_map(base_name)
local result = {} local result = {}
for k in pairs(diagnostic_severities) do for k in pairs(diagnostic_severities) do
@ -243,7 +234,6 @@ local define_default_signs = (function()
end end
end)() end)()
---@private
local function get_bufnr(bufnr) local function get_bufnr(bufnr)
if not bufnr or bufnr == 0 then if not bufnr or bufnr == 0 then
return api.nvim_get_current_buf() return api.nvim_get_current_buf()
@ -251,7 +241,6 @@ local function get_bufnr(bufnr)
return bufnr return bufnr
end end
---@private
local function diagnostic_lines(diagnostics) local function diagnostic_lines(diagnostics)
if not diagnostics then if not diagnostics then
return {} return {}
@ -269,7 +258,6 @@ local function diagnostic_lines(diagnostics)
return diagnostics_by_line return diagnostics_by_line
end end
---@private
local function set_diagnostic_cache(namespace, bufnr, diagnostics) local function set_diagnostic_cache(namespace, bufnr, diagnostics)
for _, diagnostic in ipairs(diagnostics) do for _, diagnostic in ipairs(diagnostics) do
assert(diagnostic.lnum, 'Diagnostic line number is required') assert(diagnostic.lnum, 'Diagnostic line number is required')
@ -284,7 +272,6 @@ local function set_diagnostic_cache(namespace, bufnr, diagnostics)
diagnostic_cache[bufnr][namespace] = diagnostics diagnostic_cache[bufnr][namespace] = diagnostics
end end
---@private
local function restore_extmarks(bufnr, last) local function restore_extmarks(bufnr, last)
for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do for ns, extmarks in pairs(diagnostic_cache_extmarks[bufnr]) do
local extmarks_current = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true }) local extmarks_current = api.nvim_buf_get_extmarks(bufnr, ns, 0, -1, { details = true })
@ -306,7 +293,6 @@ local function restore_extmarks(bufnr, last)
end end
end end
---@private
local function save_extmarks(namespace, bufnr) local function save_extmarks(namespace, bufnr)
bufnr = get_bufnr(bufnr) bufnr = get_bufnr(bufnr)
if not diagnostic_attached_buffers[bufnr] then if not diagnostic_attached_buffers[bufnr] then
@ -326,13 +312,11 @@ end
local registered_autocmds = {} local registered_autocmds = {}
---@private
local function make_augroup_key(namespace, bufnr) local function make_augroup_key(namespace, bufnr)
local ns = M.get_namespace(namespace) local ns = M.get_namespace(namespace)
return string.format('DiagnosticInsertLeave:%s:%s', bufnr, ns.name) return string.format('DiagnosticInsertLeave:%s:%s', bufnr, ns.name)
end end
---@private
local function execute_scheduled_display(namespace, bufnr) local function execute_scheduled_display(namespace, bufnr)
local args = bufs_waiting_to_update[bufnr][namespace] local args = bufs_waiting_to_update[bufnr][namespace]
if not args then if not args then
@ -348,7 +332,6 @@ end
--- Table of autocmd events to fire the update for displaying new diagnostic information --- Table of autocmd events to fire the update for displaying new diagnostic information
local insert_leave_auto_cmds = { 'InsertLeave', 'CursorHoldI' } local insert_leave_auto_cmds = { 'InsertLeave', 'CursorHoldI' }
---@private
local function schedule_display(namespace, bufnr, args) local function schedule_display(namespace, bufnr, args)
bufs_waiting_to_update[bufnr][namespace] = args bufs_waiting_to_update[bufnr][namespace] = args
@ -367,7 +350,6 @@ local function schedule_display(namespace, bufnr, args)
end end
end end
---@private
local function clear_scheduled_display(namespace, bufnr) local function clear_scheduled_display(namespace, bufnr)
local key = make_augroup_key(namespace, bufnr) local key = make_augroup_key(namespace, bufnr)
@ -377,7 +359,6 @@ local function clear_scheduled_display(namespace, bufnr)
end end
end end
---@private
local function get_diagnostics(bufnr, opts, clamp) local function get_diagnostics(bufnr, opts, clamp)
opts = opts or {} opts = opts or {}
@ -392,7 +373,6 @@ local function get_diagnostics(bufnr, opts, clamp)
end, end,
}) })
---@private
local function add(b, d) local function add(b, d)
if not opts.lnum or d.lnum == opts.lnum then if not opts.lnum or d.lnum == opts.lnum then
if clamp and api.nvim_buf_is_loaded(b) then if clamp and api.nvim_buf_is_loaded(b) then
@ -416,7 +396,6 @@ local function get_diagnostics(bufnr, opts, clamp)
end end
end end
---@private
local function add_all_diags(buf, diags) local function add_all_diags(buf, diags)
for _, diagnostic in pairs(diags) do for _, diagnostic in pairs(diags) do
add(buf, diagnostic) add(buf, diagnostic)
@ -450,7 +429,6 @@ local function get_diagnostics(bufnr, opts, clamp)
return diagnostics return diagnostics
end end
---@private
local function set_list(loclist, opts) local function set_list(loclist, opts)
opts = opts or {} opts = opts or {}
local open = vim.F.if_nil(opts.open, true) local open = vim.F.if_nil(opts.open, true)
@ -474,7 +452,6 @@ local function set_list(loclist, opts)
end end
end end
---@private
local function next_diagnostic(position, search_forward, bufnr, opts, namespace) local function next_diagnostic(position, search_forward, bufnr, opts, namespace)
position[1] = position[1] - 1 position[1] = position[1] - 1
bufnr = get_bufnr(bufnr) bufnr = get_bufnr(bufnr)
@ -525,7 +502,6 @@ local function next_diagnostic(position, search_forward, bufnr, opts, namespace)
end end
end end
---@private
local function diagnostic_move_pos(opts, pos) local function diagnostic_move_pos(opts, pos)
opts = opts or {} opts = opts or {}

View File

@ -2,7 +2,6 @@ local api = vim.api
local M = {} local M = {}
---@private
local function starsetf(ft, opts) local function starsetf(ft, opts)
return { return {
function(path, bufnr) function(path, bufnr)
@ -2317,7 +2316,6 @@ local pattern = {
-- luacheck: pop -- luacheck: pop
-- luacheck: pop -- luacheck: pop
---@private
local function sort_by_priority(t) local function sort_by_priority(t)
local sorted = {} local sorted = {}
for k, v in pairs(t) do for k, v in pairs(t) do
@ -2341,7 +2339,6 @@ end
local pattern_sorted = sort_by_priority(pattern) local pattern_sorted = sort_by_priority(pattern)
---@private
local function normalize_path(path, as_pattern) local function normalize_path(path, as_pattern)
local normal = path:gsub('\\', '/') local normal = path:gsub('\\', '/')
if normal:find('^~') then if normal:find('^~') then
@ -2456,7 +2453,6 @@ function M.add(filetypes)
end end
end end
---@private
local function dispatch(ft, path, bufnr, ...) local function dispatch(ft, path, bufnr, ...)
local on_detect local on_detect
if type(ft) == 'function' then if type(ft) == 'function' then
@ -2483,7 +2479,6 @@ end
-- Lookup table/cache for patterns that contain an environment variable pattern, e.g. ${SOME_VAR}. -- Lookup table/cache for patterns that contain an environment variable pattern, e.g. ${SOME_VAR}.
local expand_env_lookup = {} local expand_env_lookup = {}
---@private
local function match_pattern(name, path, tail, pat) local function match_pattern(name, path, tail, pat)
if expand_env_lookup[pat] == nil then if expand_env_lookup[pat] == nil then
expand_env_lookup[pat] = pat:find('%${') ~= nil expand_env_lookup[pat] = pat:find('%${') ~= nil

View File

@ -218,7 +218,6 @@ function M.find(names, opts)
local matches = {} local matches = {}
---@private
local function add(match) local function add(match)
matches[#matches + 1] = M.normalize(match) matches[#matches + 1] = M.normalize(match)
if #matches == limit then if #matches == limit then

View File

@ -18,23 +18,18 @@
---<pre>vim ---<pre>vim
--- au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false} --- au TextYankPost * silent! lua vim.highlight.on_yank {on_visual=false}
---</pre> ---</pre>
---
--- <pre>help
---vim.highlight.priorities *vim.highlight.priorities*
---
--- Table with default priorities used for highlighting:
--- • `syntax`: `50`, used for standard syntax highlighting
--- • `treesitter`: `100`, used for tree-sitter-based highlighting
--- • `semantic_tokens`: `125`, used for LSP semantic token highlighting
--- • `diagnostics`: `150`, used for code analysis such as diagnostics
--- • `user`: `200`, used for user-triggered highlights such as LSP document
--- symbols or `on_yank` autocommands
---</pre>
local api = vim.api local api = vim.api
local M = {} local M = {}
--- Table with default priorities used for highlighting:
--- - `syntax`: `50`, used for standard syntax highlighting
--- - `treesitter`: `100`, used for tree-sitter-based highlighting
--- - `semantic_tokens`: `125`, used for LSP semantic token highlighting
--- - `diagnostics`: `150`, used for code analysis such as diagnostics
--- - `user`: `200`, used for user-triggered highlights such as LSP document
--- symbols or `on_yank` autocommands
M.priorities = { M.priorities = {
syntax = 50, syntax = 50,
treesitter = 100, treesitter = 100,

View File

@ -85,7 +85,6 @@ end
--- Packed tables use this as their metatable --- Packed tables use this as their metatable
local packedmt = {} local packedmt = {}
---@private
local function unpack(t) local function unpack(t)
if type(t) == 'table' and getmetatable(t) == packedmt then if type(t) == 'table' and getmetatable(t) == packedmt then
return _G.unpack(t, 1, t.n) return _G.unpack(t, 1, t.n)
@ -93,7 +92,6 @@ local function unpack(t)
return t return t
end end
---@private
local function pack(...) local function pack(...)
local n = select('#', ...) local n = select('#', ...)
if n > 1 then if n > 1 then
@ -102,7 +100,6 @@ local function pack(...)
return ... return ...
end end
---@private
local function sanitize(t) local function sanitize(t)
if type(t) == 'table' and getmetatable(t) == packedmt then if type(t) == 'table' and getmetatable(t) == packedmt then
-- Remove length tag -- Remove length tag
@ -120,7 +117,6 @@ end
---@param ... any Function arguments. ---@param ... any Function arguments.
---@return boolean True if the iterator stage should continue, false otherwise ---@return boolean True if the iterator stage should continue, false otherwise
---@return any Function arguments. ---@return any Function arguments.
---@private
local function continue(...) local function continue(...)
if select('#', ...) > 0 then if select('#', ...) > 0 then
return false, ... return false, ...
@ -137,7 +133,6 @@ end
---@param ... any Arguments to apply to f ---@param ... any Arguments to apply to f
---@return boolean True if the iterator pipeline should continue, false otherwise ---@return boolean True if the iterator pipeline should continue, false otherwise
---@return any Return values of f ---@return any Return values of f
---@private
local function apply(f, ...) local function apply(f, ...)
if select('#', ...) > 0 then if select('#', ...) > 0 then
return continue(f(...)) return continue(f(...))
@ -230,7 +225,6 @@ function Iter.map(self, f)
--- values passed. --- values passed.
---@param ... any Values to return if cont is false. ---@param ... any Values to return if cont is false.
---@return any ---@return any
---@private
local function fn(cont, ...) local function fn(cont, ...)
if cont then if cont then
return fn(apply(f, next(self))) return fn(apply(f, next(self)))
@ -270,7 +264,6 @@ end
--- Takes all of the values returned by the previous stage --- Takes all of the values returned by the previous stage
--- in the pipeline as arguments. --- in the pipeline as arguments.
function Iter.each(self, f) function Iter.each(self, f)
---@private
local function fn(...) local function fn(...)
if select('#', ...) > 0 then if select('#', ...) > 0 then
f(...) f(...)
@ -383,7 +376,6 @@ function Iter.fold(self, init, f)
local acc = init local acc = init
--- Use a closure to handle var args returned from iterator --- Use a closure to handle var args returned from iterator
---@private
local function fn(...) local function fn(...)
if select(1, ...) ~= nil then if select(1, ...) ~= nil then
acc = f(acc, ...) acc = f(acc, ...)
@ -525,7 +517,6 @@ function Iter.find(self, f)
local result = nil local result = nil
--- Use a closure to handle var args returned from iterator --- Use a closure to handle var args returned from iterator
---@private
local function fn(...) local function fn(...)
if select(1, ...) ~= nil then if select(1, ...) ~= nil then
if f(...) then if f(...) then
@ -768,7 +759,6 @@ function Iter.any(self, pred)
local any = false local any = false
--- Use a closure to handle var args returned from iterator --- Use a closure to handle var args returned from iterator
---@private
local function fn(...) local function fn(...)
if select(1, ...) ~= nil then if select(1, ...) ~= nil then
if pred(...) then if pred(...) then
@ -792,7 +782,6 @@ end
function Iter.all(self, pred) function Iter.all(self, pred)
local all = true local all = true
---@private
local function fn(...) local function fn(...)
if select(1, ...) ~= nil then if select(1, ...) ~= nil then
if not pred(...) then if not pred(...) then
@ -929,7 +918,6 @@ function Iter.new(src, ...)
local s, var = ... local s, var = ...
--- Use a closure to handle var args returned from iterator --- Use a closure to handle var args returned from iterator
---@private
local function fn(...) local function fn(...)
if select(1, ...) ~= nil then if select(1, ...) ~= nil then
var = select(1, ...) var = select(1, ...)

View File

@ -21,7 +21,10 @@ local M = {}
---@alias LoaderStats table<string, {total:number, time:number, [string]:number?}?> ---@alias LoaderStats table<string, {total:number, time:number, [string]:number?}?>
---@nodoc
M.path = vim.fn.stdpath('cache') .. '/luac' M.path = vim.fn.stdpath('cache') .. '/luac'
---@nodoc
M.enabled = false M.enabled = false
---@class Loader ---@class Loader
@ -58,7 +61,6 @@ function Loader.get_hash(path)
return Loader._hashes[path] return Loader._hashes[path]
end end
---@private
local function normalize(path) local function normalize(path)
return vim.fs.normalize(path, { expand_env = false }) return vim.fs.normalize(path, { expand_env = false })
end end
@ -122,7 +124,6 @@ end
--- @param path string --- @param path string
--- @param mode integer --- @param mode integer
--- @return string? data --- @return string? data
--- @private
local function readfile(path, mode) local function readfile(path, mode)
local f = uv.fs_open(path, 'r', mode) local f = uv.fs_open(path, 'r', mode)
if f then if f then
@ -310,7 +311,6 @@ function M.find(modname, opts)
local results = {} local results = {}
-- Only continue if we haven't found anything yet or we want to find all -- Only continue if we haven't found anything yet or we want to find all
---@private
local function continue() local function continue()
return #results == 0 or opts.all return #results == 0 or opts.all
end end
@ -318,7 +318,6 @@ function M.find(modname, opts)
-- Checks if the given paths contain the top-level module. -- Checks if the given paths contain the top-level module.
-- If so, it tries to find the module path for the given module name. -- If so, it tries to find the module path for the given module name.
---@param paths string[] ---@param paths string[]
---@private
local function _find(paths) local function _find(paths)
for _, path in ipairs(paths) do for _, path in ipairs(paths) do
if topmod == '*' then if topmod == '*' then
@ -504,7 +503,6 @@ end
---@private ---@private
function M._inspect(opts) function M._inspect(opts)
if opts and opts.print then if opts and opts.print then
---@private
local function ms(nsec) local function ms(nsec)
return math.floor(nsec / 1e6 * 1000 + 0.5) / 1000 .. 'ms' return math.floor(nsec / 1e6 * 1000 + 0.5) / 1000 .. 'ms'
end end

View File

@ -66,7 +66,6 @@ lsp._request_name_to_capability = {
-- TODO improve handling of scratch buffers with LSP attached. -- TODO improve handling of scratch buffers with LSP attached.
---@private
--- Concatenates and writes a list of strings to the Vim error buffer. --- Concatenates and writes a list of strings to the Vim error buffer.
--- ---
---@param ... string List to write to the buffer ---@param ... string List to write to the buffer
@ -75,7 +74,6 @@ local function err_message(...)
nvim_command('redraw') nvim_command('redraw')
end end
---@private
--- Returns the buffer number for the given {bufnr}. --- Returns the buffer number for the given {bufnr}.
--- ---
---@param bufnr (integer|nil) Buffer number to resolve. Defaults to current buffer ---@param bufnr (integer|nil) Buffer number to resolve. Defaults to current buffer
@ -101,7 +99,6 @@ function lsp._unsupported_method(method)
return msg return msg
end end
---@private
--- Checks whether a given path is a directory. --- Checks whether a given path is a directory.
--- ---
---@param filename (string) path to check ---@param filename (string) path to check
@ -132,7 +129,6 @@ local format_line_ending = {
['mac'] = '\r', ['mac'] = '\r',
} }
---@private
---@param bufnr (number) ---@param bufnr (number)
---@return string ---@return string
local function buf_get_line_ending(bufnr) local function buf_get_line_ending(bufnr)
@ -140,7 +136,6 @@ local function buf_get_line_ending(bufnr)
end end
local client_index = 0 local client_index = 0
---@private
--- Returns a new, unused client id. --- Returns a new, unused client id.
--- ---
---@return integer client_id ---@return integer client_id
@ -153,7 +148,6 @@ local active_clients = {} --- @type table<integer,lsp.Client>
local all_buffer_active_clients = {} --- @type table<integer,table<integer,true>> local all_buffer_active_clients = {} --- @type table<integer,table<integer,true>>
local uninitialized_clients = {} --- @type table<integer,lsp.Client> local uninitialized_clients = {} --- @type table<integer,lsp.Client>
---@private
---@param bufnr? integer ---@param bufnr? integer
---@param fn fun(client: lsp.Client, client_id: integer, bufnr: integer) ---@param fn fun(client: lsp.Client, client_id: integer, bufnr: integer)
local function for_each_buffer_client(bufnr, fn, restrict_client_ids) local function for_each_buffer_client(bufnr, fn, restrict_client_ids)
@ -185,9 +179,10 @@ local function for_each_buffer_client(bufnr, fn, restrict_client_ids)
end end
end end
-- Error codes to be used with `on_error` from |vim.lsp.start_client|. --- Error codes to be used with `on_error` from |vim.lsp.start_client|.
-- Can be used to look up the string from a the number or the number --- Can be used to look up the string from a the number or the number
-- from the string. --- from the string.
--- @nodoc
lsp.client_errors = tbl_extend( lsp.client_errors = tbl_extend(
'error', 'error',
lsp_rpc.client_errors, lsp_rpc.client_errors,
@ -196,7 +191,6 @@ lsp.client_errors = tbl_extend(
}) })
) )
---@private
--- Normalizes {encoding} to valid LSP encoding names. --- Normalizes {encoding} to valid LSP encoding names.
--- ---
---@param encoding (string) Encoding to normalize ---@param encoding (string) Encoding to normalize
@ -243,7 +237,6 @@ function lsp._cmd_parts(input)
return cmd, cmd_args return cmd, cmd_args
end end
---@private
--- Augments a validator function with support for optional (nil) values. --- Augments a validator function with support for optional (nil) values.
--- ---
---@param fn (fun(v): boolean) The original validator function; should return a ---@param fn (fun(v): boolean) The original validator function; should return a
@ -256,7 +249,6 @@ local function optional_validator(fn)
end end
end end
---@private
--- Validates a client configuration as given to |vim.lsp.start_client()|. --- Validates a client configuration as given to |vim.lsp.start_client()|.
--- ---
---@param config (lsp.ClientConfig) ---@param config (lsp.ClientConfig)
@ -308,7 +300,6 @@ local function validate_client_config(config)
return cmd, cmd_args, offset_encoding return cmd, cmd_args, offset_encoding
end end
---@private
--- Returns full text of buffer {bufnr} as a string. --- Returns full text of buffer {bufnr} as a string.
--- ---
---@param bufnr (number) Buffer handle, or 0 for current. ---@param bufnr (number) Buffer handle, or 0 for current.
@ -322,7 +313,6 @@ local function buf_get_full_text(bufnr)
return text return text
end end
---@private
--- Memoizes a function. On first run, the function return value is saved and --- Memoizes a function. On first run, the function return value is saved and
--- immediately returned on subsequent runs. If the function returns a multival, --- immediately returned on subsequent runs. If the function returns a multival,
--- only the first returned value will be memoized and returned. The function will only be run once, --- only the first returned value will be memoized and returned. The function will only be run once,
@ -382,7 +372,6 @@ do
--- @field debounce integer debounce duration in ms --- @field debounce integer debounce duration in ms
--- @field clients table<integer, table> clients using this state. {client_id, client} --- @field clients table<integer, table> clients using this state. {client_id, client}
---@private
---@param group CTGroup ---@param group CTGroup
---@return string ---@return string
local function group_key(group) local function group_key(group)
@ -403,7 +392,6 @@ do
end, end,
}) })
---@private
---@return CTGroup ---@return CTGroup
local function get_group(client) local function get_group(client)
local allow_inc_sync = if_nil(client.config.flags.allow_incremental_sync, true) local allow_inc_sync = if_nil(client.config.flags.allow_incremental_sync, true)
@ -419,7 +407,6 @@ do
} }
end end
---@private
---@param state CTBufferState ---@param state CTBufferState
local function incremental_changes(state, encoding, bufnr, firstline, lastline, new_lastline) local function incremental_changes(state, encoding, bufnr, firstline, lastline, new_lastline)
local prev_lines = state.lines local prev_lines = state.lines
@ -543,8 +530,6 @@ do
end end
end end
---@private
--
-- Adjust debounce time by taking time of last didChange notification into -- Adjust debounce time by taking time of last didChange notification into
-- consideration. If the last didChange happened more than `debounce` time ago, -- consideration. If the last didChange happened more than `debounce` time ago,
-- debounce can be skipped and otherwise maybe reduced. -- debounce can be skipped and otherwise maybe reduced.
@ -567,7 +552,6 @@ do
return math.max(debounce - ms_since_last_flush, 0) return math.max(debounce - ms_since_last_flush, 0)
end end
---@private
---@param bufnr integer ---@param bufnr integer
---@param sync_kind integer protocol.TextDocumentSyncKind ---@param sync_kind integer protocol.TextDocumentSyncKind
---@param state CTGroupState ---@param state CTGroupState
@ -694,7 +678,6 @@ do
end end
end end
---@private
--- Default handler for the 'textDocument/didOpen' LSP notification. --- Default handler for the 'textDocument/didOpen' LSP notification.
--- ---
---@param bufnr integer Number of the buffer, or 0 for current ---@param bufnr integer Number of the buffer, or 0 for current
@ -924,7 +907,6 @@ function lsp.status()
return message return message
end end
---@private
-- Determines whether the given option can be set by `set_defaults`. -- Determines whether the given option can be set by `set_defaults`.
local function is_empty_or_default(bufnr, option) local function is_empty_or_default(bufnr, option)
if vim.bo[bufnr][option] == '' then if vim.bo[bufnr][option] == '' then
@ -1138,7 +1120,6 @@ function lsp.start_client(config)
local dispatch = {} local dispatch = {}
---@private
--- Returns the handler associated with an LSP method. --- Returns the handler associated with an LSP method.
--- Returns the default handler if the user hasn't set a custom one. --- Returns the default handler if the user hasn't set a custom one.
--- ---
@ -1208,7 +1189,6 @@ function lsp.start_client(config)
end end
end end
---@private
--- Reset defaults set by `set_defaults`. --- Reset defaults set by `set_defaults`.
--- Must only be called if the last client attached to a buffer exits. --- Must only be called if the last client attached to a buffer exits.
local function reset_defaults(bufnr) local function reset_defaults(bufnr)
@ -1337,7 +1317,6 @@ function lsp.start_client(config)
-- Store the uninitialized_clients for cleanup in case we exit before initialize finishes. -- Store the uninitialized_clients for cleanup in case we exit before initialize finishes.
uninitialized_clients[client_id] = client uninitialized_clients[client_id] = client
---@private
local function initialize() local function initialize()
local valid_traces = { local valid_traces = {
off = 'off', off = 'off',
@ -1749,7 +1728,6 @@ do
end end
end end
---@private
---Buffer lifecycle handler for textDocument/didSave ---Buffer lifecycle handler for textDocument/didSave
local function text_document_did_save_handler(bufnr) local function text_document_did_save_handler(bufnr)
bufnr = resolve_bufnr(bufnr) bufnr = resolve_bufnr(bufnr)
@ -2082,7 +2060,6 @@ api.nvim_create_autocmd('VimLeavePre', {
local poll_time = 50 local poll_time = 50
---@private
local function check_clients_closed() local function check_clients_closed()
for client_id, timeout in pairs(timeouts) do for client_id, timeout in pairs(timeouts) do
timeouts[client_id] = timeout - poll_time timeouts[client_id] = timeout - poll_time
@ -2440,12 +2417,13 @@ function lsp.buf_get_clients(bufnr)
return result return result
end end
-- Log level dictionary with reverse lookup as well. --- Log level dictionary with reverse lookup as well.
-- ---
-- Can be used to lookup the number from the name or the --- Can be used to lookup the number from the name or the
-- name from the number. --- name from the number.
-- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
-- Level numbers begin with "TRACE" at 0 --- Level numbers begin with "TRACE" at 0
--- @nodoc
lsp.log_levels = log.levels lsp.log_levels = log.levels
--- Sets the global log level for LSP logging. --- Sets the global log level for LSP logging.

View File

@ -5,7 +5,6 @@ local lpeg = vim.lpeg
local M = {} local M = {}
---@private
--- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that" --- Parses the raw pattern into an |lpeg| pattern. LPeg patterns natively support the "this" or "that"
--- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern. --- alternative constructions described in the LSP spec that cannot be expressed in a standard Lua pattern.
--- ---

View File

@ -5,7 +5,6 @@ local npcall = vim.F.npcall
local M = {} local M = {}
---@private
--- Sends an async request to all active clients attached to the current --- Sends an async request to all active clients attached to the current
--- buffer. --- buffer.
--- ---
@ -45,7 +44,6 @@ function M.hover()
request('textDocument/hover', params) request('textDocument/hover', params)
end end
---@private
local function request_with_options(name, params, options) local function request_with_options(name, params, options)
local req_handler local req_handler
if options then if options then
@ -120,7 +118,6 @@ function M.completion(context)
return request('textDocument/completion', params) return request('textDocument/completion', params)
end end
---@private
---@param bufnr integer ---@param bufnr integer
---@param mode "v"|"V" ---@param mode "v"|"V"
---@return table {start={row,col}, end={row,col}} using (1, 0) indexing ---@return table {start={row,col}, end={row,col}} using (1, 0) indexing
@ -218,7 +215,6 @@ function M.format(options)
vim.notify('[LSP] Format request failed, no matching language servers.') vim.notify('[LSP] Format request failed, no matching language servers.')
end end
---@private
local function set_range(client, params) local function set_range(client, params)
if range then if range then
local range_params = local range_params =
@ -289,7 +285,6 @@ function M.rename(new_name, options)
-- Compute early to account for cursor movements after going async -- Compute early to account for cursor movements after going async
local cword = vim.fn.expand('<cword>') local cword = vim.fn.expand('<cword>')
---@private
local function get_text_at_range(range, offset_encoding) local function get_text_at_range(range, offset_encoding)
return api.nvim_buf_get_text( return api.nvim_buf_get_text(
bufnr, bufnr,
@ -307,7 +302,6 @@ function M.rename(new_name, options)
return return
end end
---@private
local function rename(name) local function rename(name)
local params = util.make_position_params(win, client.offset_encoding) local params = util.make_position_params(win, client.offset_encoding)
params.newName = name params.newName = name
@ -408,7 +402,6 @@ function M.document_symbol(options)
request_with_options('textDocument/documentSymbol', params, options) request_with_options('textDocument/documentSymbol', params, options)
end end
---@private
local function pick_call_hierarchy_item(call_hierarchy_items) local function pick_call_hierarchy_item(call_hierarchy_items)
if not call_hierarchy_items then if not call_hierarchy_items then
return return
@ -428,7 +421,6 @@ local function pick_call_hierarchy_item(call_hierarchy_items)
return choice return choice
end end
---@private
local function call_hierarchy(method) local function call_hierarchy(method)
local params = util.make_position_params() local params = util.make_position_params()
request('textDocument/prepareCallHierarchy', params, function(err, result, ctx) request('textDocument/prepareCallHierarchy', params, function(err, result, ctx)
@ -579,8 +571,6 @@ function M.clear_references()
util.buf_clear_references() util.buf_clear_references()
end end
---@private
--
--- This is not public because the main extension point is --- This is not public because the main extension point is
--- vim.ui.select which can be overridden independently. --- vim.ui.select which can be overridden independently.
--- ---
@ -592,7 +582,6 @@ end
local function on_code_action_results(results, ctx, options) local function on_code_action_results(results, ctx, options)
local action_tuples = {} local action_tuples = {}
---@private
local function action_filter(a) local function action_filter(a)
-- filter by specified action kind -- filter by specified action kind
if options and options.context and options.context.only then if options and options.context and options.context.only then
@ -632,7 +621,6 @@ local function on_code_action_results(results, ctx, options)
return return
end end
---@private
local function apply_action(action, client) local function apply_action(action, client)
if action.edit then if action.edit then
util.apply_workspace_edit(action.edit, client.offset_encoding) util.apply_workspace_edit(action.edit, client.offset_encoding)
@ -643,7 +631,6 @@ local function on_code_action_results(results, ctx, options)
end end
end end
---@private
local function on_user_choice(action_tuple) local function on_user_choice(action_tuple)
if not action_tuple then if not action_tuple then
return return
@ -701,7 +688,6 @@ end
--- Requests code actions from all clients and calls the handler exactly once --- Requests code actions from all clients and calls the handler exactly once
--- with all aggregated results --- with all aggregated results
---@private
local function code_action_request(params, options) local function code_action_request(params, options)
local bufnr = api.nvim_get_current_buf() local bufnr = api.nvim_get_current_buf()
local method = 'textDocument/codeAction' local method = 'textDocument/codeAction'

View File

@ -26,7 +26,6 @@ local namespaces = setmetatable({}, {
---@private ---@private
M.__namespaces = namespaces M.__namespaces = namespaces
---@private
local function execute_lens(lens, bufnr, client_id) local function execute_lens(lens, bufnr, client_id)
local line = lens.range.start.line local line = lens.range.start.line
api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1) api.nvim_buf_clear_namespace(bufnr, namespaces[client_id], line, line + 1)
@ -89,7 +88,6 @@ function M.run()
end end
end end
---@private
local function resolve_bufnr(bufnr) local function resolve_bufnr(bufnr)
return bufnr == 0 and api.nvim_get_current_buf() or bufnr return bufnr == 0 and api.nvim_get_current_buf() or bufnr
end end
@ -186,7 +184,6 @@ function M.save(lenses, bufnr, client_id)
lenses_by_client[client_id] = lenses lenses_by_client[client_id] = lenses
end end
---@private
local function resolve_lenses(lenses, bufnr, client_id, callback) local function resolve_lenses(lenses, bufnr, client_id, callback)
lenses = lenses or {} lenses = lenses or {}
local num_lens = vim.tbl_count(lenses) local num_lens = vim.tbl_count(lenses)
@ -195,7 +192,6 @@ local function resolve_lenses(lenses, bufnr, client_id, callback)
return return
end end
---@private
local function countdown() local function countdown()
num_lens = num_lens - 1 num_lens = num_lens - 1
if num_lens == 0 then if num_lens == 0 then

View File

@ -5,7 +5,7 @@ local protocol = require('vim.lsp.protocol')
local M = {} local M = {}
local DEFAULT_CLIENT_ID = -1 local DEFAULT_CLIENT_ID = -1
---@private
local function get_client_id(client_id) local function get_client_id(client_id)
if client_id == nil then if client_id == nil then
client_id = DEFAULT_CLIENT_ID client_id = DEFAULT_CLIENT_ID
@ -14,7 +14,6 @@ local function get_client_id(client_id)
return client_id return client_id
end end
---@private
---@param severity lsp.DiagnosticSeverity ---@param severity lsp.DiagnosticSeverity
local function severity_lsp_to_vim(severity) local function severity_lsp_to_vim(severity)
if type(severity) == 'string' then if type(severity) == 'string' then
@ -23,7 +22,6 @@ local function severity_lsp_to_vim(severity)
return severity return severity
end end
---@private
---@return lsp.DiagnosticSeverity ---@return lsp.DiagnosticSeverity
local function severity_vim_to_lsp(severity) local function severity_vim_to_lsp(severity)
if type(severity) == 'string' then if type(severity) == 'string' then
@ -32,7 +30,6 @@ local function severity_vim_to_lsp(severity)
return severity return severity
end end
---@private
---@return integer ---@return integer
local function line_byte_from_position(lines, lnum, col, offset_encoding) local function line_byte_from_position(lines, lnum, col, offset_encoding)
if not lines or offset_encoding == 'utf-8' then if not lines or offset_encoding == 'utf-8' then
@ -48,7 +45,6 @@ local function line_byte_from_position(lines, lnum, col, offset_encoding)
return col return col
end end
---@private
local function get_buf_lines(bufnr) local function get_buf_lines(bufnr)
if vim.api.nvim_buf_is_loaded(bufnr) then if vim.api.nvim_buf_is_loaded(bufnr) then
return vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) return vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
@ -73,7 +69,6 @@ local function get_buf_lines(bufnr)
return lines return lines
end end
--- @private
--- @param diagnostic lsp.Diagnostic --- @param diagnostic lsp.Diagnostic
--- @param client_id integer --- @param client_id integer
--- @return table? --- @return table?
@ -96,7 +91,6 @@ local function tags_lsp_to_vim(diagnostic, client_id)
return tags return tags
end end
---@private
---@param diagnostics lsp.Diagnostic[] ---@param diagnostics lsp.Diagnostic[]
---@param bufnr integer ---@param bufnr integer
---@param client_id integer ---@param client_id integer
@ -133,7 +127,6 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)
end, diagnostics) end, diagnostics)
end end
--- @private
--- @param diagnostics Diagnostic[] --- @param diagnostics Diagnostic[]
--- @return lsp.Diagnostic[] --- @return lsp.Diagnostic[]
local function diagnostic_vim_to_lsp(diagnostics) local function diagnostic_vim_to_lsp(diagnostics)

View File

@ -7,7 +7,6 @@ local M = {}
-- FIXME: DOC: Expose in vimdocs -- FIXME: DOC: Expose in vimdocs
---@private
--- Writes to error buffer. --- Writes to error buffer.
---@param ... string Will be concatenated before being written ---@param ... string Will be concatenated before being written
local function err_message(...) local function err_message(...)
@ -246,7 +245,6 @@ M['textDocument/references'] = function(_, result, ctx, config)
end end
end end
---@private
--- Return a function that converts LSP responses to list items and opens the list --- Return a function that converts LSP responses to list items and opens the list
--- ---
--- The returned function has an optional {config} parameter that accepts a table --- The returned function has an optional {config} parameter that accepts a table
@ -380,7 +378,6 @@ end
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover --see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
M['textDocument/hover'] = M.hover M['textDocument/hover'] = M.hover
---@private
--- Jumps to a location. Used as a handler for multiple LSP methods. --- Jumps to a location. Used as a handler for multiple LSP methods.
---@param _ nil not used ---@param _ nil not used
---@param result (table) result of LSP method; a location or a list of locations. ---@param result (table) result of LSP method; a location or a list of locations.

View File

@ -17,7 +17,6 @@ local namespace = api.nvim_create_namespace('vim_lsp_inlayhint')
local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {}) local augroup = api.nvim_create_augroup('vim_lsp_inlayhint', {})
--- Reset the request debounce timer of a buffer --- Reset the request debounce timer of a buffer
---@private
local function reset_timer(reset_bufnr) local function reset_timer(reset_bufnr)
local timer = bufstates[reset_bufnr].timer local timer = bufstates[reset_bufnr].timer
if timer then if timer then
@ -63,7 +62,6 @@ function M.on_inlayhint(err, result, ctx, _)
end end
local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
---@private
local function pos_to_byte(position) local function pos_to_byte(position)
local col = position.character local col = position.character
if col > 0 then if col > 0 then
@ -89,7 +87,6 @@ function M.on_inlayhint(err, result, ctx, _)
api.nvim__buf_redraw_range(bufnr, 0, -1) api.nvim__buf_redraw_range(bufnr, 0, -1)
end end
---@private
local function resolve_bufnr(bufnr) local function resolve_bufnr(bufnr)
return bufnr > 0 and bufnr or api.nvim_get_current_buf() return bufnr > 0 and bufnr or api.nvim_get_current_buf()
end end
@ -100,7 +97,6 @@ end
--- - bufnr (integer, default: 0): Buffer whose hints to refresh --- - bufnr (integer, default: 0): Buffer whose hints to refresh
--- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer --- - only_visible (boolean, default: false): Whether to only refresh hints for the visible regions of the buffer
--- ---
---@private
local function refresh(opts) local function refresh(opts)
opts = opts or {} opts = opts or {}
local bufnr = resolve_bufnr(opts.bufnr or 0) local bufnr = resolve_bufnr(opts.bufnr or 0)
@ -159,7 +155,6 @@ end
--- Clear inlay hints --- Clear inlay hints
---@param bufnr (integer) Buffer handle, or 0 for current ---@param bufnr (integer) Buffer handle, or 0 for current
---@private
local function clear(bufnr) local function clear(bufnr)
bufnr = resolve_bufnr(bufnr) bufnr = resolve_bufnr(bufnr)
if not bufstates[bufnr] then if not bufstates[bufnr] then
@ -178,7 +173,6 @@ local function clear(bufnr)
api.nvim__buf_redraw_range(bufnr, 0, -1) api.nvim__buf_redraw_range(bufnr, 0, -1)
end end
---@private
local function make_request(request_bufnr) local function make_request(request_bufnr)
reset_timer(request_bufnr) reset_timer(request_bufnr)
refresh({ bufnr = request_bufnr }) refresh({ bufnr = request_bufnr })
@ -186,7 +180,6 @@ end
--- Enable inlay hints for a buffer --- Enable inlay hints for a buffer
---@param bufnr (integer) Buffer handle, or 0 for current ---@param bufnr (integer) Buffer handle, or 0 for current
---@private
local function enable(bufnr) local function enable(bufnr)
bufnr = resolve_bufnr(bufnr) bufnr = resolve_bufnr(bufnr)
local bufstate = bufstates[bufnr] local bufstate = bufstates[bufnr]
@ -228,7 +221,6 @@ end
--- Disable inlay hints for a buffer --- Disable inlay hints for a buffer
---@param bufnr (integer) Buffer handle, or 0 for current ---@param bufnr (integer) Buffer handle, or 0 for current
---@private
local function disable(bufnr) local function disable(bufnr)
bufnr = resolve_bufnr(bufnr) bufnr = resolve_bufnr(bufnr)
if bufstates[bufnr] and bufstates[bufnr].enabled then if bufstates[bufnr] and bufstates[bufnr].enabled then
@ -240,7 +232,6 @@ end
--- Toggle inlay hints for a buffer --- Toggle inlay hints for a buffer
---@param bufnr (integer) Buffer handle, or 0 for current ---@param bufnr (integer) Buffer handle, or 0 for current
---@private
local function toggle(bufnr) local function toggle(bufnr)
bufnr = resolve_bufnr(bufnr) bufnr = resolve_bufnr(bufnr)
local bufstate = bufstates[bufnr] local bufstate = bufstates[bufnr]

View File

@ -2,14 +2,12 @@
local log = {} local log = {}
-- FIXME: DOC --- Log level dictionary with reverse lookup as well.
-- Should be exposed in the vim docs. ---
-- --- Can be used to lookup the number from the name or the name from the number.
-- Log level dictionary with reverse lookup as well. --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
-- --- Level numbers begin with "TRACE" at 0
-- Can be used to lookup the number from the name or the name from the number. --- @nodoc
-- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF"
-- Level numbers begin with "TRACE" at 0
log.levels = vim.deepcopy(vim.log.levels) log.levels = vim.deepcopy(vim.log.levels)
-- Default log level is warn. -- Default log level is warn.
@ -20,7 +18,6 @@ local format_func = function(arg)
end end
do do
---@private
local function notify(msg, level) local function notify(msg, level)
if vim.in_fast_event() then if vim.in_fast_event() then
vim.schedule(function() vim.schedule(function()
@ -32,7 +29,6 @@ do
end end
local path_sep = vim.uv.os_uname().version:match('Windows') and '\\' or '/' local path_sep = vim.uv.os_uname().version:match('Windows') and '\\' or '/'
---@private
local function path_join(...) local function path_join(...)
return table.concat(vim.tbl_flatten({ ... }), path_sep) return table.concat(vim.tbl_flatten({ ... }), path_sep)
end end
@ -50,7 +46,6 @@ do
end end
local logfile, openerr local logfile, openerr
---@private
--- Opens log file. Returns true if file is open, false on error --- Opens log file. Returns true if file is open, false on error
local function open_logfile() local function open_logfile()
-- Try to open file only once -- Try to open file only once

View File

@ -5,7 +5,6 @@ local validate, schedule, schedule_wrap = vim.validate, vim.schedule, vim.schedu
local is_win = uv.os_uname().version:find('Windows') local is_win = uv.os_uname().version:find('Windows')
---@private
--- Checks whether a given path exists and is a directory. --- Checks whether a given path exists and is a directory.
---@param filename (string) path to check ---@param filename (string) path to check
---@return boolean ---@return boolean
@ -14,7 +13,6 @@ local function is_dir(filename)
return stat and stat.type == 'directory' or false return stat and stat.type == 'directory' or false
end end
---@private
--- Embeds the given string into a table and correctly computes `Content-Length`. --- Embeds the given string into a table and correctly computes `Content-Length`.
--- ---
---@param encoded_message (string) ---@param encoded_message (string)
@ -28,7 +26,6 @@ local function format_message_with_content_length(encoded_message)
}) })
end end
---@private
--- Parses an LSP Message's header --- Parses an LSP Message's header
--- ---
---@param header string: The header to parse. ---@param header string: The header to parse.
@ -60,7 +57,6 @@ local header_start_pattern = ('content'):gsub('%w', function(c)
return '[' .. c .. c:upper() .. ']' return '[' .. c .. c:upper() .. ']'
end) end)
---@private
--- The actual workhorse. --- The actual workhorse.
local function request_parser_loop() local function request_parser_loop()
local buffer = '' -- only for header part local buffer = '' -- only for header part
@ -115,8 +111,11 @@ local function request_parser_loop()
end end
end end
local M = {}
--- Mapping of error codes used by the client --- Mapping of error codes used by the client
local client_errors = { --- @nodoc
M.client_errors = {
INVALID_SERVER_MESSAGE = 1, INVALID_SERVER_MESSAGE = 1,
INVALID_SERVER_JSON = 2, INVALID_SERVER_JSON = 2,
NO_RESULT_CALLBACK_FOUND = 3, NO_RESULT_CALLBACK_FOUND = 3,
@ -126,13 +125,13 @@ local client_errors = {
SERVER_RESULT_CALLBACK_ERROR = 7, SERVER_RESULT_CALLBACK_ERROR = 7,
} }
client_errors = vim.tbl_add_reverse_lookup(client_errors) M.client_errors = vim.tbl_add_reverse_lookup(M.client_errors)
--- Constructs an error message from an LSP error object. --- Constructs an error message from an LSP error object.
--- ---
---@param err (table) The error object ---@param err (table) The error object
---@returns (string) The formatted error message ---@returns (string) The formatted error message
local function format_rpc_error(err) function M.format_rpc_error(err)
validate({ validate({
err = { err, 't' }, err = { err, 't' },
}) })
@ -163,7 +162,7 @@ end
---@param code integer RPC error code defined in `vim.lsp.protocol.ErrorCodes` ---@param code integer RPC error code defined in `vim.lsp.protocol.ErrorCodes`
---@param message string|nil arbitrary message to send to server ---@param message string|nil arbitrary message to send to server
---@param data any|nil arbitrary data to send to server ---@param data any|nil arbitrary data to send to server
local function rpc_response_error(code, message, data) function M.rpc_response_error(code, message, data)
-- TODO should this error or just pick a sane error (like InternalError)? -- TODO should this error or just pick a sane error (like InternalError)?
local code_name = assert(protocol.ErrorCodes[code], 'Invalid RPC error code') local code_name = assert(protocol.ErrorCodes[code], 'Invalid RPC error code')
return setmetatable({ return setmetatable({
@ -171,7 +170,7 @@ local function rpc_response_error(code, message, data)
message = message or code_name, message = message or code_name,
data = data, data = data,
}, { }, {
__tostring = format_rpc_error, __tostring = M.format_rpc_error,
}) })
end end
@ -185,6 +184,7 @@ local default_dispatchers = {}
function default_dispatchers.notification(method, params) function default_dispatchers.notification(method, params)
local _ = log.debug() and log.debug('notification', method, params) local _ = log.debug() and log.debug('notification', method, params)
end end
---@private ---@private
--- Default dispatcher for requests sent to an LSP server. --- Default dispatcher for requests sent to an LSP server.
--- ---
@ -194,8 +194,9 @@ end
---@return table `vim.lsp.protocol.ErrorCodes.MethodNotFound` ---@return table `vim.lsp.protocol.ErrorCodes.MethodNotFound`
function default_dispatchers.server_request(method, params) function default_dispatchers.server_request(method, params)
local _ = log.debug() and log.debug('server_request', method, params) local _ = log.debug() and log.debug('server_request', method, params)
return nil, rpc_response_error(protocol.ErrorCodes.MethodNotFound) return nil, M.rpc_response_error(protocol.ErrorCodes.MethodNotFound)
end end
---@private ---@private
--- Default dispatcher for when a client exits. --- Default dispatcher for when a client exits.
--- ---
@ -205,6 +206,7 @@ end
function default_dispatchers.on_exit(code, signal) function default_dispatchers.on_exit(code, signal)
local _ = log.info() and log.info('client_exit', { code = code, signal = signal }) local _ = log.info() and log.info('client_exit', { code = code, signal = signal })
end end
---@private ---@private
--- Default dispatcher for client errors. --- Default dispatcher for client errors.
--- ---
@ -212,11 +214,11 @@ end
---@param err (any): Details about the error ---@param err (any): Details about the error
---any) ---any)
function default_dispatchers.on_error(code, err) function default_dispatchers.on_error(code, err)
local _ = log.error() and log.error('client_error:', client_errors[code], err) local _ = log.error() and log.error('client_error:', M.client_errors[code], err)
end end
---@private ---@private
local function create_read_loop(handle_body, on_no_chunk, on_error) function M.create_read_loop(handle_body, on_no_chunk, on_error)
local parse_chunk = coroutine.wrap(request_parser_loop) local parse_chunk = coroutine.wrap(request_parser_loop)
parse_chunk() parse_chunk()
return function(err, chunk) return function(err, chunk)
@ -329,7 +331,7 @@ end
---@private ---@private
function Client:on_error(errkind, ...) function Client:on_error(errkind, ...)
assert(client_errors[errkind]) assert(M.client_errors[errkind])
-- TODO what to do if this fails? -- TODO what to do if this fails?
pcall(self.dispatchers.on_error, errkind, ...) pcall(self.dispatchers.on_error, errkind, ...)
end end
@ -356,7 +358,7 @@ end
function Client:handle_body(body) function Client:handle_body(body)
local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } }) local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } })
if not ok then if not ok then
self:on_error(client_errors.INVALID_SERVER_JSON, decoded) self:on_error(M.client_errors.INVALID_SERVER_JSON, decoded)
return return
end end
local _ = log.debug() and log.debug('rpc.receive', decoded) local _ = log.debug() and log.debug('rpc.receive', decoded)
@ -369,7 +371,7 @@ function Client:handle_body(body)
coroutine.wrap(function() coroutine.wrap(function()
local status, result local status, result
status, result, err = self:try_call( status, result, err = self:try_call(
client_errors.SERVER_REQUEST_HANDLER_ERROR, M.client_errors.SERVER_REQUEST_HANDLER_ERROR,
self.dispatchers.server_request, self.dispatchers.server_request,
decoded.method, decoded.method,
decoded.params decoded.params
@ -401,7 +403,7 @@ function Client:handle_body(body)
end end
else else
-- On an exception, result will contain the error message. -- On an exception, result will contain the error message.
err = rpc_response_error(protocol.ErrorCodes.InternalError, result) err = M.rpc_response_error(protocol.ErrorCodes.InternalError, result)
result = nil result = nil
end end
self:send_response(decoded.id, err, result) self:send_response(decoded.id, err, result)
@ -454,34 +456,33 @@ function Client:handle_body(body)
}) })
if decoded.error then if decoded.error then
decoded.error = setmetatable(decoded.error, { decoded.error = setmetatable(decoded.error, {
__tostring = format_rpc_error, __tostring = M.format_rpc_error,
}) })
end end
self:try_call( self:try_call(
client_errors.SERVER_RESULT_CALLBACK_ERROR, M.client_errors.SERVER_RESULT_CALLBACK_ERROR,
callback, callback,
decoded.error, decoded.error,
decoded.result decoded.result
) )
else else
self:on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded) self:on_error(M.client_errors.NO_RESULT_CALLBACK_FOUND, decoded)
local _ = log.error() and log.error('No callback found for server response id ' .. result_id) local _ = log.error() and log.error('No callback found for server response id ' .. result_id)
end end
elseif type(decoded.method) == 'string' then elseif type(decoded.method) == 'string' then
-- Notification -- Notification
self:try_call( self:try_call(
client_errors.NOTIFICATION_HANDLER_ERROR, M.client_errors.NOTIFICATION_HANDLER_ERROR,
self.dispatchers.notification, self.dispatchers.notification,
decoded.method, decoded.method,
decoded.params decoded.params
) )
else else
-- Invalid server message -- Invalid server message
self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded) self:on_error(M.client_errors.INVALID_SERVER_MESSAGE, decoded)
end end
end end
---@private
---@return RpcClient ---@return RpcClient
local function new_client(dispatchers, transport) local function new_client(dispatchers, transport)
local state = { local state = {
@ -494,7 +495,6 @@ local function new_client(dispatchers, transport)
return setmetatable(state, { __index = Client }) return setmetatable(state, { __index = Client })
end end
---@private
---@param client RpcClient ---@param client RpcClient
local function public_client(client) local function public_client(client)
local result = {} local result = {}
@ -531,7 +531,6 @@ local function public_client(client)
return result return result
end end
---@private
local function merge_dispatchers(dispatchers) local function merge_dispatchers(dispatchers)
if dispatchers then if dispatchers then
local user_dispatchers = dispatchers local user_dispatchers = dispatchers
@ -565,7 +564,7 @@ end
---@param host string ---@param host string
---@param port integer ---@param port integer
---@return function ---@return function
local function connect(host, port) function M.connect(host, port)
return function(dispatchers) return function(dispatchers)
dispatchers = merge_dispatchers(dispatchers) dispatchers = merge_dispatchers(dispatchers)
local tcp = uv.new_tcp() local tcp = uv.new_tcp()
@ -600,8 +599,8 @@ local function connect(host, port)
local handle_body = function(body) local handle_body = function(body)
client:handle_body(body) client:handle_body(body)
end end
tcp:read_start(create_read_loop(handle_body, transport.terminate, function(read_err) tcp:read_start(M.create_read_loop(handle_body, transport.terminate, function(read_err)
client:on_error(client_errors.READ_ERROR, read_err) client:on_error(M.client_errors.READ_ERROR, read_err)
end)) end))
end) end)
@ -630,7 +629,7 @@ end
--- - `request()` |vim.lsp.rpc.request()| --- - `request()` |vim.lsp.rpc.request()|
--- - `is_closing()` returns a boolean indicating if the RPC is closing. --- - `is_closing()` returns a boolean indicating if the RPC is closing.
--- - `terminate()` terminates the RPC client. --- - `terminate()` terminates the RPC client.
local function start(cmd, cmd_args, dispatchers, extra_spawn_params) function M.start(cmd, cmd_args, dispatchers, extra_spawn_params)
if log.info() then if log.info() then
log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params }) log.info('Starting RPC client', { cmd = cmd, args = cmd_args, extra = extra_spawn_params })
end end
@ -667,8 +666,8 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
client:handle_body(body) client:handle_body(body)
end end
local stdout_handler = create_read_loop(handle_body, nil, function(err) local stdout_handler = M.create_read_loop(handle_body, nil, function(err)
client:on_error(client_errors.READ_ERROR, err) client:on_error(M.client_errors.READ_ERROR, err)
end) end)
local stderr_handler = function(_, chunk) local stderr_handler = function(_, chunk)
@ -714,11 +713,4 @@ local function start(cmd, cmd_args, dispatchers, extra_spawn_params)
return public_client(client) return public_client(client)
end end
return { return M
start = start,
connect = connect,
rpc_response_error = rpc_response_error,
format_rpc_error = format_rpc_error,
client_errors = client_errors,
create_read_loop = create_read_loop,
}

View File

@ -41,8 +41,6 @@ local STHighlighter = { active = {} }
--- ---
--- Return the index i in range such that tokens[j].line < line for all j < i, and --- Return the index i in range such that tokens[j].line < line for all j < i, and
--- tokens[j].line >= line for all j >= i, or return hi if no such index is found. --- tokens[j].line >= line for all j >= i, or return hi if no such index is found.
---
---@private
local function lower_bound(tokens, line, lo, hi) local function lower_bound(tokens, line, lo, hi)
while lo < hi do while lo < hi do
local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2).
@ -59,8 +57,6 @@ end
--- ---
--- Return the index i in range such that tokens[j].line <= line for all j < i, and --- Return the index i in range such that tokens[j].line <= line for all j < i, and
--- tokens[j].line > line for all j >= i, or return hi if no such index is found. --- tokens[j].line > line for all j >= i, or return hi if no such index is found.
---
---@private
local function upper_bound(tokens, line, lo, hi) local function upper_bound(tokens, line, lo, hi)
while lo < hi do while lo < hi do
local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2). local mid = bit.rshift(lo + hi, 1) -- Equivalent to floor((lo + hi) / 2).
@ -75,7 +71,6 @@ end
--- Extracts modifier strings from the encoded number in the token array --- Extracts modifier strings from the encoded number in the token array
--- ---
---@private
---@return table<string, boolean> ---@return table<string, boolean>
local function modifiers_from_number(x, modifiers_table) local function modifiers_from_number(x, modifiers_table)
local modifiers = {} local modifiers = {}
@ -93,7 +88,6 @@ end
--- Converts a raw token list to a list of highlight ranges used by the on_win callback --- Converts a raw token list to a list of highlight ranges used by the on_win callback
--- ---
---@private
---@return STTokenRange[] ---@return STTokenRange[]
local function tokens_to_ranges(data, bufnr, client, request) local function tokens_to_ranges(data, bufnr, client, request)
local legend = client.server_capabilities.semanticTokensProvider.legend local legend = client.server_capabilities.semanticTokensProvider.legend
@ -137,7 +131,6 @@ local function tokens_to_ranges(data, bufnr, client, request)
local token_type = token_types[data[i + 3] + 1] local token_type = token_types[data[i + 3] + 1]
local modifiers = modifiers_from_number(data[i + 4], token_modifiers) local modifiers = modifiers_from_number(data[i + 4], token_modifiers)
---@private
local function _get_byte_pos(col) local function _get_byte_pos(col)
if col > 0 then if col > 0 then
local buf_line = lines[line + 1] or '' local buf_line = lines[line + 1] or ''

View File

@ -48,7 +48,6 @@ local str_utfindex = vim.str_utfindex
local str_utf_start = vim.str_utf_start local str_utf_start = vim.str_utf_start
local str_utf_end = vim.str_utf_end local str_utf_end = vim.str_utf_end
---@private
-- Given a line, byte idx, and offset_encoding convert to the -- Given a line, byte idx, and offset_encoding convert to the
-- utf-8, utf-16, or utf-32 index. -- utf-8, utf-16, or utf-32 index.
---@param line string the line to index into ---@param line string the line to index into
@ -74,7 +73,6 @@ local function byte_to_utf(line, byte, offset_encoding)
return utf_idx + 1 return utf_idx + 1
end end
---@private
local function compute_line_length(line, offset_encoding) local function compute_line_length(line, offset_encoding)
local length local length
local _ local _
@ -88,7 +86,6 @@ local function compute_line_length(line, offset_encoding)
return length return length
end end
---@private
-- Given a line, byte idx, alignment, and offset_encoding convert to the aligned -- Given a line, byte idx, alignment, and offset_encoding convert to the aligned
-- utf-8 index and either the utf-16, or utf-32 index. -- utf-8 index and either the utf-16, or utf-32 index.
---@param line string the line to index into ---@param line string the line to index into
@ -122,7 +119,6 @@ local function align_end_position(line, byte, offset_encoding)
return byte, char return byte, char
end end
---@private
--- Finds the first line, byte, and char index of the difference between the previous and current lines buffer normalized to the previous codepoint. --- Finds the first line, byte, and char index of the difference between the previous and current lines buffer normalized to the previous codepoint.
---@param prev_lines table list of lines from previous buffer ---@param prev_lines table list of lines from previous buffer
---@param curr_lines table list of lines from current buffer ---@param curr_lines table list of lines from current buffer
@ -198,7 +194,6 @@ local function compute_start_range(
return { line_idx = firstline, byte_idx = byte_idx, char_idx = char_idx } return { line_idx = firstline, byte_idx = byte_idx, char_idx = char_idx }
end end
---@private
--- Finds the last line and byte index of the differences between prev and current buffer. --- Finds the last line and byte index of the differences between prev and current buffer.
--- Normalized to the next codepoint. --- Normalized to the next codepoint.
--- prev_end_range is the text range sent to the server representing the changed region. --- prev_end_range is the text range sent to the server representing the changed region.
@ -307,7 +302,6 @@ local function compute_end_range(
return prev_end_range, curr_end_range return prev_end_range, curr_end_range
end end
---@private
--- Get the text of the range defined by start and end line/column --- Get the text of the range defined by start and end line/column
---@param lines table list of lines ---@param lines table list of lines
---@param start_range table table returned by first_difference ---@param start_range table table returned by first_difference
@ -343,7 +337,6 @@ local function extract_text(lines, start_range, end_range, line_ending)
end end
end end
---@private
-- rangelength depends on the offset encoding -- rangelength depends on the offset encoding
-- bytes for utf-8 (clangd with extension) -- bytes for utf-8 (clangd with extension)
-- codepoints for utf-16 -- codepoints for utf-16

View File

@ -1,7 +1,6 @@
local lsp = vim.lsp local lsp = vim.lsp
local util = lsp.util local util = lsp.util
---@private
local function mk_tag_item(name, range, uri, offset_encoding) local function mk_tag_item(name, range, uri, offset_encoding)
local bufnr = vim.uri_to_bufnr(uri) local bufnr = vim.uri_to_bufnr(uri)
-- This is get_line_byte_from_position is 0-indexed, call cursor expects a 1-indexed position -- This is get_line_byte_from_position is 0-indexed, call cursor expects a 1-indexed position
@ -13,7 +12,6 @@ local function mk_tag_item(name, range, uri, offset_encoding)
} }
end end
---@private
local function query_definition(pattern) local function query_definition(pattern)
local params = util.make_position_params() local params = util.make_position_params()
local results_by_client, err = lsp.buf_request_sync(0, 'textDocument/definition', params, 1000) local results_by_client, err = lsp.buf_request_sync(0, 'textDocument/definition', params, 1000)
@ -42,7 +40,6 @@ local function query_definition(pattern)
return results return results
end end
---@private
local function query_workspace_symbols(pattern) local function query_workspace_symbols(pattern)
local results_by_client, err = local results_by_client, err =
lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000) lsp.buf_request_sync(0, 'workspace/symbol', { query = pattern }, 1000)
@ -62,7 +59,6 @@ local function query_workspace_symbols(pattern)
return results return results
end end
---@private
local function tagfunc(pattern, flags) local function tagfunc(pattern, flags)
local matches local matches
if string.match(flags, 'c') then if string.match(flags, 'c') then

View File

@ -22,7 +22,6 @@ local default_border = {
{ ' ', 'NormalFloat' }, { ' ', 'NormalFloat' },
} }
---@private
--- Check the border given by opts or the default border for the additional --- Check the border given by opts or the default border for the additional
--- size it adds to a float. --- size it adds to a float.
---@param opts table optional options for the floating window ---@param opts table optional options for the floating window
@ -60,7 +59,6 @@ local function get_border_size(opts)
) )
) )
end end
---@private
local function border_width(id) local function border_width(id)
id = (id - 1) % #border + 1 id = (id - 1) % #border + 1
if type(border[id]) == 'table' then if type(border[id]) == 'table' then
@ -77,7 +75,6 @@ local function get_border_size(opts)
) )
) )
end end
---@private
local function border_height(id) local function border_height(id)
id = (id - 1) % #border + 1 id = (id - 1) % #border + 1
if type(border[id]) == 'table' then if type(border[id]) == 'table' then
@ -103,13 +100,11 @@ local function get_border_size(opts)
return { height = height, width = width } return { height = height, width = width }
end end
---@private
local function split_lines(value) local function split_lines(value)
value = string.gsub(value, '\r\n?', '\n') value = string.gsub(value, '\r\n?', '\n')
return split(value, '\n', { plain = true }) return split(value, '\n', { plain = true })
end end
---@private
local function create_window_without_focus() local function create_window_without_focus()
local prev = vim.api.nvim_get_current_win() local prev = vim.api.nvim_get_current_win()
vim.cmd.new() vim.cmd.new()
@ -219,7 +214,6 @@ function M.set_lines(lines, A, B, new_lines)
return lines return lines
end end
---@private
local function sort_by_key(fn) local function sort_by_key(fn)
return function(a, b) return function(a, b)
local ka, kb = fn(a), fn(b) local ka, kb = fn(a), fn(b)
@ -234,7 +228,6 @@ local function sort_by_key(fn)
end end
end end
---@private
--- Gets the zero-indexed lines from the given buffer. --- Gets the zero-indexed lines from the given buffer.
--- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events.
--- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI.
@ -250,7 +243,6 @@ local function get_lines(bufnr, rows)
bufnr = api.nvim_get_current_buf() bufnr = api.nvim_get_current_buf()
end end
---@private
local function buf_lines() local function buf_lines()
local lines = {} local lines = {}
for _, row in ipairs(rows) do for _, row in ipairs(rows) do
@ -316,7 +308,6 @@ local function get_lines(bufnr, rows)
return lines return lines
end end
---@private
--- Gets the zero-indexed line from the given buffer. --- Gets the zero-indexed line from the given buffer.
--- Works on unloaded buffers by reading the file using libuv to bypass buf reading events. --- Works on unloaded buffers by reading the file using libuv to bypass buf reading events.
--- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI. --- Falls back to loading the buffer and nvim_buf_get_lines for buffers with non-file URI.
@ -328,7 +319,6 @@ local function get_line(bufnr, row)
return get_lines(bufnr, { row })[row] return get_lines(bufnr, { row })[row]
end end
---@private
--- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position --- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position
--- Returns a zero-indexed column, since set_lines() does the conversion to --- Returns a zero-indexed column, since set_lines() does the conversion to
---@param offset_encoding string|nil utf-8|utf-16|utf-32 ---@param offset_encoding string|nil utf-8|utf-16|utf-32
@ -670,7 +660,6 @@ function M.parse_snippet(input)
return parsed return parsed
end end
---@private
--- Sorts by CompletionItem.sortText. --- Sorts by CompletionItem.sortText.
--- ---
--see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion --see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
@ -680,7 +669,6 @@ local function sort_completion_items(items)
end) end)
end end
---@private
--- Returns text that should be inserted when selecting completion item. The --- Returns text that should be inserted when selecting completion item. The
--- precedence is as follows: textEdit.newText > insertText > label --- precedence is as follows: textEdit.newText > insertText > label
--see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion --see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
@ -703,7 +691,6 @@ local function get_completion_word(item)
return item.label return item.label
end end
---@private
--- Some language servers return complementary candidates whose prefixes do not --- Some language servers return complementary candidates whose prefixes do not
--- match are also returned. So we exclude completion candidates whose prefix --- match are also returned. So we exclude completion candidates whose prefix
--- does not match. --- does not match.
@ -784,7 +771,6 @@ function M.text_document_completion_list_to_complete_items(result, prefix)
return matches return matches
end end
---@private
--- Like vim.fn.bufwinid except it works across tabpages. --- Like vim.fn.bufwinid except it works across tabpages.
local function bufwinid(bufnr) local function bufwinid(bufnr)
for _, win in ipairs(api.nvim_list_wins()) do for _, win in ipairs(api.nvim_list_wins()) do
@ -795,7 +781,6 @@ local function bufwinid(bufnr)
end end
--- Get list of buffers for a directory --- Get list of buffers for a directory
---@private
local function get_dir_bufs(path) local function get_dir_bufs(path)
path = path:gsub('([^%w])', '%%%1') path = path:gsub('([^%w])', '%%%1')
local buffers = {} local buffers = {}
@ -855,7 +840,6 @@ function M.rename(old_fname, new_fname, opts)
end end
end end
---@private
local function create_file(change) local function create_file(change)
local opts = change.options or {} local opts = change.options or {}
-- from spec: Overwrite wins over `ignoreIfExists` -- from spec: Overwrite wins over `ignoreIfExists`
@ -870,7 +854,6 @@ local function create_file(change)
vim.fn.bufadd(fname) vim.fn.bufadd(fname)
end end
---@private
local function delete_file(change) local function delete_file(change)
local opts = change.options or {} local opts = change.options or {}
local fname = vim.uri_to_fname(change.uri) local fname = vim.uri_to_fname(change.uri)
@ -1266,7 +1249,6 @@ function M.preview_location(location, opts)
return M.open_floating_preview(contents, syntax, opts) return M.open_floating_preview(contents, syntax, opts)
end end
---@private
local function find_window_by_var(name, value) local function find_window_by_var(name, value)
for _, win in ipairs(api.nvim_list_wins()) do for _, win in ipairs(api.nvim_list_wins()) do
if npcall(api.nvim_win_get_var, win, name) == value then if npcall(api.nvim_win_get_var, win, name) == value then
@ -1305,7 +1287,6 @@ end
--- Generates a table mapping markdown code block lang to vim syntax, --- Generates a table mapping markdown code block lang to vim syntax,
--- based on g:markdown_fenced_languages --- based on g:markdown_fenced_languages
---@return table table of lang -> syntax mappings ---@return table table of lang -> syntax mappings
---@private
local function get_markdown_fences() local function get_markdown_fences()
local fences = {} local fences = {}
for _, fence in pairs(vim.g.markdown_fenced_languages or {}) do for _, fence in pairs(vim.g.markdown_fenced_languages or {}) do
@ -1460,7 +1441,6 @@ function M.stylize_markdown(bufnr, contents, opts)
api.nvim_buf_set_lines(bufnr, 0, -1, false, stripped) api.nvim_buf_set_lines(bufnr, 0, -1, false, stripped)
local idx = 1 local idx = 1
---@private
-- keep track of syntaxes we already included. -- keep track of syntaxes we already included.
-- no need to include the same syntax more than once -- no need to include the same syntax more than once
local langs = {} local langs = {}
@ -1521,7 +1501,6 @@ function M.stylize_markdown(bufnr, contents, opts)
return stripped return stripped
end end
---@private
--- Closes the preview window --- Closes the preview window
--- ---
---@param winnr integer window id of preview window ---@param winnr integer window id of preview window
@ -1539,7 +1518,6 @@ local function close_preview_window(winnr, bufnrs)
end) end)
end end
---@private
--- Creates autocommands to close a preview window when events happen. --- Creates autocommands to close a preview window when events happen.
--- ---
---@param events table list of events ---@param events table list of events
@ -1905,7 +1883,6 @@ end
--- ---
---@param symbols table DocumentSymbol[] or SymbolInformation[] ---@param symbols table DocumentSymbol[] or SymbolInformation[]
function M.symbols_to_items(symbols, bufnr) function M.symbols_to_items(symbols, bufnr)
---@private
local function _symbols_to_items(_symbols, _items, _bufnr) local function _symbols_to_items(_symbols, _items, _bufnr)
for _, symbol in ipairs(_symbols) do for _, symbol in ipairs(_symbols) do
if symbol.location then -- SymbolInformation type if symbol.location then -- SymbolInformation type
@ -1991,7 +1968,6 @@ function M.try_trim_markdown_code_blocks(lines)
return 'markdown' return 'markdown'
end end
---@private
---@param window integer|nil: window handle or 0 for current, defaults to current ---@param window integer|nil: window handle or 0 for current, defaults to current
---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window` ---@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to `offset_encoding` of first client of buffer of `window`
local function make_position_param(window, offset_encoding) local function make_position_param(window, offset_encoding)
@ -2209,6 +2185,7 @@ end
M._get_line_byte_from_position = get_line_byte_from_position M._get_line_byte_from_position = get_line_byte_from_position
---@nodoc
M.buf_versions = {} M.buf_versions = {}
return M return M

View File

@ -1,6 +1,5 @@
local M = {} local M = {}
---@private
--- Reads trust database from $XDG_STATE_HOME/nvim/trust. --- Reads trust database from $XDG_STATE_HOME/nvim/trust.
--- ---
---@return (table) Contents of trust database, if it exists. Empty table otherwise. ---@return (table) Contents of trust database, if it exists. Empty table otherwise.
@ -22,7 +21,6 @@ local function read_trust()
return trust return trust
end end
---@private
--- Writes provided {trust} table to trust database at --- Writes provided {trust} table to trust database at
--- $XDG_STATE_HOME/nvim/trust. --- $XDG_STATE_HOME/nvim/trust.
--- ---

View File

@ -8,21 +8,12 @@
vim = vim or {} vim = vim or {}
--- Returns a deep copy of the given object. Non-table objects are copied as
--- in a typical Lua assignment, whereas table objects are copied recursively.
--- Functions are naively copied, so functions in the copied table point to the
--- same functions as those in the input table. Userdata and threads are not
--- copied and will throw an error.
---
---@generic T: table
---@param orig T Table to copy
---@return T Table of copied keys and (nested) values.
function vim.deepcopy(orig) end -- luacheck: no unused
vim.deepcopy = (function()
local function _id(v) local function _id(v)
return v return v
end end
local deepcopy
local deepcopy_funcs = { local deepcopy_funcs = {
table = function(orig, cache) table = function(orig, cache)
if cache[orig] then if cache[orig] then
@ -33,7 +24,7 @@ vim.deepcopy = (function()
cache[orig] = copy cache[orig] = copy
local mt = getmetatable(orig) local mt = getmetatable(orig)
for k, v in pairs(orig) do for k, v in pairs(orig) do
copy[vim.deepcopy(k, cache)] = vim.deepcopy(v, cache) copy[deepcopy(k, cache)] = deepcopy(v, cache)
end end
return setmetatable(copy, mt) return setmetatable(copy, mt)
end, end,
@ -44,10 +35,10 @@ vim.deepcopy = (function()
['function'] = _id, ['function'] = _id,
} }
return function(orig, cache) deepcopy = function(orig, _cache)
local f = deepcopy_funcs[type(orig)] local f = deepcopy_funcs[type(orig)]
if f then if f then
return f(orig, cache or {}) return f(orig, _cache or {})
else else
if type(orig) == 'userdata' and orig == vim.NIL then if type(orig) == 'userdata' and orig == vim.NIL then
return vim.NIL return vim.NIL
@ -55,7 +46,19 @@ vim.deepcopy = (function()
error('Cannot deepcopy object of type ' .. type(orig)) error('Cannot deepcopy object of type ' .. type(orig))
end end
end end
end)()
--- Returns a deep copy of the given object. Non-table objects are copied as
--- in a typical Lua assignment, whereas table objects are copied recursively.
--- Functions are naively copied, so functions in the copied table point to the
--- same functions as those in the input table. Userdata and threads are not
--- copied and will throw an error.
---
---@generic T: table
---@param orig T Table to copy
---@return T Table of copied keys and (nested) values.
function vim.deepcopy(orig)
return deepcopy(orig)
end
--- Splits a string at each instance of a separator. --- Splits a string at each instance of a separator.
--- ---
@ -318,7 +321,6 @@ function vim.tbl_isempty(t)
end end
--- We only merge empty tables or tables that are not an array (indexed by integers) --- We only merge empty tables or tables that are not an array (indexed by integers)
---@private
local function can_merge(v) local function can_merge(v)
return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_isarray(v)) return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_isarray(v))
end end
@ -770,7 +772,6 @@ do
return type(val) == t or (t == 'callable' and vim.is_callable(val)) return type(val) == t or (t == 'callable' and vim.is_callable(val))
end end
---@private
local function is_valid(opt) local function is_valid(opt)
if type(opt) ~= 'table' then if type(opt) ~= 'table' then
return false, string.format('opt: expected table, got %s', type(opt)) return false, string.format('opt: expected table, got %s', type(opt))

View File

@ -39,7 +39,10 @@ local M = setmetatable({}, {
end, end,
}) })
--- @nodoc
M.language_version = vim._ts_get_language_version() M.language_version = vim._ts_get_language_version()
--- @nodoc
M.minimum_language_version = vim._ts_get_minimum_language_version() M.minimum_language_version = vim._ts_get_minimum_language_version()
--- Creates a new parser --- Creates a new parser
@ -60,12 +63,10 @@ function M._create_parser(bufnr, lang, opts)
local self = LanguageTree.new(bufnr, lang, opts) local self = LanguageTree.new(bufnr, lang, opts)
---@private
local function bytes_cb(_, ...) local function bytes_cb(_, ...)
self:_on_bytes(...) self:_on_bytes(...)
end end
---@private
local function detach_cb(_, ...) local function detach_cb(_, ...)
if parsers[bufnr] == self then if parsers[bufnr] == self then
parsers[bufnr] = nil parsers[bufnr] = nil
@ -73,7 +74,6 @@ function M._create_parser(bufnr, lang, opts)
self:_on_detach(...) self:_on_detach(...)
end end
---@private
local function reload_cb(_) local function reload_cb(_)
self:_on_reload() self:_on_reload()
end end
@ -91,7 +91,6 @@ function M._create_parser(bufnr, lang, opts)
return self return self
end end
--- @private
local function valid_lang(lang) local function valid_lang(lang)
return lang and lang ~= '' return lang and lang ~= ''
end end
@ -205,7 +204,6 @@ function M.get_range(node, source, metadata)
return { node:range(true) } return { node:range(true) }
end end
---@private
---@param buf integer ---@param buf integer
---@param range Range ---@param range Range
---@returns string ---@returns string

View File

@ -42,7 +42,6 @@ local TSTreeView = {}
---@param injections table<integer,TSP.Node> Mapping of node ids to root nodes of injected language trees (see ---@param injections table<integer,TSP.Node> Mapping of node ids to root nodes of injected language trees (see
--- explanation above) --- explanation above)
---@param tree TSP.Node[] Output table containing a list of tables each representing a node in the tree ---@param tree TSP.Node[] Output table containing a list of tables each representing a node in the tree
---@private
local function traverse(node, depth, lang, injections, tree) local function traverse(node, depth, lang, injections, tree)
local injection = injections[node:id()] local injection = injections[node:id()]
if injection then if injection then
@ -141,7 +140,6 @@ end
local decor_ns = api.nvim_create_namespace('ts.dev') local decor_ns = api.nvim_create_namespace('ts.dev')
---@private
---@param lnum integer ---@param lnum integer
---@param col integer ---@param col integer
---@param end_lnum integer ---@param end_lnum integer

View File

@ -17,6 +17,7 @@ local query = vim.treesitter.query
local TSHighlighter = rawget(vim.treesitter, 'TSHighlighter') or {} local TSHighlighter = rawget(vim.treesitter, 'TSHighlighter') or {}
TSHighlighter.__index = TSHighlighter TSHighlighter.__index = TSHighlighter
--- @nodoc
TSHighlighter.active = TSHighlighter.active or {} TSHighlighter.active = TSHighlighter.active or {}
---@class TSHighlighterQuery ---@class TSHighlighterQuery
@ -205,7 +206,6 @@ function TSHighlighter:get_query(lang)
return self._queries[lang] return self._queries[lang]
end end
---@private
---@param self TSHighlighter ---@param self TSHighlighter
---@param buf integer ---@param buf integer
---@param line integer ---@param line integer

View File

@ -104,7 +104,6 @@ function M.add(lang, opts)
vim._ts_add_language(path, lang, symbol_name) vim._ts_add_language(path, lang, symbol_name)
end end
--- @private
--- @param x string|string[] --- @param x string|string[]
--- @return string[] --- @return string[]
local function ensure_list(x) local function ensure_list(x)

View File

@ -164,7 +164,6 @@ function LanguageTree:_set_logger()
self._parser:_set_logger(log_lex, log_parse, self._logger) self._parser:_set_logger(log_lex, log_parse, self._logger)
end end
---@private
---Measure execution time of a function ---Measure execution time of a function
---@generic R1, R2, R3 ---@generic R1, R2, R3
---@param f fun(): R1, R2, R2 ---@param f fun(): R1, R2, R2
@ -444,7 +443,6 @@ function LanguageTree:destroy()
end end
end end
---@private
---@param region Range6[] ---@param region Range6[]
local function region_tostr(region) local function region_tostr(region)
if #region == 0 then if #region == 0 then
@ -560,7 +558,6 @@ function LanguageTree:included_regions()
return regions return regions
end end
---@private
---@param node TSNode ---@param node TSNode
---@param source string|integer ---@param source string|integer
---@param metadata TSMetadata ---@param metadata TSMetadata
@ -600,7 +597,6 @@ end
---@alias TSInjection table<string,table<integer,TSInjectionElem>> ---@alias TSInjection table<string,table<integer,TSInjectionElem>>
---@private
---@param t table<integer,TSInjection> ---@param t table<integer,TSInjection>
---@param tree_index integer ---@param tree_index integer
---@param pattern integer ---@param pattern integer
@ -963,7 +959,6 @@ function LanguageTree:register_cbs(cbs, recursive)
end end
end end
---@private
---@param tree TSTree ---@param tree TSTree
---@param range Range ---@param range Range
---@return boolean ---@return boolean

View File

@ -15,7 +15,6 @@ Query.__index = Query
---@class TSQueryModule ---@class TSQueryModule
local M = {} local M = {}
---@private
---@param files string[] ---@param files string[]
---@return string[] ---@return string[]
local function dedupe_files(files) local function dedupe_files(files)
@ -33,7 +32,6 @@ local function dedupe_files(files)
return result return result
end end
---@private
local function safe_read(filename, read_quantifier) local function safe_read(filename, read_quantifier)
local file, err = io.open(filename, 'r') local file, err = io.open(filename, 'r')
if not file then if not file then
@ -44,7 +42,6 @@ local function safe_read(filename, read_quantifier)
return content return content
end end
---@private
--- Adds {ilang} to {base_langs}, only if {ilang} is different than {lang} --- Adds {ilang} to {base_langs}, only if {ilang} is different than {lang}
--- ---
---@return boolean true If lang == ilang ---@return boolean true If lang == ilang
@ -153,7 +150,6 @@ function M.get_files(lang, query_name, is_included)
return query_files return query_files
end end
---@private
---@param filenames string[] ---@param filenames string[]
---@return string ---@return string
local function read_query_files(filenames) local function read_query_files(filenames)
@ -335,7 +331,6 @@ local predicate_handlers = {
['match?'] = (function() ['match?'] = (function()
local magic_prefixes = { ['\\v'] = true, ['\\m'] = true, ['\\M'] = true, ['\\V'] = true } local magic_prefixes = { ['\\v'] = true, ['\\m'] = true, ['\\M'] = true, ['\\V'] = true }
---@private
local function check_magic(str) local function check_magic(str)
if string.len(str) < 2 or magic_prefixes[string.sub(str, 1, 2)] then if string.len(str) < 2 or magic_prefixes[string.sub(str, 1, 2)] then
return str return str
@ -624,12 +619,10 @@ function M.list_predicates()
return vim.tbl_keys(predicate_handlers) return vim.tbl_keys(predicate_handlers)
end end
---@private
local function xor(x, y) local function xor(x, y)
return (x or y) and not (x and y) return (x or y) and not (x and y)
end end
---@private
local function is_directive(name) local function is_directive(name)
return string.sub(name, -1) == '!' return string.sub(name, -1) == '!'
end end
@ -700,7 +693,6 @@ end
--- Returns the start and stop value if set else the node's range. --- Returns the start and stop value if set else the node's range.
-- When the node's range is used, the stop is incremented by 1 -- When the node's range is used, the stop is incremented by 1
-- to make the search inclusive. -- to make the search inclusive.
---@private
---@param start integer ---@param start integer
---@param stop integer ---@param stop integer
---@param node TSNode ---@param node TSNode
@ -750,7 +742,6 @@ function Query:iter_captures(node, source, start, stop)
start, stop = value_or_node_range(start, stop, node) start, stop = value_or_node_range(start, stop, node)
local raw_iter = node:_rawquery(self.query, true, start, stop) local raw_iter = node:_rawquery(self.query, true, start, stop)
---@private
local function iter() local function iter()
local capture, captured_node, match = raw_iter() local capture, captured_node, match = raw_iter()
local metadata = {} local metadata = {}

View File

@ -8,7 +8,6 @@ do
local schar = string.char local schar = string.char
--- Convert hex to char --- Convert hex to char
---@private
local function hex_to_char(hex) local function hex_to_char(hex)
return schar(tonumber(hex, 16)) return schar(tonumber(hex, 16))
end end
@ -33,7 +32,6 @@ do
local sbyte = string.byte local sbyte = string.byte
local tohex = require('bit').tohex local tohex = require('bit').tohex
---@private
local function percent_encode_char(char) local function percent_encode_char(char)
return '%' .. tohex(sbyte(char), 2) return '%' .. tohex(sbyte(char), 2)
end end
@ -46,15 +44,16 @@ do
end end
end end
---@private
local function is_windows_file_uri(uri) local function is_windows_file_uri(uri)
return uri:match('^file:/+[a-zA-Z]:') ~= nil return uri:match('^file:/+[a-zA-Z]:') ~= nil
end end
local M = {}
--- Get a URI from a file path. --- Get a URI from a file path.
---@param path string Path to file ---@param path string Path to file
---@return string URI ---@return string URI
local function uri_from_fname(path) function M.uri_from_fname(path)
local volume_path, fname = path:match('^([a-zA-Z]:)(.*)') local volume_path, fname = path:match('^([a-zA-Z]:)(.*)')
local is_windows = volume_path ~= nil local is_windows = volume_path ~= nil
if is_windows then if is_windows then
@ -76,7 +75,7 @@ local WINDOWS_URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):[a-zA-Z]:.*'
--- Get a URI from a bufnr --- Get a URI from a bufnr
---@param bufnr integer ---@param bufnr integer
---@return string URI ---@return string URI
local function uri_from_bufnr(bufnr) function M.uri_from_bufnr(bufnr)
local fname = vim.api.nvim_buf_get_name(bufnr) local fname = vim.api.nvim_buf_get_name(bufnr)
local volume_path = fname:match('^([a-zA-Z]:).*') local volume_path = fname:match('^([a-zA-Z]:).*')
local is_windows = volume_path ~= nil local is_windows = volume_path ~= nil
@ -90,14 +89,14 @@ local function uri_from_bufnr(bufnr)
if scheme then if scheme then
return fname return fname
else else
return uri_from_fname(fname) return M.uri_from_fname(fname)
end end
end end
--- Get a filename from a URI --- Get a filename from a URI
---@param uri string ---@param uri string
---@return string filename or unchanged URI for non-file URIs ---@return string filename or unchanged URI for non-file URIs
local function uri_to_fname(uri) function M.uri_to_fname(uri)
local scheme = assert(uri:match(URI_SCHEME_PATTERN), 'URI must contain a scheme: ' .. uri) local scheme = assert(uri:match(URI_SCHEME_PATTERN), 'URI must contain a scheme: ' .. uri)
if scheme ~= 'file' then if scheme ~= 'file' then
return uri return uri
@ -118,13 +117,8 @@ end
-- --
---@param uri string ---@param uri string
---@return integer bufnr ---@return integer bufnr
local function uri_to_bufnr(uri) function M.uri_to_bufnr(uri)
return vim.fn.bufadd(uri_to_fname(uri)) return vim.fn.bufadd(M.uri_to_fname(uri))
end end
return { return M
uri_from_fname = uri_from_fname,
uri_from_bufnr = uri_from_bufnr,
uri_to_fname = uri_to_fname,
uri_to_bufnr = uri_to_bufnr,
}

View File

@ -65,8 +65,6 @@ local M = {}
local Version = {} local Version = {}
Version.__index = Version Version.__index = Version
--- @private
---
--- Compares prerelease strings: per semver, number parts must be must be treated as numbers: --- Compares prerelease strings: per semver, number parts must be must be treated as numbers:
--- "pre1.10" is greater than "pre1.2". https://semver.org/#spec-item-11 --- "pre1.10" is greater than "pre1.2". https://semver.org/#spec-item-11
local function cmp_prerel(prerel1, prerel2) local function cmp_prerel(prerel1, prerel2)
@ -332,7 +330,6 @@ function M.range(spec) -- Adapted from https://github.com/folke/lazy.nvim
end end
end end
---@private
---@param v string|Version ---@param v string|Version
---@return string ---@return string
local function create_err_msg(v) local function create_err_msg(v)

View File

@ -135,7 +135,7 @@ CONFIG = {
# Section helptag. # Section helptag.
'helptag_fmt': lambda name: f'*api-{name.lower()}*', 'helptag_fmt': lambda name: f'*api-{name.lower()}*',
# Per-function helptag. # Per-function helptag.
'fn_helptag_fmt': lambda fstem, name: f'*{name}()*', 'fn_helptag_fmt': lambda fstem, name, istbl: f'*{name}()*',
# Module name overrides (for Lua). # Module name overrides (for Lua).
'module_override': {}, 'module_override': {},
# Append the docs for these modules, do not start a new section. # Append the docs for these modules, do not start a new section.
@ -193,6 +193,7 @@ CONFIG = {
'fn_name_fmt': lambda fstem, name: ( 'fn_name_fmt': lambda fstem, name: (
name if fstem in [ 'vim.iter' ] else name if fstem in [ 'vim.iter' ] else
f'vim.{name}' if fstem in [ '_editor', 'vim.regex'] else f'vim.{name}' if fstem in [ '_editor', 'vim.regex'] else
f'vim.{name}' if fstem == '_options' and not name[0].isupper() else
f'{fstem}.{name}' if fstem.startswith('vim') else f'{fstem}.{name}' if fstem.startswith('vim') else
name name
), ),
@ -210,14 +211,15 @@ CONFIG = {
'*lua-vim*' if name.lower() == '_editor' else '*lua-vim*' if name.lower() == '_editor' else
'*lua-vimscript*' if name.lower() == '_options' else '*lua-vimscript*' if name.lower() == '_options' else
f'*vim.{name.lower()}*'), f'*vim.{name.lower()}*'),
'fn_helptag_fmt': lambda fstem, name: ( 'fn_helptag_fmt': lambda fstem, name, istbl: (
f'*vim.opt:{name.split(":")[-1]}()*' if ':' in name and name.startswith('Option') else f'*vim.opt:{name.split(":")[-1]}()*' if ':' in name and name.startswith('Option') else
# Exclude fstem for methods # Exclude fstem for methods
f'*{name}()*' if ':' in name else f'*{name}()*' if ':' in name else
f'*vim.{name}()*' if fstem.lower() == '_editor' else f'*vim.{name}()*' if fstem.lower() == '_editor' else
f'*vim.{name}*' if fstem.lower() == '_options' and istbl else
# Prevents vim.regex.regex # Prevents vim.regex.regex
f'*{fstem}()*' if fstem.endswith('.' + name) else f'*{fstem}()*' if fstem.endswith('.' + name) else
f'*{fstem}.{name}()*' f'*{fstem}.{name}{"" if istbl else "()"}*'
), ),
'module_override': { 'module_override': {
# `shared` functions are exposed on the `vim` module. # `shared` functions are exposed on the `vim` module.
@ -275,14 +277,11 @@ CONFIG = {
'*lsp-core*' '*lsp-core*'
if name.lower() == 'lsp' if name.lower() == 'lsp'
else f'*lsp-{name.lower()}*'), else f'*lsp-{name.lower()}*'),
'fn_helptag_fmt': lambda fstem, name: ( 'fn_helptag_fmt': lambda fstem, name, istbl: (
f'*vim.lsp.{name}()*' f'*vim.lsp.{name}{"" if istbl else "()"}*' if fstem == 'lsp' and name != 'client' else
if fstem == 'lsp' and name != 'client'
else (
'*vim.lsp.client*'
# HACK. TODO(justinmk): class/structure support in lua2dox # HACK. TODO(justinmk): class/structure support in lua2dox
if 'lsp.client' == f'{fstem}.{name}' '*vim.lsp.client*' if 'lsp.client' == f'{fstem}.{name}' else
else f'*vim.lsp.{fstem}.{name}()*')), f'*vim.lsp.{fstem}.{name}{"" if istbl else "()"}*'),
'module_override': {}, 'module_override': {},
'append_only': [], 'append_only': [],
}, },
@ -295,10 +294,11 @@ CONFIG = {
'files': ['runtime/lua/vim/diagnostic.lua'], 'files': ['runtime/lua/vim/diagnostic.lua'],
'file_patterns': '*.lua', 'file_patterns': '*.lua',
'fn_name_prefix': '', 'fn_name_prefix': '',
'include_tables': False,
'section_name': {'diagnostic.lua': 'diagnostic'}, 'section_name': {'diagnostic.lua': 'diagnostic'},
'section_fmt': lambda _: 'Lua module: vim.diagnostic', 'section_fmt': lambda _: 'Lua module: vim.diagnostic',
'helptag_fmt': lambda _: '*diagnostic-api*', 'helptag_fmt': lambda _: '*diagnostic-api*',
'fn_helptag_fmt': lambda fstem, name: f'*vim.{fstem}.{name}()*', 'fn_helptag_fmt': lambda fstem, name, istbl: f'*vim.{fstem}.{name}{"" if istbl else "()"}*',
'module_override': {}, 'module_override': {},
'append_only': [], 'append_only': [],
}, },
@ -328,7 +328,7 @@ CONFIG = {
'*lua-treesitter-core*' '*lua-treesitter-core*'
if name.lower() == 'treesitter' if name.lower() == 'treesitter'
else f'*lua-treesitter-{name.lower()}*'), else f'*lua-treesitter-{name.lower()}*'),
'fn_helptag_fmt': lambda fstem, name: ( 'fn_helptag_fmt': lambda fstem, name, istbl: (
f'*vim.{fstem}.{name}()*' f'*vim.{fstem}.{name}()*'
if fstem == 'treesitter' if fstem == 'treesitter'
else f'*{name}()*' else f'*{name}()*'
@ -842,6 +842,13 @@ def extract_from_xml(filename, target, width, fmt_vimhelp):
if return_type == '': if return_type == '':
continue continue
if 'local_function' in return_type: # Special from lua2dox.lua.
continue
istbl = return_type.startswith('table') # Special from lua2dox.lua.
if istbl and not CONFIG[target].get('include_tables', True):
continue
if return_type.startswith(('ArrayOf', 'DictionaryOf')): if return_type.startswith(('ArrayOf', 'DictionaryOf')):
parts = return_type.strip('_').split('_') parts = return_type.strip('_').split('_')
return_type = '{}({})'.format(parts[0], ', '.join(parts[1:])) return_type = '{}({})'.format(parts[0], ', '.join(parts[1:]))
@ -904,15 +911,20 @@ def extract_from_xml(filename, target, width, fmt_vimhelp):
if '.' in compoundname: if '.' in compoundname:
fstem = compoundname.split('.')[0] fstem = compoundname.split('.')[0]
fstem = CONFIG[target]['module_override'].get(fstem, fstem) fstem = CONFIG[target]['module_override'].get(fstem, fstem)
vimtag = CONFIG[target]['fn_helptag_fmt'](fstem, name) vimtag = CONFIG[target]['fn_helptag_fmt'](fstem, name, istbl)
if 'fn_name_fmt' in CONFIG[target]: if 'fn_name_fmt' in CONFIG[target]:
name = CONFIG[target]['fn_name_fmt'](fstem, name) name = CONFIG[target]['fn_name_fmt'](fstem, name)
prefix = '%s(' % name if istbl:
suffix = '%s)' % ', '.join('{%s}' % a[1] for a in params aopen, aclose = '', ''
else:
aopen, aclose = '(', ')'
prefix = name + aopen
suffix = ', '.join('{%s}' % a[1] for a in params
if a[0] not in ('void', 'Error', 'Arena', if a[0] not in ('void', 'Error', 'Arena',
'lua_State')) 'lua_State')) + aclose
if not fmt_vimhelp: if not fmt_vimhelp:
c_decl = '%s %s(%s);' % (return_type, name, ', '.join(c_args)) c_decl = '%s %s(%s);' % (return_type, name, ', '.join(c_args))

View File

@ -160,6 +160,7 @@ end
local function process_magic(line, generics) local function process_magic(line, generics)
line = line:gsub('^%s+@', '@') line = line:gsub('^%s+@', '@')
line = line:gsub('@package', '@private') line = line:gsub('@package', '@private')
line = line:gsub('@nodoc', '@private')
if not vim.startswith(line, '@') then -- it's a magic comment if not vim.startswith(line, '@') then -- it's a magic comment
return '/// ' .. line return '/// ' .. line
@ -327,6 +328,11 @@ local function process_function_header(line)
.. fn:sub(paren_start + 1) .. fn:sub(paren_start + 1)
end end
if line:match('local') then
-- Special: tell gen_vimdoc.py this is a local function.
return 'local_function ' .. fn .. '{}'
end
-- add vanilla function -- add vanilla function
return 'function ' .. fn .. '{}' return 'function ' .. fn .. '{}'
end end
@ -336,6 +342,9 @@ end
--- @param generics table<string,string>> --- @param generics table<string,string>>
--- @return string? --- @return string?
local function process_line(line, in_stream, generics) local function process_line(line, in_stream, generics)
local line_raw = line
line = vim.trim(line)
if vim.startswith(line, '---') then if vim.startswith(line, '---') then
return process_magic(line:sub(4), generics) return process_magic(line:sub(4), generics)
end end
@ -348,6 +357,14 @@ local function process_line(line, in_stream, generics)
return process_function_header(line) return process_function_header(line)
end end
if not line:match('^local') then
local v = line_raw:match('^([A-Za-z][.a-zA-Z_]*)%s+%=')
if v and v:match('%.') then
-- Special: this lets gen_vimdoc.py handle tables.
return 'table '..v..'() {}'
end
end
if #line > 0 then -- we don't know what this line means, so just comment it out if #line > 0 then -- we don't know what this line means, so just comment it out
return '// zz: ' .. line return '// zz: ' .. line
end end
@ -363,11 +380,11 @@ function Lua2DoxFilter:filter(filename)
local generics = {} --- @type table<string,string> local generics = {} --- @type table<string,string>
while not in_stream:eof() do while not in_stream:eof() do
local line = vim.trim(in_stream:getLine()) local line = in_stream:getLine()
local out_line = process_line(line, in_stream, generics) local out_line = process_line(line, in_stream, generics)
if not vim.startswith(line, '---') then if not vim.startswith(vim.trim(line), '---') then
generics = {} generics = {}
end end