Skip to main content

gpui_base/input/editor/
indent.rs

1use crate::input::{EditorLineNumberRenderer, InputModeKind};
2use crate::input::{
3    Indent, IndentInline, InputBaseState, Outdent, OutdentInline, RopeExt, cursor::CursorSelection,
4    element::TextElement, layout::LastLayout, mode::LayoutMode,
5};
6use gpui::{
7    Bounds, Context, Hsla, Path, PathBuilder, Pixels, SharedString, TextRun, TextStyle, Window,
8    point, px,
9};
10use ropey::RopeSlice;
11
12#[derive(Debug, Copy, Clone)]
13pub struct TabSize {
14    /// Default is 2
15    pub tab_size: usize,
16    /// Set true to use `\t` as tab indent, default is false
17    pub hard_tabs: bool,
18}
19
20impl Default for TabSize {
21    fn default() -> Self {
22        Self {
23            tab_size: 2,
24            hard_tabs: false,
25        }
26    }
27}
28
29impl TabSize {
30    pub(super) fn to_string(&self) -> SharedString {
31        if self.hard_tabs {
32            "\t".into()
33        } else {
34            " ".repeat(self.tab_size).into()
35        }
36    }
37
38    /// Count the indent size of the line in spaces.
39    pub fn indent_count(&self, line: &RopeSlice) -> usize {
40        let mut count = 0;
41        for ch in line.chars() {
42            match ch {
43                '\t' => {
44                    if self.tab_size > 0 {
45                        count += self.tab_size - count % self.tab_size;
46                    }
47                }
48                ' ' => count += 1,
49                _ => break,
50            }
51        }
52        count
53    }
54}
55
56impl LayoutMode {
57    /// Whether this layout indents blocks.
58    ///
59    /// Callers gate this on the input being multi-line: indenting a one-line
60    /// text field has nothing to indent.
61    #[inline]
62    pub(super) fn is_indentable(&self) -> bool {
63        matches!(
64            self,
65            LayoutMode::PlainText { .. } | LayoutMode::CodeEditor { .. }
66        )
67    }
68
69    #[inline]
70    pub(super) fn has_indent_guides(&self) -> bool {
71        match self {
72            LayoutMode::CodeEditor { indent_guides, .. } => *indent_guides,
73            _ => false,
74        }
75    }
76
77    #[inline]
78    pub(super) fn tab_size(&self) -> TabSize {
79        match self {
80            LayoutMode::PlainText { tab, .. } => *tab,
81            LayoutMode::CodeEditor { tab, .. } => *tab,
82            _ => TabSize::default(),
83        }
84    }
85}
86
87impl<M: InputModeKind, R: EditorLineNumberRenderer> TextElement<M, R> {
88    /// Measure the indent width in pixels for given column count.
89    fn measure_indent_width(&self, style: &TextStyle, column: usize, window: &Window) -> Pixels {
90        let font_size = style.font_size.to_pixels(window.rem_size());
91        let layout = window.text_system().shape_line(
92            SharedString::from(" ".repeat(column)),
93            font_size,
94            &[TextRun {
95                len: column,
96                font: style.font(),
97                color: Hsla::default(),
98                background_color: None,
99                strikethrough: None,
100                underline: None,
101            }],
102            None,
103        );
104
105        layout.width
106    }
107
108    pub(super) fn layout_indent_guides(
109        &self,
110        state: &InputBaseState<M>,
111        bounds: &Bounds<Pixels>,
112        last_layout: &LastLayout,
113        text_style: &TextStyle,
114        window: &mut Window,
115    ) -> Option<Path> {
116        if !state.is_multi_line() || !state.mode.has_indent_guides() {
117            return None;
118        }
119
120        let indent_width =
121            self.measure_indent_width(text_style, state.mode.tab_size().tab_size, window);
122
123        let tab_size = state.mode.tab_size();
124        let line_height = last_layout.line_height;
125        let mut builder = PathBuilder::stroke(px(1.));
126        let mut offset_y = last_layout.visible_top;
127        let mut last_indents = vec![];
128
129        for (ix, (&buffer_line, line_layout)) in last_layout
130            .visible_buffer_lines
131            .iter()
132            .zip(last_layout.lines.iter())
133            .enumerate()
134        {
135            let (spacer_above, spacer_below) = last_layout.spacers(ix);
136            offset_y += spacer_above;
137            let line = state.text.slice_line(buffer_line);
138            let mut current_indents = vec![];
139            if line.len() > 0 {
140                let indent_count = tab_size.indent_count(&line);
141                for offset in (0..indent_count).step_by(tab_size.tab_size) {
142                    let x = if indent_count > 0 {
143                        indent_width * offset as f32 / tab_size.tab_size as f32
144                    } else {
145                        px(0.)
146                    };
147
148                    let pos = point(x + last_layout.text_origin_x, offset_y);
149
150                    builder.move_to(pos);
151                    builder.line_to(point(pos.x, pos.y + line_height));
152                    current_indents.push(pos.x);
153                }
154            } else if last_indents.len() > 0 {
155                for x in &last_indents {
156                    let pos = point(*x, offset_y);
157                    builder.move_to(pos);
158                    builder.line_to(point(pos.x, pos.y + line_height));
159                }
160                current_indents = last_indents.clone();
161            }
162
163            offset_y += line_layout.wrapped_lines.len() * line_height + spacer_below;
164            last_indents = current_indents;
165        }
166
167        builder.translate(bounds.origin);
168        let path = builder.build().unwrap();
169        Some(path)
170    }
171}
172
173/// Indent guides are a code-editor affordance.
174impl InputBaseState<crate::input::EditorMode> {
175    /// Set whether to show indent guides, default is true.
176    #[doc(hidden)]
177    pub fn indent_guides(mut self, indent_guides: bool) -> Self {
178        if let LayoutMode::CodeEditor {
179            indent_guides: l, ..
180        } = &mut self.mode
181        {
182            *l = indent_guides;
183        }
184        self
185    }
186
187    /// Set indent guides at runtime.
188    pub fn set_indent_guides(
189        &mut self,
190        indent_guides: bool,
191        _: &mut Window,
192        cx: &mut Context<Self>,
193    ) {
194        if let LayoutMode::CodeEditor {
195            indent_guides: l, ..
196        } = &mut self.mode
197        {
198            *l = indent_guides;
199        }
200        cx.notify();
201    }
202}
203
204impl<M: InputModeKind> InputBaseState<M> {
205    pub(super) fn indent_inline(
206        &mut self,
207        _: &IndentInline,
208        window: &mut Window,
209        cx: &mut Context<Self>,
210    ) {
211        // First, try to accept inline completion if present
212        if M::accept_inline_completion(self, window, cx) {
213            return;
214        }
215        self.indent(false, window, cx);
216    }
217
218    pub(super) fn indent_block(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
219        self.indent(true, window, cx);
220    }
221
222    pub(super) fn outdent_inline(
223        &mut self,
224        _: &OutdentInline,
225        window: &mut Window,
226        cx: &mut Context<Self>,
227    ) {
228        self.outdent(false, window, cx);
229    }
230
231    pub(super) fn outdent_block(
232        &mut self,
233        _: &Outdent,
234        window: &mut Window,
235        cx: &mut Context<Self>,
236    ) {
237        self.outdent(true, window, cx);
238    }
239
240    pub(super) fn indent(&mut self, block: bool, window: &mut Window, cx: &mut Context<Self>) {
241        self.apply_indent(IndentDirection::Indent, block, window, cx);
242    }
243
244    pub(super) fn outdent(&mut self, block: bool, window: &mut Window, cx: &mut Context<Self>) {
245        self.apply_indent(IndentDirection::Outdent, block, window, cx);
246    }
247
248    /// Apply an indent or outdent across all selections as one batch edit.
249    ///
250    /// A batch keeps the whole operation a single undo transaction (instead of
251    /// one push per line) and restores the correct multi-selection extents on
252    /// undo/redo.
253    fn apply_indent(
254        &mut self,
255        direction: IndentDirection,
256        block: bool,
257        window: &mut Window,
258        cx: &mut Context<Self>,
259    ) {
260        if !self.is_editable() || !self.is_multi_line() || !self.mode.is_indentable() {
261            cx.propagate();
262            return;
263        }
264
265        let tab_indent = self.mode.tab_size().to_string();
266        let tab_len = tab_indent.len();
267
268        // Non-collapsed selections and explicit block operations indent whole lines.
269        let has_non_collapsed = self.selections.iter().any(|sel| !sel.is_collapsed());
270        let use_block = has_non_collapsed || block;
271
272        let before: Vec<CursorSelection> = self.selections.iter().copied().collect();
273
274        let (edits, new_selections) = if use_block {
275            self.compute_block_indent(direction, &tab_indent, tab_len)
276        } else {
277            self.compute_inline_indent(direction, tab_len)
278        };
279
280        if edits.is_empty() {
281            return;
282        }
283
284        self.undo_manager.begin_transaction();
285        self.replace_text_in_ranges(&edits, window, cx);
286        self.selections.replace_all(new_selections);
287        let after: Vec<CursorSelection> = self.selections.iter().copied().collect();
288        self.undo_manager.record_selections(before, after);
289        self.undo_manager.commit_transaction();
290
291        self.scroll_to(self.cursor(), None, cx);
292        cx.notify();
293    }
294
295    /// Build the per-line edits and resulting selections for a block
296    /// indent/outdent across every selection.
297    fn compute_block_indent(
298        &self,
299        direction: IndentDirection,
300        tab_indent: &str,
301        tab_len: usize,
302    ) -> (Vec<(std::ops::Range<usize>, String)>, Vec<CursorSelection>) {
303        let mut rows: std::collections::HashSet<usize> = std::collections::HashSet::new();
304        for sel in self.selections.iter() {
305            let start_row = self.text.offset_to_point(sel.start).row;
306            let end_row = self.text.offset_to_point(sel.end).row;
307            for row in start_row..=end_row {
308                rows.insert(row);
309            }
310        }
311
312        let mut rows: Vec<usize> = rows.into_iter().collect();
313        rows.sort_unstable();
314
315        let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();
316        for row in rows {
317            let line_start = self.text.line_start_offset(row);
318            match direction {
319                IndentDirection::Indent => {
320                    edits.push((line_start..line_start, tab_indent.to_string()));
321                }
322                IndentDirection::Outdent => {
323                    if self
324                        .text
325                        .slice(line_start..)
326                        .chars()
327                        .take(tab_indent.chars().count())
328                        .eq(tab_indent.chars())
329                    {
330                        edits.push((line_start..line_start + tab_len, String::new()));
331                    }
332                }
333            }
334        }
335
336        // Map both endpoints through every earlier edit, including edits belonging
337        // to other cursors. A point inside removed indentation stays on its line.
338        let map_offset = |offset: usize| match direction {
339            IndentDirection::Indent => {
340                offset + edits.partition_point(|(range, _)| range.start <= offset) * tab_len
341            }
342            IndentDirection::Outdent => {
343                let preceding = edits.partition_point(|(range, _)| range.end <= offset);
344                let partial = edits
345                    .get(preceding)
346                    .map_or(0, |(range, _)| offset.saturating_sub(range.start));
347                offset - preceding * tab_len - partial
348            }
349        };
350        let new_selections = self
351            .selections
352            .iter()
353            .map(|sel| {
354                let mut selection = *sel;
355                selection.start = map_offset(sel.start);
356                selection.end = map_offset(sel.end);
357                selection.column_anchor = None;
358                selection
359            })
360            .collect();
361
362        (edits, new_selections)
363    }
364
365    /// Build the per-cursor edits and resulting cursors for a collapsed inline
366    /// indent/outdent.
367    fn compute_inline_indent(
368        &self,
369        direction: IndentDirection,
370        tab_len: usize,
371    ) -> (Vec<(std::ops::Range<usize>, String)>, Vec<CursorSelection>) {
372        let tab_indent = self.mode.tab_size().to_string();
373
374        // The edit range for each cursor: an insertion point for indent, the
375        // removed range for a removable outdent.
376        let mut ranges: Vec<std::ops::Range<usize>> = Vec::with_capacity(self.selections.len());
377        for sel in self.selections.iter() {
378            let cursor = sel.cursor_offset();
379            match direction {
380                IndentDirection::Indent => ranges.push(cursor..cursor),
381                IndentDirection::Outdent => {
382                    let row = self.text.offset_to_point(cursor).row;
383                    let start = self.text.line_start_offset(row);
384                    if self
385                        .text
386                        .slice(start..)
387                        .chars()
388                        .take(tab_indent.chars().count())
389                        .eq(tab_indent.chars())
390                    {
391                        ranges.push(start..start + tab_len);
392                    }
393                }
394            }
395        }
396
397        // Build disjoint edits, dropping any that would overlap a previous one.
398        ranges.sort_by_key(|range| range.start);
399        let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();
400        let mut last_end: Option<usize> = None;
401        for range in ranges {
402            if let Some(last_end) = last_end {
403                if range.start < last_end {
404                    continue;
405                }
406            }
407            last_end = Some(range.end);
408            let text = match direction {
409                IndentDirection::Indent => tab_indent.to_string(),
410                IndentDirection::Outdent => String::new(),
411            };
412            edits.push((range, text));
413        }
414
415        // Shift every cursor by the surviving edits before (or at) it. Cursors
416        // whose own edit was dropped or not applicable keep their position.
417        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(self.selections.len());
418        for sel in self.selections.iter() {
419            let cursor = sel.cursor_offset();
420            let new_offset = match direction {
421                IndentDirection::Indent => {
422                    let inserted_before = edits
423                        .iter()
424                        .filter(|(range, _)| range.start <= cursor)
425                        .count();
426                    cursor + inserted_before * tab_len
427                }
428                IndentDirection::Outdent => {
429                    let removed_before: usize = edits
430                        .iter()
431                        .map(|(range, _)| range.end.min(cursor) - range.start.min(cursor))
432                        .sum();
433                    cursor - removed_before
434                }
435            };
436            let mut selection = CursorSelection::new(sel.id, new_offset, new_offset);
437            selection.column_anchor = None;
438            new_selections.push(selection);
439        }
440
441        (edits, new_selections)
442    }
443}
444
445#[derive(Debug, Copy, Clone, PartialEq)]
446enum IndentDirection {
447    Indent,
448    Outdent,
449}
450
451#[cfg(test)]
452mod tests {
453    use ropey::RopeSlice;
454
455    use super::TabSize;
456
457    #[test]
458    fn test_tab_size() {
459        let tab = TabSize {
460            tab_size: 2,
461            hard_tabs: false,
462        };
463        assert_eq!(tab.to_string(), "  ");
464        let tab = TabSize {
465            tab_size: 4,
466            hard_tabs: false,
467        };
468        assert_eq!(tab.to_string(), "    ");
469
470        let tab = TabSize {
471            tab_size: 2,
472            hard_tabs: true,
473        };
474        assert_eq!(tab.to_string(), "\t");
475        let tab = TabSize {
476            tab_size: 4,
477            hard_tabs: true,
478        };
479        assert_eq!(tab.to_string(), "\t");
480    }
481
482    #[test]
483    fn test_tab_size_indent_count() {
484        let tab = TabSize {
485            tab_size: 4,
486            hard_tabs: false,
487        };
488        assert_eq!(tab.indent_count(&RopeSlice::from("abc")), 0);
489        assert_eq!(tab.indent_count(&RopeSlice::from("  abc")), 2);
490        assert_eq!(tab.indent_count(&RopeSlice::from("    abc")), 4);
491        assert_eq!(tab.indent_count(&RopeSlice::from("\tabc")), 4);
492        assert_eq!(tab.indent_count(&RopeSlice::from("  \tabc")), 4);
493        assert_eq!(tab.indent_count(&RopeSlice::from(" \t abc  ")), 5);
494        assert_eq!(tab.indent_count(&RopeSlice::from(" \t \tabc")), 8);
495        assert_eq!(tab.indent_count(&RopeSlice::from("    \tabc")), 8);
496        assert_eq!(tab.indent_count(&RopeSlice::from("abc")), 0);
497    }
498}
499
500/// Tab size only means something where there is more than one line to indent.
501impl<M: crate::input::MultiLineMode> InputBaseState<M> {
502    /// Set the tab size for the input.
503    #[doc(hidden)]
504    pub fn tab_size(mut self, tab: TabSize) -> Self {
505        match &mut self.mode {
506            LayoutMode::PlainText { tab: t, .. } => *t = tab,
507            LayoutMode::CodeEditor { tab: t, .. } => *t = tab,
508            _ => {}
509        }
510        self
511    }
512
513    pub fn set_tab_size(&mut self, tab: TabSize, cx: &mut Context<Self>) {
514        match &mut self.mode {
515            LayoutMode::PlainText { tab: value, .. }
516            | LayoutMode::CodeEditor { tab: value, .. } => *value = tab,
517            _ => {}
518        }
519        cx.notify();
520    }
521}