treesitter.txt 67 KB

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