Skip to main content

gpui_deck/input/editor/
indent.rs

1use crate::input::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> TextElement<M> {
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<Pixels>> {
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 (&buffer_line, line_layout) in last_layout
130            .visible_buffer_lines
131            .iter()
132            .zip(last_layout.lines.iter())
133        {
134            let line = state.text.slice_line(buffer_line);
135            let mut current_indents = vec![];
136            if line.len() > 0 {
137                let indent_count = tab_size.indent_count(&line);
138                for offset in (0..indent_count).step_by(tab_size.tab_size) {
139                    let x = if indent_count > 0 {
140                        indent_width * offset as f32 / tab_size.tab_size as f32
141                    } else {
142                        px(0.)
143                    };
144
145                    let pos = point(x + last_layout.line_number_width, offset_y);
146
147                    builder.move_to(pos);
148                    builder.line_to(point(pos.x, pos.y + line_height));
149                    current_indents.push(pos.x);
150                }
151            } else if last_indents.len() > 0 {
152                for x in &last_indents {
153                    let pos = point(*x, offset_y);
154                    builder.move_to(pos);
155                    builder.line_to(point(pos.x, pos.y + line_height));
156                }
157                current_indents = last_indents.clone();
158            }
159
160            offset_y += line_layout.wrapped_lines.len() * line_height;
161            last_indents = current_indents;
162        }
163
164        builder.translate(bounds.origin);
165        let path = builder.build().unwrap();
166        Some(path)
167    }
168}
169
170/// Indent guides are a code-editor affordance.
171impl InputBaseState<crate::input::EditorMode> {
172    /// Set whether to show indent guides, default is true.
173    #[doc(hidden)]
174    pub fn indent_guides(mut self, indent_guides: bool) -> Self {
175        if let LayoutMode::CodeEditor {
176            indent_guides: l, ..
177        } = &mut self.mode
178        {
179            *l = indent_guides;
180        }
181        self
182    }
183
184    /// Set indent guides at runtime.
185    pub fn set_indent_guides(
186        &mut self,
187        indent_guides: bool,
188        _: &mut Window,
189        cx: &mut Context<Self>,
190    ) {
191        if let LayoutMode::CodeEditor {
192            indent_guides: l, ..
193        } = &mut self.mode
194        {
195            *l = indent_guides;
196        }
197        cx.notify();
198    }
199}
200
201impl<M: InputModeKind> InputBaseState<M> {
202    pub(super) fn indent_inline(
203        &mut self,
204        _: &IndentInline,
205        window: &mut Window,
206        cx: &mut Context<Self>,
207    ) {
208        // Tab belongs to form navigation in ordinary textareas. Only a code
209        // editor consumes it for indentation or inline completion.
210        if !self.is_code_editor() {
211            cx.propagate();
212            return;
213        }
214        // First, try to accept inline completion if present
215        if M::accept_inline_completion(self, window, cx) {
216            return;
217        }
218        self.indent(false, window, cx);
219    }
220
221    pub(super) fn indent_block(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
222        self.indent(true, window, cx);
223    }
224
225    pub(super) fn outdent_inline(
226        &mut self,
227        _: &OutdentInline,
228        window: &mut Window,
229        cx: &mut Context<Self>,
230    ) {
231        if !self.is_code_editor() {
232            cx.propagate();
233            return;
234        }
235        self.outdent(false, window, cx);
236    }
237
238    pub(super) fn outdent_block(
239        &mut self,
240        _: &Outdent,
241        window: &mut Window,
242        cx: &mut Context<Self>,
243    ) {
244        self.outdent(true, window, cx);
245    }
246
247    pub(super) fn indent(&mut self, block: bool, window: &mut Window, cx: &mut Context<Self>) {
248        self.apply_indent(IndentDirection::Indent, block, window, cx);
249    }
250
251    pub(super) fn outdent(&mut self, block: bool, window: &mut Window, cx: &mut Context<Self>) {
252        self.apply_indent(IndentDirection::Outdent, block, window, cx);
253    }
254
255    /// Apply an indent or outdent across all selections as one batch edit.
256    ///
257    /// A batch keeps the whole operation a single undo transaction (instead of
258    /// one push per line) and restores the correct multi-selection extents on
259    /// undo/redo.
260    fn apply_indent(
261        &mut self,
262        direction: IndentDirection,
263        block: bool,
264        window: &mut Window,
265        cx: &mut Context<Self>,
266    ) {
267        if !self.is_editable() || !self.is_multi_line() || !self.mode.is_indentable() {
268            cx.propagate();
269            return;
270        }
271
272        let tab_indent = self.mode.tab_size().to_string();
273        let tab_len = tab_indent.len();
274
275        // Non-collapsed selections and explicit block operations indent whole lines.
276        let has_non_collapsed = self.selections.iter().any(|sel| !sel.is_collapsed());
277        let use_block = has_non_collapsed || block;
278
279        let before: Vec<CursorSelection> = self.selections.iter().copied().collect();
280
281        let (edits, new_selections) = if use_block {
282            self.compute_block_indent(direction, &tab_indent, tab_len)
283        } else {
284            self.compute_inline_indent(direction, tab_len)
285        };
286
287        if edits.is_empty() {
288            return;
289        }
290
291        self.undo_manager.begin_transaction();
292        self.replace_text_in_ranges(&edits, window, cx);
293        self.selections.replace_all(new_selections);
294        let after: Vec<CursorSelection> = self.selections.iter().copied().collect();
295        self.undo_manager.record_selections(before, after);
296        self.undo_manager.commit_transaction();
297
298        self.scroll_to(self.cursor(), None, cx);
299        cx.notify();
300    }
301
302    /// Build the per-line edits and resulting selections for a block
303    /// indent/outdent across every selection.
304    fn compute_block_indent(
305        &self,
306        direction: IndentDirection,
307        tab_indent: &str,
308        tab_len: usize,
309    ) -> (Vec<(std::ops::Range<usize>, String)>, Vec<CursorSelection>) {
310        let mut rows: std::collections::HashSet<usize> = std::collections::HashSet::new();
311        for sel in self.selections.iter() {
312            let start_row = self.text.offset_to_point(sel.start).row;
313            let end_row = self.text.offset_to_point(sel.end).row;
314            for row in start_row..=end_row {
315                rows.insert(row);
316            }
317        }
318
319        let mut rows: Vec<usize> = rows.into_iter().collect();
320        rows.sort_unstable();
321
322        let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();
323        for row in rows {
324            let line_start = self.text.line_start_offset(row);
325            match direction {
326                IndentDirection::Indent => {
327                    edits.push((line_start..line_start, tab_indent.to_string()));
328                }
329                IndentDirection::Outdent => {
330                    if self
331                        .text
332                        .slice(line_start..)
333                        .chars()
334                        .take(tab_indent.chars().count())
335                        .eq(tab_indent.chars())
336                    {
337                        edits.push((line_start..line_start + tab_len, String::new()));
338                    }
339                }
340            }
341        }
342
343        // Map both endpoints through every earlier edit, including edits belonging
344        // to other cursors. A point inside removed indentation stays on its line.
345        let map_offset = |offset: usize| match direction {
346            IndentDirection::Indent => {
347                offset + edits.partition_point(|(range, _)| range.start <= offset) * tab_len
348            }
349            IndentDirection::Outdent => {
350                let preceding = edits.partition_point(|(range, _)| range.end <= offset);
351                let partial = edits
352                    .get(preceding)
353                    .map_or(0, |(range, _)| offset.saturating_sub(range.start));
354                offset - preceding * tab_len - partial
355            }
356        };
357        let new_selections = self
358            .selections
359            .iter()
360            .map(|sel| {
361                let mut selection = *sel;
362                selection.start = map_offset(sel.start);
363                selection.end = map_offset(sel.end);
364                selection.column_anchor = None;
365                selection
366            })
367            .collect();
368
369        (edits, new_selections)
370    }
371
372    /// Build the per-cursor edits and resulting cursors for a collapsed inline
373    /// indent/outdent.
374    fn compute_inline_indent(
375        &self,
376        direction: IndentDirection,
377        tab_len: usize,
378    ) -> (Vec<(std::ops::Range<usize>, String)>, Vec<CursorSelection>) {
379        let tab_indent = self.mode.tab_size().to_string();
380
381        // The edit range for each cursor: an insertion point for indent, the
382        // removed range for a removable outdent.
383        let mut ranges: Vec<std::ops::Range<usize>> = Vec::with_capacity(self.selections.len());
384        for sel in self.selections.iter() {
385            let cursor = sel.cursor_offset();
386            match direction {
387                IndentDirection::Indent => ranges.push(cursor..cursor),
388                IndentDirection::Outdent => {
389                    let row = self.text.offset_to_point(cursor).row;
390                    let start = self.text.line_start_offset(row);
391                    if self
392                        .text
393                        .slice(start..)
394                        .chars()
395                        .take(tab_indent.chars().count())
396                        .eq(tab_indent.chars())
397                    {
398                        ranges.push(start..start + tab_len);
399                    }
400                }
401            }
402        }
403
404        // Build disjoint edits, dropping any that would overlap a previous one.
405        ranges.sort_by_key(|range| range.start);
406        let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();
407        let mut last_end: Option<usize> = None;
408        for range in ranges {
409            if let Some(last_end) = last_end {
410                if range.start < last_end {
411                    continue;
412                }
413            }
414            last_end = Some(range.end);
415            let text = match direction {
416                IndentDirection::Indent => tab_indent.to_string(),
417                IndentDirection::Outdent => String::new(),
418            };
419            edits.push((range, text));
420        }
421
422        // Shift every cursor by the surviving edits before (or at) it. Cursors
423        // whose own edit was dropped or not applicable keep their position.
424        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(self.selections.len());
425        for sel in self.selections.iter() {
426            let cursor = sel.cursor_offset();
427            let new_offset = match direction {
428                IndentDirection::Indent => {
429                    let inserted_before = edits
430                        .iter()
431                        .filter(|(range, _)| range.start <= cursor)
432                        .count();
433                    cursor + inserted_before * tab_len
434                }
435                IndentDirection::Outdent => {
436                    let removed_before: usize = edits
437                        .iter()
438                        .map(|(range, _)| range.end.min(cursor) - range.start.min(cursor))
439                        .sum();
440                    cursor - removed_before
441                }
442            };
443            let mut selection = CursorSelection::new(sel.id, new_offset, new_offset);
444            selection.column_anchor = None;
445            new_selections.push(selection);
446        }
447
448        (edits, new_selections)
449    }
450}
451
452#[derive(Debug, Copy, Clone, PartialEq)]
453enum IndentDirection {
454    Indent,
455    Outdent,
456}
457
458#[cfg(test)]
459mod tests {
460    use ropey::RopeSlice;
461
462    use super::TabSize;
463
464    #[test]
465    fn test_tab_size() {
466        let tab = TabSize {
467            tab_size: 2,
468            hard_tabs: false,
469        };
470        assert_eq!(tab.to_string(), "  ");
471        let tab = TabSize {
472            tab_size: 4,
473            hard_tabs: false,
474        };
475        assert_eq!(tab.to_string(), "    ");
476
477        let tab = TabSize {
478            tab_size: 2,
479            hard_tabs: true,
480        };
481        assert_eq!(tab.to_string(), "\t");
482        let tab = TabSize {
483            tab_size: 4,
484            hard_tabs: true,
485        };
486        assert_eq!(tab.to_string(), "\t");
487    }
488
489    #[test]
490    fn test_tab_size_indent_count() {
491        let tab = TabSize {
492            tab_size: 4,
493            hard_tabs: false,
494        };
495        assert_eq!(tab.indent_count(&RopeSlice::from("abc")), 0);
496        assert_eq!(tab.indent_count(&RopeSlice::from("  abc")), 2);
497        assert_eq!(tab.indent_count(&RopeSlice::from("    abc")), 4);
498        assert_eq!(tab.indent_count(&RopeSlice::from("\tabc")), 4);
499        assert_eq!(tab.indent_count(&RopeSlice::from("  \tabc")), 4);
500        assert_eq!(tab.indent_count(&RopeSlice::from(" \t abc  ")), 5);
501        assert_eq!(tab.indent_count(&RopeSlice::from(" \t \tabc")), 8);
502        assert_eq!(tab.indent_count(&RopeSlice::from("    \tabc")), 8);
503        assert_eq!(tab.indent_count(&RopeSlice::from("abc")), 0);
504    }
505}
506
507/// Tab size only means something where there is more than one line to indent.
508impl<M: crate::input::MultiLineMode> InputBaseState<M> {
509    /// Set the tab size for the input.
510    #[doc(hidden)]
511    pub fn tab_size(mut self, tab: TabSize) -> Self {
512        match &mut self.mode {
513            LayoutMode::PlainText { tab: t, .. } => *t = tab,
514            LayoutMode::CodeEditor { tab: t, .. } => *t = tab,
515            _ => {}
516        }
517        self
518    }
519
520    pub fn set_tab_size(&mut self, tab: TabSize, cx: &mut Context<Self>) {
521        match &mut self.mode {
522            LayoutMode::PlainText { tab: value, .. }
523            | LayoutMode::CodeEditor { tab: value, .. } => *value = tab,
524            _ => {}
525        }
526        cx.notify();
527    }
528}