treesitter.txt 66 KB

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