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