Debian Codegraph @

book/src/guides/indent.md

raw symbols SCIP
1 ## Adding indent queries
2
3 Helix uses tree-sitter to correctly indent new lines. This requires a
4 tree-sitter grammar and an `indent.scm` query file placed in
5 `runtime/queries/{language}/indents.scm`.
6
7 The indent level of a line is **the number of `@indent` scopes that contain
8 it**. An `@indent` capture on a node opens a scope spanning the lines *after*
9 the node's first line through its last line; a line is indented once for every
10 such scope wrapping it. (A few capture types adjust this — `@outdent` cancels a
11 level, `@align` aligns to a column, etc. (see [Capture types](#capture-types).)
12
13 Note that it matters where these scopes *begin*: multiple scopes that open on
14 the same physical line only increase the indent by 1 (the same-line rule). See
15 [Capture types](#capture-types).
16
17 By default, Helix uses the `hybrid` indentation heuristic. This means that
18 indent queries are not used to compute the expected absolute indentation of a
19 line but rather the expected difference in indentation between the new and an
20 already existing line. This difference is then added to the actual indentation
21 of the already existing line. Since this makes errors in the indent queries
22 harder to find, it is recommended to disable it when testing via
23 `:set indent-heuristic tree-sitter`. The rest of this guide assumes that
24 the `tree-sitter` heuristic is used.
25
26 ## Indent queries
27
28 When Helix is inserting a new line through `o`, `O`, or `<ret>`, to determine
29 the indent level for the new line, the query in `indents.scm` is run on the
30 document. The starting position of the query is the end of the line above where
31 a new line will be inserted.
32
33 For `o`, the inserted line is the line below the cursor, so that starting
34 position of the query is the end of the current line.
35
36 ```rust
37 fn need_hero(some_hero: Hero, life: Life) -> {
38 matches!(some_hero, Hero { // ←─────────────────╮
39 strong: true,//←╮ ↑ ↑ │
40 fast: true, // │ │ ╰── query start │
41 sure: true, // │ ╰───── cursor ├─ traversal
42 soon: true, // ╰──────── new line inserted │ start node
43 }) && // │
44 // ↑ │
45 // ╰───────────────────────────────────────────────╯
46 some_hero > life
47 }
48 ```
49
50 For `O`, the newly inserted line is the *current* line, so the starting position
51 of the query is the end of the line above the cursor.
52
53 ```rust
54 fn need_hero(some_hero: Hero, life: Life) -> { // ←─╮
55 matches!(some_hero, Hero { // ←╮ ↑ │
56 strong: true,// ↑ ╭───╯ │ │
57 fast: true, // │ │ query start ─╯ │
58 sure: true, // ╰───┼ cursor ├─ traversal
59 soon: true, // ╰ new line inserted │ start node
60 }) && // │
61 some_hero > life // │
62 } // ←──────────────────────────────────────────────╯
63 ```
64
65 From this starting node, the syntax tree is walked up to the root, collecting
66 every `@indent`/`@outdent`/`@align`/... capture on an ancestor. Each `@indent`
67 ancestor whose scope *contains* the line counts for one indent level (scopes
68 opening on the same line collapse to one); the [capture types](#capture-types)
69 describe the adjustments.
70
71 ### Capture types
72
73 - `@indent`:
74 Open an indent scope on this node — every line it contains is indented one
75 more level. Scopes that open on the same line collapse: multiple `@indent`
76 beginning on one line only add 1. A node captured by *both* `@indent` and
77 `@outdent` contributes nothing (its level is cancelled) — used e.g. for a
78 nested `else if` that should not stack a second level.
79 By default the scope opens at the node's own first line; see the
80 [`header`](#scope-header) scope to open it at the parent (header) line instead.
81 - `@outdent`:
82 Decrease by 1 the indent of the line on which this (usually a closing token
83 like `}`/`)`/`]`, or a keyword like `else`) begins.
84 - `@indent.always`:
85 Like `@indent` but does *not* collapse — multiple on the same line each add a
86 level. The net level contribution is `@indent.always` − `@outdent.always`.
87 - `@outdent.always`:
88 Like `@outdent` but stacks, the counterpart to `@indent.always`.
89 - `@align` (default scope `all`):
90 Align everything inside this node to some anchor. The anchor is given
91 by the start of the node captured by `@anchor` in the same pattern.
92 Every pattern with an `@align` should contain exactly one `@anchor`.
93 Indent (and outdent) for nodes below (in terms of their starting line)
94 the `@align` node is added to the indentation required for alignment.
95 - `@extend`:
96 Extend the range of this node to the end of the line and to lines that are
97 indented more than the line that this node starts on. This is useful for
98 languages like Python, where for the purpose of indentation some nodes (like
99 functions or classes) should also contain indented lines that follow them.
100 - `@extend.prevent-once`:
101 Prevents the first extension of an ancestor of this node. For example, in Python
102 a return expression always ends the block that it is in. Note that this only
103 stops the extension of the next `@extend` capture. If multiple ancestors are
104 captured, only the extension of the innermost one is prevented. All other
105 ancestors are unaffected (regardless of whether the innermost ancestor would
106 actually have been extended).
107 - `@opaque`:
108 Mark a literal body such as a string, heredoc, or block comment. Lines that
109 begin inside the captured node keep their existing indentation instead of being
110 reindented, so the contents of multi-line literals are left untouched.
111
112 #### `@indent` / `@outdent`
113
114 Consider this example:
115
116 ```rust
117 fn shout(things: Vec<Thing>) {
118 // ↑
119 // ├───────────────────────╮ indent level
120 // @indent ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄
121 // │
122 let it_all = |out| { things.filter(|thing| { // │ 1
123 // ↑ ↑ │
124 // ├───────────────────────┼─────┼┄┄┄┄┄┄┄┄┄┄┄┄┄┄
125 // @indent @indent │
126 // │ 2
127 thing.can_do_with(out) // │
128 })}; // ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄
129 //↑↑↑ │ 1
130 } //╰┼┴──────────────────────────────────────────────┴┄┄┄┄┄┄┄┄┄┄┄┄┄┄
131 // 3x @outdent
132 ```
133
134 ```scm
135 ((block) @indent)
136 ["}" ")"] @outdent
137 ```
138
139 Note how on the second line two blocks open on the same line: since both scopes
140 *begin* on that line they collapse, for a net increase of 1. On the last line,
141 the three block scopes all contain it, but it begins with three `@outdent` `}`
142 tokens that cancel them, so the line lands back at the enclosing level.
143
144 #### Same-line collapse
145
146 The collapse above is a deliberate, load-bearing invariant:
147
148 > A line is indented by **one level per physical line on which a containing
149 > `@indent` scope opens**, not one level per scope. Several `@indent` scopes
150 > that *open* on the same line together add a single level.
151
152 This is what makes **method/builder chains flatten instead of staircasing**.
153 Grammars typically nest a chain so each `.method()` link is a `call` inside a
154 `member_expression` inside the previous link, and several of those nodes *begin*
155 on the receiver's line:
156
157 ```rust
158 let x = thing // ← chain opens here
159 .foo() // each link aligned one level in,
160 .bar() // not progressively deeper
161 .baz();
162 ```
163
164 ```scm
165 (call_expression) @indent
166 ```
167
168 Even though many `call_expression`/`member_expression` scopes contain the
169 `.bar()` line, they all *open* on the `thing` line, so they collapse to a single
170 level and the continuation lines line up. Without the collapse, every link would
171 add a level and the chain would stair-step to the right.
172
173 If you instead want each scope to count even when several open on one line (for
174 example YAML's "list item *and* map both start on the same line") opt out with
175 `@indent.always` (described below), which does not collapse.
176
177 #### `@extend` / `@extend.prevent-once`
178
179 For an example of where `@extend` can be useful, consider Python, which is
180 whitespace-sensitive.
181
182 ```scm
183 ]
184 (parenthesized_expression)
185 (function_definition)
186 (class_definition)
187 ] @indent
188
189 ```
190
191 ```python
192 class Hero:
193 def __init__(self, strong, fast, sure, soon):# ←─╮
194 self.is_strong = strong # │
195 self.is_fast = fast # ╭─── query start │
196 self.is_sure = sure # │ ╭─ cursor │
197 self.is_soon = soon # │ │ │
198 # ↑ ↑ │ │ │
199 # │ ╰──────╯ │ │
200 # ╰─────────────────────╯ │
201 # ├─ traversal
202 def need_hero(self, life): # │ start node
203 return ( # │
204 self.is_strong # │
205 and self.is_fast # │
206 and self.is_sure # │
207 and self.is_soon # │
208 and self > life # │
209 ) # ←─────────────────────────────────────────╯
210 ```
211
212 Without braces to catch the scope of the function, the smallest descendant of
213 the cursor on a line feed ends up being the entire inside of the class. Because
214 of this, it will miss the entire function node and its indent capture, leading
215 to an indent level one too small.
216
217 To address this case, `@extend` tells helix to "extend" the captured node's span
218 to the line feed and every consecutive line that has a greater indent level than
219 the line of the node.
220
221 ```scm
222 (parenthesized_expression) @indent
223
224 ]
225 (function_definition)
226 (class_definition)
227 ] @indent @extend
228
229 ```
230
231 ```python
232 class Hero:
233 def __init__(self, strong, fast, sure, soon):# ←─╮
234 self.is_strong = strong # │
235 self.is_fast = fast # ╭─── query start ├─ traversal
236 self.is_sure = sure # │ ╭─ cursor │ start node
237 self.is_soon = soon # │ │ ←───────────────╯
238 # ↑ ↑ │ │
239 # │ ╰──────╯ │
240 # ╰─────────────────────╯
241 def need_hero(self, life):
242 return (
243 self.is_strong
244 and self.is_fast
245 and self.is_sure
246 and self.is_soon
247 and self > life
248 )
249 ```
250
251 Furthermore, there are some cases where extending to everything with a greater
252 indent level may not be desirable. Consider the `need_hero` function above. If
253 our cursor is on the last line of the returned expression.
254
255 ```python
256 class Hero:
257 def __init__(self, strong, fast, sure, soon):
258 self.is_strong = strong
259 self.is_fast = fast
260 self.is_sure = sure
261 self.is_soon = soon
262
263 def need_hero(self, life):
264 return (
265 self.is_strong
266 and self.is_fast
267 and self.is_sure
268 and self.is_soon
269 and self > life
270 ) # ←─── cursor
271 #←────────── where cursor should go on new line
272 ```
273
274 In Python, the are a few tokens that will always end a scope, such as a return
275 statement. Since the scope ends, so should the indent level. But because the
276 function span is extended to every line with a greater indent level, a new line
277 would just continue on the same level. And an `@outdent` would not help us here
278 either, since it would cause everything in the parentheses to become outdented
279 as well.
280
281 To help, we need to signal an end to the extension. We can do this with
282 `@extend.prevent-once`.
283
284 ```scm
285 (parenthesized_expression) @indent
286
287 ]
288 (function_definition)
289 (class_definition)
290 ] @indent @extend
291
292 (return_statement) @extend.prevent-once
293 ```
294
295 #### Brace-less bodies
296
297 A brace-less single-statement body — `if (cond)` with its statement on the next
298 line and no `{}` — is a body the indent must wrap, but the body node's *own*
299 first line is the line that needs the indent (there is no separate opening line).
300 Capture the body and give it the [`header`](#scope-header) scope, which opens the
301 scope at the **header** (the captured node's parent) line instead of the body's
302 own line, so the body line is contained:
303
304 ```scm
305 (if_statement
306 consequence: (_) @indent
307 (#not-kind-eq? @indent "compound_statement")
308 (#set! "scope" "header"))
309 (while_statement
310 body: (_) @indent
311 (#not-kind-eq? @indent "compound_statement")
312 (#set! "scope" "header"))
313 ```
314
315 The query already names exactly the brace-less body (the `consequence:` /
316 `body:` field, with `#not-kind-eq?` skipping the braced form the surrounding
317 block indents), so the engine just opens that capture's scope at its parent — it
318 does not itself inspect node kinds or field names. This works for a multi-line
319 brace-less body too (e.g. one returning a lambda). Give `else` and `do / while`
320 their own pattern (on the `alternative` / `body` field) so the trailing `else` /
321 `while` keyword line is not indented along with the body.
322
323 #### `@indent.always` / `@outdent.always`
324
325 As mentioned before, normally if there is more than one `@indent` or `@outdent`
326 capture on the same line, they are combined.
327
328 Sometimes, there are cases when you may want to ensure that every indent capture
329 is additive, regardless of how many occur on the same line. Consider this
330 example in YAML.
331
332 ```yaml
333 - foo: bar
334 # ↑ ↑
335 # │ ╰─────────────── start of map
336 # ╰───────────────── start of list element
337 baz: quux # ←─── cursor
338 # ←───────────── where the cursor should go on a new line
339 garply: waldo
340 - quux:
341 bar: baz
342 xyzzy: thud
343 fred: plugh
344 ```
345
346 In YAML, you often have lists of maps. In these cases, the syntax is such that
347 the list element and the map both start on the same line. But we really do want
348 to start an indentation for each of these so that subsequent keys in the map
349 hang over the list and align properly. This is where `@indent.always` helps.
350
351 ```scm
352 ((block_sequence_item) @item @indent.always @extend
353 (#not-one-line? @item))
354
355 ((block_mapping_pair
356 key: (_) @key
357 value: (_) @val
358 (#not-same-line? @key @val)
359 ) @indent.always @extend
360 )
361 ```
362
363 ## Predicates
364
365 In some cases, an S-expression cannot express exactly what pattern should be matched.
366 For that, tree-sitter allows for predicates to appear anywhere within a pattern,
367 similar to how `#set!` declarations work:
368
369 ```scm
370 (some_kind
371 (child_kind) @indent
372 (#predicate? arg1 arg2 ...)
373 )
374 ```
375
376 The number of arguments depends on the predicate that's used.
377 Each argument is either a capture (`@name`) or a string (`"some string"`).
378 The following predicates are supported by tree-sitter:
379
380 - `#eq?`/`#not-eq?`:
381 The first argument (a capture) must/must not be equal to the second argument
382 (a capture or a string).
383
384 - `#match?`/`#not-match?`:
385 The first argument (a capture) must/must not match the regex given in the
386 second argument (a string).
387
388 - `#any-of?`/`#not-any-of?`:
389 The first argument (a capture) must/must not be one of the other arguments
390 (strings).
391
392 Additionally, we support some custom predicates for indent queries:
393
394 - `#not-kind-eq?`:
395 The kind of the first argument (a capture) must not be equal to the second
396 argument (a string).
397
398 - `#same-line?`/`#not-same-line?`:
399 The captures given by the 2 arguments must/must not start on the same line.
400
401 - `#one-line?`/`#not-one-line?`:
402 The captures given by the fist argument must/must span a total of one line.
403
404 ### <a name="scope-header"></a>The `header` scope
405
406 By default an `@indent` scope opens at the captured node's own first line, so the
407 lines *inside* it are indented and its first line is not. Sometimes the node you
408 must capture *is* the line that needs indenting — a brace-less body such as the
409 statement after `if (cond)` (see [Brace-less bodies](#brace-less-bodies)). For
410 this, set `scope` to `header`:
411
412 ```scm
413 (if_statement
414 consequence: (_) @indent
415 (#not-kind-eq? @indent "compound_statement")
416 (#set! "scope" "header"))
417 ```
418
419 `header` opens the scope at the captured node's **parent** (the `if_statement`
420 header) line instead of the node's own line, so the body's first line is
421 contained and indented. The query selects exactly the body, so the engine just
422 honours the annotation — it does not match on node kinds or field names itself.
423
424 (Older queries used `tail` / `all` scopes to control whether a node's first line
425 was included; under the containment model those are no longer needed and have
426 been removed. `header` is the one scope the engine reads.)
427
428 ## Testing
429
430 `cargo xtask indent-check [language]` checks the queries against the fixtures in
431 `tests/indent/<language-id>.<ext>` in both modes: re-indenting each line
432 and simulating a newline typed after it, so a rule that is correct one way but
433 wrong the other is caught.