fix(doc): improve doc generation of types using lpeg

Added a lpeg grammar for LuaCATS and use it in lua2dox.lua
This commit is contained in:
Lewis Russell
2024-01-09 17:36:46 +00:00
committed by Lewis Russell
parent a767c046f4
commit 2f9ee9b6cf
20 changed files with 1239 additions and 925 deletions

View File

@ -3381,9 +3381,8 @@ nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()*
• |autocmd-groups| • |autocmd-groups|
nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()*
Creates an |autocommand| event handler, defined by `callback` (Lua Creates an |autocommand| event handler, defined by `callback` (Lua function
function or Vimscript function name string) or `command` (Ex command or Vimscript function name string) or `command` (Ex command string).
string).
Example using Lua callback: >lua Example using Lua callback: >lua
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {

View File

@ -390,7 +390,7 @@ config({opts}, {namespace}) *vim.diagnostic.config()*
any of the above. any of the above.
Parameters: ~ Parameters: ~
• {opts} (table|nil) When omitted or "nil", retrieve the current • {opts} (`table?`) When omitted or "nil", retrieve the current
configuration. Otherwise, a configuration table with the configuration. Otherwise, a configuration table with the
following keys: following keys:
• underline: (default true) Use underline for • underline: (default true) Use underline for
@ -475,55 +475,55 @@ config({opts}, {namespace}) *vim.diagnostic.config()*
severities are displayed before lower severities (e.g. severities are displayed before lower severities (e.g.
ERROR is displayed before WARN). Options: ERROR is displayed before WARN). Options:
• reverse: (boolean) Reverse sort order • reverse: (boolean) Reverse sort order
• {namespace} (integer|nil) Update the options for the given namespace. • {namespace} (`integer?`) Update the options for the given namespace.
When omitted, update the global diagnostic options. When omitted, update the global diagnostic options.
Return: ~ Return: ~
(table|nil) table of current diagnostic config if `opts` is omitted. (`table?`) table of current diagnostic config if `opts` is omitted.
count({bufnr}, {opts}) *vim.diagnostic.count()* count({bufnr}, {opts}) *vim.diagnostic.count()*
Get current diagnostics count. Get current diagnostics count.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer number to get diagnostics from. Use 0 • {bufnr} (`integer?`) Buffer number to get diagnostics from. Use 0 for
for current buffer or nil for all buffers. current buffer or nil for all buffers.
• {opts} (table|nil) A table with the following keys: • {opts} (`table?`) A table with the following keys:
• namespace: (number) Limit diagnostics to the given • namespace: (number) Limit diagnostics to the given
namespace. namespace.
• lnum: (number) Limit diagnostics to the given line number. • lnum: (number) Limit diagnostics to the given line number.
• severity: See |diagnostic-severity|. • severity: See |diagnostic-severity|.
Return: ~ Return: ~
(table) A table with actually present severity values as keys (see (`table`) A table with actually present severity values as keys (see
|diagnostic-severity|) and integer counts as values. |diagnostic-severity|) and integer counts as values.
disable({bufnr}, {namespace}) *vim.diagnostic.disable()* disable({bufnr}, {namespace}) *vim.diagnostic.disable()*
Disable diagnostics in the given buffer. Disable diagnostics in the given buffer.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer number, or 0 for current buffer. • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When
When omitted, disable diagnostics in all buffers. omitted, disable diagnostics in all buffers.
• {namespace} (integer|nil) Only disable diagnostics for the given • {namespace} (`integer?`) Only disable diagnostics for the given
namespace. namespace.
enable({bufnr}, {namespace}) *vim.diagnostic.enable()* enable({bufnr}, {namespace}) *vim.diagnostic.enable()*
Enable diagnostics in the given buffer. Enable diagnostics in the given buffer.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer number, or 0 for current buffer. • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When
When omitted, enable diagnostics in all buffers. omitted, enable diagnostics in all buffers.
• {namespace} (integer|nil) Only enable diagnostics for the given • {namespace} (`integer?`) Only enable diagnostics for the given
namespace. namespace.
fromqflist({list}) *vim.diagnostic.fromqflist()* fromqflist({list}) *vim.diagnostic.fromqflist()*
Convert a list of quickfix items to a list of diagnostics. Convert a list of quickfix items to a list of diagnostics.
Parameters: ~ Parameters: ~
• {list} table[] List of quickfix items from |getqflist()| or • {list} (`table[]`) List of quickfix items from |getqflist()| or
|getloclist()|. |getloclist()|.
Return: ~ Return: ~
Diagnostic [] array of |diagnostic-structure| (`Diagnostic[]`) array of |diagnostic-structure|
get({bufnr}, {opts}) *vim.diagnostic.get()* get({bufnr}, {opts}) *vim.diagnostic.get()*
Get current diagnostics. Get current diagnostics.
@ -532,77 +532,77 @@ get({bufnr}, {opts}) *vim.diagnostic.get()*
diagnostics in a buffer, use |vim.diagnostic.set()|. diagnostics in a buffer, use |vim.diagnostic.set()|.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer number to get diagnostics from. Use 0 • {bufnr} (`integer?`) Buffer number to get diagnostics from. Use 0 for
for current buffer or nil for all buffers. current buffer or nil for all buffers.
• {opts} (table|nil) A table with the following keys: • {opts} (`table?`) A table with the following keys:
• namespace: (number) Limit diagnostics to the given • namespace: (number) Limit diagnostics to the given
namespace. namespace.
• lnum: (number) Limit diagnostics to the given line number. • lnum: (number) Limit diagnostics to the given line number.
• severity: See |diagnostic-severity|. • severity: See |diagnostic-severity|.
Return: ~ Return: ~
Diagnostic [] table A list of diagnostic items |diagnostic-structure|. (`Diagnostic[]`) table A list of diagnostic items
Keys `bufnr` , `end_lnum` , `end_col` , and `severity` are |diagnostic-structure|. Keys `bufnr` , `end_lnum` , `end_col` , and `severity` are
guaranteed to be present. guaranteed to be present.
get_namespace({namespace}) *vim.diagnostic.get_namespace()* get_namespace({namespace}) *vim.diagnostic.get_namespace()*
Get namespace metadata. Get namespace metadata.
Parameters: ~ Parameters: ~
• {namespace} (integer) Diagnostic namespace • {namespace} (`integer`) Diagnostic namespace
Return: ~ Return: ~
(table) Namespace metadata (`table`) Namespace metadata
get_namespaces() *vim.diagnostic.get_namespaces()* get_namespaces() *vim.diagnostic.get_namespaces()*
Get current diagnostic namespaces. Get current diagnostic namespaces.
Return: ~ Return: ~
(table) A list of active diagnostic namespaces |vim.diagnostic|. (`table`) A list of active diagnostic namespaces |vim.diagnostic|.
get_next({opts}) *vim.diagnostic.get_next()* get_next({opts}) *vim.diagnostic.get_next()*
Get the next diagnostic closest to the cursor position. Get the next diagnostic closest to the cursor position.
Parameters: ~ Parameters: ~
• {opts} (table|nil) See |vim.diagnostic.goto_next()| • {opts} (`table?`) See |vim.diagnostic.goto_next()|
Return: ~ Return: ~
Diagnostic|nil Next diagnostic (`Diagnostic?`) Next diagnostic
get_next_pos({opts}) *vim.diagnostic.get_next_pos()* get_next_pos({opts}) *vim.diagnostic.get_next_pos()*
Return the position of the next diagnostic in the current buffer. Return the position of the next diagnostic in the current buffer.
Parameters: ~ Parameters: ~
• {opts} (table|nil) See |vim.diagnostic.goto_next()| • {opts} (`table?`) See |vim.diagnostic.goto_next()|
Return: ~ Return: ~
table|false Next diagnostic position as a (row, col) tuple or false if (`table|false`) Next diagnostic position as a (row, col) tuple or
no next diagnostic. false if no next diagnostic.
get_prev({opts}) *vim.diagnostic.get_prev()* get_prev({opts}) *vim.diagnostic.get_prev()*
Get the previous diagnostic closest to the cursor position. Get the previous diagnostic closest to the cursor position.
Parameters: ~ Parameters: ~
• {opts} nil|table See |vim.diagnostic.goto_next()| • {opts} (`table?`) See |vim.diagnostic.goto_next()|
Return: ~ Return: ~
Diagnostic|nil Previous diagnostic (`Diagnostic?`) Previous diagnostic
get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()* get_prev_pos({opts}) *vim.diagnostic.get_prev_pos()*
Return the position of the previous diagnostic in the current buffer. Return the position of the previous diagnostic in the current buffer.
Parameters: ~ Parameters: ~
• {opts} (table|nil) See |vim.diagnostic.goto_next()| • {opts} (`table?`) See |vim.diagnostic.goto_next()|
Return: ~ Return: ~
table|false Previous diagnostic position as a (row, col) tuple or (`table|false`) Previous diagnostic position as a (row, col) tuple or
false if there is no prior diagnostic false if there is no prior diagnostic
goto_next({opts}) *vim.diagnostic.goto_next()* goto_next({opts}) *vim.diagnostic.goto_next()*
Move to the next diagnostic. Move to the next diagnostic.
Parameters: ~ Parameters: ~
• {opts} (table|nil) Configuration table with the following keys: • {opts} (`table?`) Configuration table with the following keys:
• namespace: (number) Only consider diagnostics from the given • namespace: (number) Only consider diagnostics from the given
namespace. namespace.
• cursor_position: (cursor position) Cursor position as a • cursor_position: (cursor position) Cursor position as a
@ -623,7 +623,7 @@ goto_prev({opts}) *vim.diagnostic.goto_prev()*
Move to the previous diagnostic in the current buffer. Move to the previous diagnostic in the current buffer.
Parameters: ~ Parameters: ~
• {opts} (table|nil) See |vim.diagnostic.goto_next()| • {opts} (`table?`) See |vim.diagnostic.goto_next()|
hide({namespace}, {bufnr}) *vim.diagnostic.hide()* hide({namespace}, {bufnr}) *vim.diagnostic.hide()*
Hide currently displayed diagnostics. Hide currently displayed diagnostics.
@ -636,22 +636,22 @@ hide({namespace}, {bufnr}) *vim.diagnostic.hide()*
|vim.diagnostic.disable()|. |vim.diagnostic.disable()|.
Parameters: ~ Parameters: ~
• {namespace} (integer|nil) Diagnostic namespace. When omitted, hide • {namespace} (`integer?`) Diagnostic namespace. When omitted, hide
diagnostics from all namespaces. diagnostics from all namespaces.
• {bufnr} (integer|nil) Buffer number, or 0 for current buffer. • {bufnr} (`integer?`) Buffer number, or 0 for current buffer. When
When omitted, hide diagnostics in all buffers. omitted, hide diagnostics in all buffers.
is_disabled({bufnr}, {namespace}) *vim.diagnostic.is_disabled()* is_disabled({bufnr}, {namespace}) *vim.diagnostic.is_disabled()*
Check whether diagnostics are disabled in a given buffer. Check whether diagnostics are disabled in a given buffer.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer number, or 0 for current buffer. • {bufnr} (`integer?`) Buffer number, or 0 for current buffer.
• {namespace} (integer|nil) Diagnostic namespace. When omitted, checks • {namespace} (`integer?`) Diagnostic namespace. When omitted, checks if
if all diagnostics are disabled in {bufnr}. Otherwise, all diagnostics are disabled in {bufnr}. Otherwise, only
only checks if diagnostics from {namespace} are disabled. checks if diagnostics from {namespace} are disabled.
Return: ~ Return: ~
(boolean) (`boolean`)
*vim.diagnostic.match()* *vim.diagnostic.match()*
match({str}, {pat}, {groups}, {severity_map}, {defaults}) match({str}, {pat}, {groups}, {severity_map}, {defaults})
@ -669,25 +669,25 @@ match({str}, {pat}, {groups}, {severity_map}, {defaults})
< <
Parameters: ~ Parameters: ~
• {str} (string) String to parse diagnostics from. • {str} (`string`) String to parse diagnostics from.
• {pat} (string) Lua pattern with capture groups. • {pat} (`string`) Lua pattern with capture groups.
• {groups} (table) List of fields in a |diagnostic-structure| to • {groups} (`table`) List of fields in a |diagnostic-structure|
associate with captures from {pat}. to associate with captures from {pat}.
• {severity_map} (table) A table mapping the severity field from • {severity_map} (`table`) A table mapping the severity field from
{groups} with an item from |vim.diagnostic.severity|. {groups} with an item from |vim.diagnostic.severity|.
• {defaults} (table|nil) Table of default values for any fields not • {defaults} (`table?`) Table of default values for any fields not
listed in {groups}. When omitted, numeric values listed in {groups}. When omitted, numeric values
default to 0 and "severity" defaults to ERROR. default to 0 and "severity" defaults to ERROR.
Return: ~ Return: ~
Diagnostic|nil: |diagnostic-structure| or `nil` if {pat} fails to (`Diagnostic?`) |diagnostic-structure| or `nil` if {pat} fails to match
match {str}. {str}.
open_float({opts}, {...}) *vim.diagnostic.open_float()* open_float({opts}, {...}) *vim.diagnostic.open_float()*
Show diagnostics in a floating window. Show diagnostics in a floating window.
Parameters: ~ Parameters: ~
• {opts} (table|nil) Configuration table with the same keys as • {opts} (`table?`) Configuration table with the same keys as
|vim.lsp.util.open_floating_preview()| in addition to the |vim.lsp.util.open_floating_preview()| in addition to the
following: following:
• bufnr: (number) Buffer number to show diagnostics from. • bufnr: (number) Buffer number to show diagnostics from.
@ -737,7 +737,7 @@ open_float({opts}, {...}) *vim.diagnostic.open_float()*
from |vim.diagnostic.config()|. from |vim.diagnostic.config()|.
Return: ~ Return: ~
integer|nil, integer|nil: ({float_bufnr}, {win_id}) (`integer?, integer?`) ({float_bufnr}, {win_id})
reset({namespace}, {bufnr}) *vim.diagnostic.reset()* reset({namespace}, {bufnr}) *vim.diagnostic.reset()*
Remove all diagnostics from the given namespace. Remove all diagnostics from the given namespace.
@ -748,27 +748,27 @@ reset({namespace}, {bufnr}) *vim.diagnostic.reset()*
re-displayed, use |vim.diagnostic.hide()|. re-displayed, use |vim.diagnostic.hide()|.
Parameters: ~ Parameters: ~
• {namespace} (integer|nil) Diagnostic namespace. When omitted, remove • {namespace} (`integer?`) Diagnostic namespace. When omitted, remove
diagnostics from all namespaces. diagnostics from all namespaces.
• {bufnr} (integer|nil) Remove diagnostics for the given buffer. • {bufnr} (`integer?`) Remove diagnostics for the given buffer.
When omitted, diagnostics are removed for all buffers. When omitted, diagnostics are removed for all buffers.
set({namespace}, {bufnr}, {diagnostics}, {opts}) *vim.diagnostic.set()* set({namespace}, {bufnr}, {diagnostics}, {opts}) *vim.diagnostic.set()*
Set diagnostics for the given namespace and buffer. Set diagnostics for the given namespace and buffer.
Parameters: ~ Parameters: ~
• {namespace} (integer) The diagnostic namespace • {namespace} (`integer`) The diagnostic namespace
• {bufnr} (integer) Buffer number • {bufnr} (`integer`) Buffer number
• {diagnostics} (table) A list of diagnostic items • {diagnostics} (`table`) A list of diagnostic items
|diagnostic-structure| |diagnostic-structure|
• {opts} (table|nil) Display options to pass to • {opts} (`table?`) Display options to pass to
|vim.diagnostic.show()| |vim.diagnostic.show()|
setloclist({opts}) *vim.diagnostic.setloclist()* setloclist({opts}) *vim.diagnostic.setloclist()*
Add buffer diagnostics to the location list. Add buffer diagnostics to the location list.
Parameters: ~ Parameters: ~
• {opts} (table|nil) Configuration table with the following keys: • {opts} (`table?`) Configuration table with the following keys:
• namespace: (number) Only add diagnostics from the given • namespace: (number) Only add diagnostics from the given
namespace. namespace.
• winnr: (number, default 0) Window number to set location • winnr: (number, default 0) Window number to set location
@ -783,7 +783,7 @@ setqflist({opts}) *vim.diagnostic.setqflist()*
Add all diagnostics to the quickfix list. Add all diagnostics to the quickfix list.
Parameters: ~ Parameters: ~
• {opts} (table|nil) Configuration table with the following keys: • {opts} (`table?`) Configuration table with the following keys:
• namespace: (number) Only add diagnostics from the given • namespace: (number) Only add diagnostics from the given
namespace. namespace.
• open: (boolean, default true) Open quickfix list after • open: (boolean, default true) Open quickfix list after
@ -797,17 +797,17 @@ show({namespace}, {bufnr}, {diagnostics}, {opts})
Display diagnostics for the given namespace and buffer. Display diagnostics for the given namespace and buffer.
Parameters: ~ Parameters: ~
• {namespace} (integer|nil) Diagnostic namespace. When omitted, show • {namespace} (`integer?`) Diagnostic namespace. When omitted, show
diagnostics from all namespaces. diagnostics from all namespaces.
• {bufnr} (integer|nil) Buffer number, or 0 for current buffer. • {bufnr} (`integer?`) Buffer number, or 0 for current buffer.
When omitted, show diagnostics in all buffers. When omitted, show diagnostics in all buffers.
• {diagnostics} (table|nil) The diagnostics to display. When omitted, • {diagnostics} (`table?`) The diagnostics to display. When omitted,
use the saved diagnostics for the given namespace and use the saved diagnostics for the given namespace and
buffer. This can be used to display a list of buffer. This can be used to display a list of
diagnostics without saving them or to display only a diagnostics without saving them or to display only a
subset of diagnostics. May not be used when {namespace} subset of diagnostics. May not be used when {namespace}
or {bufnr} is nil. or {bufnr} is nil.
• {opts} (table|nil) Display options. See • {opts} (`table?`) Display options. See
|vim.diagnostic.config()|. |vim.diagnostic.config()|.
toqflist({diagnostics}) *vim.diagnostic.toqflist()* toqflist({diagnostics}) *vim.diagnostic.toqflist()*
@ -815,9 +815,9 @@ toqflist({diagnostics}) *vim.diagnostic.toqflist()*
passed to |setqflist()| or |setloclist()|. passed to |setqflist()| or |setloclist()|.
Parameters: ~ Parameters: ~
• {diagnostics} (table) List of diagnostics |diagnostic-structure|. • {diagnostics} (`table`) List of diagnostics |diagnostic-structure|.
Return: ~ Return: ~
table[] of quickfix list items |setqflist-what| (`table[]`) of quickfix list items |setqflist-what|
vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -567,10 +567,10 @@ foldexpr({lnum}) *vim.treesitter.foldexpr()*
< <
Parameters: ~ Parameters: ~
• {lnum} (integer|nil) Line number to calculate fold level for • {lnum} (`integer?`) Line number to calculate fold level for
Return: ~ Return: ~
(string) (`string`)
foldtext() *vim.treesitter.foldtext()* foldtext() *vim.treesitter.foldtext()*
Returns the highlighted content of the first line of the fold or falls Returns the highlighted content of the first line of the fold or falls
@ -580,17 +580,17 @@ foldtext() *vim.treesitter.foldtext()*
< <
Return: ~ Return: ~
`{ [1]: string, [2]: string[] }[]` | string (`{ [1]: string, [2]: string[] }[]|string`)
*vim.treesitter.get_captures_at_cursor()* *vim.treesitter.get_captures_at_cursor()*
get_captures_at_cursor({winnr}) get_captures_at_cursor({winnr})
Returns a list of highlight capture names under the cursor Returns a list of highlight capture names under the cursor
Parameters: ~ Parameters: ~
• {winnr} (integer|nil) Window handle or 0 for current window (default) • {winnr} (`integer?`) Window handle or 0 for current window (default)
Return: ~ Return: ~
string[] List of capture names (`string[]`) List of capture names
*vim.treesitter.get_captures_at_pos()* *vim.treesitter.get_captures_at_pos()*
get_captures_at_pos({bufnr}, {row}, {col}) get_captures_at_pos({bufnr}, {row}, {col})
@ -601,12 +601,13 @@ get_captures_at_pos({bufnr}, {row}, {col})
if none are defined). if none are defined).
Parameters: ~ Parameters: ~
• {bufnr} (integer) Buffer number (0 for current buffer) • {bufnr} (`integer`) Buffer number (0 for current buffer)
• {row} (integer) Position row • {row} (`integer`) Position row
• {col} (integer) Position column • {col} (`integer`) Position column
Return: ~ Return: ~
table[] List of captures `{ capture = "name", metadata = { ... } }` (`table[]`) List of captures `{ capture = "name", metadata = { ... }
}`
get_node({opts}) *vim.treesitter.get_node()* get_node({opts}) *vim.treesitter.get_node()*
Returns the smallest named node at the given position Returns the smallest named node at the given position
@ -618,7 +619,7 @@ get_node({opts}) *vim.treesitter.get_node()*
< <
Parameters: ~ Parameters: ~
• {opts} (table|nil) Optional keyword arguments: • {opts} (`table?`) Optional keyword arguments:
• bufnr integer|nil Buffer number (nil or 0 for current • bufnr integer|nil Buffer number (nil or 0 for current
buffer) buffer)
• pos table|nil 0-indexed (row, col) tuple. Defaults to cursor • pos table|nil 0-indexed (row, col) tuple. Defaults to cursor
@ -630,35 +631,35 @@ get_node({opts}) *vim.treesitter.get_node()*
true) true)
Return: ~ Return: ~
|TSNode| | nil Node at the given position (`TSNode?`) Node at the given position
get_node_range({node_or_range}) *vim.treesitter.get_node_range()* get_node_range({node_or_range}) *vim.treesitter.get_node_range()*
Returns the node's range or an unpacked range table Returns the node's range or an unpacked range table
Parameters: ~ Parameters: ~
• {node_or_range} (|TSNode| | table) Node or table of positions • {node_or_range} (`TSNode|table`) Node or table of positions
Return (multiple): ~ Return (multiple): ~
(integer) start_row (`integer`) start_row
(integer) start_col (`integer`) start_col
(integer) end_row (`integer`) end_row
(integer) end_col (`integer`) end_col
*vim.treesitter.get_node_text()* *vim.treesitter.get_node_text()*
get_node_text({node}, {source}, {opts}) get_node_text({node}, {source}, {opts})
Gets the text corresponding to a given node Gets the text corresponding to a given node
Parameters: ~ Parameters: ~
• {node} |TSNode| • {node} (`TSNode`)
• {source} (integer|string) Buffer or string from which the {node} is • {source} (`integer|string`) Buffer or string from which the {node} is
extracted extracted
• {opts} (table|nil) Optional parameters. • {opts} (`table?`) Optional parameters.
• metadata (table) Metadata of a specific capture. This • metadata (table) Metadata of a specific capture. This
would be set to `metadata[capture_id]` when using would be set to `metadata[capture_id]` when using
|vim.treesitter.query.add_directive()|. |vim.treesitter.query.add_directive()|.
Return: ~ Return: ~
(string) (`string`)
get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()*
Returns the parser for a specific buffer and attaches it to the buffer Returns the parser for a specific buffer and attaches it to the buffer
@ -666,39 +667,39 @@ get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()*
If needed, this will create the parser. If needed, this will create the parser.
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer the parser should be tied to (default: • {bufnr} (`integer?`) Buffer the parser should be tied to (default:
current buffer) current buffer)
• {lang} (string|nil) Filetype of this parser (default: buffer • {lang} (`string?`) Filetype of this parser (default: buffer
filetype) filetype)
• {opts} (table|nil) Options to pass to the created language tree • {opts} (`table?`) Options to pass to the created language tree
Return: ~ Return: ~
|LanguageTree| object to use for parsing (`LanguageTree`) object to use for parsing
get_range({node}, {source}, {metadata}) *vim.treesitter.get_range()* get_range({node}, {source}, {metadata}) *vim.treesitter.get_range()*
Get the range of a |TSNode|. Can also supply {source} and {metadata} to Get the range of a |TSNode|. Can also supply {source} and {metadata} to
get the range with directives applied. get the range with directives applied.
Parameters: ~ Parameters: ~
• {node} |TSNode| • {node} (`TSNode`)
• {source} integer|string|nil Buffer or string from which the {node} • {source} (`integer|string?`) Buffer or string from which the {node}
is extracted is extracted
• {metadata} TSMetadata|nil • {metadata} (`TSMetadata?`)
Return: ~ Return: ~
(table) (`Range6`)
*vim.treesitter.get_string_parser()* *vim.treesitter.get_string_parser()*
get_string_parser({str}, {lang}, {opts}) get_string_parser({str}, {lang}, {opts})
Returns a string parser Returns a string parser
Parameters: ~ Parameters: ~
• {str} (string) Text to parse • {str} (`string`) Text to parse
• {lang} (string) Language of this string • {lang} (`string`) Language of this string
• {opts} (table|nil) Options to pass to the created language tree • {opts} (`table?`) Options to pass to the created language tree
Return: ~ Return: ~
|LanguageTree| object to use for parsing (`LanguageTree`) object to use for parsing
inspect_tree({opts}) *vim.treesitter.inspect_tree()* inspect_tree({opts}) *vim.treesitter.inspect_tree()*
Open a window that displays a textual representation of the nodes in the Open a window that displays a textual representation of the nodes in the
@ -712,7 +713,7 @@ inspect_tree({opts}) *vim.treesitter.inspect_tree()*
Can also be shown with `:InspectTree`. *:InspectTree* Can also be shown with `:InspectTree`. *:InspectTree*
Parameters: ~ Parameters: ~
• {opts} (table|nil) Optional options table with the following possible • {opts} (`table?`) Optional options table with the following possible
keys: keys:
• lang (string|nil): The language of the source buffer. If • lang (string|nil): The language of the source buffer. If
omitted, the filetype of the source buffer is used. omitted, the filetype of the source buffer is used.
@ -732,33 +733,33 @@ is_ancestor({dest}, {source}) *vim.treesitter.is_ancestor()*
Determines whether a node is the ancestor of another Determines whether a node is the ancestor of another
Parameters: ~ Parameters: ~
• {dest} |TSNode| Possible ancestor • {dest} (`TSNode`) Possible ancestor
• {source} |TSNode| Possible descendant • {source} (`TSNode`) Possible descendant
Return: ~ Return: ~
(boolean) True if {dest} is an ancestor of {source} (`boolean`) True if {dest} is an ancestor of {source}
*vim.treesitter.is_in_node_range()* *vim.treesitter.is_in_node_range()*
is_in_node_range({node}, {line}, {col}) is_in_node_range({node}, {line}, {col})
Determines whether (line, col) position is in node range Determines whether (line, col) position is in node range
Parameters: ~ Parameters: ~
• {node} |TSNode| defining the range • {node} (`TSNode`) defining the range
• {line} (integer) Line (0-based) • {line} (`integer`) Line (0-based)
• {col} (integer) Column (0-based) • {col} (`integer`) Column (0-based)
Return: ~ Return: ~
(boolean) True if the position is in node range (`boolean`) True if the position is in node range
node_contains({node}, {range}) *vim.treesitter.node_contains()* node_contains({node}, {range}) *vim.treesitter.node_contains()*
Determines if a node contains a range Determines if a node contains a range
Parameters: ~ Parameters: ~
• {node} |TSNode| • {node} (`TSNode`)
• {range} (table) • {range} (`table`)
Return: ~ Return: ~
(boolean) True if the {node} contains the {range} (`boolean`) True if the {node} contains the {range}
start({bufnr}, {lang}) *vim.treesitter.start()* start({bufnr}, {lang}) *vim.treesitter.start()*
Starts treesitter highlighting for a buffer Starts treesitter highlighting for a buffer
@ -779,16 +780,15 @@ start({bufnr}, {lang}) *vim.treesitter.start()*
< <
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer to be highlighted (default: current • {bufnr} (`integer?`) Buffer to be highlighted (default: current
buffer) buffer)
• {lang} (string|nil) Language of the parser (default: buffer • {lang} (`string?`) Language of the parser (default: buffer filetype)
filetype)
stop({bufnr}) *vim.treesitter.stop()* stop({bufnr}) *vim.treesitter.stop()*
Stops treesitter highlighting for a buffer Stops treesitter highlighting for a buffer
Parameters: ~ Parameters: ~
• {bufnr} (integer|nil) Buffer to stop highlighting (default: current • {bufnr} (`integer?`) Buffer to stop highlighting (default: current
buffer) buffer)
@ -802,8 +802,8 @@ add({lang}, {opts}) *vim.treesitter.language.add()*
{path} {path}
Parameters: ~ Parameters: ~
• {lang} (string) Name of the parser (alphanumerical and `_` only) • {lang} (`string`) Name of the parser (alphanumerical and `_` only)
• {opts} (table|nil) Options: • {opts} (`table?`) Options:
• filetype (string|string[]) Default filetype the parser • filetype (string|string[]) Default filetype the parser
should be associated with. Defaults to {lang}. should be associated with. Defaults to {lang}.
• path (string|nil) Optional path the parser is located at • path (string|nil) Optional path the parser is located at
@ -814,17 +814,17 @@ get_filetypes({lang}) *vim.treesitter.language.get_filetypes()*
Get the filetypes associated with the parser named {lang}. Get the filetypes associated with the parser named {lang}.
Parameters: ~ Parameters: ~
• {lang} (string) Name of parser • {lang} (`string`) Name of parser
Return: ~ Return: ~
string[] filetypes (`string[]`) filetypes
get_lang({filetype}) *vim.treesitter.language.get_lang()* get_lang({filetype}) *vim.treesitter.language.get_lang()*
Parameters: ~ Parameters: ~
• {filetype} (string) • {filetype} (`string`)
Return: ~ Return: ~
(string|nil) (`string?`)
inspect({lang}) *vim.treesitter.language.inspect()* inspect({lang}) *vim.treesitter.language.inspect()*
Inspects the provided language. Inspects the provided language.
@ -833,10 +833,10 @@ inspect({lang}) *vim.treesitter.language.inspect()*
names, ... names, ...
Parameters: ~ Parameters: ~
• {lang} (string) Language • {lang} (`string`) Language
Return: ~ Return: ~
(table) (`table`)
register({lang}, {filetype}) *vim.treesitter.language.register()* register({lang}, {filetype}) *vim.treesitter.language.register()*
Register a parser named {lang} to be used for {filetype}(s). Register a parser named {lang} to be used for {filetype}(s).
@ -845,8 +845,8 @@ register({lang}, {filetype}) *vim.treesitter.language.register()*
mappings from other filetypes to {lang} will be preserved. mappings from other filetypes to {lang} will be preserved.
Parameters: ~ Parameters: ~
• {lang} (string) Name of parser • {lang} (`string`) Name of parser
• {filetype} string|string[] Filetype(s) to associate with lang • {filetype} (`string|string[]`) Filetype(s) to associate with lang
============================================================================== ==============================================================================
@ -862,9 +862,8 @@ add_directive({name}, {handler}, {force})
`metadata[capture_id].key = value` `metadata[capture_id].key = value`
Parameters: ~ Parameters: ~
• {name} (string) Name of the directive, without leading # • {name} (`string`) Name of the directive, without leading #
• {handler} function(match:table<string,|TSNode|>, pattern:string, • {handler} (`function`)
bufnr:integer, predicate:string[], metadata:table)
• match: see |treesitter-query| • match: see |treesitter-query|
• node-level data are accessible via `match[capture_id]` • node-level data are accessible via `match[capture_id]`
@ -872,19 +871,18 @@ add_directive({name}, {handler}, {force})
• predicate: list of strings containing the full directive • predicate: list of strings containing the full directive
being called, e.g. `(node (#set! conceal "-"))` would get being called, e.g. `(node (#set! conceal "-"))` would get
the predicate `{ "#set!", "conceal", "-" }` the predicate `{ "#set!", "conceal", "-" }`
• {force} (boolean|nil) • {force} (`boolean?`)
*vim.treesitter.query.add_predicate()* *vim.treesitter.query.add_predicate()*
add_predicate({name}, {handler}, {force}) add_predicate({name}, {handler}, {force})
Adds a new predicate to be used in queries Adds a new predicate to be used in queries
Parameters: ~ Parameters: ~
• {name} (string) Name of the predicate, without leading # • {name} (`string`) Name of the predicate, without leading #
• {handler} function(match:table<string,|TSNode|>, pattern:string, • {handler} (`function`)
bufnr:integer, predicate:string[])
• see |vim.treesitter.query.add_directive()| for argument • see |vim.treesitter.query.add_directive()| for argument
meanings meanings
• {force} (boolean|nil) • {force} (`boolean?`)
edit({lang}) *vim.treesitter.query.edit()* edit({lang}) *vim.treesitter.query.edit()*
Opens a live editor to query the buffer you started from. Opens a live editor to query the buffer you started from.
@ -897,31 +895,32 @@ edit({lang}) *vim.treesitter.query.edit()*
`$VIMRUNTIME/queries/`. `$VIMRUNTIME/queries/`.
Parameters: ~ Parameters: ~
• {lang} (string|nil) language to open the query editor for. If • {lang} (`string?`) language to open the query editor for. If omitted,
omitted, inferred from the current buffer's filetype. inferred from the current buffer's filetype.
get({lang}, {query_name}) *vim.treesitter.query.get()* get({lang}, {query_name}) *vim.treesitter.query.get()*
Returns the runtime query {query_name} for {lang}. Returns the runtime query {query_name} for {lang}.
Parameters: ~ Parameters: ~
• {lang} (string) Language to use for the query • {lang} (`string`) Language to use for the query
• {query_name} (string) Name of the query (e.g. "highlights") • {query_name} (`string`) Name of the query (e.g. "highlights")
Return: ~ Return: ~
Query|nil Parsed query (`Query?`) Parsed query
*vim.treesitter.query.get_files()* *vim.treesitter.query.get_files()*
get_files({lang}, {query_name}, {is_included}) get_files({lang}, {query_name}, {is_included})
Gets the list of files used to make up a query Gets the list of files used to make up a query
Parameters: ~ Parameters: ~
• {lang} (string) Language to get query for • {lang} (`string`) Language to get query for
• {query_name} (string) Name of the query to load (e.g., "highlights") • {query_name} (`string`) Name of the query to load (e.g.,
• {is_included} (boolean|nil) Internal parameter, most of the time left "highlights")
• {is_included} (`boolean?`) Internal parameter, most of the time left
as `nil` as `nil`
Return: ~ Return: ~
string[] query_files List of files to load for given query and (`string[]`) query_files List of files to load for given query and
language language
lint({buf}, {opts}) *vim.treesitter.query.lint()* lint({buf}, {opts}) *vim.treesitter.query.lint()*
@ -940,8 +939,8 @@ lint({buf}, {opts}) *vim.treesitter.query.lint()*
for the `lua` language will be used. for the `lua` language will be used.
Parameters: ~ Parameters: ~
• {buf} (integer) Buffer handle • {buf} (`integer`) Buffer handle
• {opts} (QueryLinterOpts|nil) Optional keyword arguments: • {opts} (`table?`) Optional keyword arguments:
• langs (string|string[]|nil) Language(s) to use for checking • langs (string|string[]|nil) Language(s) to use for checking
the query. If multiple languages are specified, queries are the query. If multiple languages are specified, queries are
validated for all of them validated for all of them
@ -951,13 +950,13 @@ list_directives() *vim.treesitter.query.list_directives()*
Lists the currently available directives to use in queries. Lists the currently available directives to use in queries.
Return: ~ Return: ~
string[] List of supported directives. (`string[]`) List of supported directives.
list_predicates() *vim.treesitter.query.list_predicates()* list_predicates() *vim.treesitter.query.list_predicates()*
Lists the currently available predicates to use in queries. Lists the currently available predicates to use in queries.
Return: ~ Return: ~
string[] List of supported predicates. (`string[]`) List of supported predicates.
omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()* omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()*
Omnifunc for completing node names and predicates in treesitter queries. Omnifunc for completing node names and predicates in treesitter queries.
@ -980,11 +979,11 @@ parse({lang}, {query}) *vim.treesitter.query.parse()*
• `info.patterns` contains information about predicates. • `info.patterns` contains information about predicates.
Parameters: ~ Parameters: ~
• {lang} (string) Language to use for the query • {lang} (`string`) Language to use for the query
• {query} (string) Query in s-expr syntax • {query} (`string`) Query in s-expr syntax
Return: ~ Return: ~
Query Parsed query (`Query`) Parsed query
*Query:iter_captures()* *Query:iter_captures()*
Query:iter_captures({node}, {source}, {start}, {stop}) Query:iter_captures({node}, {source}, {start}, {stop})
@ -1010,14 +1009,14 @@ Query:iter_captures({node}, {source}, {start}, {stop})
< <
Parameters: ~ Parameters: ~
• {node} |TSNode| under which the search will occur • {node} (`TSNode`) under which the search will occur
• {source} (integer|string) Source buffer or string to extract text • {source} (`integer|string`) Source buffer or string to extract text
from from
• {start} (integer) Starting line for the search • {start} (`integer`) Starting line for the search
• {stop} (integer) Stopping line for the search (end-exclusive) • {stop} (`integer`) Stopping line for the search (end-exclusive)
Return: ~ Return: ~
(fun(end_line: integer|nil): integer, TSNode, TSMetadata): capture id, (`fun(end_line: integer?): integer, TSNode, TSMetadata`) capture id,
capture node, metadata capture node, metadata
*Query:iter_matches()* *Query:iter_matches()*
@ -1044,18 +1043,18 @@ Query:iter_matches({node}, {source}, {start}, {stop}, {opts})
< <
Parameters: ~ Parameters: ~
• {node} |TSNode| under which the search will occur • {node} (`TSNode`) under which the search will occur
• {source} (integer|string) Source buffer or string to search • {source} (`integer|string`) Source buffer or string to search
• {start} (integer) Starting line for the search • {start} (`integer`) Starting line for the search
• {stop} (integer) Stopping line for the search (end-exclusive) • {stop} (`integer`) Stopping line for the search (end-exclusive)
• {opts} (table|nil) Options: • {opts} (`table?`) Options:
• max_start_depth (integer) if non-zero, sets the maximum • max_start_depth (integer) if non-zero, sets the maximum
start depth for each match. This is used to prevent start depth for each match. This is used to prevent
traversing too deep into a tree. Requires treesitter >= traversing too deep into a tree. Requires treesitter >=
0.20.9. 0.20.9.
Return: ~ Return: ~
(fun(): integer, table<integer,TSNode>, table): pattern id, match, (`fun(): integer, table<integer,TSNode>, table`) pattern id, match,
metadata metadata
set({lang}, {query_name}, {text}) *vim.treesitter.query.set()* set({lang}, {query_name}, {text}) *vim.treesitter.query.set()*
@ -1065,9 +1064,9 @@ set({lang}, {query_name}, {text}) *vim.treesitter.query.set()*
by plugins. by plugins.
Parameters: ~ Parameters: ~
• {lang} (string) Language to use for the query • {lang} (`string`) Language to use for the query
• {query_name} (string) Name of the query (e.g., "highlights") • {query_name} (`string`) Name of the query (e.g., "highlights")
• {text} (string) Query text (unparsed). • {text} (`string`) Query text (unparsed).
============================================================================== ==============================================================================
@ -1117,10 +1116,10 @@ LanguageTree:contains({range}) *LanguageTree:contains()*
Determines whether {range} is contained in the |LanguageTree|. Determines whether {range} is contained in the |LanguageTree|.
Parameters: ~ Parameters: ~
• {range} (table) `{ start_line, start_col, end_line, end_col }` • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }`
Return: ~ Return: ~
(boolean) (`boolean`)
LanguageTree:destroy() *LanguageTree:destroy()* LanguageTree:destroy() *LanguageTree:destroy()*
Destroys this |LanguageTree| and all its children. Destroys this |LanguageTree| and all its children.
@ -1136,21 +1135,21 @@ LanguageTree:for_each_tree({fn}) *LanguageTree:for_each_tree()*
Note: This includes the invoking tree's child trees as well. Note: This includes the invoking tree's child trees as well.
Parameters: ~ Parameters: ~
• {fn} fun(tree: TSTree, ltree: LanguageTree) • {fn} (`fun(tree: TSTree, ltree: LanguageTree)`)
LanguageTree:included_regions() *LanguageTree:included_regions()* LanguageTree:included_regions() *LanguageTree:included_regions()*
Gets the set of included regions managed by this LanguageTree . This can Gets the set of included regions managed by this LanguageTree . This can be
be different from the regions set by injection query, because a partial different from the regions set by injection query, because a partial
|LanguageTree:parse()| drops the regions outside the requested range. |LanguageTree:parse()| drops the regions outside the requested range.
Return: ~ Return: ~
table<integer, Range6[]> (`table<integer, Range6[]>`)
LanguageTree:invalidate({reload}) *LanguageTree:invalidate()* LanguageTree:invalidate({reload}) *LanguageTree:invalidate()*
Invalidates this parser and all its children Invalidates this parser and all its children
Parameters: ~ Parameters: ~
• {reload} (boolean|nil) • {reload} (`boolean?`)
LanguageTree:is_valid({exclude_children}) *LanguageTree:is_valid()* LanguageTree:is_valid({exclude_children}) *LanguageTree:is_valid()*
Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()|
@ -1158,11 +1157,11 @@ LanguageTree:is_valid({exclude_children}) *LanguageTree:is_valid()*
|LanguageTree:parse()|. |LanguageTree:parse()|.
Parameters: ~ Parameters: ~
• {exclude_children} (boolean|nil) whether to ignore the validity of • {exclude_children} (`boolean?`) whether to ignore the validity of
children (default `false`) children (default `false`)
Return: ~ Return: ~
(boolean) (`boolean`)
LanguageTree:lang() *LanguageTree:lang()* LanguageTree:lang() *LanguageTree:lang()*
Gets the language of this tree node. Gets the language of this tree node.
@ -1172,23 +1171,23 @@ LanguageTree:language_for_range({range})
Gets the appropriate language that contains {range}. Gets the appropriate language that contains {range}.
Parameters: ~ Parameters: ~
• {range} (table) `{ start_line, start_col, end_line, end_col }` • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }`
Return: ~ Return: ~
|LanguageTree| Managing {range} (`LanguageTree`) Managing {range}
*LanguageTree:named_node_for_range()* *LanguageTree:named_node_for_range()*
LanguageTree:named_node_for_range({range}, {opts}) LanguageTree:named_node_for_range({range}, {opts})
Gets the smallest named node that contains {range}. Gets the smallest named node that contains {range}.
Parameters: ~ Parameters: ~
• {range} (table) `{ start_line, start_col, end_line, end_col }` • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }`
• {opts} (table|nil) Optional keyword arguments: • {opts} (`table?`) Optional keyword arguments:
• ignore_injections boolean Ignore injected languages • ignore_injections boolean Ignore injected languages
(default true) (default true)
Return: ~ Return: ~
|TSNode| | nil Found node (`TSNode?`) Found node
LanguageTree:parse({range}) *LanguageTree:parse()* LanguageTree:parse({range}) *LanguageTree:parse()*
Recursively parse all regions in the language tree using Recursively parse all regions in the language tree using
@ -1201,21 +1200,21 @@ LanguageTree:parse({range}) *LanguageTree:parse()*
if {range} is `true`). if {range} is `true`).
Parameters: ~ Parameters: ~
• {range} boolean|Range|nil: Parse this range in the parser's source. • {range} (`boolean|Range?`) Parse this range in the parser's source.
Set to `true` to run a complete parse of the source (Note: Set to `true` to run a complete parse of the source (Note:
Can be slow!) Set to `false|nil` to only parse regions with Can be slow!) Set to `false|nil` to only parse regions with
empty ranges (typically only the root tree without empty ranges (typically only the root tree without
injections). injections).
Return: ~ Return: ~
table<integer, TSTree> (`table<integer, TSTree>`)
*LanguageTree:register_cbs()* *LanguageTree:register_cbs()*
LanguageTree:register_cbs({cbs}, {recursive}) LanguageTree:register_cbs({cbs}, {recursive})
Registers callbacks for the |LanguageTree|. Registers callbacks for the |LanguageTree|.
Parameters: ~ Parameters: ~
• {cbs} (table) An |nvim_buf_attach()|-like table argument with • {cbs} (`table`) An |nvim_buf_attach()|-like table argument with
the following handlers: the following handlers:
• `on_bytes` : see |nvim_buf_attach()|, but this will be • `on_bytes` : see |nvim_buf_attach()|, but this will be
called after the parsers callback. called after the parsers callback.
@ -1230,7 +1229,7 @@ LanguageTree:register_cbs({cbs}, {recursive})
• `on_detach` : emitted when the buffer is detached, see • `on_detach` : emitted when the buffer is detached, see
|nvim_buf_detach_event|. Takes one argument, the number |nvim_buf_detach_event|. Takes one argument, the number
of the buffer. of the buffer.
• {recursive} (boolean|nil) Apply callbacks recursively for all • {recursive} (`boolean?`) Apply callbacks recursively for all
children. Any new children will also inherit the children. Any new children will also inherit the
callbacks. callbacks.
@ -1242,13 +1241,13 @@ LanguageTree:tree_for_range({range}, {opts})
Gets the tree that contains {range}. Gets the tree that contains {range}.
Parameters: ~ Parameters: ~
• {range} (table) `{ start_line, start_col, end_line, end_col }` • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }`
• {opts} (table|nil) Optional keyword arguments: • {opts} (`table?`) Optional keyword arguments:
• ignore_injections boolean Ignore injected languages • ignore_injections boolean Ignore injected languages
(default true) (default true)
Return: ~ Return: ~
TSTree|nil (`TSTree?`)
LanguageTree:trees() *LanguageTree:trees()* LanguageTree:trees() *LanguageTree:trees()*
Returns all trees of the regions parsed by this parser. Does not include Returns all trees of the regions parsed by this parser. Does not include
@ -1258,6 +1257,6 @@ LanguageTree:trees() *LanguageTree:trees()*
• the root LanguageTree is fully parsed. • the root LanguageTree is fully parsed.
Return: ~ Return: ~
table<integer, TSTree> (`table<integer, TSTree>`)
vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:

View File

@ -95,7 +95,7 @@ vim.log = {
--- throws an error if {cmd} cannot be run. --- throws an error if {cmd} cannot be run.
--- ---
--- @param cmd (string[]) Command to execute --- @param cmd (string[]) Command to execute
--- @param opts (SystemOpts|nil) Options: --- @param opts vim.SystemOpts? Options:
--- - cwd: (string) Set the current working directory for the sub-process. --- - cwd: (string) Set the current working directory for the sub-process.
--- - env: table<string,string> Set environment variables for the new process. Inherits the --- - env: table<string,string> Set environment variables for the new process. Inherits the
--- current environment with `NVIM` set to |v:servername|. --- current environment with `NVIM` set to |v:servername|.
@ -118,7 +118,7 @@ vim.log = {
--- parent exits. Note that the child process will still keep the parent's event loop alive --- parent exits. Note that the child process will still keep the parent's event loop alive
--- unless the parent process calls |uv.unref()| on the child's process handle. --- unless the parent process calls |uv.unref()| on the child's process handle.
--- ---
--- @param on_exit (function|nil) Called when subprocess exits. When provided, the command runs --- @param on_exit? fun(out: vim.SystemCompleted) Called when subprocess exits. When provided, the command runs
--- asynchronously. Receives SystemCompleted object, see return of SystemObj:wait(). --- asynchronously. Receives SystemCompleted object, see return of SystemObj:wait().
--- ---
--- @return vim.SystemObj Object with the fields: --- @return vim.SystemObj Object with the fields:
@ -219,10 +219,9 @@ do
--- ``` --- ```
--- ---
---@see |paste| ---@see |paste|
---@alias paste_phase -1 | 1 | 2 | 3
--- ---
---@param lines string[] # |readfile()|-style list of lines to paste. |channel-lines| ---@param lines string[] # |readfile()|-style list of lines to paste. |channel-lines|
---@param phase paste_phase -1: "non-streaming" paste: the call contains all lines. ---@param phase (-1|1|2|3) -1: "non-streaming" paste: the call contains all lines.
--- If paste is "streamed", `phase` indicates the stream state: --- If paste is "streamed", `phase` indicates the stream state:
--- - 1: starts the paste (exactly once) --- - 1: starts the paste (exactly once)
--- - 2: continues the paste (zero or more times) --- - 2: continues the paste (zero or more times)

View File

@ -812,9 +812,8 @@ function vim.api.nvim_complete_set(index, opts) end
--- @return integer --- @return integer
function vim.api.nvim_create_augroup(name, opts) end function vim.api.nvim_create_augroup(name, opts) end
--- Creates an `autocommand` event handler, defined by `callback` (Lua --- Creates an `autocommand` event handler, defined by `callback` (Lua function
--- function or Vimscript function name string) or `command` (Ex command --- or Vimscript function name string) or `command` (Ex command string).
--- string).
--- Example using Lua callback: --- Example using Lua callback:
--- ---
--- ```lua --- ```lua

View File

@ -1,6 +1,6 @@
local uv = vim.uv local uv = vim.uv
--- @class SystemOpts --- @class vim.SystemOpts
--- @field stdin? string|string[]|true --- @field stdin? string|string[]|true
--- @field stdout? fun(err:string?, data: string?)|false --- @field stdout? fun(err:string?, data: string?)|false
--- @field stderr? fun(err:string?, data: string?)|false --- @field stderr? fun(err:string?, data: string?)|false
@ -302,7 +302,7 @@ end
--- Run a system command --- Run a system command
--- ---
--- @param cmd string[] --- @param cmd string[]
--- @param opts? SystemOpts --- @param opts? vim.SystemOpts
--- @param on_exit? fun(out: vim.SystemCompleted) --- @param on_exit? fun(out: vim.SystemCompleted)
--- @return vim.SystemObj --- @return vim.SystemObj
function M.run(cmd, opts, on_exit) function M.run(cmd, opts, on_exit)

View File

@ -2165,7 +2165,7 @@ end
--- } --- }
--- ``` --- ```
--- ---
---@param filetypes vim.filetype.add.filetypes A table containing new filetype maps (see example). ---@param filetypes vim.filetype.add.filetypes (table) A table containing new filetype maps (see example).
function M.add(filetypes) function M.add(filetypes)
for k, v in pairs(filetypes.extension or {}) do for k, v in pairs(filetypes.extension or {}) do
extension[k] = v extension[k] = v
@ -2300,7 +2300,7 @@ end
--- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} }) --- vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
--- ``` --- ```
--- ---
---@param args vim.filetype.match.args Table specifying which matching strategy to use. ---@param args vim.filetype.match.args (table) Table specifying which matching strategy to use.
--- Accepted keys are: --- Accepted keys are:
--- * buf (number): Buffer number to use for matching. Mutually exclusive with --- * buf (number): Buffer number to use for matching. Mutually exclusive with
--- {contents} --- {contents}

View File

@ -315,7 +315,7 @@ end
--- Run a system command and timeout after 30 seconds. --- Run a system command and timeout after 30 seconds.
--- ---
--- @param cmd table List of command arguments to execute --- @param cmd table List of command arguments to execute
--- @param args ?table Optional arguments: --- @param args? table Optional arguments:
--- - stdin (string): Data to write to the job's stdin --- - stdin (string): Data to write to the job's stdin
--- - stderr (boolean): Append stderr to stdout --- - stderr (boolean): Append stderr to stdout
--- - ignore_error (boolean): If true, ignore error output --- - ignore_error (boolean): If true, ignore error output

View File

@ -181,9 +181,9 @@ end
--- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded) --- local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
--- ``` --- ```
--- ---
---@param f function(...):bool Takes all values returned from the previous stage ---@param f fun(...):bool Takes all values returned from the previous stage
--- in the pipeline and returns false or nil if the --- in the pipeline and returns false or nil if the
--- current iterator element should be removed. --- current iterator element should be removed.
---@return Iter ---@return Iter
function Iter.filter(self, f) function Iter.filter(self, f)
return self:map(function(...) return self:map(function(...)
@ -272,11 +272,11 @@ end
--- -- { 6, 12 } --- -- { 6, 12 }
--- ``` --- ```
--- ---
---@param f function(...):any Mapping function. Takes all values returned from ---@param f fun(...):any Mapping function. Takes all values returned from
--- the previous stage in the pipeline as arguments --- the previous stage in the pipeline as arguments
--- and returns one or more new values, which are used --- and returns one or more new values, which are used
--- in the next pipeline stage. Nil return values --- in the next pipeline stage. Nil return values
--- are filtered from the output. --- are filtered from the output.
---@return Iter ---@return Iter
function Iter.map(self, f) function Iter.map(self, f)
-- Implementation note: the reader may be forgiven for observing that this -- Implementation note: the reader may be forgiven for observing that this
@ -340,9 +340,9 @@ end
--- ---
--- For functions with side effects. To modify the values in the iterator, use |Iter:map()|. --- For functions with side effects. To modify the values in the iterator, use |Iter:map()|.
--- ---
---@param f function(...) Function to execute for each item in the pipeline. ---@param f fun(...) Function to execute for each item in the pipeline.
--- 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)
local function fn(...) local function fn(...)
if select(1, ...) ~= nil then if select(1, ...) ~= nil then
@ -464,7 +464,7 @@ end
---@generic A ---@generic A
--- ---
---@param init A Initial value of the accumulator. ---@param init A Initial value of the accumulator.
---@param f function(acc:A, ...):A Accumulation function. ---@param f fun(acc:A, ...):A Accumulation function.
---@return A ---@return A
function Iter.fold(self, init, f) function Iter.fold(self, init, f)
local acc = init local acc = init
@ -884,9 +884,9 @@ end
--- Returns true if any of the items in the iterator match the given predicate. --- Returns true if any of the items in the iterator match the given predicate.
--- ---
---@param pred function(...):bool Predicate function. Takes all values returned from the previous ---@param pred fun(...):bool Predicate function. Takes all values returned from the previous
--- stage in the pipeline as arguments and returns true if the --- stage in the pipeline as arguments and returns true if the
--- predicate matches. --- predicate matches.
function Iter.any(self, pred) function Iter.any(self, pred)
local any = false local any = false
@ -908,9 +908,9 @@ end
--- Returns true if all items in the iterator match the given predicate. --- Returns true if all items in the iterator match the given predicate.
--- ---
---@param pred function(...):bool Predicate function. Takes all values returned from the previous ---@param pred fun(...):bool Predicate function. Takes all values returned from the previous
--- stage in the pipeline as arguments and returns true if the --- stage in the pipeline as arguments and returns true if the
--- predicate matches. --- predicate matches.
function Iter.all(self, pred) function Iter.all(self, pred)
local all = true local all = true
@ -1106,9 +1106,9 @@ end
--- ---
---@see |Iter:filter()| ---@see |Iter:filter()|
--- ---
---@param f function(...):bool Filter function. Accepts the current iterator or table values as ---@param f fun(...):bool Filter function. Accepts the current iterator or table values as
--- arguments and returns true if those values should be kept in the --- arguments and returns true if those values should be kept in the
--- final table --- final table
---@param src table|function Table or iterator function to filter ---@param src table|function Table or iterator function to filter
---@return table ---@return table
function M.filter(f, src, ...) function M.filter(f, src, ...)
@ -1124,9 +1124,9 @@ end
--- ---
---@see |Iter:map()| ---@see |Iter:map()|
--- ---
---@param f function(...):?any Map function. Accepts the current iterator or table values as ---@param f fun(...): any? Map function. Accepts the current iterator or table values as
--- arguments and returns one or more new values. Nil values are removed --- arguments and returns one or more new values. Nil values are removed
--- from the final table. --- from the final table.
---@param src table|function Table or iterator function to filter ---@param src table|function Table or iterator function to filter
---@return table ---@return table
function M.map(f, src, ...) function M.map(f, src, ...)

View File

@ -516,7 +516,7 @@ end
--- ---
--- Displays call hierarchy in the quickfix window. --- Displays call hierarchy in the quickfix window.
--- ---
---@param direction `"from"` for incoming calls and `"to"` for outgoing calls ---@param direction 'from'|'to' `"from"` for incoming calls and `"to"` for outgoing calls
---@return function ---@return function
--- `CallHierarchyIncomingCall[]` if {direction} is `"from"`, --- `CallHierarchyIncomingCall[]` if {direction} is `"from"`,
--- `CallHierarchyOutgoingCall[]` if {direction} is `"to"`, --- `CallHierarchyOutgoingCall[]` if {direction} is `"to"`,

View File

@ -790,7 +790,7 @@ end
--- Note that if the input is of type `MarkupContent` and its kind is `plaintext`, --- Note that if the input is of type `MarkupContent` and its kind is `plaintext`,
--- then the corresponding value is returned without further modifications. --- then the corresponding value is returned without further modifications.
--- ---
---@param input (`MarkedString` | `MarkedString[]` | `MarkupContent`) ---@param input (lsp.MarkedString | lsp.MarkedString[] | lsp.MarkupContent)
---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}. ---@param contents (table|nil) List of strings to extend with converted lines. Defaults to {}.
---@return string[] extended with lines of converted markdown. ---@return string[] extended with lines of converted markdown.
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover ---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover
@ -2115,8 +2115,8 @@ end
--- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer. --- Returns the UTF-32 and UTF-16 offsets for a position in a certain buffer.
--- ---
---@param buf integer buffer number (0 for current) ---@param buf integer buffer number (0 for current)
---@param row 0-indexed line ---@param row integer 0-indexed line
---@param col 0-indexed byte offset in line ---@param col integer 0-indexed byte offset in line
---@param offset_encoding string utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf` ---@param offset_encoding string utf-8|utf-16|utf-32 defaults to `offset_encoding` of first client of `buf`
---@return integer `offset_encoding` index of the character in line {row} column {col} in buffer {buf} ---@return integer `offset_encoding` index of the character in line {row} column {col} in buffer {buf}
function M.character_offset(buf, row, col, offset_encoding) function M.character_offset(buf, row, col, offset_encoding)

View File

@ -875,7 +875,7 @@ end
--- a.b.c = 1 --- a.b.c = 1
--- ``` --- ```
--- ---
---@param createfn function?(key:any):any Provides the value for a missing `key`. ---@param createfn? fun(key:any):any Provides the value for a missing `key`.
---@return table # Empty table with `__index` metamethod. ---@return table # Empty table with `__index` metamethod.
function vim.defaulttable(createfn) function vim.defaulttable(createfn)
createfn = createfn or function(_) createfn = createfn or function(_)

View File

@ -793,7 +793,7 @@ end
--- of the query file, e.g., if the path ends in `/lua/highlights.scm`, the parser for the --- of the query file, e.g., if the path ends in `/lua/highlights.scm`, the parser for the
--- `lua` language will be used. --- `lua` language will be used.
---@param buf (integer) Buffer handle ---@param buf (integer) Buffer handle
---@param opts (QueryLinterOpts|nil) Optional keyword arguments: ---@param opts? QueryLinterOpts (table) Optional keyword arguments:
--- - langs (string|string[]|nil) Language(s) to use for checking the query. --- - langs (string|string[]|nil) Language(s) to use for checking the query.
--- If multiple languages are specified, queries are validated for all of them --- If multiple languages are specified, queries are validated for all of them
--- - clear (boolean) if `true`, just clear current lint errors --- - clear (boolean) if `true`, just clear current lint errors

View File

@ -717,12 +717,14 @@ def render_node(n: Element, text: str, prefix='', *,
elif n.nodeName in ('para', 'heading'): elif n.nodeName in ('para', 'heading'):
did_prefix = False did_prefix = False
for c in n.childNodes: for c in n.childNodes:
c_text = render_node(c, text, prefix=(prefix if not did_prefix else ''), indent=indent, width=width)
if (is_inline(c) if (is_inline(c)
and '' != get_text(c).strip() and '' != c_text.strip()
and text and text
and ' ' != text[-1]): and text[-1] not in (' ', '(', '|')
and not c_text.startswith(')')):
text += ' ' text += ' '
text += render_node(c, text, prefix=(prefix if not did_prefix else ''), indent=indent, width=width) text += c_text
did_prefix = True did_prefix = True
elif n.nodeName == 'itemizedlist': elif n.nodeName == 'itemizedlist':
for c in n.childNodes: for c in n.childNodes:
@ -840,15 +842,17 @@ def para_as_map(parent: Element,
raise RuntimeError('unhandled simplesect: {}\n{}'.format( raise RuntimeError('unhandled simplesect: {}\n{}'.format(
child.nodeName, child.toprettyxml(indent=' ', newl='\n'))) child.nodeName, child.toprettyxml(indent=' ', newl='\n')))
else: else:
child_text = render_node(child, text, indent=indent, width=width)
if (prev is not None if (prev is not None
and is_inline(self_or_child(prev)) and is_inline(self_or_child(prev))
and is_inline(self_or_child(child)) and is_inline(self_or_child(child))
and '' != get_text(self_or_child(child)).strip() and '' != get_text(self_or_child(child)).strip()
and text and text
and ' ' != text[-1]): and text[-1] not in (' ', '(', '|')
and not child_text.startswith(')')):
text += ' ' text += ' '
text += render_node(child, text, indent=indent, width=width) text += child_text
prev = child prev = child
chunks['text'] += text chunks['text'] += text

View File

@ -55,17 +55,7 @@ The effect is that you will get the function documented, but not with the parame
local TYPES = { 'integer', 'number', 'string', 'table', 'list', 'boolean', 'function' } local TYPES = { 'integer', 'number', 'string', 'table', 'list', 'boolean', 'function' }
local TAGGED_TYPES = { 'TSNode', 'LanguageTree' } local luacats_parser = require('src/nvim/generators/luacats_grammar')
-- Document these as 'table'
local ALIAS_TYPES = {
'Range',
'Range4',
'Range6',
'TSMetadata',
'vim.filetype.add.filetypes',
'vim.filetype.match.args',
}
local debug_outfile = nil --- @type string? local debug_outfile = nil --- @type string?
local debug_output = {} local debug_output = {}
@ -161,6 +151,91 @@ local function removeCommentFromLine(line)
return line:sub(1, pos_comment - 1), line:sub(pos_comment) return line:sub(1, pos_comment - 1), line:sub(pos_comment)
end end
--- @param parsed luacats.Return
--- @return string
local function get_return_type(parsed)
local elems = {} --- @type string[]
for _, v in ipairs(parsed) do
local e = v.type --- @type string
if v.name then
e = e .. ' ' .. v.name --- @type string
end
elems[#elems + 1] = e
end
return '(' .. table.concat(elems, ', ') .. ')'
end
--- @param name string
--- @return string
local function process_name(name, optional)
if optional then
name = name:sub(1, -2) --- @type string
end
return name
end
--- @param ty string
--- @param generics table<string,string>
--- @return string
local function process_type(ty, generics, optional)
-- replace generic types
for k, v in pairs(generics) do
ty = ty:gsub(k, v) --- @type string
end
-- strip parens
ty = ty:gsub('^%((.*)%)$', '%1')
if optional and not ty:find('nil') then
ty = ty .. '?'
end
-- remove whitespace in unions
ty = ty:gsub('%s*|%s*', '|')
-- replace '|nil' with '?'
ty = ty:gsub('|nil', '?')
ty = ty:gsub('nil|(.*)', '%1?')
return '(`' .. ty .. '`)'
end
--- @param parsed luacats.Param
--- @param generics table<string,string>
--- @return string
local function process_param(parsed, generics)
local name, ty = parsed.name, parsed.type
local optional = vim.endswith(name, '?')
return table.concat({
'/// @param',
process_name(name, optional),
process_type(ty, generics, optional),
parsed.desc,
}, ' ')
end
--- @param parsed luacats.Return
--- @param generics table<string,string>
--- @return string
local function process_return(parsed, generics)
local ty, name --- @type string, string
if #parsed == 1 then
ty, name = parsed[1].type, parsed[1].name or ''
else
ty, name = get_return_type(parsed), ''
end
local optional = vim.endswith(name, '?')
return table.concat({
'/// @return',
process_type(ty, generics, optional),
process_name(name, optional),
parsed.desc,
}, ' ')
end
--- Processes "@…" directives in a docstring line. --- Processes "@…" directives in a docstring line.
--- ---
--- @param line string --- @param line string
@ -175,93 +250,54 @@ local function process_magic(line, generics)
return '/// ' .. line return '/// ' .. line
end end
local magic = line:sub(2) local magic_split = vim.split(line, ' ', { plain = true })
local magic_split = vim.split(magic, ' ', { plain = true })
local directive = magic_split[1] local directive = magic_split[1]
if if
vim.list_contains({ vim.list_contains({
'cast', '@cast',
'diagnostic', '@diagnostic',
'overload', '@overload',
'meta', '@meta',
'type', '@type',
}, directive) }, directive)
then then
-- Ignore LSP directives -- Ignore LSP directives
return '// gg:"' .. line .. '"' return '// gg:"' .. line .. '"'
end elseif directive == '@defgroup' or directive == '@addtogroup' then
if directive == 'defgroup' or directive == 'addtogroup' then
-- Can't use '.' in defgroup, so convert to '--' -- Can't use '.' in defgroup, so convert to '--'
return '/// @' .. magic:gsub('%.', '-dot-') return '/// ' .. line:gsub('%.', '-dot-')
end end
if directive == 'generic' then -- preprocess line before parsing
local generic_name, generic_type = line:match('@generic%s*(%w+)%s*:?%s*(.*)') if directive == '@param' or directive == '@return' then
if generic_type == '' then for _, type in ipairs(TYPES) do
generic_type = 'any' line = line:gsub('^@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. ')%)', '@param %1 %2')
line = line:gsub('^@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '|nil)%)', '@param %1 %2')
line = line:gsub('^@return%s+.*%((' .. type .. ')%)', '@return %1')
line = line:gsub('^@return%s+.*%((' .. type .. '|nil)%)', '@return %1')
end end
generics[generic_name] = generic_type end
local parsed = luacats_parser:match(line)
if not parsed then
return '/// ' .. line
end
local kind = parsed.kind
if kind == 'generic' then
generics[parsed.name] = parsed.type or 'any'
return return
elseif kind == 'param' then
return process_param(parsed --[[@as luacats.Param]], generics)
elseif kind == 'return' then
return process_return(parsed --[[@as luacats.Return]], generics)
end end
local type_index = 2 error(string.format('unhandled parsed line %q: %s', line, parsed))
if directive == 'param' then
for _, type in ipairs(TYPES) do
magic = magic:gsub('^param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. ')%)', 'param %1 %2')
magic = magic:gsub('^param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '|nil)%)', 'param %1 %2')
end
magic_split = vim.split(magic, ' ', { plain = true })
type_index = 3
elseif directive == 'return' then
for _, type in ipairs(TYPES) do
magic = magic:gsub('^return%s+.*%((' .. type .. ')%)', 'return %1')
magic = magic:gsub('^return%s+.*%((' .. type .. '|nil)%)', 'return %1')
end
-- Remove first "#" comment char, if any. https://github.com/LuaLS/lua-language-server/wiki/Annotations#return
magic = magic:gsub('# ', '', 1)
-- handle the return of vim.spell.check
magic = magic:gsub('({.*}%[%])', '`%1`')
magic_split = vim.split(magic, ' ', { plain = true })
end
local ty = magic_split[type_index]
if ty then
-- fix optional parameters
if magic_split[2]:find('%?$') then
if not ty:find('nil') then
ty = ty .. '|nil'
end
magic_split[2] = magic_split[2]:sub(1, -2)
end
-- replace generic types
for k, v in pairs(generics) do
ty = ty:gsub(k, v) --- @type string
end
for _, type in ipairs(TAGGED_TYPES) do
ty = ty:gsub(type, '|%1|')
end
for _, type in ipairs(ALIAS_TYPES) do
ty = ty:gsub('^' .. type .. '$', 'table') --- @type string
end
-- surround some types by ()
for _, type in ipairs(TYPES) do
ty = ty:gsub('^(' .. type .. '|nil):?$', '(%1)'):gsub('^(' .. type .. '):?$', '(%1)')
end
magic_split[type_index] = ty
end
magic = table.concat(magic_split, ' ')
return '/// @' .. magic
end end
--- @param line string --- @param line string

View File

@ -925,6 +925,8 @@ add_custom_command(
${API_SOURCES} ${API_SOURCES}
${LUA_SOURCES} ${LUA_SOURCES}
${VIMDOC_FILES} ${VIMDOC_FILES}
${PROJECT_SOURCE_DIR}/scripts/gen_vimdoc.py
${PROJECT_SOURCE_DIR}/scripts/lua2dox.lua
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
) )

View File

@ -0,0 +1,136 @@
--[[!
LPEG grammar for LuaCATS
Currently only partially supports:
- @param
- @return
]]
local lpeg = vim.lpeg
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local Ct, Cg = lpeg.Ct, lpeg.Cg
--- @param x vim.lpeg.Pattern
local function rep(x)
return x ^ 0
end
--- @param x vim.lpeg.Pattern
local function rep1(x)
return x ^ 1
end
--- @param x vim.lpeg.Pattern
local function opt(x)
return x ^ -1
end
local nl = P('\r\n') + P('\n')
local ws = rep1(S(' \t') + nl)
local fill = opt(ws)
local any = P(1) -- (consume one character)
local letter = R('az', 'AZ') + S('_$')
local num = R('09')
local ident = letter * rep(letter + num + S '-.')
local string_single = P "'" * rep(any - P "'") * P "'"
local string_double = P '"' * rep(any - P '"') * P '"'
local literal = (string_single + string_double + (opt(P '-') * num) + P 'false' + P 'true')
local lname = (ident + P '...') * opt(P '?')
--- @param x string
local function Pf(x)
return fill * P(x) * fill
end
--- @param x string
local function Sf(x)
return fill * S(x) * fill
end
--- @param x vim.lpeg.Pattern
local function comma(x)
return x * rep(Pf ',' * x)
end
--- @param x vim.lpeg.Pattern
local function parenOpt(x)
return (Pf('(') * x ^ -1 * fill * P(')')) + x ^ -1
end
--- @type table<string,vim.lpeg.Pattern>
local v = setmetatable({}, {
__index = function(_, k)
return lpeg.V(k)
end,
})
local desc_delim = Sf '#:' + ws
--- @class luacats.Param
--- @field kind 'param'
--- @field name string
--- @field type string
--- @field desc? string
--- @class luacats.Return
--- @field kind 'return'
--- @field [integer] { type: string, name?: string}
--- @field desc? string
--- @class luacats.Generic
--- @field kind 'generic'
--- @field name string
--- @field type? string
--- @alias luacats.grammar.result
--- | luacats.Param
--- | luacats.Return
--- | luacats.Generic
--- @class luacats.grammar
--- @field match fun(self, input: string): luacats.grammar.result?
local grammar = P {
rep1(P('@') * v.ats),
ats = (v.at_param + v.at_return + v.at_generic),
at_param = Ct(
Cg(P('param'), 'kind')
* ws
* Cg(lname, 'name')
* ws
* Cg(v.ltype, 'type')
* opt(desc_delim * Cg(rep(any), 'desc'))
),
at_return = Ct(
Cg(P('return'), 'kind')
* ws
* parenOpt(comma(Ct(Cg(v.ltype, 'type') * opt(ws * Cg(ident, 'name')))))
* opt(desc_delim * Cg(rep(any), 'desc'))
),
at_generic = Ct(
Cg(P('generic'), 'kind') * ws * Cg(ident, 'name') * opt(Pf ':' * Cg(v.ltype, 'type'))
),
ltype = v.ty_union + Pf '(' * v.ty_union * fill * P ')',
ty_union = v.ty_opt * rep(Pf '|' * v.ty_opt),
ty = v.ty_fun + ident + v.ty_table + literal,
ty_param = Pf '<' * comma(v.ltype) * fill * P '>',
ty_opt = v.ty * opt(v.ty_param) * opt(P '[]') * opt(P '?'),
table_key = (Pf '[' * literal * Pf ']') + lname,
table_elem = v.table_key * Pf ':' * v.ltype,
ty_table = Pf '{' * comma(v.table_elem) * Pf '}',
fun_param = lname * opt(Pf ':' * v.ltype),
ty_fun = Pf 'fun(' * rep(comma(v.fun_param)) * fill * P ')' * opt(Pf ':' * v.ltype),
}
return grammar --[[@as luacats.grammar]]

View File

@ -0,0 +1,133 @@
local helpers = require('test.functional.helpers')(after_each)
local eq = helpers.eq
local grammar = require('src/nvim/generators/luacats_grammar')
describe('luacats grammar', function()
--- @param text string
--- @param exp table<string,string>
local function test(text, exp)
it(string.format('can parse %q', text), function()
eq(exp, grammar:match(text))
end)
end
test('@param hello vim.type', {
kind = 'param',
name = 'hello',
type = 'vim.type',
})
test('@param hello vim.type this is a description', {
kind = 'param',
name = 'hello',
type = 'vim.type',
desc = 'this is a description',
})
test('@param hello vim.type|string this is a description', {
kind = 'param',
name = 'hello',
type = 'vim.type|string',
desc = 'this is a description',
})
test('@param hello vim.type?|string? this is a description', {
kind = 'param',
name = 'hello',
type = 'vim.type?|string?',
desc = 'this is a description',
})
test('@return string hello this is a description', {
kind = 'return',
{
name = 'hello',
type = 'string',
},
desc = 'this is a description',
})
test('@return fun() hello this is a description', {
kind = 'return',
{
name = 'hello',
type = 'fun()',
},
desc = 'this is a description',
})
test('@return fun(a: string[]): string hello this is a description', {
kind = 'return',
{
name = 'hello',
type = 'fun(a: string[]): string',
},
desc = 'this is a description',
})
test('@return fun(a: table<string,any>): string hello this is a description', {
kind = 'return',
{
name = 'hello',
type = 'fun(a: table<string,any>): string',
},
desc = 'this is a description',
})
test('@param ... string desc', {
kind = 'param',
name = '...',
type = 'string',
desc = 'desc',
})
test('@param level (integer|string) desc', {
kind = 'param',
name = 'level',
type = '(integer|string)',
desc = 'desc',
})
test('@return (string command) the command and arguments', {
kind = 'return',
{
name = 'command',
type = 'string',
},
desc = 'the command and arguments',
})
test('@return (string command, string[] args) the command and arguments', {
kind = 'return',
{
name = 'command',
type = 'string',
},
{
name = 'args',
type = 'string[]',
},
desc = 'the command and arguments',
})
test('@param rfc "rfc2396" | "rfc2732" | "rfc3986" | nil', {
kind = 'param',
name = 'rfc',
type = '"rfc2396" | "rfc2732" | "rfc3986" | nil',
})
test('@param offset_encoding "utf-8" | "utf-16" | "utf-32" | nil', {
kind = 'param',
name = 'offset_encoding',
type = '"utf-8" | "utf-16" | "utf-32" | nil',
})
-- handle a : after the param type
test('@param a b: desc', {
kind = 'param',
name = 'a',
type = 'b',
desc = 'desc',
})
end)