diff options
Diffstat (limited to 'runtime/doc/treesitter.txt')
-rw-r--r-- | runtime/doc/treesitter.txt | 726 |
1 files changed, 445 insertions, 281 deletions
diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt index 9bdc6b8d24..5f33802ad5 100644 --- a/runtime/doc/treesitter.txt +++ b/runtime/doc/treesitter.txt @@ -17,25 +17,33 @@ changes. This documentation may also not fully reflect the latest changes. ============================================================================== PARSER FILES *treesitter-parsers* -Parsers are the heart of tree-sitter. They are libraries that tree-sitter will +Parsers are the heart of treesitter. They are libraries that treesitter will search for in the `parser` runtime directory. By default, Nvim bundles parsers for C, Lua, Vimscript, Vimdoc and Treesitter query files, but parsers can be -installed manually or via a plugin like -https://github.com/nvim-treesitter/nvim-treesitter. Parsers are searched for -as `parser/{lang}.*` in any 'runtimepath' directory. If multiple parsers for -the same language are found, the first one is used. (This typically implies -the priority "user config > plugins > bundled". +installed via a plugin like https://github.com/nvim-treesitter/nvim-treesitter +or even manually. + +Parsers are searched for as `parser/{lang}.*` in any 'runtimepath' directory. +If multiple parsers for the same language are found, the first one is used. +(NOTE: This typically implies the priority "user config > plugins > bundled".) A parser can also be loaded manually using a full path: >lua vim.treesitter.language.add('python', { path = "/path/to/python.so" }) < +To associate certain |filetypes| with a treesitter language (name of parser), +use |vim.treesitter.language.register()|. For example, to use the `xml` +treesitter parser for buffers with filetype `svg` or `xslt`, use: >lua + + vim.treesitter.language.register('xml', { 'svg', 'xslt' }) +< + ============================================================================== TREESITTER TREES *treesitter-tree* *TSTree* A "treesitter tree" represents the parsed contents of a buffer, which can be used to perform further analysis. It is a |userdata| reference to an object -held by the tree-sitter library. +held by the treesitter library. An instance `TSTree` of a treesitter tree supports the following methods. @@ -51,7 +59,7 @@ TREESITTER NODES *treesitter-node* A "treesitter node" represents one specific element of the parsed contents of a buffer, which can be captured by a |Query| for, e.g., highlighting. It is -a |userdata| reference to an object held by the tree-sitter library. +a |userdata| reference to an object held by the treesitter library. An instance `TSNode` of a treesitter node supports the following methods. @@ -202,33 +210,53 @@ TREESITTER QUERY PREDICATES *treesitter-predicates* Predicates are special scheme nodes that are evaluated to conditionally capture nodes. For example, the `eq?` predicate can be used as follows: >query - ((identifier) @foo (#eq? @foo "foo")) + ((identifier) @variable.builtin + (#eq? @variable.builtin "self")) < -to only match identifier corresponding to the `"foo"` text. +to only match identifier corresponding to the `"self"` text. Such queries can +be used to highlight built-in functions or variables differently, for instance. The following predicates are built in: `eq?` *treesitter-predicate-eq?* Match a string against the text corresponding to a node: >query - ((identifier) @foo (#eq? @foo "foo")) + ((identifier) @variable.builtin (#eq? @variable.builtin "self")) ((node1) @left (node2) @right (#eq? @left @right)) < + `any-eq?` *treesitter-predicate-any-eq?* + Like `eq?`, but for quantified patterns only one captured node must + match. + `match?` *treesitter-predicate-match?* `vim-match?` *treesitter-predicate-vim-match?* Match a |regexp| against the text corresponding to a node: >query ((identifier) @constant (#match? @constant "^[A-Z_]+$")) -< Note: The `^` and `$` anchors will match the start and end of the +< + Note: The `^` and `$` anchors will match the start and end of the node's text. + `any-match?` *treesitter-predicate-any-match?* + `any-vim-match?` *treesitter-predicate-any-vim-match?* + Like `match?`, but for quantified patterns only one captured node must + match. + `lua-match?` *treesitter-predicate-lua-match?* Match |lua-patterns| against the text corresponding to a node, similar to `match?` + `any-lua-match?` *treesitter-predicate-any-lua-match?* + Like `lua-match?`, but for quantified patterns only one captured node + must match. + `contains?` *treesitter-predicate-contains?* Match a string against parts of the text corresponding to a node: >query ((identifier) @foo (#contains? @foo "foo")) ((identifier) @foo-bar (#contains? @foo-bar "foo" "bar")) < + `any-contains?` *treesitter-predicate-any-contains?* + Like `contains?`, but for quantified patterns only one captured node + must match. + `any-of?` *treesitter-predicate-any-of?* Match any of the given strings against the text corresponding to a node: >query @@ -254,6 +282,32 @@ The following predicates are built in: Each predicate has a `not-` prefixed predicate that is just the negation of the predicate. + *lua-treesitter-all-predicate* + *lua-treesitter-any-predicate* +Queries can use quantifiers to capture multiple nodes. When a capture contains +multiple nodes, predicates match only if ALL nodes contained by the capture +match the predicate. Some predicates (`eq?`, `match?`, `lua-match?`, +`contains?`) accept an `any-` prefix to instead match if ANY of the nodes +contained by the capture match the predicate. + +As an example, consider the following Lua code: >lua + + -- TODO: This is a + -- very long + -- comment (just imagine it) +< +using the following predicated query: +>query + (((comment)+ @comment) + (#match? @comment "TODO")) +< +This query will not match because not all of the nodes captured by @comment +match the predicate. Instead, use: +>query + (((comment)+ @comment) + (#any-match? @comment "TODO")) +< + Further predicates can be added via |vim.treesitter.query.add_predicate()|. Use |vim.treesitter.query.list_predicates()| to list all available predicates. @@ -280,11 +334,12 @@ The following directives are built in: Examples: >query ((identifier) @foo (#set! @foo "kind" "parameter")) ((node1) @left (node2) @right (#set! "type" "pair")) + ((codeblock) @markup.raw.block (#set! "priority" 90)) < `offset!` *treesitter-directive-offset!* Takes the range of the captured node and applies an offset. This will - generate a new range object for the captured node as - `metadata[capture_id].range`. + set a new `Range4` object for the captured node with `capture_id` as + `metadata[capture_id].range`. Useful for |treesitter-language-injections|. Parameters: ~ {capture_id} @@ -297,12 +352,13 @@ The following directives are built in: ((identifier) @constant (#offset! @constant 0 1 0 -1)) < `gsub!` *treesitter-directive-gsub!* - Transforms the content of the node using a Lua pattern. This will set + Transforms the content of the node using a |lua-pattern|. This will set a new `metadata[capture_id].text`. Parameters: ~ {capture_id} {pattern} + {replacement} Example: >query (#gsub! @_node ".*%.(.*)" "%1") @@ -344,13 +400,13 @@ currently supported modeline alternatives: Note: These modeline comments must be at the top of the query, but can be repeated, for example, the following two modeline blocks are both valid: >query - ;; inherits: foo,bar + ;; inherits: typescript,jsx ;; extends < >query ;; extends ;; - ;; inherits: baz + ;; inherits: css < ============================================================================== TREESITTER SYNTAX HIGHLIGHTING *treesitter-highlight* @@ -359,30 +415,47 @@ Syntax highlighting is specified through queries named `highlights.scm`, which match a |TSNode| in the parsed |TSTree| to a `capture` that can be assigned a highlight group. For example, the query >query - (parameters (identifier) @parameter) + (parameters (identifier) @variable.parameter) < -matches any `identifier` node inside a function `parameter` node (e.g., the -`bar` in `foo(bar)`) to the capture named `@parameter`. It is also possible to -match literal expressions (provided the parser returns them): >query +matches any `identifier` node inside a function `parameters` node to the +capture named `@variable.parameter`. For example, for a Lua code >lua - "return" @keyword.return + function f(foo, bar) end +< +which will be parsed as (see |:InspectTree|): >query + + (function_declaration ; [1:1 - 24] + name: (identifier) ; [1:10 - 10] + parameters: (parameters ; [1:11 - 20] + name: (identifier) ; [1:12 - 14] + name: (identifier))) ; [1:17 - 19] +< +the above query will highlight `foo` and `bar` as `@variable.parameter`. + +It is also possible to match literal expressions (provided the parser returns +them): +>query + [ + "if" + "else" + ] @keyword.conditional < Assuming a suitable parser and `highlights.scm` query is found in runtimepath, treesitter highlighting for the current buffer can be enabled simply via |vim.treesitter.start()|. *treesitter-highlight-groups* -The capture names, with `@` included, are directly usable as highlight groups. +The capture names, prefixed with `@`, are directly usable as highlight groups. For many commonly used captures, the corresponding highlight groups are linked -to Nvim's standard |highlight-groups| by default but can be overridden in -colorschemes. +to Nvim's standard |highlight-groups| by default (e.g., `@comment` links to +`Comment`) but can be overridden in colorschemes. A fallback system is implemented, so that more specific groups fallback to -more generic ones. For instance, in a language that has separate doc comments, -`@comment.doc` could be used. If this group is not defined, the highlighting -for an ordinary `@comment` is used. This way, existing color schemes already -work out of the box, but it is possible to add more specific variants for -queries that make them available. +more generic ones. For instance, in a language that has separate doc comments +(e.g., c, java, etc.), `@comment.documentation` could be used. If this group +is not defined, the highlighting for an ordinary `@comment` is used. This way, +existing color schemes already work out of the box, but it is possible to add +more specific variants for queries that make them available. As an additional rule, capture highlights can always be specialized by language, by appending the language name after an additional dot. For @@ -390,61 +463,119 @@ instance, to highlight comments differently per language: >vim hi @comment.c guifg=Blue hi @comment.lua guifg=DarkBlue - hi link @comment.doc.java String -< -The following captures are linked by default to standard |group-name|s: -> - @text.literal Comment - @text.reference Identifier - @text.title Title - @text.uri Underlined - @text.underline Underlined - @text.todo Todo - - @comment Comment - @punctuation Delimiter - - @constant Constant - @constant.builtin Special - @constant.macro Define - @define Define - @macro Macro - @string String - @string.escape SpecialChar - @string.special SpecialChar - @character Character - @character.special SpecialChar - @number Number - @boolean Boolean - @float Float - - @function Function - @function.builtin Special - @function.macro Macro - @parameter Identifier - @method Function - @field Identifier - @property Identifier - @constructor Special - - @conditional Conditional - @repeat Repeat - @label Label - @operator Operator - @keyword Keyword - @exception Exception - - @variable Identifier - @type Type - @type.definition Typedef - @storageclass StorageClass - @structure Structure - @namespace Identifier - @include Include - @preproc PreProc - @debug Debug - @tag Tag + hi link @comment.documentation.java String < +The following is a list of standard captures used in queries for Nvim, +highlighted according to the current colorscheme (use |:Inspect| on one to see +the exact definition): + +@variable various variable names +@variable.builtin built-in variable names (e.g. `this` / `self`) +@variable.parameter parameters of a function +@variable.member object and struct fields + +@constant constant identifiers +@constant.builtin built-in constant values +@constant.macro constants defined by the preprocessor + +@module modules or namespaces +@module.builtin built-in modules or namespaces +@label GOTO and other labels (e.g. `label:` in C), including heredoc labels + +@string string literals +@string.documentation string documenting code (e.g. Python docstrings) +@string.regexp regular expressions +@string.escape escape sequences +@string.special other special strings (e.g. dates) +@string.special.symbol symbols or atoms +@string.special.path filenames +@string.special.url URIs (e.g. hyperlinks) + +@character character literals +@character.special special characters (e.g. wildcards) + +@boolean boolean literals +@number numeric literals +@number.float floating-point number literals + +@type type or class definitions and annotations +@type.builtin built-in types +@type.definition identifiers in type definitions (e.g. `typedef <type> <identifier>` in C) +@type.qualifier type qualifiers (e.g. `const`) + +@attribute attribute annotations (e.g. Python decorators) +@property the key in key/value pairs + +@function function definitions +@function.builtin built-in functions +@function.call function calls +@function.macro preprocessor macros + +@function.method method definitions +@function.method.call method calls + +@constructor constructor calls and definitions +@operator symbolic operators (e.g. `+` / `*`) + +@keyword keywords not fitting into specific categories +@keyword.coroutine keywords related to coroutines (e.g. `go` in Go, `async/await` in Python) +@keyword.function keywords that define a function (e.g. `func` in Go, `def` in Python) +@keyword.operator operators that are English words (e.g. `and` / `or`) +@keyword.import keywords for including modules (e.g. `import` / `from` in Python) +@keyword.storage modifiers that affect storage in memory or life-time +@keyword.repeat keywords related to loops (e.g. `for` / `while`) +@keyword.return keywords like `return` and `yield` +@keyword.debug keywords related to debugging +@keyword.exception keywords related to exceptions (e.g. `throw` / `catch`) + +@keyword.conditional keywords related to conditionals (e.g. `if` / `else`) +@keyword.conditional.ternary ternary operator (e.g. `?` / `:`) + +@keyword.directive various preprocessor directives and shebangs +@keyword.directive.define preprocessor definition directives + +@punctuation.delimiter delimiters (e.g. `;` / `.` / `,`) +@punctuation.bracket brackets (e.g. `()` / `{}` / `[]`) +@punctuation.special special symbols (e.g. `{}` in string interpolation) + +@comment line and block comments +@comment.documentation comments documenting code + +@comment.error error-type comments (e.g. `ERROR`, `FIXME`, `DEPRECATED`) +@comment.warning warning-type comments (e.g. `WARNING`, `FIX`, `HACK`) +@comment.todo todo-type comments (e.g. `TODO`, `WIP`, `FIXME`) +@comment.note note-type comments (e.g. `NOTE`, `INFO`, `XXX`) + +@markup.strong bold text +@markup.italic italic text +@markup.strikethrough struck-through text +@markup.underline underlined text (only for literal underline markup!) + +@markup.heading headings, titles (including markers) + +@markup.quote block quotes +@markup.math math environments (e.g. `$ ... $` in LaTeX) +@markup.environment environments (e.g. in LaTeX) + +@markup.link text references, footnotes, citations, etc. +@markup.link.label link, reference descriptions +@markup.link.url URL-style links + +@markup.raw literal or verbatim text (e.g. inline code) +@markup.raw.block literal or verbatim text as a stand-alone block + +@markup.list list markers +@markup.list.checked checked todo-style list markers +@markup.list.unchecked unchecked todo-style list markers + +@diff.plus added text (for diff files) +@diff.minus deleted text (for diff files) +@diff.delta changed text (for diff files) + +@tag XML-style tag names (e.g. in XML, HTML, etc.) +@tag.attribute XML-style tag attributes +@tag.delimiter XML-style tag delimiters + *treesitter-highlight-spell* The special `@spell` capture can be used to indicate that a node should be spell checked by Nvim's builtin |spell| checker. For example, the following @@ -475,7 +606,7 @@ Conceals specified in this way respect 'conceallevel'. *treesitter-highlight-priority* Treesitter uses |nvim_buf_set_extmark()| to set highlights with a default priority of 100. This enables plugins to set a highlighting priority lower or -higher than tree-sitter. It is also possible to change the priority of an +higher than treesitter. It is also possible to change the priority of an individual query pattern manually by setting its `"priority"` metadata attribute: >query @@ -536,17 +667,17 @@ associated with patterns: VIM.TREESITTER *lua-treesitter* The remainder of this document is a reference manual for the `vim.treesitter` -Lua module, which is the main interface for Nvim's tree-sitter integration. +Lua module, which is the main interface for Nvim's treesitter integration. Most of the following content is automatically generated from the function documentation. *vim.treesitter.language_version* -The latest parser ABI version that is supported by the bundled tree-sitter +The latest parser ABI version that is supported by the bundled treesitter library. *vim.treesitter.minimum_language_version* -The earliest parser ABI version that is supported by the bundled tree-sitter +The earliest parser ABI version that is supported by the bundled treesitter library. ============================================================================== @@ -559,30 +690,20 @@ foldexpr({lnum}) *vim.treesitter.foldexpr()* < Parameters: ~ - • {lnum} (integer|nil) Line number to calculate fold level for - - Return: ~ - (string) - -foldtext() *vim.treesitter.foldtext()* - Returns the highlighted content of the first line of the fold or falls - back to |foldtext()| if no treesitter parser is found. Can be set directly - to 'foldtext': >lua - vim.wo.foldtext = 'v:lua.vim.treesitter.foldtext()' -< + • {lnum} (`integer?`) Line number to calculate fold level for Return: ~ - `{ [1]: string, [2]: string[] }[]` | string + (`string`) *vim.treesitter.get_captures_at_cursor()* get_captures_at_cursor({winnr}) Returns a list of highlight capture names under the cursor Parameters: ~ - • {winnr} (integer|nil) Window handle or 0 for current window (default) + • {winnr} (`integer?`) Window handle or 0 for current window (default) Return: ~ - string[] List of capture names + (`string[]`) List of capture names *vim.treesitter.get_captures_at_pos()* get_captures_at_pos({bufnr}, {row}, {col}) @@ -593,12 +714,13 @@ get_captures_at_pos({bufnr}, {row}, {col}) if none are defined). Parameters: ~ - • {bufnr} (integer) Buffer number (0 for current buffer) - • {row} (integer) Position row - • {col} (integer) Position column + • {bufnr} (`integer`) Buffer number (0 for current buffer) + • {row} (`integer`) Position row + • {col} (`integer`) Position column Return: ~ - table[] List of captures `{ capture = "name", metadata = { ... } }` + (`table[]`) List of captures + `{ capture = "name", metadata = { ... } }` get_node({opts}) *vim.treesitter.get_node()* Returns the smallest named node at the given position @@ -610,45 +732,47 @@ get_node({opts}) *vim.treesitter.get_node()* < Parameters: ~ - • {opts} (table|nil) Optional keyword arguments: - • bufnr integer|nil Buffer number (nil or 0 for current + • {opts} (`table?`) Optional keyword arguments: + • {bufnr} (`integer?`) Buffer number (nil or 0 for current buffer) - • pos table|nil 0-indexed (row, col) tuple. Defaults to cursor - position in the current window. Required if {bufnr} is not - the current buffer - • ignore_injections boolean Ignore injected languages (default - true) + • {pos} (`{ [1]: integer, [2]: integer }?`) 0-indexed (row, + col) tuple. Defaults to cursor position in the current + window. Required if {bufnr} is not the current buffer + • {lang} (`string?`) Parser language. (default: from buffer + filetype) + • {ignore_injections} (`boolean?`) Ignore injected languages + (default true) 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()* Returns the node's range or an unpacked range table Parameters: ~ - • {node_or_range} (|TSNode| | table) Node or table of positions + • {node_or_range} (`TSNode|table`) Node or table of positions Return (multiple): ~ - (integer) start_row - (integer) start_col - (integer) end_row - (integer) end_col + (`integer`) start_row + (`integer`) start_col + (`integer`) end_row + (`integer`) end_col *vim.treesitter.get_node_text()* get_node_text({node}, {source}, {opts}) Gets the text corresponding to a given node Parameters: ~ - • {node} |TSNode| - • {source} (integer|string) Buffer or string from which the {node} is + • {node} (`TSNode`) + • {source} (`integer|string`) Buffer or string from which the {node} is extracted - • {opts} (table|nil) Optional parameters. + • {opts} (`table?`) Optional parameters. • metadata (table) Metadata of a specific capture. This would be set to `metadata[capture_id]` when using |vim.treesitter.query.add_directive()|. Return: ~ - (string) + (`string`) get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* Returns the parser for a specific buffer and attaches it to the buffer @@ -656,39 +780,39 @@ get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()* If needed, this will create the parser. Parameters: ~ - • {bufnr} (integer|nil) Buffer the parser should be tied to (default: + • {bufnr} (`integer?`) Buffer the parser should be tied to (default: current buffer) - • {lang} (string|nil) Filetype of this parser (default: buffer + • {lang} (`string?`) Language of this parser (default: from buffer filetype) - • {opts} (table|nil) Options to pass to the created language tree + • {opts} (`table?`) Options to pass to the created language tree Return: ~ - |LanguageTree| object to use for parsing + (`vim.treesitter.LanguageTree`) object to use for parsing 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 with directives applied. Parameters: ~ - • {node} |TSNode| - • {source} integer|string|nil Buffer or string from which the {node} + • {node} (`TSNode`) + • {source} (`integer|string?`) Buffer or string from which the {node} is extracted - • {metadata} TSMetadata|nil + • {metadata} (`vim.treesitter.query.TSMetadata?`) Return: ~ - (table) + (`Range6`) *vim.treesitter.get_string_parser()* get_string_parser({str}, {lang}, {opts}) Returns a string parser Parameters: ~ - • {str} (string) Text to parse - • {lang} (string) Language of this string - • {opts} (table|nil) Options to pass to the created language tree + • {str} (`string`) Text to parse + • {lang} (`string`) Language of this string + • {opts} (`table?`) Options to pass to the created language tree Return: ~ - |LanguageTree| object to use for parsing + (`vim.treesitter.LanguageTree`) object to use for parsing inspect_tree({opts}) *vim.treesitter.inspect_tree()* Open a window that displays a textual representation of the nodes in the @@ -697,15 +821,15 @@ inspect_tree({opts}) *vim.treesitter.inspect_tree()* While in the window, press "a" to toggle display of anonymous nodes, "I" to toggle the display of the source language of each node, "o" to toggle the query editor, and press <Enter> to jump to the node under the cursor - in the source buffer. + in the source buffer. Folding also works (try |zo|, |zc|, etc.). Can also be shown with `:InspectTree`. *:InspectTree* Parameters: ~ - • {opts} (table|nil) Optional options table with the following possible + • {opts} (`table?`) Optional options table with the following possible keys: • lang (string|nil): The language of the source buffer. If - omitted, the filetype of the source buffer is used. + omitted, detect from the filetype of the source buffer. • bufnr (integer|nil): Buffer to draw the tree into. If omitted, a new buffer is created. • winid (integer|nil): Window id to display the tree buffer @@ -722,33 +846,33 @@ is_ancestor({dest}, {source}) *vim.treesitter.is_ancestor()* Determines whether a node is the ancestor of another Parameters: ~ - • {dest} |TSNode| Possible ancestor - • {source} |TSNode| Possible descendant + • {dest} (`TSNode`) Possible ancestor + • {source} (`TSNode`) Possible descendant 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()* is_in_node_range({node}, {line}, {col}) Determines whether (line, col) position is in node range Parameters: ~ - • {node} |TSNode| defining the range - • {line} (integer) Line (0-based) - • {col} (integer) Column (0-based) + • {node} (`TSNode`) defining the range + • {line} (`integer`) Line (0-based) + • {col} (`integer`) Column (0-based) 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()* Determines if a node contains a range Parameters: ~ - • {node} |TSNode| - • {range} (table) + • {node} (`TSNode`) + • {range} (`table`) Return: ~ - (boolean) True if the {node} contains the {range} + (`boolean`) True if the {node} contains the {range} start({bufnr}, {lang}) *vim.treesitter.start()* Starts treesitter highlighting for a buffer @@ -769,16 +893,16 @@ start({bufnr}, {lang}) *vim.treesitter.start()* < Parameters: ~ - • {bufnr} (integer|nil) Buffer to be highlighted (default: current + • {bufnr} (`integer?`) Buffer to be highlighted (default: current buffer) - • {lang} (string|nil) Language of the parser (default: buffer + • {lang} (`string?`) Language of the parser (default: from buffer filetype) stop({bufnr}) *vim.treesitter.stop()* Stops treesitter highlighting for a buffer Parameters: ~ - • {bufnr} (integer|nil) Buffer to stop highlighting (default: current + • {bufnr} (`integer?`) Buffer to stop highlighting (default: current buffer) @@ -792,29 +916,30 @@ add({lang}, {opts}) *vim.treesitter.language.add()* {path} Parameters: ~ - • {lang} (string) Name of the parser (alphanumerical and `_` only) - • {opts} (table|nil) Options: - • filetype (string|string[]) Default filetype the parser - should be associated with. Defaults to {lang}. - • path (string|nil) Optional path the parser is located at - • symbol_name (string|nil) Internal symbol name for the + • {lang} (`string`) Name of the parser (alphanumerical and `_` only) + • {opts} (`table?`) Options: + • {filetype}? (`string|string[]`, default: {lang}) Default + filetype the parser should be associated with. + • {path}? (`string`) Optional path the parser is located at + • {symbol_name}? (`string`) Internal symbol name for the language to load get_filetypes({lang}) *vim.treesitter.language.get_filetypes()* Get the filetypes associated with the parser named {lang}. Parameters: ~ - • {lang} (string) Name of parser + • {lang} (`string`) Name of parser Return: ~ - string[] filetypes + (`string[]`) filetypes get_lang({filetype}) *vim.treesitter.language.get_lang()* + Parameters: ~ - • {filetype} (string) + • {filetype} (`string`) Return: ~ - (string|nil) + (`string?`) inspect({lang}) *vim.treesitter.language.inspect()* Inspects the provided language. @@ -823,55 +948,70 @@ inspect({lang}) *vim.treesitter.language.inspect()* names, ... Parameters: ~ - • {lang} (string) Language + • {lang} (`string`) Language Return: ~ - (table) + (`table`) register({lang}, {filetype}) *vim.treesitter.language.register()* Register a parser named {lang} to be used for {filetype}(s). + Note: this adds or overrides the mapping for {filetype}, any existing + mappings from other filetypes to {lang} will be preserved. + Parameters: ~ - • {lang} (string) Name of parser - • {filetype} string|string[] Filetype(s) to associate with lang + • {lang} (`string`) Name of parser + • {filetype} (`string|string[]`) Filetype(s) to associate with lang ============================================================================== Lua module: vim.treesitter.query *lua-treesitter-query* *vim.treesitter.query.add_directive()* -add_directive({name}, {handler}, {force}) +add_directive({name}, {handler}, {opts}) Adds a new directive to be used in queries Handlers can set match level data by setting directly on the metadata - object `metadata.key = value`, additionally, handlers can set node level + object `metadata.key = value`. Additionally, handlers can set node level data by using the capture id on the metadata table `metadata[capture_id].key = value` Parameters: ~ - • {name} (string) Name of the directive, without leading # - • {handler} function(match:table<string,|TSNode|>, pattern:string, - bufnr:integer, predicate:string[], metadata:table) - • match: see |treesitter-query| - • node-level data are accessible via `match[capture_id]` - - • pattern: see |treesitter-query| + • {name} (`string`) Name of the directive, without leading # + • {handler} (`function`) + • match: A table mapping capture IDs to a list of captured + nodes + • pattern: the index of the matching pattern in the query + file • predicate: list of strings containing the full directive being called, e.g. `(node (#set! conceal "-"))` would get the predicate `{ "#set!", "conceal", "-" }` - • {force} (boolean|nil) + • {opts} (`table<string, any>`) Optional options: + • force (boolean): Override an existing predicate of the + same name + • all (boolean): Use the correct implementation of the + match table where capture IDs map to a list of nodes + instead of a single node. Defaults to false (for backward + compatibility). This option will eventually become the + default and removed. *vim.treesitter.query.add_predicate()* -add_predicate({name}, {handler}, {force}) +add_predicate({name}, {handler}, {opts}) Adds a new predicate to be used in queries Parameters: ~ - • {name} (string) Name of the predicate, without leading # - • {handler} function(match:table<string,|TSNode|>, pattern:string, - bufnr:integer, predicate:string[]) + • {name} (`string`) Name of the predicate, without leading # + • {handler} (`function`) • see |vim.treesitter.query.add_directive()| for argument meanings - • {force} (boolean|nil) + • {opts} (`table<string, any>`) Optional options: + • force (boolean): Override an existing predicate of the + same name + • all (boolean): Use the correct implementation of the + match table where capture IDs map to a list of nodes + instead of a single node. Defaults to false (for backward + compatibility). This option will eventually become the + default and removed. edit({lang}) *vim.treesitter.query.edit()* Opens a live editor to query the buffer you started from. @@ -884,31 +1024,33 @@ edit({lang}) *vim.treesitter.query.edit()* `$VIMRUNTIME/queries/`. Parameters: ~ - • {lang} (string|nil) language to open the query editor for. If - omitted, inferred from the current buffer's filetype. + • {lang} (`string?`) language to open the query editor for. If omitted, + inferred from the current buffer's filetype. get({lang}, {query_name}) *vim.treesitter.query.get()* Returns the runtime query {query_name} for {lang}. Parameters: ~ - • {lang} (string) Language to use for the query - • {query_name} (string) Name of the query (e.g. "highlights") + • {lang} (`string`) Language to use for the query + • {query_name} (`string`) Name of the query (e.g. "highlights") Return: ~ - Query|nil Parsed query + (`vim.treesitter.Query?`) Parsed query. `nil` if no query files are + found. *vim.treesitter.query.get_files()* get_files({lang}, {query_name}, {is_included}) Gets the list of files used to make up a query Parameters: ~ - • {lang} (string) Language to get query for - • {query_name} (string) Name of the query to load (e.g., "highlights") - • {is_included} (boolean|nil) Internal parameter, most of the time left + • {lang} (`string`) Language to get query for + • {query_name} (`string`) Name of the query to load (e.g., + "highlights") + • {is_included} (`boolean?`) Internal parameter, most of the time left as `nil` 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 lint({buf}, {opts}) *vim.treesitter.query.lint()* @@ -916,34 +1058,34 @@ lint({buf}, {opts}) *vim.treesitter.query.lint()* Use |treesitter-parsers| in runtimepath to check the query file in {buf} for errors: - • verify that used nodes are valid identifiers in the grammar. • verify that predicates and directives are valid. • verify that top-level s-expressions are valid. The found diagnostics are reported using |diagnostic-api|. By default, the parser used for verification is determined by the containing folder of the - query file, e.g., if the path ends in `/lua/highlights.scm` , the parser for the `lua` language will be used. + query file, e.g., if the path ends in `/lua/highlights.scm`, the parser + for the `lua` language will be used. Parameters: ~ - • {buf} (integer) Buffer handle - • {opts} (QueryLinterOpts|nil) Optional keyword arguments: - • langs (string|string[]|nil) Language(s) to use for checking + • {buf} (`integer`) Buffer handle + • {opts} (`table?`) Optional keyword arguments: + • {langs}? (`string|string[]`) Language(s) to use for checking the query. If multiple languages are specified, queries are validated for all of them - • clear (boolean) if `true`, just clear current lint errors + • {clear} (`boolean`) Just clear current lint errors list_directives() *vim.treesitter.query.list_directives()* Lists the currently available directives to use in queries. Return: ~ - string[] List of supported directives. + (`string[]`) List of supported directives. list_predicates() *vim.treesitter.query.list_predicates()* Lists the currently available predicates to use in queries. Return: ~ - string[] List of supported predicates. + (`string[]`) List of supported predicates. omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()* Omnifunc for completing node names and predicates in treesitter queries. @@ -952,24 +1094,32 @@ omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()* vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc' < + Parameters: ~ + • {findstart} (`0|1`) + • {base} (`string`) + parse({lang}, {query}) *vim.treesitter.query.parse()* Parse {query} as a string. (If the query is in a file, the caller should read the contents into a string before calling). - Returns a `Query` (see |lua-treesitter-query|) object which can be used to search nodes in - the syntax tree for the patterns defined in {query} using `iter_*` methods below. + Returns a `Query` (see |lua-treesitter-query|) object which can be used to + search nodes in the syntax tree for the patterns defined in {query} using + the `iter_captures` and `iter_matches` methods. Exposes `info` and `captures` with additional context about {query}. • `captures` contains the list of unique capture names defined in {query}. - -`info.captures` also points to `captures`. + • `info.captures` also points to `captures`. • `info.patterns` contains information about predicates. Parameters: ~ - • {lang} (string) Language to use for the query - • {query} (string) Query in s-expr syntax + • {lang} (`string`) Language to use for the query + • {query} (`string`) Query in s-expr syntax Return: ~ - Query Parsed query + (`vim.treesitter.Query`) Parsed query + + See also: ~ + • |vim.treesitter.query.get()| *Query:iter_captures()* Query:iter_captures({node}, {source}, {start}, {stop}) @@ -995,15 +1145,17 @@ Query:iter_captures({node}, {source}, {start}, {stop}) < Parameters: ~ - • {node} |TSNode| under which the search will occur - • {source} (integer|string) Source buffer or string to extract text + • {node} (`TSNode`) under which the search will occur + • {source} (`integer|string`) Source buffer or string to extract text from - • {start} (integer) Starting line for the search - • {stop} (integer) Stopping line for the search (end-exclusive) + • {start} (`integer?`) Starting line for the search. Defaults to + `node:start()`. + • {stop} (`integer?`) Stopping line for the search (end-exclusive). + Defaults to `node:end_()`. Return: ~ - (fun(end_line: integer|nil): integer, TSNode, TSMetadata): capture id, - capture node, metadata + (`fun(end_line: integer?): integer, TSNode, vim.treesitter.query.TSMetadata`) + capture id, capture node, metadata *Query:iter_matches()* Query:iter_matches({node}, {source}, {start}, {stop}, {opts}) @@ -1012,35 +1164,48 @@ Query:iter_matches({node}, {source}, {start}, {stop}, {opts}) Iterate over all matches within a {node}. The arguments are the same as for |Query:iter_captures()| but the iterated values are different: an (1-based) index of the pattern in the query, a table mapping capture - indices to nodes, and metadata from any directives processing the match. - If the query has more than one pattern, the capture table might be sparse - and e.g. `pairs()` method should be used over `ipairs`. Here is an example - iterating over all captures in every match: >lua - for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do - for id, node in pairs(match) do - local name = query.captures[id] - -- `node` was captured by the `name` capture in the match + indices to a list of nodes, and metadata from any directives processing + the match. + + WARNING: Set `all=true` to ensure all matching nodes in a match are + returned, otherwise only the last node in a match is returned, breaking + captures involving quantifiers such as `(comment)+ @comment`. The default + option `all=false` is only provided for backward compatibility and will be + removed after Nvim 0.10. - local node_data = metadata[id] -- Node level metadata + Example: >lua + for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, 0, -1, { all = true }) do + for id, nodes in pairs(match) do + local name = query.captures[id] + for _, node in ipairs(nodes) do + -- `node` was captured by the `name` capture in the match - -- ... use the info here ... + local node_data = metadata[id] -- Node level metadata + ... use the info here ... + end end end < Parameters: ~ - • {node} |TSNode| under which the search will occur - • {source} (integer|string) Source buffer or string to search - • {start} (integer) Starting line for the search - • {stop} (integer) Stopping line for the search (end-exclusive) - • {opts} (table|nil) Options: + • {node} (`TSNode`) under which the search will occur + • {source} (`integer|string`) Source buffer or string to search + • {start} (`integer?`) Starting line for the search. Defaults to + `node:start()`. + • {stop} (`integer?`) Stopping line for the search (end-exclusive). + Defaults to `node:end_()`. + • {opts} (`table?`) Optional keyword arguments: • max_start_depth (integer) if non-zero, sets the maximum start depth for each match. This is used to prevent - traversing too deep into a tree. Requires treesitter >= - 0.20.9. + traversing too deep into a tree. + • all (boolean) When set, the returned match table maps + capture IDs to a list of nodes. Older versions of + iter_matches incorrectly mapped capture IDs to a single + node, which is incorrect behavior. This option will + eventually become the default and removed. Return: ~ - (fun(): integer, table<integer,TSNode>, table): pattern id, match, + (`fun(): integer, table<integer, TSNode[]>, table`) pattern id, match, metadata set({lang}, {query_name}, {text}) *vim.treesitter.query.set()* @@ -1050,49 +1215,44 @@ set({lang}, {query_name}, {text}) *vim.treesitter.query.set()* by plugins. Parameters: ~ - • {lang} (string) Language to use for the query - • {query_name} (string) Name of the query (e.g., "highlights") - • {text} (string) Query text (unparsed). + • {lang} (`string`) Language to use for the query + • {query_name} (`string`) Name of the query (e.g., "highlights") + • {text} (`string`) Query text (unparsed). ============================================================================== Lua module: vim.treesitter.languagetree *lua-treesitter-languagetree* - -A *LanguageTree* contains a tree of parsers: the root treesitter parser -for {lang} and any "injected" language parsers, which themselves may -inject other languages, recursively. For example a Lua buffer containing -some Vimscript commands needs multiple parsers to fully understand its -contents. +A *LanguageTree* contains a tree of parsers: the root treesitter parser for +{lang} and any "injected" language parsers, which themselves may inject other +languages, recursively. For example a Lua buffer containing some Vimscript +commands needs multiple parsers to fully understand its contents. To create a LanguageTree (parser object) for a given buffer and language, use: >lua local parser = vim.treesitter.get_parser(bufnr, lang) - < -(where `bufnr=0` means current buffer). `lang` defaults to 'filetype'. -Note: currently the parser is retained for the lifetime of a buffer but -this may change; a plugin should keep a reference to the parser object if -it wants incremental updates. +(where `bufnr=0` means current buffer). `lang` defaults to 'filetype'. Note: +currently the parser is retained for the lifetime of a buffer but this may +change; a plugin should keep a reference to the parser object if it wants +incremental updates. Whenever you need to access the current syntax tree, parse the buffer: >lua local tree = parser:parse({ start_row, end_row }) - < -This returns a table of immutable |treesitter-tree| objects representing -the current state of the buffer. When the plugin wants to access the state -after a (possible) edit it must call `parse()` again. If the buffer wasn't -edited, the same tree will be returned again without extra work. If the -buffer was parsed before, incremental parsing will be done of the changed -parts. +This returns a table of immutable |treesitter-tree| objects representing the +current state of the buffer. When the plugin wants to access the state after a +(possible) edit it must call `parse()` again. If the buffer wasn't edited, the +same tree will be returned again without extra work. If the buffer was parsed +before, incremental parsing will be done of the changed parts. + +Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, +you must call |vim.treesitter.get_parser()| before you register your callback. +But preferably parsing shouldn't be done directly in the change callback +anyway as they will be very frequent. Rather a plugin that does any kind of +analysis on a tree should use a timer to throttle too frequent updates. -Note: To use the parser directly inside a |nvim_buf_attach()| Lua -callback, you must call |vim.treesitter.get_parser()| before you register -your callback. But preferably parsing shouldn't be done directly in the -change callback anyway as they will be very frequent. Rather a plugin that -does any kind of analysis on a tree should use a timer to throttle too -frequent updates. LanguageTree:children() *LanguageTree:children()* Returns a map of language to child tree. @@ -1101,10 +1261,10 @@ LanguageTree:contains({range}) *LanguageTree:contains()* Determines whether {range} is contained in the |LanguageTree|. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` Return: ~ - (boolean) + (`boolean`) LanguageTree:destroy() *LanguageTree:destroy()* Destroys this |LanguageTree| and all its children. @@ -1120,32 +1280,33 @@ LanguageTree:for_each_tree({fn}) *LanguageTree:for_each_tree()* Note: This includes the invoking tree's child trees as well. Parameters: ~ - • {fn} fun(tree: TSTree, ltree: LanguageTree) + • {fn} (`fun(tree: TSTree, ltree: vim.treesitter.LanguageTree)`) LanguageTree:included_regions() *LanguageTree:included_regions()* - Gets the set of included regions managed by this LanguageTree . This can be different from the regions set by injection query, because a - partial |LanguageTree:parse()| drops the regions outside the requested - range. + Gets the set of included regions managed by this LanguageTree. This can be + different from the regions set by injection query, because a partial + |LanguageTree:parse()| drops the regions outside the requested range. Return: ~ - table<integer, Range6[]> + (`table<integer, Range6[]>`) LanguageTree:invalidate({reload}) *LanguageTree:invalidate()* Invalidates this parser and all its children Parameters: ~ - • {reload} (boolean|nil) + • {reload} (`boolean?`) LanguageTree:is_valid({exclude_children}) *LanguageTree:is_valid()* - Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| reflects the latest state of the - source. If invalid, user should call |LanguageTree:parse()|. + Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| + reflects the latest state of the source. If invalid, user should call + |LanguageTree:parse()|. Parameters: ~ - • {exclude_children} (boolean|nil) whether to ignore the validity of + • {exclude_children} (`boolean?`) whether to ignore the validity of children (default `false`) Return: ~ - (boolean) + (`boolean`) LanguageTree:lang() *LanguageTree:lang()* Gets the language of this tree node. @@ -1155,23 +1316,23 @@ LanguageTree:language_for_range({range}) Gets the appropriate language that contains {range}. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` Return: ~ - |LanguageTree| Managing {range} + (`vim.treesitter.LanguageTree`) Managing {range} *LanguageTree:named_node_for_range()* LanguageTree:named_node_for_range({range}, {opts}) Gets the smallest named node that contains {range}. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` - • {opts} (table|nil) Optional keyword arguments: + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` + • {opts} (`table?`) Optional keyword arguments: • ignore_injections boolean Ignore injected languages (default true) Return: ~ - |TSNode| | nil Found node + (`TSNode?`) Found node LanguageTree:parse({range}) *LanguageTree:parse()* Recursively parse all regions in the language tree using @@ -1184,23 +1345,24 @@ LanguageTree:parse({range}) *LanguageTree:parse()* if {range} is `true`). 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: Can be slow!) Set to `false|nil` to only parse regions with empty ranges (typically only the root tree without injections). Return: ~ - table<integer, TSTree> + (`table<integer, TSTree>`) *LanguageTree:register_cbs()* LanguageTree:register_cbs({cbs}, {recursive}) Registers callbacks for the |LanguageTree|. Parameters: ~ - • {cbs} (table) An |nvim_buf_attach()|-like table argument with + • {cbs} (`table`) An |nvim_buf_attach()|-like table argument with the following handlers: - • `on_bytes` : see |nvim_buf_attach()|, but this will be called after the parsers callback. + • `on_bytes` : see |nvim_buf_attach()|, but this will be + called after the parsers callback. • `on_changedtree` : a callback that will be called every time the tree has syntactical changes. It will be passed two arguments: a table of the ranges (as node @@ -1212,7 +1374,7 @@ LanguageTree:register_cbs({cbs}, {recursive}) • `on_detach` : emitted when the buffer is detached, see |nvim_buf_detach_event|. Takes one argument, the number 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 callbacks. @@ -1224,21 +1386,23 @@ LanguageTree:tree_for_range({range}, {opts}) Gets the tree that contains {range}. Parameters: ~ - • {range} (table) `{ start_line, start_col, end_line, end_col }` - • {opts} (table|nil) Optional keyword arguments: + • {range} (`Range4`) `{ start_line, start_col, end_line, end_col }` + • {opts} (`table?`) Optional keyword arguments: • ignore_injections boolean Ignore injected languages (default true) Return: ~ - TSTree|nil + (`TSTree?`) LanguageTree:trees() *LanguageTree:trees()* Returns all trees of the regions parsed by this parser. Does not include child languages. The result is list-like if - • this LanguageTree is the root, in which case the result is empty or a singleton list; or + • this LanguageTree is the root, in which case the result is empty or a + singleton list; or • the root LanguageTree is fully parsed. Return: ~ - table<integer, TSTree> + (`table<integer, TSTree>`) + vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: |