robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1*treesitter.txt* Nvim 2 3 4 NVIM REFERENCE MANUAL 5 6 7Treesitter integration *treesitter* 8 9Nvim integrates the `tree-sitter` library for incremental parsing of buffers: 10https://tree-sitter.github.io/tree-sitter/ 11 12WARNING: Treesitter support is still experimental and subject to frequent 13changes. This documentation may also not fully reflect the latest changes. 14 15 Type |gO| to see the table of contents. 16 17============================================================================== 18PARSER FILES *treesitter-parsers* 19 20Parsers are the heart of treesitter. They are libraries that treesitter will 21search for in the `parser` runtime directory. 22 23Nvim includes these parsers: 24 25- C 26- Diff 27- Lua 28- Markdown 29- Vimscript 30- Vimdoc 31- Treesitter query files |ft-query-plugin| 32 33You can install more parsers manually, or with a plugin like 34https://github.com/nvim-treesitter/nvim-treesitter . 35 36Parsers are searched for as `parser/{lang}.*` in any 'runtimepath' directory. 37If multiple parsers for the same language are found, the first one is used. 38(NOTE: This typically implies the priority "user config > plugins > bundled".) 39 40To load a parser from its filepath: >lua 41 42 vim.treesitter.language.add('python', { path = "/path/to/python.so" }) 43< 44Parser names are assumed to be lower case if the file system is 45case-sensitive. 46 47To associate certain |filetypes| with a treesitter language (name of parser), 48use |vim.treesitter.language.register()|. For example, to use the `xml` 49treesitter parser for buffers with filetype `svg` or `xslt`, use: >lua 50 51 vim.treesitter.language.register('xml', { 'svg', 'xslt' }) 52< 53 *treesitter-parsers-wasm* 54 55If Nvim is built with `ENABLE_WASMTIME`, then wasm parsers can also be 56loaded: >lua 57 58 vim.treesitter.language.add('python', { path = "/path/to/python.wasm" }) 59< 60 61============================================================================== 62TREESITTER QUERIES *treesitter-query* 63 64Treesitter queries are a way to extract information about a parsed |TSTree|, 65e.g., for the purpose of highlighting. Briefly, a `query` consists of one or 66more patterns. A `pattern` is defined over node types in the syntax tree. A 67`match` corresponds to specific elements of the syntax tree which match a 68pattern. Patterns may optionally define captures and predicates. A `capture` 69allows you to associate names with a specific node in a pattern. A `predicate` 70adds arbitrary metadata and conditional data to a match. 71 72Queries are written in a lisp-like language documented in 73https://tree-sitter.github.io/tree-sitter/using-parsers/queries/1-syntax.html 74Note: The predicates listed there differ from those Nvim supports. See 75|treesitter-predicates| for a complete list of predicates supported by Nvim. 76 77Nvim looks for queries as `*.scm` files in a `queries` directory under 78`runtimepath`, where each file contains queries for a specific language and 79purpose, e.g., `queries/lua/highlights.scm` for highlighting Lua files. 80By default, the first query on `runtimepath` is used (which usually implies 81that user config takes precedence over plugins, which take precedence over 82queries bundled with Nvim). If a query should extend other queries instead 83of replacing them, use |treesitter-query-modeline-extends|. 84 85The Lua interface is described at |lua-treesitter-query|. 86 87 88TREESITTER QUERY PREDICATES *treesitter-predicates* 89 90Predicates are special scheme nodes that are evaluated to conditionally capture 91nodes. For example, the `eq?` predicate can be used as follows: >query 92 93 ((identifier) @variable.builtin 94 (#eq? @variable.builtin "self")) 95< 96to only match identifier corresponding to the `"self"` text. Such queries can 97be used to highlight built-in functions or variables differently, for instance. 98 99The following predicates are built in: 100 101 `eq?` *treesitter-predicate-eq?* 102 Match a string against the text corresponding to a node: >query 103 ((identifier) @variable.builtin (#eq? @variable.builtin "self")) 104 ((node1) @left (node2) @right (#eq? @left @right)) 105< 106 `any-eq?` *treesitter-predicate-any-eq?* 107 Like `eq?`, but for quantified patterns only one captured node must 108 match. 109 110 `match?` *treesitter-predicate-match?* 111 `vim-match?` *treesitter-predicate-vim-match?* 112 Match a |regexp| against the text corresponding to a node: >query 113 ((identifier) @constant (#match? @constant "^[A-Z_]+$")) 114< 115 Note: The `^` and `$` anchors will match the start and end of the 116 node's text. 117 118 `any-match?` *treesitter-predicate-any-match?* 119 `any-vim-match?` *treesitter-predicate-any-vim-match?* 120 Like `match?`, but for quantified patterns only one captured node must 121 match. 122 123 `lua-match?` *treesitter-predicate-lua-match?* 124 Match |lua-pattern|s against the text corresponding to a node, 125 similar to `match?` 126 127 `any-lua-match?` *treesitter-predicate-any-lua-match?* 128 Like `lua-match?`, but for quantified patterns only one captured node 129 must match. 130 131 `contains?` *treesitter-predicate-contains?* 132 Match a string against parts of the text corresponding to a node: >query 133 ((identifier) @foo (#contains? @foo "foo")) 134 ((identifier) @foo-bar (#contains? @foo-bar "foo" "bar")) 135< 136 `any-contains?` *treesitter-predicate-any-contains?* 137 Like `contains?`, but for quantified patterns only one captured node 138 must match. 139 140 `any-of?` *treesitter-predicate-any-of?* 141 Match any of the given strings against the text corresponding to 142 a node: >query 143 ((identifier) @foo (#any-of? @foo "foo" "bar")) 144< 145 This is the recommended way to check if the node matches one of many 146 keywords, as it has been optimized for this. 147 148 `has-ancestor?` *treesitter-predicate-has-ancestor?* 149 Match any of the given node types against all ancestors of a node: >query 150 ((identifier) @variable.builtin 151 (#any-of? @variable.builtin "begin" "end") 152 (#has-ancestor? @variable.builtin range_expression)) 153< 154 `has-parent?` *treesitter-predicate-has-parent?* 155 Match any of the given node types against the direct ancestor of a 156 node: >query 157 (((field_expression 158 (field_identifier) @method)) @_parent 159 (#has-parent? @_parent template_method function_declarator)) 160< 161 *treesitter-predicate-not* 162Each predicate has a `not-` prefixed predicate that is just the negation of 163the predicate. 164 165 *treesitter-predicate-all* 166 *treesitter-predicate-any* 167Queries can use quantifiers to capture multiple nodes. When a capture contains 168multiple nodes, predicates match only if ALL nodes contained by the capture 169match the predicate. Some predicates (`eq?`, `match?`, `lua-match?`, 170`contains?`) accept an `any-` prefix to instead match if ANY of the nodes 171contained by the capture match the predicate. 172 173As an example, consider the following Lua code: >lua 174 175 -- TODO: This is a 176 -- very long 177 -- comment (just imagine it) 178< 179using the following predicated query: 180>query 181 (((comment)+ @comment) 182 (#match? @comment "TODO")) 183< 184This query will not match because not all of the nodes captured by @comment 185match the predicate. Instead, use: 186>query 187 (((comment)+ @comment) 188 (#any-match? @comment "TODO")) 189< 190 191Further predicates can be added via |vim.treesitter.query.add_predicate()|. 192Use |vim.treesitter.query.list_predicates()| to list all available predicates. 193 194 195TREESITTER QUERY DIRECTIVES *treesitter-directives* 196 197Treesitter directives store metadata for a node or match and perform side 198effects. For example, the `set!` directive sets metadata on the match or node: >query 199 200 ((identifier) @foo (#set! type "parameter")) 201< 202The following directives are built in: 203 204 `set!` *treesitter-directive-set!* 205 Sets key/value metadata for a specific match or capture. Value is 206 accessible as either `metadata[key]` (match specific) or 207 `metadata[capture_id][key]` (capture specific). 208 209 Parameters: ~ 210 {capture_id} (optional) 211 {key} 212 {value} 213 214 Examples: >query 215 ((identifier) @foo (#set! @foo kind "parameter")) 216 ((node1) @left (node2) @right (#set! type "pair")) 217 ((codeblock) @markup.raw.block (#set! priority 90)) 218< 219 `offset!` *treesitter-directive-offset!* 220 Takes the range of the captured node and applies an offset. This will 221 set a new range in the form of a list like { {start_row}, {start_col}, 222 {end_row}, {end_col} } for the captured node with `capture_id` as 223 `metadata[capture_id].offset`. This offset will be applied to the 224 range returned in |vim.treesitter.get_range()|. Useful for 225 |treesitter-language-injections|. 226 227 Parameters: ~ 228 {capture_id} 229 {start_row} 230 {start_col} 231 {end_row} 232 {end_col} 233 234 Example: >query 235 ((identifier) @constant (#offset! @constant 0 1 0 -1)) 236< 237 `gsub!` *treesitter-directive-gsub!* 238 Transforms the content of the node using a |lua-pattern|. This will set 239 a new `metadata[capture_id].text`. 240 241 Parameters: ~ 242 {capture_id} 243 {pattern} 244 {replacement} 245 246 Example: >query 247 (#gsub! @_node ".*%.(.*)" "%1") 248< 249 `trim!` *treesitter-directive-trim!* 250 Trims whitespace from the node. Sets a new 251 `metadata[capture_id].range`. Takes a capture ID and, optionally, four 252 integers to customize trimming behavior (`1` meaning trim, `0` meaning 253 don't trim). When only given a capture ID, trims blank lines (lines 254 that contain only whitespace, or are empty) from the end of the node 255 (for backwards compatibility). Can trim all whitespace from both sides 256 of the node if parameters are given. 257 258 Examples: >query 259 ; only trim blank lines from the end of the node 260 ; (equivalent to (#trim! @fold 0 0 1 0)) 261 (#trim! @fold) 262 263 ; trim blank lines from both sides of the node 264 (#trim! @fold 1 0 1 0) 265 266 ; trim all whitespace around the node 267 (#trim! @fold 1 1 1 1) 268< 269 Parameters: ~ 270 {capture_id} 271 {trim_start_linewise} 272 {trim_start_charwise} 273 {trim_end_linewise} (default `1` if only given {capture_id}) 274 {trim_end_charwise} 275 276Further directives can be added via |vim.treesitter.query.add_directive()|. 277Use |vim.treesitter.query.list_directives()| to list all available directives. 278 279 280TREESITTER QUERY MODELINES *treesitter-query-modeline* 281 282Nvim supports to customize the behavior of the queries using a set of 283"modelines", that is comments in the queries starting with `;`. Here are the 284currently supported modeline alternatives: 285 286 `inherits: {lang}...` *treesitter-query-modeline-inherits* 287 Specifies that this query should inherit the queries from {lang}. 288 This will recursively descend in the queries of {lang} unless wrapped 289 in parentheses: `({lang})`. 290 Note: This is meant to be used to include queries from another 291 language. If you want your query to extend the queries of the same 292 language, use `extends`. 293 294 `extends` *treesitter-query-modeline-extends* 295 Specifies that this query should be used as an extension for the 296 query, i.e. that it should be merged with the others. 297 Note: The order of the extensions, and the query that will be used as 298 a base depends on your 'runtimepath' value. 299 300Note: These modeline comments must be at the top of the query, but can be 301repeated, for example, the following two modeline blocks are both valid: 302>query 303 ;; inherits: typescript,jsx 304 ;; extends 305< 306>query 307 ;; extends 308 ;; 309 ;; inherits: css 310< 311============================================================================== 312TREESITTER SYNTAX HIGHLIGHTING *treesitter-highlight* 313 314Syntax highlighting is specified through queries named `highlights.scm`, 315which match a |TSNode| in the parsed |TSTree| to a `capture` that can be 316assigned a highlight group. For example, the query >query 317 318 (parameters (identifier) @variable.parameter) 319< 320matches any `identifier` node inside a function `parameters` node to the 321capture named `@variable.parameter`. For example, for a Lua code >lua 322 323 function f(foo, bar) end 324< 325which will be parsed as (see |:InspectTree|): >query 326 327 (function_declaration ; [1:1 - 24] 328 name: (identifier) ; [1:10 - 10] 329 parameters: (parameters ; [1:11 - 20] 330 name: (identifier) ; [1:12 - 14] 331 name: (identifier))) ; [1:17 - 19] 332< 333the above query will highlight `foo` and `bar` as `@variable.parameter`. 334 335It is also possible to match literal expressions (provided the parser returns 336them): 337>query 338 [ 339 "if" 340 "else" 341 ] @keyword.conditional 342< 343Assuming a suitable parser and `highlights.scm` query is found in runtimepath, 344treesitter highlighting for the current buffer can be enabled simply via 345|vim.treesitter.start()|. 346 347 *treesitter-highlight-groups* 348The capture names, prefixed with `@`, are directly usable as highlight groups. 349For many commonly used captures, the corresponding highlight groups are linked 350to Nvim's standard |highlight-groups| by default (e.g., `@comment` links to 351`Comment`) but can be overridden in colorschemes. 352 353A fallback system is implemented, so that more specific groups fallback to 354more generic ones. For instance, in a language that has separate doc comments 355(e.g., c, java, etc.), `@comment.documentation` could be used. If this group 356is not defined, the highlighting for an ordinary `@comment` is used. This way, 357existing color schemes already work out of the box, but it is possible to add 358more specific variants for queries that make them available. 359 360As an additional rule, capture highlights can always be specialized by 361language, by appending the language name after an additional dot. For 362instance, to highlight comments differently per language: >vim 363 364 hi @comment.c guifg=Blue 365 hi @comment.lua guifg=DarkBlue 366 hi link @comment.documentation.java String 367< 368The following is a list of standard captures used in queries for Nvim, 369highlighted according to the current colorscheme (use |:Inspect| on one to see 370the exact definition): 371 372@variable various variable names 373@variable.builtin built-in variable names (e.g. `this`, `self`) 374@variable.parameter parameters of a function 375@variable.parameter.builtin special parameters (e.g. `_`, `it`) 376@variable.member object and struct fields 377 378@constant constant identifiers 379@constant.builtin built-in constant values 380@constant.macro constants defined by the preprocessor 381 382@module modules or namespaces 383@module.builtin built-in modules or namespaces 384@label `GOTO` and other labels (e.g. `label:` in C), including heredoc labels 385 386@string string literals 387@string.documentation string documenting code (e.g. Python docstrings) 388@string.regexp regular expressions 389@string.escape escape sequences 390@string.special other special strings (e.g. dates) 391@string.special.symbol symbols or atoms 392@string.special.path filenames 393@string.special.url URIs (e.g. hyperlinks) 394 395@character character literals 396@character.special special characters (e.g. wildcards) 397 398@boolean boolean literals 399@number numeric literals 400@number.float floating-point number literals 401 402@type type or class definitions and annotations 403@type.builtin built-in types 404@type.definition identifiers in type definitions (e.g. `typedef <type> <identifier>` in C) 405 406@attribute attribute annotations (e.g. Python decorators, Rust lifetimes) 407@attribute.builtin builtin annotations (e.g. `@property` in Python) 408@property the key in key/value pairs 409 410@function function definitions 411@function.builtin built-in functions 412@function.call function calls 413@function.macro preprocessor macros 414 415@function.method method definitions 416@function.method.call method calls 417 418@constructor constructor calls and definitions 419@operator symbolic operators (e.g. `+`, `*`) 420 421@keyword keywords not fitting into specific categories 422@keyword.coroutine keywords related to coroutines (e.g. `go` in Go, `async/await` in Python) 423@keyword.function keywords that define a function (e.g. `func` in Go, `def` in Python) 424@keyword.operator operators that are English words (e.g. `and`, `or`) 425@keyword.import keywords for including or exporting modules (e.g. `import`, `from` in Python) 426@keyword.type keywords describing namespaces and composite types (e.g. `struct`, `enum`) 427@keyword.modifier keywords modifying other constructs (e.g. `const`, `static`, `public`) 428@keyword.repeat keywords related to loops (e.g. `for`, `while`) 429@keyword.return keywords like `return` and `yield` 430@keyword.debug keywords related to debugging 431@keyword.exception keywords related to exceptions (e.g. `throw`, `catch`) 432 433@keyword.conditional keywords related to conditionals (e.g. `if`, `else`) 434@keyword.conditional.ternary ternary operator (e.g. `?`, `:`) 435 436@keyword.directive various preprocessor directives and shebangs 437@keyword.directive.define preprocessor definition directives 438 439@punctuation.delimiter delimiters (e.g. `;`, `.`, `,`) 440@punctuation.bracket brackets (e.g. `()`, `{}`, `[]`) 441@punctuation.special special symbols (e.g. `{}` in string interpolation) 442 443@comment line and block comments 444@comment.documentation comments documenting code 445 446@comment.error error-type comments (e.g. `ERROR`, `FIXME`, `DEPRECATED`) 447@comment.warning warning-type comments (e.g. `WARNING`, `FIX`, `HACK`) 448@comment.todo todo-type comments (e.g. `TODO`, `WIP`) 449@comment.note note-type comments (e.g. `NOTE`, `INFO`, `XXX`) 450 451@markup.strong bold text 452@markup.italic italic text 453@markup.strikethrough struck-through text 454@markup.underline underlined text (only for literal underline markup!) 455 456@markup.heading headings, titles (including markers) 457@markup.heading.1 top-level heading 458@markup.heading.2 section heading 459@markup.heading.3 subsection heading 460@markup.heading.4 and so on 461@markup.heading.5 and so forth 462@markup.heading.6 six levels ought to be enough for anybody 463 464@markup.quote block quotes 465@markup.math math environments (e.g. `$ ... $` in LaTeX) 466 467@markup.link text references, footnotes, citations, etc. 468@markup.link.label link, reference descriptions 469@markup.link.url URL-style links 470 471@markup.raw literal or verbatim text (e.g. inline code) 472@markup.raw.block literal or verbatim text as a stand-alone block 473 474@markup.list list markers 475@markup.list.checked checked todo-style list markers 476@markup.list.unchecked unchecked todo-style list markers 477 478@diff.plus added text (for diff files) 479@diff.minus deleted text (for diff files) 480@diff.delta changed text (for diff files) 481 482@tag XML-style tag names (e.g. in XML, HTML, etc.) 483@tag.builtin builtin tag names (e.g. HTML5 tags) 484@tag.attribute XML-style tag attributes 485@tag.delimiter XML-style tag delimiters 486 487 *treesitter-highlight-spell* 488The special `@spell` capture can be used to indicate that a node should be 489spell checked by Nvim's builtin |spell| checker. For example, the following 490capture marks comments as to be checked: >query 491 492 (comment) @spell 493< 494 495There is also `@nospell` which disables spellchecking regions with `@spell`. 496 497 *treesitter-highlight-conceal* 498Treesitter highlighting supports |conceal| via the `conceal` and `conceal_lines` 499metadata. By convention, nodes to be concealed are captured as `@conceal`, but 500any capture can be used. For example, the following query can be used to hide 501code block delimiters in Markdown: >query 502 503 ((fenced_code_block_delimiter) @conceal (#set! conceal "")) 504< 505It is also possible to replace a node with a single character, which (unlike 506legacy syntax) can be given a custom highlight. For example, the following 507(ill-advised) query replaces the `!=` operator by a Unicode glyph, which is 508still highlighted the same as other operators: >query 509 510 "!=" @operator (#set! conceal "≠") 511< 512To conceal an entire line (do not draw it at all), a query with `conceal_lines` 513metadata can be used: >query 514 515 ((comment) @comment @spell 516 (#set! conceal_lines "")) 517< 518Conceals specified in this way respect 'conceallevel' and 'concealcursor'. 519 520Note that although you can use any string for `conceal`, only the first 521character will be used: >query 522 523 ; identifiers will be concealed with 'f'. 524 ((identifier) @conceal (#set! conceal "foo")) 525< 526To remove a conceal highlight, you can use the `@noconceal` capture to 527override any existing conceal highlight set for the range. >query 528 529 ((identifier) @noconceal) 530< 531 532 *treesitter-highlight-priority* 533Treesitter uses |nvim_buf_set_extmark()| to set highlights with a default 534priority of 100. This enables plugins to set a highlighting priority lower or 535higher than treesitter. It is also possible to change the priority of an 536individual query pattern manually by setting its `"priority"` metadata 537attribute: >query 538 539 ((super_important_node) @superimportant (#set! priority 105)) 540< 541 542 *treesitter-highlight-commentstring* 543Treesitter highlighting supports finer-grained 'commentstring's, used by the 544built-in |commenting| plugin. When the cursor is within a node that sets the 545`bo.commentstring` metadata property (|treesitter-directive-set!|), that 546property defines the comment delimiter (where "innermost wins"). This is 547useful for languages like `JSX` that have different comment syntax depending 548on the code region, for example: >query 549 550 ((jsx_element) @_tag (#set! @_tag bo.commentstring "{/* %s */}")) 551< 552When multiple captures set this metadata over a region, only the innermost 553(most specific) one is applied to a given area. 554 555============================================================================== 556TREESITTER LANGUAGE INJECTIONS *treesitter-language-injections* 557 558Note the following information is adapted from: 559https://tree-sitter.github.io/tree-sitter/3-syntax-highlighting.html#language-injection 560 561Some source files contain code written in multiple different languages. 562Examples include: 563 564 • HTML files, which can contain JavaScript inside of `<script>` tags and 565 CSS inside of `<style>` tags 566 • ERB files, which contain Ruby inside of `<%` `%>` tags, and HTML outside of 567 those tags 568 • PHP files, which can contain HTML between the `<php` tags 569 • JavaScript files, which contain regular expression syntax within regex 570 literals 571 • Ruby, which can contain snippets of code inside of heredoc literals, 572 where the heredoc delimiter often indicates the language 573 • Lua, which can contain snippets of Vimscript inside |vim.cmd()| calls. 574 • Vimscript, which can contain snippets of Lua inside |:lua-heredoc| 575 blocks. 576 577All of these examples can be modeled in terms of a parent syntax tree and one 578or more injected syntax trees, which reside inside of certain nodes in the 579parent tree. The language injection query allows you to specify these 580“injections” using the following captures: 581 582 • `@injection.content` - indicates that the captured node should have its 583 contents re-parsed using another language. If there are multiple 584 `@injection.content` captures in one pattern, all ranges will be 585 collected and parsed as one tree. This allows query authors to create 586 "scoped" injections with injection query quantifiers. 587 • `@injection.language` - indicates that the captured node’s text may 588 contain the name of a language that should be used to re-parse the 589 `@injection.content`. 590 • `@injection.filename` - indicates that the captured node’s text may 591 contain a filename; the corresponding filetype is then looked-up up via 592 |vim.filetype.match()| and treated as the name of a language that should 593 be used to re-parse the `@injection.content`. 594 595The language injection behavior can also be configured by some properties 596associated with patterns: 597 598 • `injection.language` - can be used to hard-code the name of a specific 599 language. 600 • `injection.combined` - indicates that all of the matching nodes in the 601 tree should have their content parsed as one nested document. 602 • `injection.include-children` - indicates that the `@injection.content` 603 node's entire text should be re-parsed, including the text of its child 604 nodes. By default, child nodes' text will be excluded from the injected 605 document. 606 • `injection.self` - indicates that the node's text should be parsed with 607 the same language as the node's LanguageTree. 608 • `injection.parent` - indicates that the captured node’s text should 609 be parsed with the same language as the node's parent LanguageTree. 610 611Injection queries are currently run over the entire buffer, which can be slow 612for large buffers. To disable injections for, e.g., `c`, just place an 613empty `queries/c/injections.scm` file in your 'runtimepath'. 614 615============================================================================== 616DEFAULTS *treesitter-defaults* 617 618 *treesitter-incremental-selection* 619 *v_an* 620an Selects [count]th parent node. 621 622 If buffer has no treesitter parser, 623 falls back to |vim.lsp.buf.selection_range()|. 624 625 *v_in* 626in Selects [count]th previous (or first) child node. 627 628 If buffer has no treesitter parser, 629 falls back to |vim.lsp.buf.selection_range()|. 630 631 *v_]n* 632]n Selects [count]th next node. 633 634 *v_[n* 635[n Selects [count]th previous node. 636 637 *v_]N* 638]N Expands selection to [count]th next node. 639 640 *v_[N* 641[N Expands selection to [count]th previous node. 642 643============================================================================== 644VIM.TREESITTER *lua-treesitter* *vim.treesitter* 645 646The remainder of this document is a reference manual for the `vim.treesitter` 647Lua module, which is the main interface for Nvim's treesitter integration. 648Most of the following content is automatically generated from the function 649documentation. 650 651 652 *vim.treesitter.language_version* 653The latest parser ABI version that is supported by the bundled treesitter 654library. 655 656 *vim.treesitter.minimum_language_version* 657The earliest parser ABI version that is supported by the bundled treesitter 658library. 659 660============================================================================== 661TREESITTER TREES *treesitter-tree* *TSTree* 662 663A "treesitter tree" represents the parsed contents of a buffer, which can be 664used to perform further analysis. It is a |userdata| reference to an object 665held by the treesitter library. 666 667An instance `TSTree` of a treesitter tree supports the following methods. 668 669 670TSTree:copy() *TSTree:copy()* 671 Returns a copy of the `TSTree`. 672 673 Return: ~ 674 (`TSTree`) 675 676TSTree:root() *TSTree:root()* 677 Return the root node of this tree. 678 679 Return: ~ 680 (`TSNode`) 681 682 683============================================================================== 684TREESITTER NODES *treesitter-node* *TSNode* 685 686A "treesitter node" represents one specific element of the parsed contents of 687a buffer, which can be captured by a |treesitter-query| for, e.g., 688highlighting. It is a |userdata| reference to an object held by the treesitter 689library. 690 691An instance `TSNode` of a treesitter node supports the following methods. 692 693 694TSNode:byte_length() *TSNode:byte_length()* 695 Return the number of bytes spanned by this node. 696 697 Return: ~ 698 (`integer`) 699 700TSNode:child({index}) *TSNode:child()* 701 Get the node's child at the given {index}, where zero represents the first 702 child. 703 704 Parameters: ~ 705 • {index} (`integer`) 706 707 Return: ~ 708 (`TSNode?`) 709 710TSNode:child_count() *TSNode:child_count()* 711 Get the node's number of children. 712 713 Return: ~ 714 (`integer`) 715 716 *TSNode:child_with_descendant()* 717TSNode:child_with_descendant({descendant}) 718 Get the node's child that contains {descendant} (includes {descendant}). 719 720 For example, with the following node hierarchy: > 721 a -> b -> c 722 723 a:child_with_descendant(c) == b 724 a:child_with_descendant(b) == b 725 a:child_with_descendant(a) == nil 726< 727 728 Parameters: ~ 729 • {descendant} (`TSNode`) 730 731 Return: ~ 732 (`TSNode?`) 733 734 *TSNode:descendant_for_range()* 735TSNode:descendant_for_range({start_row}, {start_col}, {end_row}, {end_col}) 736 Get the smallest node within this node that spans the given range of (row, 737 column) positions 738 739 Parameters: ~ 740 • {start_row} (`integer`) 741 • {start_col} (`integer`) 742 • {end_row} (`integer`) 743 • {end_col} (`integer`) 744 745 Return: ~ 746 (`TSNode?`) 747 748TSNode:end_() *TSNode:end_()* 749 Get the node's end position. Return three values: the row, column and 750 total byte count (all zero-based). 751 752 Return (multiple): ~ 753 (`integer`) 754 (`integer`) 755 (`integer`) 756 757TSNode:equal({node}) *TSNode:equal()* 758 Check if {node} refers to the same node within the same tree. 759 760 Parameters: ~ 761 • {node} (`TSNode`) 762 763 Return: ~ 764 (`boolean`) 765 766TSNode:extra() *TSNode:extra()* 767 Check if the node is extra. Extra nodes represent things like comments, 768 which are not required by the grammar but can appear anywhere. 769 770 Return: ~ 771 (`boolean`) 772 773TSNode:field({name}) *TSNode:field()* 774 Returns a list of all the node's children that have the given field name. 775 776 Parameters: ~ 777 • {name} (`string`) 778 779 Return: ~ 780 (`TSNode[]`) 781 782TSNode:has_changes() *TSNode:has_changes()* 783 Check if a syntax node has been edited. 784 785 Return: ~ 786 (`boolean`) 787 788TSNode:has_error() *TSNode:has_error()* 789 Check if the node is a syntax error or contains any syntax errors. 790 791 Return: ~ 792 (`boolean`) 793 794TSNode:id() *TSNode:id()* 795 Get a unique identifier for the node inside its own tree. 796 797 No guarantees are made about this identifier's internal representation, 798 except for being a primitive Lua type with value equality (so not a 799 table). Presently it is a (non-printable) string. 800 801 Note: The `id` is not guaranteed to be unique for nodes from different 802 trees. 803 804 Return: ~ 805 (`string`) 806 807TSNode:iter_children() *TSNode:iter_children()* 808 Iterates over all the direct children of {TSNode}, regardless of whether 809 they are named or not. Returns the child node plus the eventual field name 810 corresponding to this child node. 811 812 Return: ~ 813 (`fun(): TSNode, string`) 814 815TSNode:missing() *TSNode:missing()* 816 Check if the node is missing. Missing nodes are inserted by the parser in 817 order to recover from certain kinds of syntax errors. 818 819 Return: ~ 820 (`boolean`) 821 822TSNode:named() *TSNode:named()* 823 Check if the node is named. Named nodes correspond to named rules in the 824 grammar, whereas anonymous nodes correspond to string literals in the 825 grammar. 826 827 Return: ~ 828 (`boolean`) 829 830TSNode:named_child({index}) *TSNode:named_child()* 831 Get the node's named child at the given {index}, where zero represents the 832 first named child. 833 834 Parameters: ~ 835 • {index} (`integer`) 836 837 Return: ~ 838 (`TSNode?`) 839 840TSNode:named_child_count() *TSNode:named_child_count()* 841 Get the node's number of named children. 842 843 Return: ~ 844 (`integer`) 845 846TSNode:named_children() *TSNode:named_children()* 847 Returns a list of the node's named children. 848 849 Return: ~ 850 (`TSNode[]`) 851 852 *TSNode:named_descendant_for_range()* 853TSNode:named_descendant_for_range({start_row}, {start_col}, {end_row}, 854 {end_col}) 855 Get the smallest named node within this node that spans the given range of 856 (row, column) positions 857 858 Parameters: ~ 859 • {start_row} (`integer`) 860 • {start_col} (`integer`) 861 • {end_row} (`integer`) 862 • {end_col} (`integer`) 863 864 Return: ~ 865 (`TSNode?`) 866 867TSNode:next_named_sibling() *TSNode:next_named_sibling()* 868 Get the node's next named sibling. 869 870 Return: ~ 871 (`TSNode?`) 872 873TSNode:next_sibling() *TSNode:next_sibling()* 874 Get the node's next sibling. 875 876 Return: ~ 877 (`TSNode?`) 878 879TSNode:parent() *TSNode:parent()* 880 Get the node's immediate parent. Prefer |TSNode:child_with_descendant()| 881 for iterating over the node's ancestors. 882 883 Return: ~ 884 (`TSNode?`) 885 886TSNode:prev_named_sibling() *TSNode:prev_named_sibling()* 887 Get the node's previous named sibling. 888 889 Return: ~ 890 (`TSNode?`) 891 892TSNode:prev_sibling() *TSNode:prev_sibling()* 893 Get the node's previous sibling. 894 895 Return: ~ 896 (`TSNode?`) 897 898TSNode:range({include_bytes}) *TSNode:range()* 899 Get the range of the node. 900 901 Return four or six values: 902 • start row 903 • start column 904 • start byte (if {include_bytes} is `true`) 905 • end row 906 • end column 907 • end byte (if {include_bytes} is `true`) 908 909 Parameters: ~ 910 • {include_bytes} (`false?`) 911 912 Overloads: ~ 913 • `fun(self: TSNode, include_bytes: true): integer, integer, integer, integer, integer, integer` 914 915 Return (multiple): ~ 916 (`integer`) 917 (`integer`) 918 (`integer`) 919 (`integer`) 920 921TSNode:sexpr() *TSNode:sexpr()* 922 Get an S-expression representing the node as a string. 923 924 Return: ~ 925 (`string`) 926 927TSNode:start() *TSNode:start()* 928 Get the node's start position. Return three values: the row, column and 929 total byte count (all zero-based). 930 931 Return (multiple): ~ 932 (`integer`) 933 (`integer`) 934 (`integer`) 935 936TSNode:symbol() *TSNode:symbol()* 937 Get the node's type as a numerical id. 938 939 Return: ~ 940 (`integer`) 941 942TSNode:tree() *TSNode:tree()* 943 Get the |TSTree| of the node. 944 945 Return: ~ 946 (`TSTree`) 947 948TSNode:type() *TSNode:type()* 949 Get the node's type as a string. 950 951 Return: ~ 952 (`string`) 953 954 955============================================================================== 956Lua module: vim.treesitter *lua-treesitter-core* 957 958foldexpr({lnum}) *vim.treesitter.foldexpr()* 959 Returns the fold level for {lnum} in the current buffer. Can be set 960 directly to 'foldexpr': >lua 961 vim.wo.foldexpr = vim.treesitter.foldexpr 962< 963 964 Attributes: ~ 965 Since: 0.9.0 966 967 Parameters: ~ 968 • {lnum} (`integer?`) Line number to calculate fold level for 969 970 Return: ~ 971 (`string`) 972 973get_captures({buf}, {start}, {stop}) *vim.treesitter.get_captures()* 974 Returns highlight captures at a position, on a line, or overlapping a 975 range. 976 977 {start} and {stop} can be a row number or a `{row, col}` pair. All rows 978 and columns are 0-based; columns are byte offsets. 979 980 Without {stop}, a row number queries the whole line and a `{row, col}` 981 pair queries one position. 982 983 With {stop}, return captures that overlap the range. The stop position is 984 excluded; a row number excludes that row. Empty ranges return no captures. 985 986 Each result includes the full captured node range, which may extend 987 outside the requested range. Returns an empty list if treesitter 988 highlighting is not active in {buf}. 989 990 Attributes: ~ 991 Since: 0.13.0 992 993 Parameters: ~ 994 • {buf} (`integer`) Buffer number (0 for current buffer) 995 • {start} (`integer|[integer,integer]`) Start row or `{row, col}` 996 • {stop} (`integer|[integer,integer]?`) Stop row or `{row, col}` 997 (excluded) 998 999 Return: ~ 1000 (`table[]`) A list of objects with the following fields: 1001 • {capture} (`string`) Capture name 1002 • {col} (`integer`) Start column 1003 • {end_col} (`integer`) End column (excluded) 1004 • {end_row} (`integer`) End row 1005 • {id} (`integer`) 1-based capture id in the query 1006 • {lang} (`string`) Language name 1007 • {metadata} (`vim.treesitter.query.TSMetadata`) Query metadata, e.g. 1008 `priority` or `conceal` 1009 • {pattern_id} (`integer`) 1-based id of the matched pattern in the 1010 query 1011 • {row} (`integer`) Start row 1012 1013get_captures_at_cursor({win}) *vim.treesitter.get_captures_at_cursor()* 1014 Returns a list of highlight capture names under the cursor 1015 1016 Parameters: ~ 1017 • {win} (`integer?`) |window-ID| or 0 for current window (default) 1018 1019 Return: ~ 1020 (`string[]`) List of capture names 1021 1022get_node({opts}) *vim.treesitter.get_node()* 1023 Returns the smallest named node at the given position 1024 1025 NOTE: Calling this on an unparsed tree can yield an invalid node. If the 1026 tree is not known to be parsed by, e.g., an active highlighter, parse the 1027 tree first via >lua 1028 vim.treesitter.get_parser(bufnr):parse(range) 1029< 1030 1031 Parameters: ~ 1032 • {opts} (`table?`) Optional keyword arguments: 1033 • {bufnr} (`integer?`) Buffer number (nil or 0 for current 1034 buffer) 1035 • {ignore_injections} (`boolean?`, default: true) Ignore 1036 injected languages 1037 • {include_anonymous} (`boolean?`, default: false) Include 1038 anonymous nodes 1039 • {lang} (`string?`, default: from 'filetype') Parser 1040 language. 1041 • {pos} (`[integer, integer]?`, default: window-local cursor) 1042 0-indexed (row, col) tuple. Required if {bufnr} is not the 1043 current buffer 1044 1045 Return: ~ 1046 (`TSNode?`) Node at the given position 1047 1048get_node_range({node_or_range}) *vim.treesitter.get_node_range()* 1049 Returns the node's range or an unpacked range table 1050 1051 Parameters: ~ 1052 • {node_or_range} (`TSNode|Range4`) Node or table of positions 1053 1054 Return (multiple): ~ 1055 (`integer`) start_row 1056 (`integer`) start_col (byte offset) 1057 (`integer`) end_row 1058 (`integer`) end_col (byte offset) 1059 1060 *vim.treesitter.get_node_text()* 1061get_node_text({node}, {source}, {opts}) 1062 Gets the text corresponding to a given node 1063 1064 Parameters: ~ 1065 • {node} (`TSNode`) 1066 • {source} (`integer|string`) Buffer or string from which the {node} is 1067 extracted 1068 • {opts} (`table?`) Optional parameters. 1069 • metadata (table) Metadata of a specific capture. This 1070 would be set to `metadata[capture_id]` when using 1071 |vim.treesitter.query.add_directive()|. 1072 1073 Return: ~ 1074 (`string`) 1075 1076get_parser({buf}, {lang}, {opts}) *vim.treesitter.get_parser()* 1077 Returns the parser for a specific buffer and attaches it to the buffer 1078 1079 If needed, this will create the parser. 1080 1081 If no parser can be created, nil (and an error message) is returned. 1082 1083 Parameters: ~ 1084 • {buf} (`integer?`) (default: current buffer) Buffer the parser 1085 should be tied to 1086 • {lang} (`string?`) (default: from 'filetype') Language of this parser 1087 • {opts} (`table?`) Options to pass to the created language tree 1088 1089 Return (multiple): ~ 1090 (`vim.treesitter.LanguageTree?`) object to use for parsing 1091 (`string?`) error message, if applicable 1092 1093get_range({node}, {source}, {metadata}) *vim.treesitter.get_range()* 1094 Get the range of a |TSNode|. Can also supply {source} and {metadata} to 1095 get the range with directives applied. 1096 1097 Parameters: ~ 1098 • {node} (`TSNode`) 1099 • {source} (`integer|string?`) Buffer or string from which the {node} 1100 is extracted 1101 • {metadata} (`vim.treesitter.query.TSMetadata?`) 1102 1103 Return: ~ 1104 (`table`) A table with the following fields: 1105 • {[1]} (`integer`) start row 1106 • {[2]} (`integer`) start column 1107 • {[3]} (`integer`) start bytes 1108 • {[4]} (`integer`) end row 1109 • {[5]} (`integer`) end column 1110 • {[6]} (`integer`) end bytes 1111 1112 *vim.treesitter.get_string_parser()* 1113get_string_parser({str}, {lang}, {opts}) 1114 Returns a string parser 1115 1116 Parameters: ~ 1117 • {str} (`string`) Text to parse 1118 • {lang} (`string`) Language of this string 1119 • {opts} (`table?`) Options to pass to the created language tree 1120 1121 Return: ~ 1122 (`vim.treesitter.LanguageTree`) object to use for parsing 1123 1124inspect_tree({opts}) *vim.treesitter.inspect_tree()* 1125 Open a window that displays a textual representation of the nodes in the 1126 language tree. 1127 1128 While in the window, press "a" to toggle display of anonymous nodes, "I" 1129 to toggle the display of the source language of each node, "o" to toggle 1130 the query editor, and press <Enter> to jump to the node under the cursor 1131 in the source buffer. Folding also works (try |zo|, |zc|, etc.). 1132 1133 Can also be shown with `:InspectTree`. *:InspectTree* 1134 1135 Attributes: ~ 1136 Since: 0.9.0 1137 1138 Parameters: ~ 1139 • {opts} (`table?`) Optional options table with the following possible 1140 keys: 1141 • bufnr (integer|nil): Buffer to draw the tree into. If 1142 omitted, a new buffer is created. 1143 • command (string|nil): Vimscript command to create the 1144 window. Default value is "60vnew". Only used when {winid} is 1145 nil. 1146 • lang (string|nil): The language of the source buffer. If 1147 omitted, detect from the filetype of the source buffer. 1148 • title (string|fun(bufnr:integer):string|nil): Title of the 1149 window. If a function, it accepts the buffer number of the 1150 source buffer as its only argument and should return a 1151 string. 1152 • winid (integer|nil): Window id to display the tree buffer 1153 in. If omitted, a new window is created with {command}. 1154 1155is_ancestor({dest}, {source}) *vim.treesitter.is_ancestor()* 1156 Determines whether a node is the ancestor of another 1157 1158 Parameters: ~ 1159 • {dest} (`TSNode`) Possible ancestor 1160 • {source} (`TSNode`) Possible descendant 1161 1162 Return: ~ 1163 (`boolean`) True if {dest} is an ancestor of {source} 1164 1165 *vim.treesitter.is_in_node_range()* 1166is_in_node_range({node}, {line}, {col}) 1167 Determines whether (line, col) position is in node range 1168 1169 Parameters: ~ 1170 • {node} (`TSNode`) defining the range 1171 • {line} (`integer`) Line (0-based) 1172 • {col} (`integer`) Column (0-based) 1173 1174 Return: ~ 1175 (`boolean`) True if the position is in node range 1176 1177node_contains({node}, {range}) *vim.treesitter.node_contains()* 1178 Determines if a node contains a range 1179 1180 Parameters: ~ 1181 • {node} (`TSNode`) 1182 • {range} (`table`) 1183 1184 Return: ~ 1185 (`boolean`) True if the {node} contains the {range} 1186 1187select({target}, {count}) *vim.treesitter.select()* 1188 Starts or adjusts a |Visual| selection at cursor, based on tree nodes. The 1189 `target` parameter decides the selection behavior. 1190 1191 Parameters: ~ 1192 • {target} (`'parent'|'child'|'next'|'prev'|'extend_next'|'extend_prev'`) 1193 Decides the selection behavior. 1194 • {count} (`integer?`) (default: 1) Expand or adjust the selection 1195 this many times. 1196 1197start({buf}, {lang}) *vim.treesitter.start()* 1198 Starts treesitter highlighting for a buffer 1199 1200 Can be used in an ftplugin or FileType autocommand. 1201 1202 Note: By default, disables regex syntax highlighting, which may be 1203 required for some plugins. In this case, add `vim.bo.syntax = 'ON'` after 1204 the call to `start`. 1205 1206 Note: By default, the highlighter parses code asynchronously, using a 1207 segment time of 3ms. 1208 1209 Example: >lua 1210 vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex', 1211 callback = function(ev) 1212 vim.treesitter.start(ev.buf, 'latex') 1213 vim.bo[ev.buf].syntax = 'ON' -- only if additional legacy syntax is needed 1214 end 1215 }) 1216< 1217 1218 Parameters: ~ 1219 • {buf} (`integer?`) (default: current buffer) Buffer to be 1220 highlighted 1221 • {lang} (`string?`) (default: from 'filetype') Language of the parser 1222 1223stop({buf}) *vim.treesitter.stop()* 1224 Stops treesitter highlighting for a buffer 1225 1226 Parameters: ~ 1227 • {buf} (`integer?`) (default: current buffer) Buffer to stop 1228 highlighting 1229 1230 1231============================================================================== 1232Lua module: vim.treesitter.language *treesitter-language* 1233 1234add({lang}, {opts}) *vim.treesitter.language.add()* 1235 Load parser with name {lang} 1236 1237 Parsers are searched in the `parser` runtime directory, or the provided 1238 {path}. Can be used to check for available parsers before enabling 1239 treesitter features, e.g., >lua 1240 if vim.treesitter.language.add('markdown') then 1241 vim.treesitter.start(bufnr, 'markdown') 1242 end 1243< 1244 1245 Parameters: ~ 1246 • {lang} (`string`) Name of the parser (alphanumerical and `_` only) 1247 • {opts} (`table?`) Options: 1248 • {path}? (`string`) Optional path the parser is located at 1249 • {symbol_name}? (`string`) Internal symbol name for the 1250 language to load 1251 1252 Return (multiple): ~ 1253 (`boolean?`) True if parser is loaded 1254 (`string?`) Error if parser cannot be loaded 1255 1256get_filetypes({lang}) *vim.treesitter.language.get_filetypes()* 1257 Returns the filetypes for which a parser named {lang} is used. 1258 1259 The list includes {lang} itself plus all filetypes registered via 1260 |vim.treesitter.language.register()|. 1261 1262 Parameters: ~ 1263 • {lang} (`string`) Name of parser 1264 1265 Return: ~ 1266 (`string[]`) filetypes 1267 1268get_lang({filetype}) *vim.treesitter.language.get_lang()* 1269 Returns the language name to be used when loading a parser for {filetype}. 1270 1271 If no language has been explicitly registered via 1272 |vim.treesitter.language.register()|, default to {filetype}. For composite 1273 filetypes like `html.glimmer`, only the main filetype is returned. 1274 1275 Parameters: ~ 1276 • {filetype} (`string`) 1277 1278 Return: ~ 1279 (`string?`) 1280 1281inspect({lang}) *vim.treesitter.language.inspect()* 1282 Inspects the provided language. 1283 1284 Inspecting provides some useful information on the language like ABI 1285 version, parser state count (a measure of parser complexity), node and 1286 field names, and whether the language came from a WASM module. 1287 1288 Node names are returned in a table mapping each node name to a `boolean` 1289 indicating whether or not the node is named (i.e., not anonymous). 1290 Anonymous nodes are surrounded with double quotes (`"`). 1291 1292 For ABI 15 parsers, also show parser metadata (major, minor, patch 1293 version) and a table of supertypes with their respective subtypes. 1294 1295 Parameters: ~ 1296 • {lang} (`string`) Language 1297 1298 Return: ~ 1299 (`TSLangInfo`) 1300 1301register({lang}, {filetype}) *vim.treesitter.language.register()* 1302 Register a parser named {lang} to be used for {filetype}(s). 1303 1304 Note: this adds or overrides the mapping for {filetype}, any existing 1305 mappings from other filetypes to {lang} will be preserved. 1306 1307 Parameters: ~ 1308 • {lang} (`string`) Name of parser 1309 • {filetype} (`string|string[]`) Filetype(s) to associate with lang 1310 1311 1312============================================================================== 1313Lua module: vim.treesitter.languagetree *treesitter-languagetree* 1314 1315A *LanguageTree* contains a tree of parsers: the root treesitter parser for 1316{lang} and any "injected" language parsers, which themselves may inject other 1317languages, recursively. For example a Lua buffer containing some Vimscript 1318commands needs multiple parsers to fully understand its contents. 1319 1320To create a LanguageTree (parser object) for a given buffer and language, use: >lua 1321 local parser = vim.treesitter.get_parser(bufnr, lang) 1322< 1323 1324(where `bufnr=0` means current buffer). `lang` defaults to 'filetype'. Note: 1325currently the parser is retained for the lifetime of a buffer but this may 1326change; a plugin should keep a reference to the parser object if it wants 1327incremental updates. 1328 1329Whenever you need to access the current syntax tree, parse the buffer: >lua 1330 local tree = parser:parse({ start_row, end_row }) 1331< 1332 1333This returns a table of immutable |treesitter-tree| objects representing the 1334current state of the buffer. When the plugin wants to access the state after a 1335(possible) edit it must call `parse()` again. If the buffer wasn't edited, the 1336same tree will be returned again without extra work. If the buffer was parsed 1337before, incremental parsing will be done of the changed parts. 1338 1339Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback, 1340you must call |vim.treesitter.get_parser()| before you register your callback. 1341But preferably parsing shouldn't be done directly in the change callback 1342anyway as they will be very frequent. Rather a plugin that does any kind of 1343analysis on a tree should use a timer to throttle too frequent updates. 1344 1345 1346LanguageTree:children() *LanguageTree:children()* 1347 Returns a map of language to child tree. 1348 1349 Return: ~ 1350 (`table<string,vim.treesitter.LanguageTree>`) 1351 1352LanguageTree:contains({range}) *LanguageTree:contains()* 1353 Determines whether {range} is contained in the |LanguageTree|. 1354 1355 Parameters: ~ 1356 • {range} (`table`) A table with the following fields: 1357 • {[1]} (`integer`) start row 1358 • {[2]} (`integer`) start column 1359 • {[3]} (`integer`) end row 1360 • {[4]} (`integer`) end column 1361 1362 Return: ~ 1363 (`boolean`) 1364 1365LanguageTree:destroy() *LanguageTree:destroy()* 1366 Destroys this |LanguageTree| and all its children. 1367 1368 Any cleanup logic should be performed here. 1369 1370 Note: This DOES NOT remove this tree from a parent. Instead, 1371 `remove_child` must be called on the parent to remove it. 1372 1373LanguageTree:for_each_tree({fn}) *LanguageTree:for_each_tree()* 1374 Invokes the callback for each |LanguageTree| recursively. 1375 1376 Note: This includes the invoking tree's child trees as well. 1377 1378 Parameters: ~ 1379 • {fn} (`fun(tree: TSTree, ltree: vim.treesitter.LanguageTree)`) 1380 1381LanguageTree:included_regions() *LanguageTree:included_regions()* 1382 Gets the set of included regions managed by this LanguageTree. This can be 1383 different from the regions set by injection query, because a partial 1384 |LanguageTree:parse()| drops the regions outside the requested range. Each 1385 list represents a range in the form of { {start_row}, {start_col}, 1386 {start_bytes}, {end_row}, {end_col}, {end_bytes} }. 1387 1388 Return: ~ 1389 (`table<integer, Range6[]>`) 1390 1391LanguageTree:invalidate({reload}) *LanguageTree:invalidate()* 1392 Invalidates this parser and its children. 1393 1394 Should only be called when the tracked state of the LanguageTree is not 1395 valid against the parse tree in treesitter. Doesn't clear filesystem 1396 cache. Called often, so needs to be fast. 1397 1398 Parameters: ~ 1399 • {reload} (`boolean?`) 1400 1401 *LanguageTree:is_valid()* 1402LanguageTree:is_valid({exclude_children}, {range}) 1403 Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()| 1404 reflects the latest state of the source. If invalid, user should call 1405 |LanguageTree:parse()|. 1406 1407 Parameters: ~ 1408 • {exclude_children} (`boolean?`) whether to ignore the validity of 1409 children (default `false`) 1410 • {range} (`Range|Range[]?`) range (or list of ranges, 1411 sorted by starting point in ascending order) to 1412 check for validity 1413 1414 Return: ~ 1415 (`boolean`) 1416 1417LanguageTree:lang() *LanguageTree:lang()* 1418 Gets the language of this tree node. 1419 1420 Return: ~ 1421 (`string`) 1422 1423 *LanguageTree:language_for_range()* 1424LanguageTree:language_for_range({range}) 1425 Gets the appropriate language that contains {range}. 1426 1427 Parameters: ~ 1428 • {range} (`table`) A table with the following fields: 1429 • {[1]} (`integer`) start row 1430 • {[2]} (`integer`) start column 1431 • {[3]} (`integer`) end row 1432 • {[4]} (`integer`) end column 1433 1434 Return: ~ 1435 (`vim.treesitter.LanguageTree`) tree Managing {range} 1436 1437 *LanguageTree:named_node_for_range()* 1438LanguageTree:named_node_for_range({range}, {opts}) 1439 Gets the smallest named node that contains {range}. 1440 1441 Parameters: ~ 1442 • {range} (`table`) A table with the following fields: 1443 • {[1]} (`integer`) start row 1444 • {[2]} (`integer`) start column 1445 • {[3]} (`integer`) end row 1446 • {[4]} (`integer`) end column 1447 • {opts} (`table?`) A table with the following fields: 1448 • {ignore_injections}? (`boolean`, default: `true`) Ignore 1449 injected languages 1450 1451 Return: ~ 1452 (`TSNode?`) 1453 1454 *LanguageTree:node_for_range()* 1455LanguageTree:node_for_range({range}, {opts}) 1456 Gets the smallest node that contains {range}. 1457 1458 Parameters: ~ 1459 • {range} (`table`) A table with the following fields: 1460 • {[1]} (`integer`) start row 1461 • {[2]} (`integer`) start column 1462 • {[3]} (`integer`) end row 1463 • {[4]} (`integer`) end column 1464 • {opts} (`table?`) A table with the following fields: 1465 • {ignore_injections}? (`boolean`, default: `true`) Ignore 1466 injected languages 1467 1468 Return: ~ 1469 (`TSNode?`) 1470 1471LanguageTree:parent() *LanguageTree:parent()* 1472 Returns the parent tree. `nil` for the root tree. 1473 1474 Return: ~ 1475 (`vim.treesitter.LanguageTree?`) 1476 1477LanguageTree:parse({range}, {on_parse}) *LanguageTree:parse()* 1478 Recursively parse all regions in the language tree using 1479 |treesitter-parsers| for the corresponding languages and run injection 1480 queries on the parsed trees to determine whether child trees should be 1481 created and parsed. 1482 1483 Any region with empty range (`{}`, typically only the root tree) is always 1484 parsed; otherwise (typically injections) only if it intersects {range} (or 1485 if {range} is `true`). 1486 1487 Parameters: ~ 1488 • {range} (`boolean|Range|Range[]?`) Parse this range (or list of 1489 ranges, sorted by starting point in ascending order) in 1490 the parser's source. Set to `true` to run a complete parse 1491 of the source (Note: Can be slow!) Set to `false|nil` to 1492 only parse regions with empty ranges (typically only the 1493 root tree without injections). 1494 • {on_parse} (`fun(err?: string, trees?: table<integer, TSTree>)?`) 1495 Function invoked when parsing completes. When omitted, 1496 parsing is synchronous and always returns the trees. When 1497 provided and `vim.g._ts_force_sync_parsing` is not set, 1498 parsing will run asynchronously. The first argument to the 1499 function is a string representing the error type, in case 1500 of a failure (currently only possible for timeouts). The 1501 second argument is the list of trees returned by the parse 1502 (upon success), or `nil` if the parse timed out 1503 (determined by 'redrawtime'). 1504 1505 If parsing was still able to finish synchronously (within 1506 3ms), `parse()` returns the list of trees. Otherwise, it 1507 returns `nil`. 1508 1509 Overloads: ~ 1510 • `fun(self: vim.treesitter.LanguageTree, range?: boolean|Range|Range[]): table<integer, TSTree>` 1511 1512 Return: ~ 1513 (`table<integer, TSTree>?`) 1514 1515 *LanguageTree:register_cbs()* 1516LanguageTree:register_cbs({cbs}, {recursive}) 1517 Registers callbacks for the |LanguageTree|. 1518 1519 Parameters: ~ 1520 • {cbs} (`table<TSCallbackNameOn,function>`) An 1521 |nvim_buf_attach()|-like table argument with the 1522 following handlers: 1523 • `on_bytes` : see |nvim_buf_attach()|. 1524 • `on_changedtree` : a callback that will be called every 1525 time the tree has syntactical changes. It will be 1526 passed two arguments: a table of the ranges (as node 1527 ranges) that changed and the changed tree. 1528 • `on_child_added` : emitted when a child is added to the 1529 tree. 1530 • `on_child_removed` : emitted when a child is removed 1531 from the tree. 1532 • `on_detach` : emitted when the buffer is detached, see 1533 |nvim_buf_detach_event|. Takes one argument, the number 1534 of the buffer. 1535 • {recursive} (`boolean?`) Apply callbacks recursively for all 1536 children. Any new children will also inherit the 1537 callbacks. 1538 1539LanguageTree:source() *LanguageTree:source()* 1540 Returns the source content of the language tree (bufnr or string). 1541 1542 Return: ~ 1543 (`integer|string`) 1544 1545 *LanguageTree:tree_for_range()* 1546LanguageTree:tree_for_range({range}, {opts}) 1547 Gets the tree that contains {range}. 1548 1549 Parameters: ~ 1550 • {range} (`table`) A table with the following fields: 1551 • {[1]} (`integer`) start row 1552 • {[2]} (`integer`) start column 1553 • {[3]} (`integer`) end row 1554 • {[4]} (`integer`) end column 1555 • {opts} (`table?`) A table with the following fields: 1556 • {ignore_injections}? (`boolean`, default: `true`) Ignore 1557 injected languages 1558 1559 Return: ~ 1560 (`TSTree?`) 1561 1562LanguageTree:trees() *LanguageTree:trees()* 1563 Returns all trees of the regions parsed by this parser. Does not include 1564 child languages. The result is list-like if 1565 • this LanguageTree is the root, in which case the result is empty or a 1566 singleton list; or 1567 • the root LanguageTree is fully parsed. 1568 1569 Return: ~ 1570 (`table<integer, TSTree>`) 1571 1572 1573============================================================================== 1574Lua module: vim.treesitter.query *lua-treesitter-query* 1575 1576This Lua |treesitter-query| interface allows you to create queries and use 1577them to parse text. See |vim.treesitter.query.parse()| for a working example. 1578 1579 1580*TSQuery* 1581 Extends: |userdata| 1582 1583 Reference to an object held by the treesitter library that is used as a 1584 component of the |vim.treesitter.Query| for language feature support. See 1585 |treesitter-query| for more about queries or 1586 |vim.treesitter.query.parse()| for an example of how to obtain a query 1587 object. 1588 1589 Fields: ~ 1590 • {disable_capture} (`fun(self: TSQuery, capture_name: string)`) See 1591 |TSQuery:disable_capture()|. 1592 • {disable_pattern} (`fun(self: TSQuery, pattern_index: integer)`) See 1593 |TSQuery:disable_pattern()|. 1594 1595*vim.treesitter.Query* 1596 Parsed query, see |vim.treesitter.query.parse()| 1597 1598 Fields: ~ 1599 • {captures} (`string[]`) list of (unique) capture names 1600 defined in query 1601 • {has_combined_injections} (`boolean`) whether the query contains 1602 combined injections 1603 • {has_conceal_line} (`boolean`) whether the query sets 1604 conceal_lines metadata 1605 • {info} (`vim.treesitter.QueryInfo`) query context 1606 (e.g. captures, predicates, directives) 1607 • {iter_captures} (`fun(self: vim.treesitter.Query, node: TSNode, source: integer|string, start_row: integer?, end_row: integer?, opts: table?): fun(end_line: integer?, end_col: integer?): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree`) 1608 See |Query:iter_captures()|. 1609 • {iter_matches} (`fun(self: vim.treesitter.Query, node: TSNode, source: integer|string, start: integer?, stop: integer?, opts: table?): fun(): integer, table<integer, TSNode[]>, vim.treesitter.query.TSMetadata, TSTree`) 1610 See |Query:iter_matches()|. 1611 • {lang} (`string`) parser language name 1612 • {query} (`TSQuery`) userdata query object 1613 1614 1615 *vim.treesitter.query.add_directive()* 1616add_directive({name}, {handler}, {opts}) 1617 Adds a new directive to be used in queries 1618 1619 Handlers can set match level data by setting directly on the metadata 1620 object `metadata.key = value`. Additionally, handlers can set node level 1621 data by using the capture id on the metadata table 1622 `metadata[capture_id].key = value` 1623 1624 Parameters: ~ 1625 • {name} (`string`) Name of the directive, without leading # 1626 • {handler} (`fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata)`) 1627 • match: A table mapping capture IDs to a list of captured 1628 nodes 1629 • pattern: the index of the matching pattern in the query 1630 file 1631 • predicate: list of strings containing the full directive 1632 being called, e.g. `(node (#set! conceal "-"))` would get 1633 the predicate `{ "#set!", "conceal", "-" }` 1634 • {opts} (`table`) A table with the following fields: 1635 • {force}? (`boolean`) Override an existing predicate of 1636 the same name 1637 1638 *vim.treesitter.query.add_predicate()* 1639add_predicate({name}, {handler}, {opts}) 1640 Adds a new predicate to be used in queries 1641 1642 Parameters: ~ 1643 • {name} (`string`) Name of the predicate, without leading # 1644 • {handler} (`fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata): boolean?`) 1645 • see |vim.treesitter.query.add_directive()| for argument 1646 meanings 1647 • {opts} (`table?`) A table with the following fields: 1648 • {force}? (`boolean`) Override an existing predicate of 1649 the same name 1650 1651edit({lang}) *vim.treesitter.query.edit()* 1652 Opens a live editor to query the buffer you started from. 1653 1654 Can also be shown with the *:EditQuery* command. `:EditQuery <tab>` 1655 completes available parsers. 1656 1657 If you move the cursor to a capture name ("@foo"), text matching the 1658 capture is highlighted with |hl-DiagnosticVirtualTextHint| in the source 1659 buffer. The query editor is a scratch buffer, use `:write` to save it. You 1660 can find example queries at `$VIMRUNTIME/queries/`. 1661 1662 Parameters: ~ 1663 • {lang} (`string?`) language to open the query editor for. If omitted, 1664 inferred from the current buffer's filetype. 1665 1666get({lang}, {query_name}) *vim.treesitter.query.get()* 1667 Returns the runtime query {query_name} for {lang}. 1668 1669 Parameters: ~ 1670 • {lang} (`string`) Language to use for the query 1671 • {query_name} (`string`) Name of the query (e.g. "highlights") 1672 1673 Return: ~ 1674 (`vim.treesitter.Query?`) Parsed query. `nil` if no query files are 1675 found. 1676 1677 *vim.treesitter.query.get_files()* 1678get_files({lang}, {query_name}, {is_included}) 1679 Gets the list of files used to make up a query 1680 1681 Parameters: ~ 1682 • {lang} (`string`) Language to get query for 1683 • {query_name} (`string`) Name of the query to load (e.g., 1684 "highlights") 1685 • {is_included} (`boolean?`) Internal parameter, most of the time left 1686 as `nil` 1687 1688 Return: ~ 1689 (`string[]`) query_files List of files to load for given query and 1690 language 1691 1692lint({buf}, {opts}) *vim.treesitter.query.lint()* 1693 Lint treesitter queries using installed parser, or clear lint errors. 1694 1695 Use |treesitter-parsers| in runtimepath to check the query file in {buf} 1696 for errors: 1697 • verify that used nodes are valid identifiers in the grammar. 1698 • verify that predicates and directives are valid. 1699 • verify that top-level s-expressions are valid. 1700 1701 The found diagnostics are reported using |diagnostic-api|. By default, the 1702 parser used for verification is determined by the containing folder of the 1703 query file, e.g., if the path ends in `/lua/highlights.scm`, the parser 1704 for the `lua` language will be used. 1705 1706 Parameters: ~ 1707 • {buf} (`integer`) Buffer handle 1708 • {opts} (`table?`) Optional keyword arguments: 1709 • {clear}? (`boolean`) Just clear current lint errors 1710 • {langs}? (`string|string[]`) Language(s) to use for checking 1711 the query. If multiple languages are specified, queries are 1712 validated for all of them 1713 1714list_directives() *vim.treesitter.query.list_directives()* 1715 Lists the currently available directives to use in queries. 1716 1717 Return: ~ 1718 (`string[]`) Supported directives. 1719 1720list_predicates() *vim.treesitter.query.list_predicates()* 1721 Lists the currently available predicates to use in queries. 1722 1723 Return: ~ 1724 (`string[]`) Supported predicates. 1725 1726omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()* 1727 Omnifunc for completing node names and predicates in treesitter queries. 1728 1729 Use via >lua 1730 vim.bo.omnifunc = vim.treesitter.query.omnifunc 1731< 1732 1733 Parameters: ~ 1734 • {findstart} (`0|1`) 1735 • {base} (`string`) 1736 1737parse({lang}, {query}) *vim.treesitter.query.parse()* 1738 Parses a {query} string and returns a `Query` object 1739 (|lua-treesitter-query|), which can be used to search the tree for the 1740 query patterns (via |Query:iter_captures()|, |Query:iter_matches()|), or 1741 inspect/modify the query via these fields: 1742 • `captures`: a list of unique capture names defined in the query (alias: 1743 `info.captures`). 1744 • `info.patterns`: information about predicates. 1745 • `query`: the underlying |TSQuery| which can be used to disable patterns 1746 or captures. 1747 1748 Example: >lua 1749 local query = vim.treesitter.query.parse('vimdoc', [[ 1750 ; query 1751 ((h1) @str 1752 (#trim! @str 1 1 1 1)) 1753 ]]) 1754 local tree = vim.treesitter.get_parser():parse()[1] 1755 for id, node, metadata in query:iter_captures(tree:root(), 0) do 1756 -- Print the node name and source text. 1757 vim.print({node:type(), vim.treesitter.get_node_text(node, vim.api.nvim_get_current_buf())}) 1758 end 1759< 1760 1761 Parameters: ~ 1762 • {lang} (`string`) Language to use for the query 1763 • {query} (`string`) Query text, in s-expr syntax 1764 1765 Return: ~ 1766 (`vim.treesitter.Query`) Parsed query 1767 1768 See also: ~ 1769 • |vim.treesitter.query.get()| 1770 1771 *Query:iter_captures()* 1772Query:iter_captures({node}, {source}, {start_row}, {end_row}, {opts}) 1773 Iterates over all captures from all matches in {node}. 1774 1775 {source} is required if the query contains predicates; then the caller 1776 must ensure to use a freshly parsed tree consistent with the current text 1777 of the buffer (if relevant). {start} and {stop} can be used to limit 1778 matches inside a row range (this is typically used with root node as the 1779 {node}, i.e., to get syntax highlight matches in the current viewport). 1780 When omitted, the {start} and {stop} row values are used from the given 1781 node. 1782 1783 The iterator returns four values: 1784 1. the numeric id identifying the capture 1785 2. the captured node 1786 3. metadata from any directives processing the match 1787 4. the match itself 1788 1789 Example: how to get captures by name: >lua 1790 for id, node, metadata, match in query:iter_captures(tree:root(), bufnr, first, last) do 1791 local name = query.captures[id] -- name of the capture in the query 1792 -- typically useful info about the node: 1793 local type = node:type() -- type of the captured node 1794 local row1, col1, row2, col2 = node:range() -- range of the capture 1795 -- ... use the info here ... 1796 end 1797< 1798 1799 Note: ~ 1800 • Captures are only returned if the query pattern of a specific capture 1801 contained predicates. 1802 1803 Parameters: ~ 1804 • {node} (`TSNode`) under which the search will occur 1805 • {source} (`integer|string`) Source buffer or string to extract 1806 text from 1807 • {start_row} (`integer?`) Starting line for the search. Defaults to 1808 `node:start()`. 1809 • {end_row} (`integer?`) Stopping line for the search (end-inclusive, 1810 unless `stop_col` is provided). Defaults to 1811 `node:end_()`. 1812 • {opts} (`table?`) Optional keyword arguments: 1813 • end_col (integer) Stopping column for the search 1814 (end-exclusive). 1815 • match_limit (integer) Set the maximum number of 1816 in-progress matches (Default: none). 1817 • max_start_depth (integer) if non-zero, sets the maximum 1818 start depth for each match. This is used to prevent 1819 traversing too deep into a tree. 1820 • start_col (integer) Starting column for the search. 1821 1822 Return: ~ 1823 (`fun(end_line: integer?, end_col: integer?): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree`) 1824 capture-id, capture-node, metadata, match, tree 1825 1826 *Query:iter_matches()* 1827Query:iter_matches({node}, {source}, {start}, {stop}, {opts}) 1828 Iterates the matches of self on a given range. 1829 1830 Iterate over all matches within a {node}. The arguments are the same as 1831 for |Query:iter_captures()| but the iterated values are different: an 1832 (1-based) index of the pattern in the query, a table mapping capture 1833 indices to a list of nodes, and metadata from any directives processing 1834 the match. 1835 1836 Example: >lua 1837 for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, 0, -1) do 1838 for id, nodes in pairs(match) do 1839 local name = query.captures[id] 1840 for _, node in ipairs(nodes) do 1841 -- `node` was captured by the `name` capture in the match 1842 1843 local node_data = metadata[id] -- Node level metadata 1844 -- ... use the info here ... 1845 end 1846 end 1847 end 1848< 1849 1850 Parameters: ~ 1851 • {node} (`TSNode`) under which the search will occur 1852 • {source} (`integer|string`) Source buffer or string to search 1853 • {start} (`integer?`) Starting line for the search. Defaults to 1854 `node:start()`. 1855 • {stop} (`integer?`) Stopping line for the search (end-exclusive). 1856 Defaults to `node:end_()`. 1857 • {opts} (`table?`) Optional keyword arguments: 1858 • match_limit (integer) Set the maximum number of 1859 in-progress matches (Default: none). 1860 • max_start_depth (integer) if non-zero, sets the maximum 1861 start depth for each match. This is used to prevent 1862 traversing too deep into a tree. 1863 1864 Return: ~ 1865 (`fun(): integer, table<integer, TSNode[]>, vim.treesitter.query.TSMetadata, TSTree`) 1866 pattern-id, match, metadata, tree 1867 1868set({lang}, {query_name}, {text}) *vim.treesitter.query.set()* 1869 Sets the runtime query named {query_name} for {lang} 1870 1871 This allows users to override or extend any runtime files and/or 1872 configuration set by plugins. 1873 1874 For example, you could enable spellchecking of `C` identifiers with the 1875 following code: >lua 1876 vim.treesitter.query.set( 1877 'c', 1878 'highlights', 1879 [[;inherits c 1880 (identifier) @spell]] 1881 ) 1882< 1883 1884 Parameters: ~ 1885 • {lang} (`string`) Language to use for the query 1886 • {query_name} (`string`) Name of the query (e.g., "highlights") 1887 • {text} (`string`) Query text (unparsed). 1888 1889TSQuery:disable_capture({capture_name}) *TSQuery:disable_capture()* 1890 Disable a specific capture in this query; once disabled the capture cannot 1891 be re-enabled. {capture_name} should not include a leading "@". 1892 1893 Example: To disable the `@variable.parameter` capture from the vimdoc 1894 highlights query: >lua 1895 local query = vim.treesitter.query.get('vimdoc', 'highlights') 1896 query.query:disable_capture("variable.parameter") 1897 vim.treesitter.get_parser():parse() 1898< 1899 1900 Parameters: ~ 1901 • {capture_name} (`string`) 1902 1903TSQuery:disable_pattern({pattern_index}) *TSQuery:disable_pattern()* 1904 Disable a specific pattern in this query; once disabled the pattern cannot 1905 be re-enabled. The {pattern_index} for a particular match can be obtained 1906 with |:Inspect!|, or by reading the source of the query (i.e. from 1907 |vim.treesitter.query.get_files()|). 1908 1909 Example: To disable `|` links in vimdoc but keep other `@markup.link`s 1910 highlighted: >lua 1911 local link_pattern = 9 -- from :Inspect! 1912 local query = vim.treesitter.query.get('vimdoc', 'highlights') 1913 query.query:disable_pattern(link_pattern) 1914 local tree = vim.treesitter.get_parser():parse()[1] 1915< 1916 1917 Parameters: ~ 1918 • {pattern_index} (`integer`) 1919 1920 1921 vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: