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