treesitter.txt 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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 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. Note that although you can use any string for `conceal`, only the first
  409. character will be used: >query
  410. ; identifiers will be concealed with 'f'.
  411. ((identifier) @conceal (#set! conceal "foo"))
  412. <
  413. *treesitter-highlight-priority*
  414. Treesitter uses |nvim_buf_set_extmark()| to set highlights with a default
  415. priority of 100. This enables plugins to set a highlighting priority lower or
  416. higher than treesitter. It is also possible to change the priority of an
  417. individual query pattern manually by setting its `"priority"` metadata
  418. attribute: >query
  419. ((super_important_node) @superimportant (#set! priority 105))
  420. <
  421. ==============================================================================
  422. TREESITTER LANGUAGE INJECTIONS *treesitter-language-injections*
  423. <
  424. Note the following information is adapted from:
  425. https://tree-sitter.github.io/tree-sitter/syntax-highlighting#language-injection
  426. Some source files contain code written in multiple different languages.
  427. Examples include:
  428. • HTML files, which can contain JavaScript inside of `<script>` tags and
  429. CSS inside of `<style>` tags
  430. • ERB files, which contain Ruby inside of `<%` `%>` tags, and HTML outside of
  431. those tags
  432. • PHP files, which can contain HTML between the `<php` tags
  433. • JavaScript files, which contain regular expression syntax within regex
  434. literals
  435. • Ruby, which can contain snippets of code inside of heredoc literals,
  436. where the heredoc delimiter often indicates the language
  437. • Lua, which can contain snippets of Vimscript inside |vim.cmd()| calls.
  438. • Vimscript, which can contain snippets of Lua inside |:lua-heredoc|
  439. blocks.
  440. All of these examples can be modeled in terms of a parent syntax tree and one
  441. or more injected syntax trees, which reside inside of certain nodes in the
  442. parent tree. The language injection query allows you to specify these
  443. “injections” using the following captures:
  444. • `@injection.content` - indicates that the captured node should have its
  445. contents re-parsed using another language.
  446. • `@injection.language` - indicates that the captured node’s text may
  447. contain the name of a language that should be used to re-parse the
  448. `@injection.content`.
  449. • `@injection.filename` - indicates that the captured node’s text may
  450. contain a filename; the corresponding filetype is then looked-up up via
  451. |vim.filetype.match()| and treated as the name of a language that should
  452. be used to re-parse the `@injection.content`.
  453. The language injection behavior can also be configured by some properties
  454. associated with patterns:
  455. • `injection.language` - can be used to hard-code the name of a specific
  456. language.
  457. • `injection.combined` - indicates that all of the matching nodes in the
  458. tree should have their content parsed as one nested document.
  459. • `injection.include-children` - indicates that the `@injection.content`
  460. node's entire text should be re-parsed, including the text of its child
  461. nodes. By default, child nodes' text will be excluded from the injected
  462. document.
  463. • `injection.self` - indicates that the node's text should be parsed with
  464. the same language as the node's LanguageTree.
  465. • `injection.parent` - indicates that the captured node’s text should
  466. be parsed with the same language as the node's parent LanguageTree.
  467. Injection queries are currently run over the entire buffer, which can be slow
  468. for large buffers. To disable injections for, e.g., `c`, just place an
  469. empty `queries/c/injections.scm` file in your 'runtimepath'.
  470. ==============================================================================
  471. VIM.TREESITTER *lua-treesitter*
  472. The remainder of this document is a reference manual for the `vim.treesitter`
  473. Lua module, which is the main interface for Nvim's treesitter integration.
  474. Most of the following content is automatically generated from the function
  475. documentation.
  476. *vim.treesitter.language_version*
  477. The latest parser ABI version that is supported by the bundled treesitter
  478. library.
  479. *vim.treesitter.minimum_language_version*
  480. The earliest parser ABI version that is supported by the bundled treesitter
  481. library.
  482. ==============================================================================
  483. TREESITTER TREES *treesitter-tree* *TSTree*
  484. A "treesitter tree" represents the parsed contents of a buffer, which can be
  485. used to perform further analysis. It is a |userdata| reference to an object
  486. held by the treesitter library.
  487. An instance `TSTree` of a treesitter tree supports the following methods.
  488. TSTree:copy() *TSTree:copy()*
  489. Returns a copy of the `TSTree`.
  490. Return: ~
  491. (`TSTree`)
  492. TSTree:root() *TSTree:root()*
  493. Return the root node of this tree.
  494. Return: ~
  495. (`TSNode`)
  496. ==============================================================================
  497. TREESITTER NODES *treesitter-node* *TSNode*
  498. A "treesitter node" represents one specific element of the parsed contents of
  499. a buffer, which can be captured by a |Query| for, e.g., highlighting. It is a
  500. |userdata| reference to an object held by the treesitter library.
  501. An instance `TSNode` of a treesitter node supports the following methods.
  502. TSNode:byte_length() *TSNode:byte_length()*
  503. Return the number of bytes spanned by this node.
  504. Return: ~
  505. (`integer`)
  506. TSNode:child({index}) *TSNode:child()*
  507. Get the node's child at the given {index}, where zero represents the first
  508. child.
  509. Parameters: ~
  510. • {index} (`integer`)
  511. Return: ~
  512. (`TSNode?`)
  513. TSNode:child_count() *TSNode:child_count()*
  514. Get the node's number of children.
  515. Return: ~
  516. (`integer`)
  517. *TSNode:child_with_descendant()*
  518. TSNode:child_with_descendant({descendant})
  519. Get the node's child that contains {descendant} (includes {descendant}).
  520. For example, with the following node hierarchy: >
  521. a -> b -> c
  522. a:child_with_descendant(c) == b
  523. a:child_with_descendant(b) == b
  524. a:child_with_descendant(a) == nil
  525. <
  526. Parameters: ~
  527. • {descendant} (`TSNode`)
  528. Return: ~
  529. (`TSNode?`)
  530. *TSNode:descendant_for_range()*
  531. TSNode:descendant_for_range({start_row}, {start_col}, {end_row}, {end_col})
  532. Get the smallest node within this node that spans the given range of (row,
  533. column) positions
  534. Parameters: ~
  535. • {start_row} (`integer`)
  536. • {start_col} (`integer`)
  537. • {end_row} (`integer`)
  538. • {end_col} (`integer`)
  539. Return: ~
  540. (`TSNode?`)
  541. TSNode:end_() *TSNode:end_()*
  542. Get the node's end position. Return three values: the row, column and
  543. total byte count (all zero-based).
  544. Return (multiple): ~
  545. (`integer`)
  546. (`integer`)
  547. (`integer`)
  548. TSNode:equal({node}) *TSNode:equal()*
  549. Check if {node} refers to the same node within the same tree.
  550. Parameters: ~
  551. • {node} (`TSNode`)
  552. Return: ~
  553. (`boolean`)
  554. TSNode:extra() *TSNode:extra()*
  555. Check if the node is extra. Extra nodes represent things like comments,
  556. which are not required by the grammar but can appear anywhere.
  557. Return: ~
  558. (`boolean`)
  559. TSNode:field({name}) *TSNode:field()*
  560. Returns a table of the nodes corresponding to the {name} field.
  561. Parameters: ~
  562. • {name} (`string`)
  563. Return: ~
  564. (`TSNode[]`)
  565. TSNode:has_changes() *TSNode:has_changes()*
  566. Check if a syntax node has been edited.
  567. Return: ~
  568. (`boolean`)
  569. TSNode:has_error() *TSNode:has_error()*
  570. Check if the node is a syntax error or contains any syntax errors.
  571. Return: ~
  572. (`boolean`)
  573. TSNode:id() *TSNode:id()*
  574. Get a unique identifier for the node inside its own tree.
  575. No guarantees are made about this identifier's internal representation,
  576. except for being a primitive Lua type with value equality (so not a
  577. table). Presently it is a (non-printable) string.
  578. Note: The `id` is not guaranteed to be unique for nodes from different
  579. trees.
  580. Return: ~
  581. (`string`)
  582. TSNode:iter_children() *TSNode:iter_children()*
  583. Iterates over all the direct children of {TSNode}, regardless of whether
  584. they are named or not. Returns the child node plus the eventual field name
  585. corresponding to this child node.
  586. Return: ~
  587. (`fun(): TSNode, string`)
  588. TSNode:missing() *TSNode:missing()*
  589. Check if the node is missing. Missing nodes are inserted by the parser in
  590. order to recover from certain kinds of syntax errors.
  591. Return: ~
  592. (`boolean`)
  593. TSNode:named() *TSNode:named()*
  594. Check if the node is named. Named nodes correspond to named rules in the
  595. grammar, whereas anonymous nodes correspond to string literals in the
  596. grammar.
  597. Return: ~
  598. (`boolean`)
  599. TSNode:named_child({index}) *TSNode:named_child()*
  600. Get the node's named child at the given {index}, where zero represents the
  601. first named child.
  602. Parameters: ~
  603. • {index} (`integer`)
  604. Return: ~
  605. (`TSNode?`)
  606. TSNode:named_child_count() *TSNode:named_child_count()*
  607. Get the node's number of named children.
  608. Return: ~
  609. (`integer`)
  610. *TSNode:named_descendant_for_range()*
  611. TSNode:named_descendant_for_range({start_row}, {start_col}, {end_row},
  612. {end_col})
  613. Get the smallest named node within this node that spans the given range of
  614. (row, column) positions
  615. Parameters: ~
  616. • {start_row} (`integer`)
  617. • {start_col} (`integer`)
  618. • {end_row} (`integer`)
  619. • {end_col} (`integer`)
  620. Return: ~
  621. (`TSNode?`)
  622. TSNode:next_named_sibling() *TSNode:next_named_sibling()*
  623. Get the node's next named sibling.
  624. Return: ~
  625. (`TSNode?`)
  626. TSNode:next_sibling() *TSNode:next_sibling()*
  627. Get the node's next sibling.
  628. Return: ~
  629. (`TSNode?`)
  630. TSNode:parent() *TSNode:parent()*
  631. Get the node's immediate parent. Prefer |TSNode:child_with_descendant()|
  632. for iterating over the node's ancestors.
  633. Return: ~
  634. (`TSNode?`)
  635. TSNode:prev_named_sibling() *TSNode:prev_named_sibling()*
  636. Get the node's previous named sibling.
  637. Return: ~
  638. (`TSNode?`)
  639. TSNode:prev_sibling() *TSNode:prev_sibling()*
  640. Get the node's previous sibling.
  641. Return: ~
  642. (`TSNode?`)
  643. TSNode:range({include_bytes}) *TSNode:range()*
  644. Get the range of the node.
  645. Return four or six values:
  646. • start row
  647. • start column
  648. • start byte (if {include_bytes} is `true`)
  649. • end row
  650. • end column
  651. • end byte (if {include_bytes} is `true`)
  652. Parameters: ~
  653. • {include_bytes} (`false?`)
  654. Return (multiple): ~
  655. (`integer`)
  656. (`integer`)
  657. (`integer`)
  658. (`integer`)
  659. TSNode:sexpr() *TSNode:sexpr()*
  660. Get an S-expression representing the node as a string.
  661. Return: ~
  662. (`string`)
  663. TSNode:start() *TSNode:start()*
  664. Get the node's start position. Return three values: the row, column and
  665. total byte count (all zero-based).
  666. Return (multiple): ~
  667. (`integer`)
  668. (`integer`)
  669. (`integer`)
  670. TSNode:symbol() *TSNode:symbol()*
  671. Get the node's type as a numerical id.
  672. Return: ~
  673. (`integer`)
  674. TSNode:tree() *TSNode:tree()*
  675. Get the |TSTree| of the node.
  676. Return: ~
  677. (`TSTree`)
  678. TSNode:type() *TSNode:type()*
  679. Get the node's type as a string.
  680. Return: ~
  681. (`string`)
  682. ==============================================================================
  683. Lua module: vim.treesitter *lua-treesitter-core*
  684. foldexpr({lnum}) *vim.treesitter.foldexpr()*
  685. Returns the fold level for {lnum} in the current buffer. Can be set
  686. directly to 'foldexpr': >lua
  687. vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
  688. <
  689. Attributes: ~
  690. Since: 0.9.0
  691. Parameters: ~
  692. • {lnum} (`integer?`) Line number to calculate fold level for
  693. Return: ~
  694. (`string`)
  695. *vim.treesitter.get_captures_at_cursor()*
  696. get_captures_at_cursor({winnr})
  697. Returns a list of highlight capture names under the cursor
  698. Parameters: ~
  699. • {winnr} (`integer?`) Window handle or 0 for current window (default)
  700. Return: ~
  701. (`string[]`) List of capture names
  702. *vim.treesitter.get_captures_at_pos()*
  703. get_captures_at_pos({bufnr}, {row}, {col})
  704. Returns a list of highlight captures at the given position
  705. Each capture is represented by a table containing the capture name as a
  706. string, the capture's language, a table of metadata (`priority`,
  707. `conceal`, ...; empty if none are defined), and the id of the capture.
  708. Parameters: ~
  709. • {bufnr} (`integer`) Buffer number (0 for current buffer)
  710. • {row} (`integer`) Position row
  711. • {col} (`integer`) Position column
  712. Return: ~
  713. (`{capture: string, lang: string, metadata: vim.treesitter.query.TSMetadata, id: integer}[]`)
  714. get_node({opts}) *vim.treesitter.get_node()*
  715. Returns the smallest named node at the given position
  716. NOTE: Calling this on an unparsed tree can yield an invalid node. If the
  717. tree is not known to be parsed by, e.g., an active highlighter, parse the
  718. tree first via >lua
  719. vim.treesitter.get_parser(bufnr):parse(range)
  720. <
  721. Parameters: ~
  722. • {opts} (`table?`) Optional keyword arguments:
  723. • {bufnr} (`integer?`) Buffer number (nil or 0 for current
  724. buffer)
  725. • {pos} (`[integer, integer]?`) 0-indexed (row, col) tuple.
  726. Defaults to cursor position in the current window. Required
  727. if {bufnr} is not the current buffer
  728. • {lang} (`string?`) Parser language. (default: from buffer
  729. filetype)
  730. • {ignore_injections} (`boolean?`) Ignore injected languages
  731. (default true)
  732. • {include_anonymous} (`boolean?`) Include anonymous nodes
  733. (default false)
  734. Return: ~
  735. (`TSNode?`) Node at the given position
  736. get_node_range({node_or_range}) *vim.treesitter.get_node_range()*
  737. Returns the node's range or an unpacked range table
  738. Parameters: ~
  739. • {node_or_range} (`TSNode|Range4`) Node or table of positions
  740. Return (multiple): ~
  741. (`integer`) start_row
  742. (`integer`) start_col
  743. (`integer`) end_row
  744. (`integer`) end_col
  745. *vim.treesitter.get_node_text()*
  746. get_node_text({node}, {source}, {opts})
  747. Gets the text corresponding to a given node
  748. Parameters: ~
  749. • {node} (`TSNode`)
  750. • {source} (`integer|string`) Buffer or string from which the {node} is
  751. extracted
  752. • {opts} (`table?`) Optional parameters.
  753. • metadata (table) Metadata of a specific capture. This
  754. would be set to `metadata[capture_id]` when using
  755. |vim.treesitter.query.add_directive()|.
  756. Return: ~
  757. (`string`)
  758. get_parser({bufnr}, {lang}, {opts}) *vim.treesitter.get_parser()*
  759. Returns the parser for a specific buffer and attaches it to the buffer
  760. If needed, this will create the parser.
  761. If no parser can be created, an error is thrown. Set `opts.error = false`
  762. to suppress this and return nil (and an error message) instead. WARNING:
  763. This behavior will become default in Nvim 0.12 and the option will be
  764. removed.
  765. Parameters: ~
  766. • {bufnr} (`integer?`) Buffer the parser should be tied to (default:
  767. current buffer)
  768. • {lang} (`string?`) Language of this parser (default: from buffer
  769. filetype)
  770. • {opts} (`table?`) Options to pass to the created language tree
  771. Return (multiple): ~
  772. (`vim.treesitter.LanguageTree?`) object to use for parsing
  773. (`string?`) error message, if applicable
  774. get_range({node}, {source}, {metadata}) *vim.treesitter.get_range()*
  775. Get the range of a |TSNode|. Can also supply {source} and {metadata} to
  776. get the range with directives applied.
  777. Parameters: ~
  778. • {node} (`TSNode`)
  779. • {source} (`integer|string?`) Buffer or string from which the {node}
  780. is extracted
  781. • {metadata} (`vim.treesitter.query.TSMetadata?`)
  782. Return: ~
  783. (`table`) A table with the following fields:
  784. • {[1]} (`integer`) start row
  785. • {[2]} (`integer`) start column
  786. • {[3]} (`integer`) start bytes
  787. • {[4]} (`integer`) end row
  788. • {[5]} (`integer`) end column
  789. • {[6]} (`integer`) end bytes
  790. *vim.treesitter.get_string_parser()*
  791. get_string_parser({str}, {lang}, {opts})
  792. Returns a string parser
  793. Parameters: ~
  794. • {str} (`string`) Text to parse
  795. • {lang} (`string`) Language of this string
  796. • {opts} (`table?`) Options to pass to the created language tree
  797. Return: ~
  798. (`vim.treesitter.LanguageTree`) object to use for parsing
  799. inspect_tree({opts}) *vim.treesitter.inspect_tree()*
  800. Open a window that displays a textual representation of the nodes in the
  801. language tree.
  802. While in the window, press "a" to toggle display of anonymous nodes, "I"
  803. to toggle the display of the source language of each node, "o" to toggle
  804. the query editor, and press <Enter> to jump to the node under the cursor
  805. in the source buffer. Folding also works (try |zo|, |zc|, etc.).
  806. Can also be shown with `:InspectTree`. *:InspectTree*
  807. Attributes: ~
  808. Since: 0.9.0
  809. Parameters: ~
  810. • {opts} (`table?`) Optional options table with the following possible
  811. keys:
  812. • lang (string|nil): The language of the source buffer. If
  813. omitted, detect from the filetype of the source buffer.
  814. • bufnr (integer|nil): Buffer to draw the tree into. If
  815. omitted, a new buffer is created.
  816. • winid (integer|nil): Window id to display the tree buffer
  817. in. If omitted, a new window is created with {command}.
  818. • command (string|nil): Vimscript command to create the
  819. window. Default value is "60vnew". Only used when {winid} is
  820. nil.
  821. • title (string|fun(bufnr:integer):string|nil): Title of the
  822. window. If a function, it accepts the buffer number of the
  823. source buffer as its only argument and should return a
  824. string.
  825. is_ancestor({dest}, {source}) *vim.treesitter.is_ancestor()*
  826. Determines whether a node is the ancestor of another
  827. Parameters: ~
  828. • {dest} (`TSNode`) Possible ancestor
  829. • {source} (`TSNode`) Possible descendant
  830. Return: ~
  831. (`boolean`) True if {dest} is an ancestor of {source}
  832. *vim.treesitter.is_in_node_range()*
  833. is_in_node_range({node}, {line}, {col})
  834. Determines whether (line, col) position is in node range
  835. Parameters: ~
  836. • {node} (`TSNode`) defining the range
  837. • {line} (`integer`) Line (0-based)
  838. • {col} (`integer`) Column (0-based)
  839. Return: ~
  840. (`boolean`) True if the position is in node range
  841. node_contains({node}, {range}) *vim.treesitter.node_contains()*
  842. Determines if a node contains a range
  843. Parameters: ~
  844. • {node} (`TSNode`)
  845. • {range} (`table`)
  846. Return: ~
  847. (`boolean`) True if the {node} contains the {range}
  848. start({bufnr}, {lang}) *vim.treesitter.start()*
  849. Starts treesitter highlighting for a buffer
  850. Can be used in an ftplugin or FileType autocommand.
  851. Note: By default, disables regex syntax highlighting, which may be
  852. required for some plugins. In this case, add `vim.bo.syntax = 'on'` after
  853. the call to `start`.
  854. Note: By default, the highlighter parses code asynchronously, using a
  855. segment time of 3ms.
  856. Example: >lua
  857. vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
  858. callback = function(args)
  859. vim.treesitter.start(args.buf, 'latex')
  860. vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed
  861. end
  862. })
  863. <
  864. Parameters: ~
  865. • {bufnr} (`integer?`) Buffer to be highlighted (default: current
  866. buffer)
  867. • {lang} (`string?`) Language of the parser (default: from buffer
  868. filetype)
  869. stop({bufnr}) *vim.treesitter.stop()*
  870. Stops treesitter highlighting for a buffer
  871. Parameters: ~
  872. • {bufnr} (`integer?`) Buffer to stop highlighting (default: current
  873. buffer)
  874. ==============================================================================
  875. Lua module: vim.treesitter.language *treesitter-language*
  876. add({lang}, {opts}) *vim.treesitter.language.add()*
  877. Load parser with name {lang}
  878. Parsers are searched in the `parser` runtime directory, or the provided
  879. {path}. Can be used to check for available parsers before enabling
  880. treesitter features, e.g., >lua
  881. if vim.treesitter.language.add('markdown') then
  882. vim.treesitter.start(bufnr, 'markdown')
  883. end
  884. <
  885. Parameters: ~
  886. • {lang} (`string`) Name of the parser (alphanumerical and `_` only)
  887. • {opts} (`table?`) Options:
  888. • {path}? (`string`) Optional path the parser is located at
  889. • {symbol_name}? (`string`) Internal symbol name for the
  890. language to load
  891. Return (multiple): ~
  892. (`boolean?`) True if parser is loaded
  893. (`string?`) Error if parser cannot be loaded
  894. get_filetypes({lang}) *vim.treesitter.language.get_filetypes()*
  895. Returns the filetypes for which a parser named {lang} is used.
  896. The list includes {lang} itself plus all filetypes registered via
  897. |vim.treesitter.language.register()|.
  898. Parameters: ~
  899. • {lang} (`string`) Name of parser
  900. Return: ~
  901. (`string[]`) filetypes
  902. get_lang({filetype}) *vim.treesitter.language.get_lang()*
  903. Returns the language name to be used when loading a parser for {filetype}.
  904. If no language has been explicitly registered via
  905. |vim.treesitter.language.register()|, default to {filetype}. For composite
  906. filetypes like `html.glimmer`, only the main filetype is returned.
  907. Parameters: ~
  908. • {filetype} (`string`)
  909. Return: ~
  910. (`string?`)
  911. inspect({lang}) *vim.treesitter.language.inspect()*
  912. Inspects the provided language.
  913. Inspecting provides some useful information on the language like node and
  914. field names, ABI version, and whether the language came from a WASM
  915. module.
  916. Node names are returned in a table mapping each node name to a `boolean`
  917. indicating whether or not the node is named (i.e., not anonymous).
  918. Anonymous nodes are surrounded with double quotes (`"`).
  919. Parameters: ~
  920. • {lang} (`string`) Language
  921. Return: ~
  922. (`TSLangInfo`)
  923. register({lang}, {filetype}) *vim.treesitter.language.register()*
  924. Register a parser named {lang} to be used for {filetype}(s).
  925. Note: this adds or overrides the mapping for {filetype}, any existing
  926. mappings from other filetypes to {lang} will be preserved.
  927. Parameters: ~
  928. • {lang} (`string`) Name of parser
  929. • {filetype} (`string|string[]`) Filetype(s) to associate with lang
  930. ==============================================================================
  931. Lua module: vim.treesitter.query *lua-treesitter-query*
  932. This Lua |treesitter-query| interface allows you to create queries and use
  933. them to parse text. See |vim.treesitter.query.parse()| for a working example.
  934. *vim.treesitter.query.add_directive()*
  935. add_directive({name}, {handler}, {opts})
  936. Adds a new directive to be used in queries
  937. Handlers can set match level data by setting directly on the metadata
  938. object `metadata.key = value`. Additionally, handlers can set node level
  939. data by using the capture id on the metadata table
  940. `metadata[capture_id].key = value`
  941. Parameters: ~
  942. • {name} (`string`) Name of the directive, without leading #
  943. • {handler} (`fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata)`)
  944. • match: A table mapping capture IDs to a list of captured
  945. nodes
  946. • pattern: the index of the matching pattern in the query
  947. file
  948. • predicate: list of strings containing the full directive
  949. being called, e.g. `(node (#set! conceal "-"))` would get
  950. the predicate `{ "#set!", "conceal", "-" }`
  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. *vim.treesitter.query.add_predicate()*
  959. add_predicate({name}, {handler}, {opts})
  960. Adds a new predicate to be used in queries
  961. Parameters: ~
  962. • {name} (`string`) Name of the predicate, without leading #
  963. • {handler} (`fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: vim.treesitter.query.TSMetadata): boolean?`)
  964. • see |vim.treesitter.query.add_directive()| for argument
  965. meanings
  966. • {opts} (`table?`) A table with the following fields:
  967. • {force}? (`boolean`) Override an existing predicate of
  968. the same name
  969. • {all}? (`boolean`) Use the correct implementation of the
  970. match table where capture IDs map to a list of nodes
  971. instead of a single node. Defaults to true. This option
  972. will be removed in a future release.
  973. edit({lang}) *vim.treesitter.query.edit()*
  974. Opens a live editor to query the buffer you started from.
  975. Can also be shown with *:EditQuery*.
  976. If you move the cursor to a capture name ("@foo"), text matching the
  977. capture is highlighted in the source buffer. The query editor is a scratch
  978. buffer, use `:write` to save it. You can find example queries at
  979. `$VIMRUNTIME/queries/`.
  980. Parameters: ~
  981. • {lang} (`string?`) language to open the query editor for. If omitted,
  982. inferred from the current buffer's filetype.
  983. get({lang}, {query_name}) *vim.treesitter.query.get()*
  984. Returns the runtime query {query_name} for {lang}.
  985. Parameters: ~
  986. • {lang} (`string`) Language to use for the query
  987. • {query_name} (`string`) Name of the query (e.g. "highlights")
  988. Return: ~
  989. (`vim.treesitter.Query?`) Parsed query. `nil` if no query files are
  990. found.
  991. *vim.treesitter.query.get_files()*
  992. get_files({lang}, {query_name}, {is_included})
  993. Gets the list of files used to make up a query
  994. Parameters: ~
  995. • {lang} (`string`) Language to get query for
  996. • {query_name} (`string`) Name of the query to load (e.g.,
  997. "highlights")
  998. • {is_included} (`boolean?`) Internal parameter, most of the time left
  999. as `nil`
  1000. Return: ~
  1001. (`string[]`) query_files List of files to load for given query and
  1002. language
  1003. lint({buf}, {opts}) *vim.treesitter.query.lint()*
  1004. Lint treesitter queries using installed parser, or clear lint errors.
  1005. Use |treesitter-parsers| in runtimepath to check the query file in {buf}
  1006. for errors:
  1007. • verify that used nodes are valid identifiers in the grammar.
  1008. • verify that predicates and directives are valid.
  1009. • verify that top-level s-expressions are valid.
  1010. The found diagnostics are reported using |diagnostic-api|. By default, the
  1011. parser used for verification is determined by the containing folder of the
  1012. query file, e.g., if the path ends in `/lua/highlights.scm`, the parser
  1013. for the `lua` language will be used.
  1014. Parameters: ~
  1015. • {buf} (`integer`) Buffer handle
  1016. • {opts} (`table?`) Optional keyword arguments:
  1017. • {langs}? (`string|string[]`) Language(s) to use for checking
  1018. the query. If multiple languages are specified, queries are
  1019. validated for all of them
  1020. • {clear} (`boolean`) Just clear current lint errors
  1021. list_directives() *vim.treesitter.query.list_directives()*
  1022. Lists the currently available directives to use in queries.
  1023. Return: ~
  1024. (`string[]`) Supported directives.
  1025. list_predicates() *vim.treesitter.query.list_predicates()*
  1026. Lists the currently available predicates to use in queries.
  1027. Return: ~
  1028. (`string[]`) Supported predicates.
  1029. omnifunc({findstart}, {base}) *vim.treesitter.query.omnifunc()*
  1030. Omnifunc for completing node names and predicates in treesitter queries.
  1031. Use via >lua
  1032. vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc'
  1033. <
  1034. Parameters: ~
  1035. • {findstart} (`0|1`)
  1036. • {base} (`string`)
  1037. parse({lang}, {query}) *vim.treesitter.query.parse()*
  1038. Parses a {query} string and returns a `Query` object
  1039. (|lua-treesitter-query|), which can be used to search the tree for the
  1040. query patterns (via |Query:iter_captures()|, |Query:iter_matches()|), or
  1041. inspect the query via these fields:
  1042. • `captures`: a list of unique capture names defined in the query (alias:
  1043. `info.captures`).
  1044. • `info.patterns`: information about predicates.
  1045. Example: >lua
  1046. local query = vim.treesitter.query.parse('vimdoc', [[
  1047. ; query
  1048. ((h1) @str
  1049. (#trim! @str 1 1 1 1))
  1050. ]])
  1051. local tree = vim.treesitter.get_parser():parse()[1]
  1052. for id, node, metadata in query:iter_captures(tree:root(), 0) do
  1053. -- Print the node name and source text.
  1054. vim.print({node:type(), vim.treesitter.get_node_text(node, vim.api.nvim_get_current_buf())})
  1055. end
  1056. <
  1057. Parameters: ~
  1058. • {lang} (`string`) Language to use for the query
  1059. • {query} (`string`) Query text, in s-expr syntax
  1060. Return: ~
  1061. (`vim.treesitter.Query`) Parsed query
  1062. See also: ~
  1063. • |vim.treesitter.query.get()|
  1064. *Query:iter_captures()*
  1065. Query:iter_captures({node}, {source}, {start}, {stop})
  1066. Iterates over all captures from all matches in {node}.
  1067. {source} is required if the query contains predicates; then the caller
  1068. must ensure to use a freshly parsed tree consistent with the current text
  1069. of the buffer (if relevant). {start} and {stop} can be used to limit
  1070. matches inside a row range (this is typically used with root node as the
  1071. {node}, i.e., to get syntax highlight matches in the current viewport).
  1072. When omitted, the {start} and {stop} row values are used from the given
  1073. node.
  1074. The iterator returns four values:
  1075. 1. the numeric id identifying the capture
  1076. 2. the captured node
  1077. 3. metadata from any directives processing the match
  1078. 4. the match itself
  1079. Example: how to get captures by name: >lua
  1080. for id, node, metadata, match in query:iter_captures(tree:root(), bufnr, first, last) do
  1081. local name = query.captures[id] -- name of the capture in the query
  1082. -- typically useful info about the node:
  1083. local type = node:type() -- type of the captured node
  1084. local row1, col1, row2, col2 = node:range() -- range of the capture
  1085. -- ... use the info here ...
  1086. end
  1087. <
  1088. Note: ~
  1089. • Captures are only returned if the query pattern of a specific capture
  1090. contained predicates.
  1091. Parameters: ~
  1092. • {node} (`TSNode`) under which the search will occur
  1093. • {source} (`integer|string`) Source buffer or string to extract text
  1094. from
  1095. • {start} (`integer?`) Starting line for the search. Defaults to
  1096. `node:start()`.
  1097. • {stop} (`integer?`) Stopping line for the search (end-exclusive).
  1098. Defaults to `node:end_()`.
  1099. Return: ~
  1100. (`fun(end_line: integer?): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch, TSTree`)
  1101. capture id, capture node, metadata, match, tree
  1102. *Query:iter_matches()*
  1103. Query:iter_matches({node}, {source}, {start}, {stop}, {opts})
  1104. Iterates the matches of self on a given range.
  1105. Iterate over all matches within a {node}. The arguments are the same as
  1106. for |Query:iter_captures()| but the iterated values are different: an
  1107. (1-based) index of the pattern in the query, a table mapping capture
  1108. indices to a list of nodes, and metadata from any directives processing
  1109. the match.
  1110. Example: >lua
  1111. for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, 0, -1) do
  1112. for id, nodes in pairs(match) do
  1113. local name = query.captures[id]
  1114. for _, node in ipairs(nodes) do
  1115. -- `node` was captured by the `name` capture in the match
  1116. local node_data = metadata[id] -- Node level metadata
  1117. -- ... use the info here ...
  1118. end
  1119. end
  1120. end
  1121. <
  1122. Parameters: ~
  1123. • {node} (`TSNode`) under which the search will occur
  1124. • {source} (`integer|string`) Source buffer or string to search
  1125. • {start} (`integer?`) Starting line for the search. Defaults to
  1126. `node:start()`.
  1127. • {stop} (`integer?`) Stopping line for the search (end-exclusive).
  1128. Defaults to `node:end_()`.
  1129. • {opts} (`table?`) Optional keyword arguments:
  1130. • max_start_depth (integer) if non-zero, sets the maximum
  1131. start depth for each match. This is used to prevent
  1132. traversing too deep into a tree.
  1133. • match_limit (integer) Set the maximum number of
  1134. in-progress matches (Default: 256). all (boolean) When
  1135. `false` (default `true`), the returned table maps capture
  1136. IDs to a single (last) node instead of the full list of
  1137. matching nodes. This option is only for backward
  1138. compatibility and will be removed in a future release.
  1139. Return: ~
  1140. (`fun(): integer, table<integer, TSNode[]>, vim.treesitter.query.TSMetadata, TSTree`)
  1141. pattern id, match, metadata, tree
  1142. set({lang}, {query_name}, {text}) *vim.treesitter.query.set()*
  1143. Sets the runtime query named {query_name} for {lang}
  1144. This allows users to override or extend any runtime files and/or
  1145. configuration set by plugins.
  1146. For example, you could enable spellchecking of `C` identifiers with the
  1147. following code: >lua
  1148. vim.treesitter.query.set(
  1149. 'c',
  1150. 'highlights',
  1151. [[;inherits c
  1152. (identifier) @spell]])
  1153. ]])
  1154. <
  1155. Parameters: ~
  1156. • {lang} (`string`) Language to use for the query
  1157. • {query_name} (`string`) Name of the query (e.g., "highlights")
  1158. • {text} (`string`) Query text (unparsed).
  1159. ==============================================================================
  1160. Lua module: vim.treesitter.languagetree *treesitter-languagetree*
  1161. A *LanguageTree* contains a tree of parsers: the root treesitter parser for
  1162. {lang} and any "injected" language parsers, which themselves may inject other
  1163. languages, recursively. For example a Lua buffer containing some Vimscript
  1164. commands needs multiple parsers to fully understand its contents.
  1165. To create a LanguageTree (parser object) for a given buffer and language, use: >lua
  1166. local parser = vim.treesitter.get_parser(bufnr, lang)
  1167. <
  1168. (where `bufnr=0` means current buffer). `lang` defaults to 'filetype'. Note:
  1169. currently the parser is retained for the lifetime of a buffer but this may
  1170. change; a plugin should keep a reference to the parser object if it wants
  1171. incremental updates.
  1172. Whenever you need to access the current syntax tree, parse the buffer: >lua
  1173. local tree = parser:parse({ start_row, end_row })
  1174. <
  1175. This returns a table of immutable |treesitter-tree| objects representing the
  1176. current state of the buffer. When the plugin wants to access the state after a
  1177. (possible) edit it must call `parse()` again. If the buffer wasn't edited, the
  1178. same tree will be returned again without extra work. If the buffer was parsed
  1179. before, incremental parsing will be done of the changed parts.
  1180. Note: To use the parser directly inside a |nvim_buf_attach()| Lua callback,
  1181. you must call |vim.treesitter.get_parser()| before you register your callback.
  1182. But preferably parsing shouldn't be done directly in the change callback
  1183. anyway as they will be very frequent. Rather a plugin that does any kind of
  1184. analysis on a tree should use a timer to throttle too frequent updates.
  1185. LanguageTree:children() *LanguageTree:children()*
  1186. Returns a map of language to child tree.
  1187. Return: ~
  1188. (`table<string,vim.treesitter.LanguageTree>`)
  1189. LanguageTree:contains({range}) *LanguageTree:contains()*
  1190. Determines whether {range} is contained in the |LanguageTree|.
  1191. Parameters: ~
  1192. • {range} (`table`) A table with the following fields:
  1193. • {[1]} (`integer`) start row
  1194. • {[2]} (`integer`) start column
  1195. • {[3]} (`integer`) end row
  1196. • {[4]} (`integer`) end column
  1197. Return: ~
  1198. (`boolean`)
  1199. LanguageTree:destroy() *LanguageTree:destroy()*
  1200. Destroys this |LanguageTree| and all its children.
  1201. Any cleanup logic should be performed here.
  1202. Note: This DOES NOT remove this tree from a parent. Instead,
  1203. `remove_child` must be called on the parent to remove it.
  1204. LanguageTree:for_each_tree({fn}) *LanguageTree:for_each_tree()*
  1205. Invokes the callback for each |LanguageTree| recursively.
  1206. Note: This includes the invoking tree's child trees as well.
  1207. Parameters: ~
  1208. • {fn} (`fun(tree: TSTree, ltree: vim.treesitter.LanguageTree)`)
  1209. LanguageTree:included_regions() *LanguageTree:included_regions()*
  1210. Gets the set of included regions managed by this LanguageTree. This can be
  1211. different from the regions set by injection query, because a partial
  1212. |LanguageTree:parse()| drops the regions outside the requested range. Each
  1213. list represents a range in the form of { {start_row}, {start_col},
  1214. {start_bytes}, {end_row}, {end_col}, {end_bytes} }.
  1215. Return: ~
  1216. (`table<integer, Range6[]>`)
  1217. LanguageTree:invalidate({reload}) *LanguageTree:invalidate()*
  1218. Invalidates this parser and its children.
  1219. Should only be called when the tracked state of the LanguageTree is not
  1220. valid against the parse tree in treesitter. Doesn't clear filesystem
  1221. cache. Called often, so needs to be fast.
  1222. Parameters: ~
  1223. • {reload} (`boolean?`)
  1224. LanguageTree:is_valid({exclude_children}) *LanguageTree:is_valid()*
  1225. Returns whether this LanguageTree is valid, i.e., |LanguageTree:trees()|
  1226. reflects the latest state of the source. If invalid, user should call
  1227. |LanguageTree:parse()|.
  1228. Parameters: ~
  1229. • {exclude_children} (`boolean?`) whether to ignore the validity of
  1230. children (default `false`)
  1231. Return: ~
  1232. (`boolean`)
  1233. LanguageTree:lang() *LanguageTree:lang()*
  1234. Gets the language of this tree node.
  1235. Return: ~
  1236. (`string`)
  1237. *LanguageTree:language_for_range()*
  1238. LanguageTree:language_for_range({range})
  1239. Gets the appropriate language that contains {range}.
  1240. Parameters: ~
  1241. • {range} (`table`) A table with the following fields:
  1242. • {[1]} (`integer`) start row
  1243. • {[2]} (`integer`) start column
  1244. • {[3]} (`integer`) end row
  1245. • {[4]} (`integer`) end column
  1246. Return: ~
  1247. (`vim.treesitter.LanguageTree`) tree Managing {range}
  1248. *LanguageTree:named_node_for_range()*
  1249. LanguageTree:named_node_for_range({range}, {opts})
  1250. Gets the smallest named node that contains {range}.
  1251. Parameters: ~
  1252. • {range} (`table`) A table with the following fields:
  1253. • {[1]} (`integer`) start row
  1254. • {[2]} (`integer`) start column
  1255. • {[3]} (`integer`) end row
  1256. • {[4]} (`integer`) end column
  1257. • {opts} (`table?`) A table with the following fields:
  1258. • {ignore_injections}? (`boolean`, default: `true`) Ignore
  1259. injected languages
  1260. Return: ~
  1261. (`TSNode?`)
  1262. *LanguageTree:node_for_range()*
  1263. LanguageTree:node_for_range({range}, {opts})
  1264. Gets the smallest node that contains {range}.
  1265. Parameters: ~
  1266. • {range} (`table`) A table with the following fields:
  1267. • {[1]} (`integer`) start row
  1268. • {[2]} (`integer`) start column
  1269. • {[3]} (`integer`) end row
  1270. • {[4]} (`integer`) end column
  1271. • {opts} (`table?`) A table with the following fields:
  1272. • {ignore_injections}? (`boolean`, default: `true`) Ignore
  1273. injected languages
  1274. Return: ~
  1275. (`TSNode?`)
  1276. LanguageTree:parent() *LanguageTree:parent()*
  1277. Returns the parent tree. `nil` for the root tree.
  1278. Return: ~
  1279. (`vim.treesitter.LanguageTree?`)
  1280. LanguageTree:parse({range}, {on_parse}) *LanguageTree:parse()*
  1281. Recursively parse all regions in the language tree using
  1282. |treesitter-parsers| for the corresponding languages and run injection
  1283. queries on the parsed trees to determine whether child trees should be
  1284. created and parsed.
  1285. Any region with empty range (`{}`, typically only the root tree) is always
  1286. parsed; otherwise (typically injections) only if it intersects {range} (or
  1287. if {range} is `true`).
  1288. Parameters: ~
  1289. • {range} (`boolean|Range?`) Parse this range in the parser's
  1290. source. Set to `true` to run a complete parse of the
  1291. source (Note: Can be slow!) Set to `false|nil` to only
  1292. parse regions with empty ranges (typically only the root
  1293. tree without injections).
  1294. • {on_parse} (`fun(err?: string, trees?: table<integer, TSTree>)?`)
  1295. Function invoked when parsing completes. When provided and
  1296. `vim.g._ts_force_sync_parsing` is not set, parsing will
  1297. run asynchronously. The first argument to the function is
  1298. a string representing the error type, in case of a failure
  1299. (currently only possible for timeouts). The second
  1300. argument is the list of trees returned by the parse (upon
  1301. success), or `nil` if the parse timed out (determined by
  1302. 'redrawtime').
  1303. If parsing was still able to finish synchronously (within
  1304. 3ms), `parse()` returns the list of trees. Otherwise, it
  1305. returns `nil`.
  1306. Return: ~
  1307. (`table<integer, TSTree>?`)
  1308. *LanguageTree:register_cbs()*
  1309. LanguageTree:register_cbs({cbs}, {recursive})
  1310. Registers callbacks for the |LanguageTree|.
  1311. Parameters: ~
  1312. • {cbs} (`table<TSCallbackNameOn,function>`) An
  1313. |nvim_buf_attach()|-like table argument with the
  1314. following handlers:
  1315. • `on_bytes` : see |nvim_buf_attach()|.
  1316. • `on_changedtree` : a callback that will be called every
  1317. time the tree has syntactical changes. It will be
  1318. passed two arguments: a table of the ranges (as node
  1319. ranges) that changed and the changed tree.
  1320. • `on_child_added` : emitted when a child is added to the
  1321. tree.
  1322. • `on_child_removed` : emitted when a child is removed
  1323. from the tree.
  1324. • `on_detach` : emitted when the buffer is detached, see
  1325. |nvim_buf_detach_event|. Takes one argument, the number
  1326. of the buffer.
  1327. • {recursive} (`boolean?`) Apply callbacks recursively for all
  1328. children. Any new children will also inherit the
  1329. callbacks.
  1330. LanguageTree:source() *LanguageTree:source()*
  1331. Returns the source content of the language tree (bufnr or string).
  1332. Return: ~
  1333. (`integer|string`)
  1334. *LanguageTree:tree_for_range()*
  1335. LanguageTree:tree_for_range({range}, {opts})
  1336. Gets the tree that contains {range}.
  1337. Parameters: ~
  1338. • {range} (`table`) A table with the following fields:
  1339. • {[1]} (`integer`) start row
  1340. • {[2]} (`integer`) start column
  1341. • {[3]} (`integer`) end row
  1342. • {[4]} (`integer`) end column
  1343. • {opts} (`table?`) A table with the following fields:
  1344. • {ignore_injections}? (`boolean`, default: `true`) Ignore
  1345. injected languages
  1346. Return: ~
  1347. (`TSTree?`)
  1348. LanguageTree:trees() *LanguageTree:trees()*
  1349. Returns all trees of the regions parsed by this parser. Does not include
  1350. child languages. The result is list-like if
  1351. • this LanguageTree is the root, in which case the result is empty or a
  1352. singleton list; or
  1353. • the root LanguageTree is fully parsed.
  1354. Return: ~
  1355. (`table<integer, TSTree>`)
  1356. vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl: