Debian Codegraph @

helix-core/src/indent.rs

raw symbols SCIP
1 use std::{
2 borrow::Cow,
3 collections::{HashMap, HashSet},
4 };
5
6 use helix_stdx::rope::RopeSliceExt;
7 use tree_house::TREE_SITTER_MATCH_LIMIT;
8
9 use crate::{
10 chars::{char_is_line_ending, char_is_whitespace},
11 graphemes::{grapheme_width, tab_width_at},
12 syntax::{self, config::IndentationHeuristic},
13 tree_sitter::{
14 self,
15 query::{InvalidPredicateError, UserPredicate},
16 Capture, Grammar, InactiveQueryCursor, Node, Pattern, Query, QueryMatch, RopeInput,
17 },
18 Position, Rope, RopeSlice, Syntax, Tendril,
19 };
20
21 /// Enum representing indentation style.
22 ///
23 /// Only values 1-8 are valid for the `Spaces` variant.
24 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
25 pub enum IndentStyle {
26 Tabs,
27 Spaces(u8),
28 }
29
30 // 16 spaces
31 const INDENTS: &str = " ";
32 pub const MAX_INDENT: u8 = 16;
33
34 impl IndentStyle {
35 /// Creates an `IndentStyle` from an indentation string.
36 ///
37 /// For example, passing `" "` (four spaces) will create `IndentStyle::Spaces(4)`.
38 #[allow(clippy::should_implement_trait)]
39 #[inline]
40 pub fn from_str(indent: &str) -> Self {
41 // XXX: do we care about validating the input more than this? Probably not...?
42 debug_assert!(!indent.is_empty() && indent.len() <= MAX_INDENT as usize);
43
44 if indent.starts_with(' ') {
45 IndentStyle::Spaces(indent.len().clamp(1, MAX_INDENT as usize) as u8)
46 } else {
47 IndentStyle::Tabs
48 }
49 }
50
51 #[inline]
52 pub fn as_str(&self) -> &'static str {
53 match *self {
54 IndentStyle::Tabs => "\t",
55 IndentStyle::Spaces(n) => {
56 // Unsupported indentation style. This should never happen,
57 debug_assert!(n > 0 && n <= MAX_INDENT);
58
59 // Either way, clamp to the nearest supported value
60 let closest_n = n.clamp(1, MAX_INDENT) as usize;
61 &INDENTS[0..closest_n]
62 }
63 }
64 }
65
66 #[inline]
67 pub fn indent_width(&self, tab_width: usize) -> usize {
68 match *self {
69 IndentStyle::Tabs => tab_width,
70 IndentStyle::Spaces(width) => width as usize,
71 }
72 }
73 }
74
75 /// Attempts to detect the indentation style used in a document.
76 ///
77 /// Returns the indentation style if the auto-detect confidence is
78 /// reasonably high, otherwise returns `None`.
79 pub fn auto_detect_indent_style(document_text: &Rope) -> Option<IndentStyle> {
80 // Build a histogram of the indentation *increases* between
81 // subsequent lines, ignoring lines that are all whitespace.
82 //
83 // Index 0 is for tabs, the rest are 1-MAX_INDENT spaces.
84 let histogram: [usize; MAX_INDENT as usize + 1] = {
85 let mut histogram = [0; MAX_INDENT as usize + 1];
86 let mut prev_line_is_tabs = false;
87 let mut prev_line_leading_count = 0usize;
88
89 // Loop through the lines, checking for and recording indentation
90 // increases as we go.
91 'outer: for line in document_text.lines().take(1000) {
92 let mut c_iter = line.chars();
93
94 // Is first character a tab or space?
95 let is_tabs = match c_iter.next() {
96 Some('\t') => true,
97 Some(' ') => false,
98
99 // Ignore blank lines.
100 Some(c) if char_is_line_ending(c) => continue,
101
102 _ => {
103 prev_line_is_tabs = false;
104 prev_line_leading_count = 0;
105 continue;
106 }
107 };
108
109 // Count the line's total leading tab/space characters.
110 let mut leading_count = 1;
111 let mut count_is_done = false;
112 for c in c_iter {
113 match c {
114 '\t' if is_tabs && !count_is_done => leading_count += 1,
115 ' ' if !is_tabs && !count_is_done => leading_count += 1,
116
117 // We stop counting if we hit whitespace that doesn't
118 // qualify as indent or doesn't match the leading
119 // whitespace, but we don't exit the loop yet because
120 // we still want to determine if the line is blank.
121 c if char_is_whitespace(c) => count_is_done = true,
122
123 // Ignore blank lines.
124 c if char_is_line_ending(c) => continue 'outer,
125
126 _ => break,
127 }
128
129 // Bound the worst-case execution time for weird text files.
130 if leading_count > 256 {
131 continue 'outer;
132 }
133 }
134
135 // If there was an increase in indentation over the previous
136 // line, update the histogram with that increase.
137 if (prev_line_is_tabs == is_tabs || prev_line_leading_count == 0)
138 && prev_line_leading_count < leading_count
139 {
140 if is_tabs {
141 histogram[0] += 1;
142 } else {
143 let amount = leading_count - prev_line_leading_count;
144 if amount <= MAX_INDENT as usize {
145 histogram[amount] += 1;
146 }
147 }
148 }
149
150 // Store this line's leading whitespace info for use with
151 // the next line.
152 prev_line_is_tabs = is_tabs;
153 prev_line_leading_count = leading_count;
154 }
155
156 // Give more weight to tabs, because their presence is a very
157 // strong indicator.
158 histogram[0] *= 2;
159 // Gives less weight to single indent, as single spaces are
160 // often used in certain languages' comment systems and rarely
161 // used as the actual document indentation.
162 if histogram[1] > 1 {
163 histogram[1] /= 2;
164 }
165
166 histogram
167 };
168
169 // Find the most frequent indent, its frequency, and the frequency of
170 // the next-most frequent indent.
171 let indent = histogram
172 .iter()
173 .enumerate()
174 .max_by_key(|kv| kv.1)
175 .unwrap()
176 .0;
177 let indent_freq = histogram[indent];
178 let indent_freq_2 = *histogram
179 .iter()
180 .enumerate()
181 .filter(|kv| kv.0 != indent)
182 .map(|kv| kv.1)
183 .max()
184 .unwrap();
185
186 // Return the auto-detected result if we're confident enough in its
187 // accuracy, based on some heuristics.
188 if indent_freq >= 1 && (indent_freq_2 as f64 / indent_freq as f64) < 0.66 {
189 Some(match indent {
190 0 => IndentStyle::Tabs,
191 _ => IndentStyle::Spaces(indent as u8),
192 })
193 } else {
194 None
195 }
196 }
197
198 /// To determine indentation of a newly inserted line, figure out the indentation at the last col
199 /// of the previous line.
200 pub fn indent_level_for_line(line: RopeSlice, tab_width: usize, indent_width: usize) -> usize {
201 let mut len = 0;
202 for ch in line.chars() {
203 match ch {
204 '\t' => len += tab_width_at(len, tab_width as u16),
205 ' ' => len += 1,
206 _ => break,
207 }
208 }
209
210 len / indent_width
211 }
212
213 /// Create a string of tabs & spaces that has the same visual width as the given RopeSlice (independent of the tab width).
214 fn whitespace_with_same_width(text: RopeSlice) -> String {
215 let mut s = String::new();
216 for grapheme in text.graphemes() {
217 if grapheme == "\t" {
218 s.push('\t');
219 } else {
220 s.extend(std::iter::repeat_n(
221 ' ',
222 grapheme_width(&Cow::from(grapheme)),
223 ));
224 }
225 }
226 s
227 }
228
229 /// normalizes indentation to tabs/spaces based on user configuration
230 /// This function does not change the actual indentation width, just the character
231 /// composition.
232 pub fn normalize_indentation(
233 prefix: RopeSlice<'_>,
234 line: RopeSlice<'_>,
235 dst: &mut Tendril,
236 indent_style: IndentStyle,
237 tab_width: usize,
238 ) -> usize {
239 #[allow(deprecated)]
240 let off = crate::visual_coords_at_pos(prefix, prefix.len_chars(), tab_width).col;
241 let mut len = 0;
242 let mut original_len = 0;
243 for ch in line.chars() {
244 match ch {
245 '\t' => len += tab_width_at(len + off, tab_width as u16),
246 ' ' => len += 1,
247 _ => break,
248 }
249 original_len += 1;
250 }
251 if indent_style == IndentStyle::Tabs {
252 dst.extend(std::iter::repeat_n('\t', len / tab_width));
253 len %= tab_width;
254 }
255 dst.extend(std::iter::repeat_n(' ', len));
256 original_len
257 }
258
259 fn add_indent_level(
260 mut base_indent: String,
261 added_indent_level: isize,
262 indent_style: &IndentStyle,
263 tab_width: usize,
264 ) -> String {
265 if added_indent_level >= 0 {
266 // Adding a non-negative indent is easy, we can simply append the indent string
267 base_indent.push_str(&indent_style.as_str().repeat(added_indent_level as usize));
268 base_indent
269 } else {
270 // In this case, we want to return a prefix of `base_indent`.
271 // Since the width of a tab depends on its offset, we cannot simply iterate over
272 // the chars of `base_indent` in reverse until we have the desired indent reduction,
273 // instead we iterate over them twice in forward direction.
274 let base_indent_rope = RopeSlice::from(base_indent.as_str());
275 #[allow(deprecated)]
276 let base_indent_width =
277 crate::visual_coords_at_pos(base_indent_rope, base_indent_rope.len_chars(), tab_width)
278 .col;
279 let target_indent_width = base_indent_width
280 .saturating_sub((-added_indent_level) as usize * indent_style.indent_width(tab_width));
281 #[allow(deprecated)]
282 let char_end_idx = crate::pos_at_visual_coords(
283 base_indent_rope,
284 Position {
285 row: 0,
286 col: target_indent_width,
287 },
288 tab_width,
289 );
290 let byte_end_idx = base_indent_rope.char_to_byte(char_end_idx);
291 base_indent.truncate(byte_end_idx);
292 base_indent
293 }
294 }
295
296 #[derive(Debug, Default)]
297 pub struct IndentQueryPredicates {
298 not_kind_eq: Vec<(Capture, Box<str>)>,
299 same_line: Option<(Capture, Capture, bool)>,
300 one_line: Option<(Capture, bool)>,
301 }
302
303 impl IndentQueryPredicates {
304 fn are_satisfied(
305 &self,
306 match_: &QueryMatch,
307 text: RopeSlice,
308 new_line_byte_pos: Option<u32>,
309 ) -> bool {
310 for (capture, not_expected_kind) in self.not_kind_eq.iter() {
311 let node = match_.nodes_for_capture(*capture).next();
312 if node.is_some_and(|n| n.kind() == not_expected_kind.as_ref()) {
313 return false;
314 }
315 }
316
317 if let Some((capture1, capture2, negated)) = self.same_line {
318 let n1 = match_.nodes_for_capture(capture1).next();
319 let n2 = match_.nodes_for_capture(capture2).next();
320 let satisfied = n1.zip(n2).is_some_and(|(n1, n2)| {
321 let n1_line = get_node_start_line(text, n1, new_line_byte_pos);
322 let n2_line = get_node_start_line(text, n2, new_line_byte_pos);
323 let same_line = n1_line == n2_line;
324 same_line != negated
325 });
326
327 if !satisfied {
328 return false;
329 }
330 }
331
332 if let Some((capture, negated)) = self.one_line {
333 let node = match_.nodes_for_capture(capture).next();
334 let satisfied = node.is_some_and(|node| {
335 let start_line = get_node_start_line(text, node, new_line_byte_pos);
336 let end_line = get_node_end_line(text, node, new_line_byte_pos);
337 let one_line = end_line == start_line;
338 one_line != negated
339 });
340
341 if !satisfied {
342 return false;
343 }
344 }
345
346 true
347 }
348 }
349
350 #[derive(Debug)]
351 pub struct IndentQuery {
352 query: Query,
353 /// Patterns carrying `(#set! "scope" "header")` — the only indent scope the
354 /// containment engine reads.
355 header_patterns: HashSet<Pattern>,
356 predicates: HashMap<Pattern, IndentQueryPredicates>,
357 indent_capture: Option<Capture>,
358 indent_always_capture: Option<Capture>,
359 outdent_capture: Option<Capture>,
360 outdent_always_capture: Option<Capture>,
361 align_capture: Option<Capture>,
362 anchor_capture: Option<Capture>,
363 extend_capture: Option<Capture>,
364 extend_prevent_once_capture: Option<Capture>,
365 opaque_capture: Option<Capture>,
366 }
367
368 impl IndentQuery {
369 pub fn new(grammar: Grammar, source: &str) -> Result<Self, tree_sitter::query::ParseError> {
370 let mut header_patterns = HashSet::new();
371 let mut predicates: HashMap<Pattern, IndentQueryPredicates> = HashMap::new();
372 let query = Query::new(grammar, source, |pattern, predicate| match predicate {
373 UserPredicate::SetProperty { key: "scope", val } => {
374 match val {
375 Some("header") => {
376 header_patterns.insert(pattern);
377 }
378 Some(other) => {
379 return Err(format!("unknown scope (#set! scope \"{other}\")").into())
380 }
381 None => return Err("missing scope value (#set! scope ...)".into()),
382 };
383
384 Ok(())
385 }
386 UserPredicate::Other(predicate) => {
387 let name = predicate.name();
388 match name {
389 "not-kind-eq?" => {
390 predicate.check_arg_count(2)?;
391 let capture = predicate.capture_arg(0)?;
392 let not_expected_kind = predicate.str_arg(1)?;
393
394 predicates
395 .entry(pattern)
396 .or_default()
397 .not_kind_eq
398 .push((capture, not_expected_kind.into()));
399 Ok(())
400 }
401 "same-line?" | "not-same-line?" => {
402 predicate.check_arg_count(2)?;
403 let capture1 = predicate.capture_arg(0)?;
404 let capture2 = predicate.capture_arg(1)?;
405 let negated = name == "not-same-line?";
406
407 predicates.entry(pattern).or_default().same_line =
408 Some((capture1, capture2, negated));
409 Ok(())
410 }
411 "one-line?" | "not-one-line?" => {
412 predicate.check_arg_count(1)?;
413 let capture = predicate.capture_arg(0)?;
414 let negated = name == "not-one-line?";
415
416 predicates.entry(pattern).or_default().one_line = Some((capture, negated));
417 Ok(())
418 }
419 _ => Err(InvalidPredicateError::unknown(UserPredicate::Other(
420 predicate,
421 ))),
422 }
423 }
424 _ => Err(InvalidPredicateError::unknown(predicate)),
425 })?;
426
427 Ok(Self {
428 header_patterns,
429 predicates,
430 indent_capture: query.get_capture("indent"),
431 indent_always_capture: query.get_capture("indent.always"),
432 outdent_capture: query.get_capture("outdent"),
433 outdent_always_capture: query.get_capture("outdent.always"),
434 align_capture: query.get_capture("align"),
435 anchor_capture: query.get_capture("anchor"),
436 extend_capture: query.get_capture("extend"),
437 extend_prevent_once_capture: query.get_capture("extend.prevent-once"),
438 opaque_capture: query.get_capture("opaque"),
439 query,
440 })
441 }
442 }
443
444 /// The total indent for some line of code.
445 /// This is usually constructed in one of 2 ways:
446 /// - Successively add indent captures to get the (added) indent from a single line
447 /// - Successively add the indent results for each line
448 /// The string that this indentation defines starts with the string contained in the align field (unless it is None), followed by:
449 /// - max(0, indent - outdent) tabs, if tabs are used for indentation
450 /// - max(0, indent - outdent)*indent_width spaces, if spaces are used for indentation
451 #[derive(Default, Debug, PartialEq, Eq, Clone)]
452 pub struct Indentation<'a> {
453 indent: usize,
454 indent_always: usize,
455 outdent: usize,
456 outdent_always: usize,
457 /// The alignment, as a string containing only tabs & spaces. Storing this as a string instead of e.g.
458 /// the (visual) width ensures that the alignment is preserved even if the tab width changes.
459 align: Option<RopeSlice<'a>>,
460 }
461
462 impl<'a> Indentation<'a> {
463 /// Add some other [Indentation] to this.
464 fn net_indent(&self) -> isize {
465 (self.indent + self.indent_always) as isize
466 - ((self.outdent + self.outdent_always) as isize)
467 }
468 /// Convert `self` into a string, taking into account the computed and actual indentation of some other line.
469 fn relative_indent(
470 &self,
471 other_computed_indent: &Self,
472 other_leading_whitespace: RopeSlice,
473 indent_style: &IndentStyle,
474 tab_width: usize,
475 ) -> Option<String> {
476 if self.align == other_computed_indent.align {
477 // If self and baseline are either not aligned to anything or both aligned the same way,
478 // we can simply take `other_leading_whitespace` and add some indent / outdent to it (in the second
479 // case, the alignment should already be accounted for in `other_leading_whitespace`).
480 let indent_diff = self.net_indent() - other_computed_indent.net_indent();
481 Some(add_indent_level(
482 String::from(other_leading_whitespace),
483 indent_diff,
484 indent_style,
485 tab_width,
486 ))
487 } else {
488 // If the alignment of both lines is different, we cannot compare their indentation in any meaningful way
489 None
490 }
491 }
492 pub fn to_string(&self, indent_style: &IndentStyle, tab_width: usize) -> String {
493 add_indent_level(
494 self.align
495 .map_or_else(String::new, whitespace_with_same_width),
496 self.net_indent(),
497 indent_style,
498 tab_width,
499 )
500 }
501 }
502
503 /// An indent definition which corresponds to a capture from the indent query
504 #[derive(Debug)]
505 struct IndentCapture<'a> {
506 capture_type: IndentCaptureType<'a>,
507 /// `(#set! "scope" "header")`: open this `@indent`'s scope at the captured
508 /// node's *header* (its parent's start line) instead of the node's own first
509 /// line, so a brace-less body (`if (c)\n stmt;`) whose own first line needs
510 /// the indent is contained.
511 header: bool,
512 }
513 #[derive(Debug, Clone, PartialEq)]
514 enum IndentCaptureType<'a> {
515 Indent,
516 IndentAlways,
517 Outdent,
518 OutdentAlways,
519 /// Alignment given as a string of whitespace
520 Align(RopeSlice<'a>),
521 }
522
523 /// A capture from the indent query which does not define an indent but extends
524 /// the range of a node. This is used before the indent is calculated.
525 #[derive(Debug)]
526 enum ExtendCapture {
527 Extend,
528 PreventOnce,
529 }
530
531 /// The result of running a tree-sitter indent query. This stores for
532 /// each node (identified by its ID) the relevant captures (already filtered
533 /// by predicates).
534 #[derive(Debug)]
535 struct IndentQueryResult<'a> {
536 indent_captures: HashMap<usize, Vec<IndentCapture<'a>>>,
537 extend_captures: HashMap<usize, Vec<ExtendCapture>>,
538 /// Byte ranges of nodes captured by `@opaque`, collected in the same pass so the
539 /// opaque-interior check doesn't need a second query.
540 opaque_ranges: Vec<std::ops::Range<u32>>,
541 }
542
543 fn get_node_start_line(text: RopeSlice, node: &Node, new_line_byte_pos: Option<u32>) -> usize {
544 let mut node_line = text.byte_to_line(node.start_byte() as usize);
545 // Adjust for the new line that will be inserted
546 if new_line_byte_pos.is_some_and(|pos| node.start_byte() >= pos) {
547 node_line += 1;
548 }
549 node_line
550 }
551 fn get_node_end_line(text: RopeSlice, node: &Node, new_line_byte_pos: Option<u32>) -> usize {
552 let mut node_line = text.byte_to_line(node.end_byte() as usize);
553 // Adjust for the new line that will be inserted (with a strict inequality since end_byte is exclusive)
554 if new_line_byte_pos.is_some_and(|pos| node.end_byte() > pos) {
555 node_line += 1;
556 }
557 node_line
558 }
559
560 fn query_indents<'a>(
561 query: &IndentQuery,
562 root: &Node,
563 text: RopeSlice<'a>,
564 range: std::ops::Range<u32>,
565 new_line_byte_pos: Option<u32>,
566 ) -> IndentQueryResult<'a> {
567 let mut indent_captures: HashMap<usize, Vec<IndentCapture>> = HashMap::new();
568 let mut extend_captures: HashMap<usize, Vec<ExtendCapture>> = HashMap::new();
569 let mut opaque_ranges: Vec<std::ops::Range<u32>> = Vec::new();
570
571 let mut cursor = InactiveQueryCursor::new(range, TREE_SITTER_MATCH_LIMIT).execute_query(
572 &query.query,
573 root,
574 RopeInput::new(text),
575 );
576
577 // Iterate over all captures from the query
578 while let Some(m) = cursor.next_match() {
579 // Skip matches where not all custom predicates are fulfilled
580 if query
581 .predicates
582 .get(&m.pattern())
583 .is_some_and(|preds| !preds.are_satisfied(&m, text, new_line_byte_pos))
584 {
585 continue;
586 }
587 // A list of pairs (node_id, indent_capture) that are added by this match.
588 // They cannot be added to indent_captures immediately since they may depend on other captures (such as an @anchor).
589 let mut added_indent_captures: Vec<(usize, IndentCapture)> = Vec::new();
590 // The row/column position of the optional anchor in this query
591 let mut anchor: Option<&Node> = None;
592 for matched_node in m.matched_nodes() {
593 let node_id = matched_node.node.id();
594 let capture = Some(matched_node.capture);
595 let capture_type = if capture == query.indent_capture {
596 IndentCaptureType::Indent
597 } else if capture == query.indent_always_capture {
598 IndentCaptureType::IndentAlways
599 } else if capture == query.outdent_capture {
600 IndentCaptureType::Outdent
601 } else if capture == query.outdent_always_capture {
602 IndentCaptureType::OutdentAlways
603 } else if capture == query.align_capture {
604 IndentCaptureType::Align(RopeSlice::from(""))
605 } else if capture == query.anchor_capture {
606 if anchor.is_some() {
607 log::error!("Invalid indent query: Encountered more than one @anchor in the same match.")
608 } else {
609 anchor = Some(&matched_node.node);
610 }
611 continue;
612 } else if capture == query.extend_capture {
613 extend_captures
614 .entry(node_id)
615 .or_insert_with(|| Vec::with_capacity(1))
616 .push(ExtendCapture::Extend);
617 continue;
618 } else if capture == query.extend_prevent_once_capture {
619 extend_captures
620 .entry(node_id)
621 .or_insert_with(|| Vec::with_capacity(1))
622 .push(ExtendCapture::PreventOnce);
623 continue;
624 } else if capture == query.opaque_capture {
625 // Collected here so `treesitter_indent_for_pos` can test for an
626 // opaque interior without a second query pass.
627 opaque_ranges.push(matched_node.node.start_byte()..matched_node.node.end_byte());
628 continue;
629 } else {
630 // Ignore any unknown captures (these may be needed for predicates such as #match?)
631 continue;
632 };
633
634 // Apply additional settings for this capture
635 let indent_capture = IndentCapture {
636 capture_type,
637 header: query.header_patterns.contains(&m.pattern()),
638 };
639 added_indent_captures.push((node_id, indent_capture))
640 }
641 for (node_id, mut capture) in added_indent_captures {
642 // Set the anchor for all align queries.
643 if let IndentCaptureType::Align(_) = capture.capture_type {
644 let Some(anchor) = anchor else {
645 log::error!("Invalid indent query: @align requires an accompanying @anchor.");
646 continue;
647 };
648 let line = text.byte_to_line(anchor.start_byte() as usize);
649 let line_start = text.line_to_byte(line);
650 capture.capture_type = IndentCaptureType::Align(
651 text.byte_slice(line_start..anchor.start_byte() as usize),
652 );
653 }
654 indent_captures
655 .entry(node_id)
656 .or_insert_with(|| Vec::with_capacity(1))
657 .push(capture);
658 }
659 }
660
661 let result = IndentQueryResult {
662 indent_captures,
663 extend_captures,
664 opaque_ranges,
665 };
666
667 log::trace!("indent result = {:?}", result);
668
669 result
670 }
671
672 /// Handle extend queries. deepest_preceding is the deepest descendant of node that directly precedes the cursor position.
673 /// Any ancestor of deepest_preceding which is also a descendant of node may be "extended". In that case, node will be updated,
674 /// so that the indent computation starts with the correct syntax node.
675 fn extend_nodes<'a>(
676 node: &mut Node<'a>,
677 mut deepest_preceding: Node<'a>,
678 extend_captures: &HashMap<usize, Vec<ExtendCapture>>,
679 text: RopeSlice,
680 line: usize,
681 tab_width: usize,
682 indent_width: usize,
683 ) {
684 let mut stop_extend = false;
685
686 while deepest_preceding != *node {
687 let mut extend_node = false;
688 // This will be set to true if this node is captured, regardless of whether
689 // it actually will be extended (e.g. because the cursor isn't indented
690 // more than the node).
691 let mut node_captured = false;
692 if let Some(captures) = extend_captures.get(&deepest_preceding.id()) {
693 for capture in captures {
694 match capture {
695 ExtendCapture::PreventOnce => {
696 stop_extend = true;
697 }
698 ExtendCapture::Extend => {
699 node_captured = true;
700 // We extend the node if
701 // - the cursor is on the same line as the end of the node OR
702 // - the line that the cursor is on is more indented than the
703 // first line of the node
704 if text.byte_to_line(deepest_preceding.end_byte() as usize) == line {
705 extend_node = true;
706 } else {
707 let cursor_indent =
708 indent_level_for_line(text.line(line), tab_width, indent_width);
709 let node_indent = indent_level_for_line(
710 text.line(
711 text.byte_to_line(deepest_preceding.start_byte() as usize),
712 ),
713 tab_width,
714 indent_width,
715 );
716 if cursor_indent > node_indent {
717 extend_node = true;
718 }
719 }
720 }
721 }
722 }
723 }
724 // If we encountered some `StopExtend` capture before, we don't
725 // extend the node even if we otherwise would
726 if node_captured && stop_extend {
727 stop_extend = false;
728 } else if extend_node && !stop_extend {
729 *node = deepest_preceding.clone();
730 break;
731 }
732 // If the tree contains a syntax error, `deepest_preceding` may not
733 // have a parent despite being a descendant of `node`.
734 deepest_preceding = match deepest_preceding.parent() {
735 Some(parent) => parent,
736 None => return,
737 }
738 }
739 }
740
741 /// When a newline is typed after a header (`while (c)`, `if x:`), the body it
742 /// opens begins on the *next* line — a following sibling the upward indent walk
743 /// never reaches, which is why brace-less bodies need either a wrapper `@indent`
744 /// rule or descent into the body before the containment walk starts.
745 ///
746 /// Walk up from the deepest preceding node and return the immediate next sibling
747 /// of the first ancestor whose end lies before the cursor. The caller then
748 /// decides whether to actually descend — the signal is the query's
749 /// `(#set! "scope" "header")` annotation on that sibling, which is exactly how
750 /// brace-less body rules already mark their body capture (c/java/nix and parts
751 /// of ecma). This keeps tree-sitter field names out of the engine: the query
752 /// alone says what is a body. A statement-list child is not header-scoped in any
753 /// query, so `foo();` then `bar();` correctly finds no descent target.
754 fn candidate_body_for_new_line<'a>(
755 deepest_preceding: &Node<'a>,
756 byte_pos: u32,
757 ) -> Option<Node<'a>> {
758 let mut node = deepest_preceding.clone();
759 while let Some(parent) = node.parent() {
760 // Only consider ancestors that lie entirely before the cursor: those are
761 // part of the header. Once an ancestor extends past the cursor it
762 // *contains* the new line (an already-open body like `if (c) {`), which
763 // the normal containment walk handles — stop.
764 if node.end_byte() > byte_pos {
765 break;
766 }
767 // The body the new line opens is the sibling immediately after this
768 // header node (`while (c)` -> body, `if x:` -> consequence). Requiring
769 // the *immediate* next sibling avoids jumping to a later body such as
770 // an `else` arm while the cursor is still in the consequence.
771 let mut cursor = parent.walk();
772 if cursor.goto_first_child() {
773 loop {
774 if cursor.node().id() == node.id() {
775 if cursor.goto_next_sibling() {
776 let child = cursor.node();
777 if child.start_byte() >= byte_pos {
778 return Some(child);
779 }
780 }
781 break;
782 }
783 if !cursor.goto_next_sibling() {
784 break;
785 }
786 }
787 }
788 node = parent;
789 }
790 None
791 }
792
793 /// Prepare an indent query by computing:
794 /// - The node from which to start the query (this is non-trivial due to `@extend` captures)
795 /// - The indent captures for all relevant nodes.
796 #[allow(clippy::too_many_arguments)]
797 #[allow(clippy::type_complexity)]
798 fn init_indent_query<'a, 'b>(
799 query: &IndentQuery,
800 root: &Node<'a>,
801 text: RopeSlice<'b>,
802 tab_width: usize,
803 indent_width: usize,
804 line: usize,
805 byte_pos: u32,
806 new_line_byte_pos: Option<u32>,
807 ) -> Option<(
808 Node<'a>,
809 HashMap<usize, Vec<IndentCapture<'b>>>,
810 Vec<std::ops::Range<u32>>,
811 )> {
812 // The innermost tree-sitter node which is considered for the indent
813 // computation. It may change if some preceding node is extended
814 let mut node = root.descendant_for_byte_range(byte_pos, byte_pos)?;
815
816 let (query_result, deepest_preceding, candidate_body) = {
817 // The query range should intersect with all nodes directly preceding
818 // the position of the indent query in case one of them is extended.
819 let mut deepest_preceding = None; // The deepest node preceding the indent query position
820 for child in node.children() {
821 if child.byte_range().end <= byte_pos {
822 deepest_preceding = Some(child.clone());
823 }
824 }
825 deepest_preceding = deepest_preceding.map(|mut prec| {
826 // Get the deepest directly preceding node
827 while prec.child_count() > 0 {
828 prec = prec.child(prec.child_count() - 1).unwrap().clone();
829 }
830 prec
831 });
832 // When typing a newline, the body the new line opens is a sibling past
833 // the cursor — extend the query range to cover it so its capture (and
834 // in particular its `(#set! "scope" "header")` annotation) is present
835 // in the result, the signal we use to drive descent.
836 let candidate_body = new_line_byte_pos
837 .and(deepest_preceding.as_ref())
838 .and_then(|dp| candidate_body_for_new_line(dp, byte_pos));
839 let upper = candidate_body
840 .as_ref()
841 .map(|b| b.end_byte())
842 .unwrap_or(byte_pos + 1);
843 let query_range = deepest_preceding
844 .as_ref()
845 .map(|prec| prec.byte_range().end - 1..upper)
846 .unwrap_or(byte_pos..upper);
847
848 let query_result = query_indents(query, root, text, query_range, new_line_byte_pos);
849 (query_result, deepest_preceding, candidate_body)
850 };
851 let extend_captures = query_result.extend_captures;
852 let opaque_ranges = query_result.opaque_ranges;
853
854 // When typing a newline, descend into the body the new line opens so its own
855 // scope governs the indent (structural replacement for wrapper/`@extend`
856 // rules on delimited and brace-less bodies). The query — via its
857 // `(#set! "scope" "header")` annotation on the body capture — is the single
858 // source of truth for whether the candidate sibling is actually a body to
859 // descend into. Otherwise fall back to `@extend`.
860 let descended = candidate_body
861 .as_ref()
862 .filter(|body| {
863 query_result
864 .indent_captures
865 .get(&body.id())
866 .is_some_and(|defs| defs.iter().any(|c| c.header))
867 })
868 .map(|body| node = body.clone())
869 .is_some();
870
871 // Check for extend captures, potentially changing the node that the indent calculation starts with
872 if let Some(deepest_preceding) = deepest_preceding {
873 if !descended {
874 extend_nodes(
875 &mut node,
876 deepest_preceding,
877 &extend_captures,
878 text,
879 line,
880 tab_width,
881 indent_width,
882 );
883 }
884 }
885 Some((node, query_result.indent_captures, opaque_ranges))
886 }
887
888 /// Use the syntax tree to determine the indentation for a given position.
889 /// This can be used in 2 ways:
890 ///
891 /// - To get the correct indentation for an existing line (new_line=false), not necessarily equal to the current indentation.
892 /// - In this case, pos should be inside the first tree-sitter node on that line.
893 /// In most cases, this can just be the first non-whitespace on that line.
894 /// - To get the indentation for a new line (new_line=true). This behaves like the first usecase if the part of the current line
895 /// after pos were moved to a new line.
896 ///
897 /// The indentation is determined by traversing all the tree-sitter nodes containing the position.
898 /// Each of these nodes produces some [Indentation] for:
899 ///
900 /// - The line of the (beginning of the) node. This is defined by the scope `all` if this is the first node on its line.
901 /// - The line after the node. This is defined by:
902 /// - The scope `tail`.
903 /// - The scope `all` if this node is not the first node on its line.
904 ///
905 /// Intuitively, `all` applies to everything contained in this node while `tail` applies to everything except for the first line of the node.
906 /// The indents from different nodes for the same line are then combined.
907 /// The result [Indentation] is simply the sum of the [Indentation] for all lines.
908 ///
909 /// Specifying which line exactly an [Indentation] applies to is important because indents on the same line combine differently than indents on different lines:
910 /// ```ignore
911 /// some_function(|| {
912 /// // Both the function parameters as well as the contained block should be indented.
913 /// // Because they are on the same line, this only yields one indent level
914 /// });
915 /// ```
916 ///
917 /// ```ignore
918 /// some_function(
919 /// param1,
920 /// || {
921 /// // Here we get 2 indent levels because the 'parameters' and the 'block' node begin on different lines
922 /// },
923 /// );
924 /// ```
925 #[allow(clippy::too_many_arguments)]
926 /// Whether `byte_pos` falls in the interior of an `@opaque` node spanning
927 /// `[start, end)` that began on an *earlier* line — i.e. a string / heredoc /
928 /// block-comment body whose leading whitespace is literal content. Shared by the
929 /// hot path (which collects `@opaque` ranges in the containment pass) and the
930 /// standalone [`is_opaque_interior`].
931 fn opaque_hit(start: u32, end: u32, byte_pos: u32, text: RopeSlice) -> bool {
932 start <= byte_pos
933 && byte_pos < end
934 && text.byte_to_line(start as usize) < text.byte_to_line(byte_pos as usize)
935 }
936
937 /// Whether `byte_pos` lies in the *interior* of a node captured `@opaque` — a
938 /// string / heredoc / block-comment body that began on an earlier line. The
939 /// leading whitespace of such lines is literal content, so indentation must
940 /// leave it untouched rather than reformat it as code.
941 ///
942 /// `treesitter_indent_for_pos` does not call this — it derives the same answer
943 /// from the captures of its single containment pass — so this exists for external
944 /// callers (e.g. the indent-check xtask) that only need the opaque test.
945 pub fn is_opaque_interior(
946 query: &IndentQuery,
947 syntax: &Syntax,
948 text: RopeSlice,
949 byte_pos: u32,
950 ) -> bool {
951 let Some(opaque) = query.opaque_capture else {
952 return false;
953 };
954 let mut cursor = InactiveQueryCursor::new(byte_pos..byte_pos + 1, TREE_SITTER_MATCH_LIMIT)
955 .execute_query(
956 &query.query,
957 &syntax.tree_for_byte_range(byte_pos, byte_pos).root_node(),
958 RopeInput::new(text),
959 );
960 while let Some(m) = cursor.next_match() {
961 for matched in m.matched_nodes() {
962 if matched.capture == opaque
963 && opaque_hit(
964 matched.node.start_byte(),
965 matched.node.end_byte(),
966 byte_pos,
967 text,
968 )
969 {
970 return true;
971 }
972 }
973 }
974 false
975 }
976
977 #[allow(clippy::too_many_arguments)]
978 pub fn treesitter_indent_for_pos<'a>(
979 query: &IndentQuery,
980 syntax: &'a Syntax,
981 loader: &syntax::Loader,
982 tab_width: usize,
983 indent_width: usize,
984 text: RopeSlice<'a>,
985 line: usize,
986 pos: usize,
987 new_line: bool,
988 ) -> Option<Indentation<'a>> {
989 let byte_pos = text.char_to_byte(pos) as u32;
990 // Inside an injection layer indent with that language's query and tree,
991 // then shift the whole result by the injection's base indent.
992 let layer = syntax.layer_for_byte_range(byte_pos, byte_pos);
993 // Only a *different* language injection needs special handling; a
994 // same-language injection (e.g. rust macro token-trees) is already indented
995 // correctly by the root walk, and offsetting it would double-count.
996 let injected = (layer != syntax.root_layer()
997 && syntax.layer(layer).language != syntax.root_language())
998 .then(|| loader.indent_query(syntax.layer(layer).language))
999 .flatten();
1000 let query = injected.unwrap_or(query);
1001 let tree = if injected.is_some() {
1002 syntax.tree_for_byte_range(byte_pos, byte_pos)
1003 } else {
1004 syntax.tree()
1005 };
1006 let root = tree.root_node();
1007
1008 // Compute the indent by *scope containment*: the level of a line is the
1009 // number of `@indent` scopes that contain it (see `containment_accounting`).
1010 let (mut result, opaque) = containment_accounting(
1011 query,
1012 &root,
1013 text,
1014 tab_width,
1015 indent_width,
1016 line,
1017 byte_pos,
1018 new_line,
1019 )?;
1020 // Lines inside an `@opaque` node are literal content, not code: preserve their
1021 // existing leading whitespace instead of reformatting it.
1022 if opaque {
1023 let line_slice = text.line(line);
1024 let first = line_slice
1025 .first_non_whitespace_char()
1026 .unwrap_or_else(|| line_slice.len_chars());
1027 return Some(Indentation {
1028 align: Some(line_slice.slice(..first)),
1029 ..Default::default()
1030 });
1031 }
1032 // The injected walk above is relative to the injection's own tree root (the
1033 // embedded code starts at level 0). Shift it by the indent of the injection's
1034 // first content line so it sits where the host language placed the block.
1035 if injected.is_some() {
1036 result.indent += injection_base_level(syntax, text, byte_pos, tab_width, indent_width);
1037 }
1038 Some(result)
1039 }
1040
1041 /// Compute indentation by *scope containment*.
1042 ///
1043 /// Each node carrying an `@indent`/`@indent.always` capture defines a scope
1044 /// spanning the lines after its start up to its end. The indent level of a line
1045 /// is the number of such scopes containing it (collapsing scopes that open on the
1046 /// same physical line to one level), minus any `@outdent` whose token begins the line.
1047 /// `@align`/`@extend`/`@opaque` are kept as overlays.
1048 #[allow(clippy::too_many_arguments)]
1049 fn containment_accounting<'a>(
1050 query: &IndentQuery,
1051 root: &Node<'a>,
1052 text: RopeSlice<'a>,
1053 tab_width: usize,
1054 indent_width: usize,
1055 line: usize,
1056 byte_pos: u32,
1057 new_line: bool,
1058 ) -> Option<(Indentation<'a>, bool)> {
1059 let new_line_byte_pos = new_line.then_some(byte_pos);
1060 // Reuse the standard setup: this applies @extend repositioning / body-descent
1061 // and returns the per-node capture map (all ancestors of the cursor intersect
1062 // the query range, so their captures are present).
1063 let (start_node, captures, opaque_ranges) = init_indent_query(
1064 query,
1065 root,
1066 text,
1067 tab_width,
1068 indent_width,
1069 line,
1070 byte_pos,
1071 new_line_byte_pos,
1072 )?;
1073
1074 // Opaque interior: determined from the captures of the pass above, so no
1075 // second query is needed. The caller preserves the line's existing leading
1076 // whitespace in this case.
1077 if opaque_ranges
1078 .iter()
1079 .any(|r| opaque_hit(r.start, r.end, byte_pos, text))
1080 {
1081 return Some((Indentation::default(), true));
1082 }
1083
1084 // The line whose indent we are computing (post-insertion coordinates).
1085 let target_line = line + new_line as usize;
1086
1087 let mut indent_levels: usize = 0;
1088 let mut indent_always: usize = 0;
1089 let mut outdent: usize = 0;
1090 let mut outdent_always: usize = 0;
1091 let mut align: Option<RopeSlice<'a>> = None;
1092 // Same-line collapse: a scope contributes at most one level per physical line
1093 // it opens on.
1094 let mut counted_start_lines: Vec<usize> = Vec::new();
1095
1096 let mut node = start_node;
1097 loop {
1098 if let Some(defs) = captures.get(&node.id()) {
1099 // Aggregate this node's captures.
1100 let mut has_indent = false;
1101 let mut has_indent_always = false;
1102 let mut has_outdent = false;
1103 let mut has_outdent_always = false;
1104 let mut header_scoped = false;
1105 let mut node_align: Option<RopeSlice<'a>> = None;
1106 for def in defs {
1107 match def.capture_type {
1108 IndentCaptureType::Indent => {
1109 has_indent = true;
1110 header_scoped |= def.header;
1111 }
1112 IndentCaptureType::IndentAlways => {
1113 has_indent_always = true;
1114 header_scoped |= def.header;
1115 }
1116 IndentCaptureType::Outdent => has_outdent = true,
1117 IndentCaptureType::OutdentAlways => has_outdent_always = true,
1118 IndentCaptureType::Align(a) => node_align = Some(a),
1119 }
1120 }
1121
1122 let node_start = get_node_start_line(text, &node, new_line_byte_pos);
1123 let end = get_node_end_line(text, &node, new_line_byte_pos);
1124 // `scope "header"` (set by the query on a brace-less body rule such as
1125 // `(if_statement consequence: (_) @indent (#set! scope "header"))`)
1126 // opens the scope at the *header* — the captured node's parent — so the
1127 // body's own first line is contained. The query selects the body node,
1128 // so its parent is the header by construction.
1129 let start = if header_scoped {
1130 node.parent()
1131 .map(|p| get_node_start_line(text, &p, new_line_byte_pos))
1132 .unwrap_or(node_start)
1133 } else {
1134 node_start
1135 };
1136 // A scope contains the target line if it opens before it and closes on
1137 // or after it.
1138 let contains = start < target_line && target_line <= end;
1139 // A token-style outdent (`}`, `else`, `case`) sits on the line it
1140 // dedents.
1141 let opens_target = node_start == target_line;
1142
1143 if (has_indent || has_indent_always) && (has_outdent || has_outdent_always) {
1144 // A node carrying both indent and outdent (e.g. swift's nested
1145 // else-if `(if_statement (if_statement) @outdent)`) cancels its own
1146 // level: it must not create a scope.
1147 } else {
1148 if has_indent && contains && !counted_start_lines.contains(&start) {
1149 counted_start_lines.push(start);
1150 indent_levels += 1;
1151 }
1152 if has_indent_always && contains {
1153 indent_always += 1;
1154 }
1155 if has_outdent && opens_target {
1156 outdent += 1;
1157 }
1158 if has_outdent_always && opens_target {
1159 outdent_always += 1;
1160 }
1161 }
1162 // Innermost containing alignment wins (first seen on the upward walk).
1163 if let Some(a) = node_align {
1164 if contains && align.is_none() {
1165 align = Some(a);
1166 }
1167 }
1168 }
1169 match node.parent() {
1170 Some(parent) => node = parent,
1171 None => break,
1172 }
1173 }
1174
1175 // `@align` is an absolute alignment (to the anchor column); the containment
1176 // levels it spans are already encoded in that column, so don't stack them on
1177 // top.
1178 if align.is_some() {
1179 indent_levels = 0;
1180 indent_always = 0;
1181 }
1182 Some((
1183 Indentation {
1184 indent: indent_levels,
1185 indent_always,
1186 outdent,
1187 outdent_always,
1188 align,
1189 },
1190 false,
1191 ))
1192 }
1193
1194 /// The indent level (in the host document) of the first content line of the
1195 /// injection layer that `byte_pos` belongs to (i.e. where the embedded code
1196 /// begins). Used to offset an injection's own (0-based) indentation.
1197 fn injection_base_level(
1198 syntax: &Syntax,
1199 text: RopeSlice,
1200 byte_pos: u32,
1201 tab_width: usize,
1202 indent_width: usize,
1203 ) -> usize {
1204 let layer = syntax.layer_for_byte_range(byte_pos, byte_pos);
1205 // A content line of the injection is one whose first non-whitespace char
1206 // belongs to this layer (the opening `<script>` line does not — its first
1207 // token is host markup).
1208 let in_layer = |line: usize| match text.line(line).first_non_whitespace_char() {
1209 Some(fnw) => {
1210 let b = text.char_to_byte(text.line_to_char(line) + fnw) as u32;
1211 syntax.layer_for_byte_range(b, b) == layer
1212 }
1213 None => false,
1214 };
1215 let bl = text.byte_to_line(byte_pos as usize);
1216 let first = if in_layer(bl) {
1217 // Inside the injection: walk back to its first content line.
1218 let mut f = bl;
1219 while f > 0 && in_layer(f - 1) {
1220 f -= 1;
1221 }
1222 f
1223 } else {
1224 // Typing the first content line from the host boundary (e.g. just after
1225 // `<script>`): the injection begins on a following line.
1226 let total = text.len_lines();
1227 let mut f = bl + 1;
1228 while f + 1 < total && !in_layer(f) {
1229 f += 1;
1230 }
1231 f
1232 };
1233 indent_level_for_line(text.line(first), tab_width, indent_width)
1234 }
1235
1236 /// Whether the token at `byte_pos` (expected to be the first token on its line)
1237 /// is captured `@outdent`/`@outdent.always` by the indent query — i.e. the
1238 /// editor dedents that line as the token is entered (a closing bracket, a
1239 /// `case`/`else`/`except` keyword, …). Used to tell a *recoverable* typing
1240 /// over-indent (the leading token will pull the line back) from a real one (a
1241 /// plain statement that the new-line indent placed too deep).
1242 pub fn is_outdent_token_at(
1243 query: &IndentQuery,
1244 syntax: &Syntax,
1245 text: RopeSlice,
1246 byte_pos: u32,
1247 ) -> bool {
1248 let root = syntax.tree_for_byte_range(byte_pos, byte_pos).root_node();
1249 let Some(mut node) = root.descendant_for_byte_range(byte_pos, byte_pos) else {
1250 return false;
1251 };
1252 let result = query_indents(query, &root, text, byte_pos..byte_pos + 1, None);
1253 // Check the leading token and any ancestor that starts at the same byte (the
1254 // @outdent may sit on the token itself or on a node it opens, e.g.
1255 // `(access_specifier) @outdent`).
1256 loop {
1257 if result.indent_captures.get(&node.id()).is_some_and(|caps| {
1258 caps.iter().any(|c| {
1259 matches!(
1260 c.capture_type,
1261 IndentCaptureType::Outdent | IndentCaptureType::OutdentAlways
1262 )
1263 })
1264 }) {
1265 return true;
1266 }
1267 match node.parent() {
1268 Some(parent) if parent.start_byte() == node.start_byte() => node = parent,
1269 _ => return false,
1270 }
1271 }
1272 }
1273
1274 /// Returns the indentation for a new line.
1275 /// This is done either using treesitter, or if that's not available by copying the indentation from the current line
1276 #[allow(clippy::too_many_arguments)]
1277 pub fn indent_for_newline(
1278 loader: &syntax::Loader,
1279 syntax: Option<&Syntax>,
1280 indent_heuristic: &IndentationHeuristic,
1281 indent_style: &IndentStyle,
1282 tab_width: usize,
1283 text: RopeSlice,
1284 line_before: usize,
1285 line_before_end_pos: usize,
1286 current_line: usize,
1287 ) -> String {
1288 let indent_width = indent_style.indent_width(tab_width);
1289 if let (
1290 IndentationHeuristic::TreeSitter | IndentationHeuristic::Hybrid,
1291 Some(query),
1292 Some(syntax),
1293 ) = (
1294 indent_heuristic,
1295 syntax.and_then(|syntax| loader.indent_query(syntax.root_language())),
1296 syntax,
1297 ) {
1298 if let Some(indent) = treesitter_indent_for_pos(
1299 query,
1300 syntax,
1301 loader,
1302 tab_width,
1303 indent_width,
1304 text,
1305 line_before,
1306 line_before_end_pos,
1307 true,
1308 ) {
1309 if *indent_heuristic == IndentationHeuristic::Hybrid {
1310 // We want to compute the indentation not only based on the
1311 // syntax tree but also on the actual indentation of a previous
1312 // line. This makes indentation computation more resilient to
1313 // incomplete queries, incomplete source code & differing indentation
1314 // styles for the same language.
1315 // However, using the indent of a previous line as a baseline may not
1316 // make sense, e.g. if it has a different alignment than the new line.
1317 // In order to prevent edge cases with long running times, we only try
1318 // a constant number of (non-empty) lines.
1319 const MAX_ATTEMPTS: usize = 4;
1320 let mut num_attempts = 0;
1321 for line_idx in (0..=line_before).rev() {
1322 let line = text.line(line_idx);
1323 let first_non_whitespace_char = match line.first_non_whitespace_char() {
1324 Some(i) => i,
1325 None => {
1326 continue;
1327 }
1328 };
1329 if let Some(indent) = (|| {
1330 let computed_indent = treesitter_indent_for_pos(
1331 query,
1332 syntax,
1333 loader,
1334 tab_width,
1335 indent_width,
1336 text,
1337 line_idx,
1338 text.line_to_char(line_idx) + first_non_whitespace_char,
1339 false,
1340 )?;
1341 let leading_whitespace = line.slice(0..first_non_whitespace_char);
1342 indent.relative_indent(
1343 &computed_indent,
1344 leading_whitespace,
1345 indent_style,
1346 tab_width,
1347 )
1348 })() {
1349 return indent;
1350 }
1351 num_attempts += 1;
1352 if num_attempts == MAX_ATTEMPTS {
1353 break;
1354 }
1355 }
1356 }
1357 return indent.to_string(indent_style, tab_width);
1358 };
1359 }
1360 // Fallback in case we either don't have indent queries or they failed for some reason
1361 let indent_level = indent_level_for_line(text.line(current_line), tab_width, indent_width);
1362 indent_style.as_str().repeat(indent_level)
1363 }
1364
1365 pub fn get_scopes<'a>(syntax: Option<&'a Syntax>, text: RopeSlice, pos: usize) -> Vec<&'a str> {
1366 let mut scopes = Vec::new();
1367 if let Some(syntax) = syntax {
1368 let pos = text.char_to_byte(pos) as u32;
1369 let mut node = match syntax
1370 .tree()
1371 .root_node()
1372 .descendant_for_byte_range(pos, pos)
1373 {
1374 Some(node) => node,
1375 None => return scopes,
1376 };
1377
1378 scopes.push(node.kind());
1379
1380 while let Some(parent) = node.parent() {
1381 scopes.push(parent.kind());
1382 node = parent;
1383 }
1384 }
1385
1386 scopes.reverse();
1387 scopes
1388 }
1389
1390 #[cfg(test)]
1391 mod test {
1392 use super::*;
1393 use crate::Rope;
1394
1395 #[test]
1396 fn test_indent_level() {
1397 let tab_width = 4;
1398 let indent_width = 4;
1399 let line = Rope::from(" fn new"); // 8 spaces
1400 assert_eq!(
1401 indent_level_for_line(line.slice(..), tab_width, indent_width),
1402 2
1403 );
1404 let line = Rope::from("\t\t\tfn new"); // 3 tabs
1405 assert_eq!(
1406 indent_level_for_line(line.slice(..), tab_width, indent_width),
1407 3
1408 );
1409 // mixed indentation
1410 let line = Rope::from("\t \tfn new"); // 1 tab, 4 spaces, tab
1411 assert_eq!(
1412 indent_level_for_line(line.slice(..), tab_width, indent_width),
1413 3
1414 );
1415 }
1416
1417 #[test]
1418 fn test_large_indent_level() {
1419 let tab_width = 16;
1420 let indent_width = 16;
1421 let line = Rope::from(" fn new"); // 16 spaces
1422 assert_eq!(
1423 indent_level_for_line(line.slice(..), tab_width, indent_width),
1424 1
1425 );
1426 let line = Rope::from(" fn new"); // 32 spaces
1427 assert_eq!(
1428 indent_level_for_line(line.slice(..), tab_width, indent_width),
1429 2
1430 );
1431 }
1432
1433 #[test]
1434 fn test_relative_indent() {
1435 let indent_style = IndentStyle::Spaces(4);
1436 let tab_width: usize = 4;
1437 let no_align = [
1438 Indentation::default(),
1439 Indentation {
1440 indent: 1,
1441 ..Default::default()
1442 },
1443 Indentation {
1444 indent: 5,
1445 outdent: 1,
1446 ..Default::default()
1447 },
1448 ];
1449 let align = no_align.clone().map(|indent| Indentation {
1450 align: Some(RopeSlice::from("12345")),
1451 ..indent
1452 });
1453 let different_align = Indentation {
1454 align: Some(RopeSlice::from("123456")),
1455 ..Default::default()
1456 };
1457
1458 // Check that relative and absolute indentation computation are the same when the line we compare to is
1459 // indented as we expect.
1460 let check_consistency = |indent: &Indentation, other: &Indentation| {
1461 assert_eq!(
1462 indent.relative_indent(
1463 other,
1464 RopeSlice::from(other.to_string(&indent_style, tab_width).as_str()),
1465 &indent_style,
1466 tab_width
1467 ),
1468 Some(indent.to_string(&indent_style, tab_width))
1469 );
1470 };
1471 for a in &no_align {
1472 for b in &no_align {
1473 check_consistency(a, b);
1474 }
1475 }
1476 for a in &align {
1477 for b in &align {
1478 check_consistency(a, b);
1479 }
1480 }
1481
1482 // Relative indent computation makes no sense if the alignment differs
1483 assert_eq!(
1484 align[0].relative_indent(
1485 &no_align[0],
1486 RopeSlice::from(" "),
1487 &indent_style,
1488 tab_width
1489 ),
1490 None
1491 );
1492 assert_eq!(
1493 align[0].relative_indent(
1494 &different_align,
1495 RopeSlice::from(" "),
1496 &indent_style,
1497 tab_width
1498 ),
1499 None
1500 );
1501 }
1502 }