Skip to main content

rustaco_core/
commands.rs

1//! Editing commands beyond typing and cursor movement: line operations, indentation,
2//! comments, bracket pairs, occurrence selection, case changes.
3
4use std::ops::Range;
5
6use ropey::Rope;
7use unicode_segmentation::UnicodeSegmentation;
8
9use crate::change::{Assoc, ChangeSet, Edit};
10use crate::editor::{Editor, word_at};
11use crate::history::EditKind;
12use crate::position::{char_to_position, line_end, line_len};
13use crate::search::Searcher;
14use crate::selection::{Selection, Selections};
15
16/// Chars on each side of a position examined to find grapheme boundaries. Clusters longer
17/// than this (long emoji ZWJ sequences, stacked combining marks) are split at the window edge.
18const GRAPHEME_WINDOW: usize = 64;
19
20/// The grapheme cluster boundary before `pos` (`\r\n` and emoji sequences count as one).
21pub(crate) fn prev_grapheme(rope: &Rope, pos: usize) -> usize {
22    if pos == 0 {
23        return 0;
24    }
25    let start = pos.saturating_sub(GRAPHEME_WINDOW);
26    let window = rope.slice(start..pos).to_string();
27    let last = window.grapheme_indices(true).next_back().map_or(0, |(i, _)| i);
28    start + window[..last].chars().count()
29}
30
31/// The grapheme cluster boundary after `pos`.
32pub(crate) fn next_grapheme(rope: &Rope, pos: usize) -> usize {
33    let len = rope.len_chars();
34    if pos >= len {
35        return len;
36    }
37    let end = (pos + GRAPHEME_WINDOW).min(len);
38    let window = rope.slice(pos..end).to_string();
39    let first = window.graphemes(true).next().map_or(0, |g| g.chars().count());
40    pos + first.max(1)
41}
42
43/// Chars scanned in each direction when matching brackets by text.
44const BRACKET_SCAN: usize = 50_000;
45
46/// The bracket pair at `pos` found by scanning the text: when the char before `pos` (or at
47/// it) is a bracket from `pairs`, returns the positions of it and its partner, opening first.
48/// Brackets inside strings and comments are counted too; frontends with a syntax tree use the
49/// tree's answer instead.
50pub fn matching_bracket_text(rope: &Rope, pos: usize, pairs: &[(String, String)]) -> Option<(usize, usize)> {
51    let single: Vec<(char, char)> = pairs
52        .iter()
53        .filter_map(|(o, c)| {
54            let (mut oi, mut ci) = (o.chars(), c.chars());
55            match (oi.next(), oi.next(), ci.next(), ci.next()) {
56                (Some(o), None, Some(c), None) if o != c => Some((o, c)),
57                _ => None,
58            }
59        })
60        .collect();
61    let len = rope.len_chars();
62    for at in [pos.checked_sub(1), Some(pos)].into_iter().flatten().filter(|&p| p < len) {
63        let ch = rope.char(at);
64        if let Some(&(open, close)) = single.iter().find(|(o, _)| *o == ch) {
65            let mut depth = 0usize;
66            for (i, c) in rope.chars_at(at).enumerate().take(BRACKET_SCAN) {
67                if c == open {
68                    depth += 1;
69                } else if c == close {
70                    depth -= 1;
71                    if depth == 0 {
72                        return Some((at, at + i));
73                    }
74                }
75            }
76        } else if let Some(&(open, close)) = single.iter().find(|(_, c)| *c == ch) {
77            let mut depth = 0usize;
78            let mut chars = rope.chars_at(at + 1);
79            let mut i = at + 1;
80            while let Some(c) = chars.prev() {
81                i -= 1;
82                if at - i > BRACKET_SCAN {
83                    break;
84                }
85                if c == close {
86                    depth += 1;
87                } else if c == open {
88                    depth -= 1;
89                    if depth == 0 {
90                        return Some((i, at));
91                    }
92                }
93            }
94        }
95    }
96    None
97}
98
99/// Lines touched by the selections, merged into ranges. A selection ending at the start of a
100/// line does not include that line, unless it is empty.
101fn selected_line_ranges(rope: &Rope, selections: &Selections) -> Vec<Range<usize>> {
102    let mut ranges: Vec<Range<usize>> = Vec::new();
103    for s in selections.iter() {
104        let first = rope.char_to_line(s.start());
105        let mut last = rope.char_to_line(s.end());
106        if !s.is_empty() && last > first && s.end() == rope.line_to_char(last) {
107            last -= 1;
108        }
109        match ranges.last_mut() {
110            Some(r) if first <= r.end => r.end = r.end.max(last + 1),
111            _ => ranges.push(first..last + 1),
112        }
113    }
114    ranges
115}
116
117fn indent_of(rope: &Rope, line: usize) -> usize {
118    rope.line(line).chars().take(line_len(rope, line)).take_while(|c| *c == ' ' || *c == '\t').count()
119}
120
121fn is_blank(rope: &Rope, line: usize) -> bool {
122    indent_of(rope, line) == line_len(rope, line)
123}
124
125/// Maps selections through a change, keeping a selection edge at the start of a line there
126/// (so a whole-line selection keeps covering the whole line) and moving other edges past
127/// inserted text.
128fn map_keeping_line_starts(rope_before: &Rope, selections: &Selections, changes: &ChangeSet) -> Selections {
129    let map = |p: usize| {
130        let at_line_start = rope_before.line_to_char(rope_before.char_to_line(p)) == p;
131        changes.map(p, if at_line_start { Assoc::Before } else { Assoc::After })
132    };
133    selections.map(|s| Selection { anchor: map(s.anchor), head: map(s.head), goal_column: None })
134}
135
136impl Editor<'_> {
137    fn eol(&self) -> &'static str {
138        self.model.line_ending.as_str()
139    }
140
141    fn indent_unit(&self) -> String {
142        let o = self.model.options;
143        if o.insert_spaces { " ".repeat(o.tab_size) } else { "\t".to_owned() }
144    }
145
146    /// Tab: indents the selected lines when a selection spans lines, otherwise inserts
147    /// indentation at each cursor.
148    pub fn tab(&mut self) {
149        let rope = &self.model.rope;
150        let multi_line =
151            self.cursors.selections.iter().any(|s| rope.char_to_line(s.start()) != rope.char_to_line(s.end()));
152        if multi_line { self.indent_lines() } else { self.indent() }
153    }
154
155    /// Adds one indentation unit at the start of every selected non-blank line.
156    pub fn indent_lines(&mut self) {
157        let rope = self.model.rope.clone();
158        let unit = self.indent_unit();
159        let edits = selected_line_ranges(&rope, &self.cursors.selections)
160            .into_iter()
161            .flatten()
162            .filter(|&l| !is_blank(&rope, l))
163            .map(|l| Edit::insert(rope.line_to_char(l), unit.clone()))
164            .collect();
165        let changes = ChangeSet::new(edits);
166        let after = map_keeping_line_starts(&rope, &self.cursors.selections, &changes);
167        self.commit(changes, after, EditKind::Other);
168    }
169
170    /// Shift+Tab: removes up to one indentation unit from the start of every selected line.
171    pub fn outdent_lines(&mut self) {
172        let rope = self.model.rope.clone();
173        let tab = self.model.options.tab_size;
174        let edits = selected_line_ranges(&rope, &self.cursors.selections)
175            .into_iter()
176            .flatten()
177            .filter_map(|l| {
178                let start = rope.line_to_char(l);
179                let mut n = 0;
180                for c in rope.line(l).chars().take(tab) {
181                    match c {
182                        ' ' => n += 1,
183                        '\t' => {
184                            n += 1;
185                            break;
186                        }
187                        _ => break,
188                    }
189                }
190                (n > 0).then(|| Edit::delete(start, start + n))
191            })
192            .collect();
193        let changes = ChangeSet::new(edits);
194        let after = self.cursors.selections.map(|s| Selection {
195            anchor: changes.map(s.anchor, Assoc::Before),
196            head: changes.map(s.head, Assoc::Before),
197            goal_column: None,
198        });
199        self.commit(changes, after, EditKind::Other);
200    }
201
202    /// Alt+Up / Alt+Down: moves the selected lines past the line above or below.
203    pub fn move_lines(&mut self, up: bool) {
204        let rope = self.model.rope.clone();
205        let total = rope.len_lines();
206        let eol = self.eol();
207        let mut edits = Vec::new();
208        let mut moves: Vec<(Range<usize>, isize, Range<usize>, isize)> = Vec::new();
209        for block in selected_line_ranges(&rope, &self.cursors.selections) {
210            let (region, other) = if up {
211                if block.start == 0 {
212                    continue;
213                }
214                (block.start - 1..block.end, block.start - 1)
215            } else {
216                if block.end >= total {
217                    continue;
218                }
219                (block.start..block.end + 1, block.end)
220            };
221            let text = |l: usize| rope.line(l).slice(..line_len(&rope, l)).to_string();
222            let block_text: Vec<String> = block.clone().map(text).collect();
223            let other_text = text(other);
224            let mut lines = block_text.clone();
225            if up {
226                lines.push(other_text.clone())
227            } else {
228                lines.insert(0, other_text.clone())
229            }
230            let start = rope.line_to_char(region.start);
231            let end = line_end(&rope, region.end - 1);
232            edits.push(Edit::new(start, end, lines.join(eol)));
233            // Chars inside the block shift by the other line's length (plus a line break),
234            // chars of the other line by the block's length.
235            let eol_len = eol.chars().count() as isize;
236            let other_len = other_text.chars().count() as isize + eol_len;
237            let block_len = block_text.iter().map(|l| l.chars().count() as isize + eol_len).sum::<isize>();
238            let block_chars = rope.line_to_char(block.start)..line_end(&rope, block.end - 1);
239            let other_chars = rope.line_to_char(other)..line_end(&rope, other);
240            if up {
241                moves.push((block_chars, -other_len, other_chars, block_len));
242            } else {
243                moves.push((block_chars, other_len, other_chars, -block_len));
244            }
245        }
246        if edits.is_empty() {
247            return;
248        }
249        let shift = |p: usize| {
250            for (block, db, other, dother) in &moves {
251                if block.contains(&p) || p == block.end {
252                    return p.wrapping_add_signed(*db);
253                }
254                if other.contains(&p) || p == other.end {
255                    return p.wrapping_add_signed(*dother);
256                }
257            }
258            p
259        };
260        let after = self.cursors.selections.map(|s| Selection {
261            anchor: shift(s.anchor),
262            head: shift(s.head),
263            goal_column: s.goal_column,
264        });
265        self.commit(ChangeSet::new(edits), after, EditKind::Other);
266    }
267
268    /// Shift+Alt+Up / Shift+Alt+Down: duplicates the selected lines above or below; the
269    /// selections end up on the copy.
270    pub fn copy_lines(&mut self, up: bool) {
271        let rope = self.model.rope.clone();
272        let eol = self.eol();
273        let eol_len = eol.chars().count();
274        let mut edits = Vec::new();
275        let mut shifts: Vec<(Range<usize>, usize)> = Vec::new();
276        for block in selected_line_ranges(&rope, &self.cursors.selections) {
277            let start = rope.line_to_char(block.start);
278            let end = line_end(&rope, block.end - 1);
279            let text = rope.slice(start..end).to_string();
280            if up {
281                edits.push(Edit::insert(start, format!("{text}{eol}")));
282            } else {
283                shifts.push((start..end + 1, end - start + eol_len));
284                edits.push(Edit::insert(end, format!("{eol}{text}")));
285            }
286        }
287        let changes = ChangeSet::new(edits);
288        let after = self.cursors.selections.map(|s| {
289            let map = |p: usize| {
290                let base = changes.map(p, Assoc::Before);
291                shifts.iter().find(|(r, _)| r.contains(&p)).map_or(base, |(_, d)| base + d)
292            };
293            Selection { anchor: map(s.anchor), head: map(s.head), goal_column: None }
294        });
295        self.commit(changes, after, EditKind::Other);
296    }
297
298    /// Ctrl+Shift+K: deletes the selected lines; cursors keep their column on the next line.
299    pub fn delete_lines(&mut self) {
300        let rope = self.model.rope.clone();
301        let total = rope.len_lines();
302        let mut edits = Vec::new();
303        for block in selected_line_ranges(&rope, &self.cursors.selections) {
304            let (start, end) = if block.end < total {
305                (rope.line_to_char(block.start), rope.line_to_char(block.end))
306            } else if block.start > 0 {
307                (line_end(&rope, block.start - 1), rope.len_chars())
308            } else {
309                (0, rope.len_chars())
310            };
311            edits.push(Edit::delete(start, end));
312        }
313        let changes = ChangeSet::new(edits);
314        let columns: Vec<usize> =
315            self.cursors.selections.iter().map(|s| char_to_position(&rope, s.head).column).collect();
316        let mut after_rope = rope.clone();
317        changes.apply(&mut after_rope);
318        let mut i = 0;
319        let after = self.cursors.selections.map(|s| {
320            let p = changes.map(s.head, Assoc::Before);
321            let line = after_rope.char_to_line(p.min(after_rope.len_chars()));
322            let col = columns[i].min(line_len(&after_rope, line));
323            i += 1;
324            Selection::cursor(after_rope.line_to_char(line) + col)
325        });
326        self.commit(changes, after, EditKind::Other);
327    }
328
329    /// Ctrl+Enter (below) / Ctrl+Shift+Enter (above): opens a new line with the current
330    /// line's indentation and moves the cursor onto it.
331    pub fn insert_line(&mut self, below: bool) {
332        let rope = self.model.rope.clone();
333        let eol = self.eol();
334        let mut edits = Vec::new();
335        let mut carets = Vec::new();
336        let mut delta = 0isize;
337        let mut lines: Vec<usize> = self.cursors.selections.iter().map(|s| rope.char_to_line(s.head)).collect();
338        lines.dedup();
339        for line in lines {
340            let indent: String = rope.line(line).chars().take(indent_of(&rope, line)).collect();
341            let indent_len = indent.chars().count();
342            let eol_len = eol.chars().count();
343            if below {
344                let at = line_end(&rope, line);
345                edits.push(Edit::insert(at, format!("{eol}{indent}")));
346                carets.push(Selection::cursor(at.wrapping_add_signed(delta) + eol_len + indent_len));
347            } else {
348                let at = rope.line_to_char(line);
349                edits.push(Edit::insert(at, format!("{indent}{eol}")));
350                carets.push(Selection::cursor(at.wrapping_add_signed(delta) + indent_len));
351            }
352            delta += (indent_len + eol_len) as isize;
353        }
354        let after = Selections::new(carets, 0);
355        self.commit(ChangeSet::new(edits), after, EditKind::Other);
356    }
357
358    /// Ctrl+/: comments out the selected lines with the language's line comment token, or
359    /// uncomments them when every non-blank one is already commented. Falls back to a block
360    /// comment for languages without line comments.
361    pub fn toggle_line_comment(&mut self) {
362        let Some(token) = self.model.editing.line_comment.clone() else {
363            self.toggle_block_comment();
364            return;
365        };
366        let rope = self.model.rope.clone();
367        let lines: Vec<usize> = selected_line_ranges(&rope, &self.cursors.selections)
368            .into_iter()
369            .flatten()
370            .filter(|&l| !is_blank(&rope, l))
371            .collect();
372        if lines.is_empty() {
373            return;
374        }
375        let token_len = token.chars().count();
376        let starts_with_token = |l: usize| {
377            let start = rope.line_to_char(l) + indent_of(&rope, l);
378            start + token_len <= rope.len_chars() && rope.slice(start..start + token_len) == token.as_str()
379        };
380        let edits = if lines.iter().all(|&l| starts_with_token(l)) {
381            lines
382                .iter()
383                .map(|&l| {
384                    let start = rope.line_to_char(l) + indent_of(&rope, l);
385                    let space = rope.get_char(start + token_len) == Some(' ');
386                    Edit::delete(start, start + token_len + usize::from(space))
387                })
388                .collect()
389        } else {
390            let column = lines.iter().map(|&l| indent_of(&rope, l)).min().unwrap_or(0);
391            lines.iter().map(|&l| Edit::insert(rope.line_to_char(l) + column, format!("{token} "))).collect()
392        };
393        let changes = ChangeSet::new(edits);
394        let after = map_keeping_line_starts(&rope, &self.cursors.selections, &changes);
395        self.commit(changes, after, EditKind::Other);
396    }
397
398    /// Shift+Alt+A: wraps each selection in the language's block comment tokens, keeping the
399    /// selection on the wrapped text, or removes the tokens when they sit just inside or just
400    /// outside the selection.
401    pub fn toggle_block_comment(&mut self) {
402        let Some((open, close)) = self.model.editing.block_comment.clone() else { return };
403        let rope = self.model.rope.clone();
404        let (open_len, close_len) = (open.chars().count(), close.chars().count());
405        let len = rope.len_chars();
406        let matches = |at: usize, token: &str, n: usize| at + n <= len && rope.slice(at..at + n) == token;
407        let mut edits = Vec::new();
408        let mut wrapped = Vec::new();
409        for s in self.cursors.selections.iter() {
410            // Tokens just outside the selection, optionally separated by one space.
411            let before = |gap: usize| {
412                s.start()
413                    .checked_sub(open_len + gap)
414                    .filter(|&at| matches(at, &open, open_len) && (gap == 0 || rope.char(s.start() - 1) == ' '))
415            };
416            let after = |gap: usize| {
417                Some(s.end() + gap)
418                    .filter(|&at| matches(at, &close, close_len) && (gap == 0 || rope.get_char(s.end()) == Some(' ')))
419            };
420            let outside = before(1)
421                .zip(after(1))
422                .map(|(o, c)| (o, open_len + 1, c - 1, close_len + 1))
423                .or_else(|| before(0).zip(after(0)).map(|(o, c)| (o, open_len, c, close_len)));
424            // Tokens just inside it.
425            let text = rope.slice(s.start()..s.end()).to_string();
426            let lead = text.chars().take_while(|c| c.is_whitespace()).count();
427            let trail = text.chars().rev().take_while(|c| c.is_whitespace()).count();
428            let inside = (text.trim().chars().count() >= open_len + close_len
429                && matches(s.start() + lead, &open, open_len)
430                && matches(s.end() - trail - close_len, &close, close_len))
431            .then(|| {
432                let open_at = s.start() + lead;
433                let close_at = s.end() - trail - close_len;
434                let space_open = rope.get_char(open_at + open_len) == Some(' ') && open_at + open_len < close_at;
435                let space_close = close_at > open_at + open_len && rope.get_char(close_at - 1) == Some(' ');
436                (
437                    open_at,
438                    open_len + usize::from(space_open),
439                    close_at - usize::from(space_close),
440                    close_len + usize::from(space_close),
441                )
442            });
443            match outside.or(inside) {
444                Some((open_at, open_n, close_at, close_n)) => {
445                    edits.push(Edit::delete(open_at, open_at + open_n));
446                    edits.push(Edit::delete(close_at, close_at + close_n));
447                    wrapped.push(false);
448                }
449                None => {
450                    edits.push(Edit::insert(s.start(), format!("{open} ")));
451                    edits.push(Edit::insert(s.end(), format!(" {close}")));
452                    wrapped.push(true);
453                }
454            }
455        }
456        let changes = ChangeSet::new(edits);
457        let mut i = 0;
458        let after = self.cursors.selections.map(|s| {
459            let wrap = wrapped[i];
460            i += 1;
461            // After wrapping, the selection stays on the wrapped text, inside the tokens.
462            let (start_assoc, end_assoc) =
463                if wrap { (Assoc::After, Assoc::Before) } else { (Assoc::Before, Assoc::Before) };
464            if s.is_empty() && wrap {
465                // Both tokens went in at one point and merged into one edit; land between them.
466                Selection::cursor(changes.map(s.head, Assoc::Before) + open_len + 1)
467            } else if s.is_empty() {
468                Selection::cursor(changes.map(s.head, start_assoc))
469            } else {
470                let (a, b) = (changes.map(s.start(), start_assoc), changes.map(s.end(), end_assoc));
471                if s.is_backward() { Selection::new(b, a) } else { Selection::new(a, b) }
472            }
473        });
474        self.commit(changes, after, EditKind::Other);
475    }
476
477    /// Types one char with bracket handling: an opening char of an auto-closing pair inserts
478    /// the pair (or wraps a selection in it), a closing char steps over the same char after
479    /// the cursor. Other chars are typed as usual.
480    pub fn type_char(&mut self, c: char) {
481        self.type_char_in(c, false);
482    }
483
484    /// Like [`Editor::type_char`]; inside a string or comment (`in_literal`) no pair is
485    /// opened, but a closing char still steps over the same char after the cursor.
486    pub fn type_char_in(&mut self, c: char, in_literal: bool) {
487        let mut pairs = self.model.editing.auto_closing.clone();
488        if in_literal {
489            // No pair opens; closing chars keep stepping over.
490            pairs.iter_mut().for_each(|(open, _)| open.clear());
491        }
492        let mut buf = [0u8; 4];
493        let typed: &str = c.encode_utf8(&mut buf);
494        let open_pair = pairs.iter().find(|(o, _)| o == typed).cloned();
495        let closes = pairs.iter().any(|(_, cl)| cl == typed);
496        if open_pair.is_none() && !closes {
497            self.insert(typed);
498            return;
499        }
500        let rope = self.model.rope.clone();
501        let mut edits = Vec::new();
502        let mut after = Vec::new();
503        let mut delta = 0isize;
504        for s in self.cursors.selections.iter() {
505            let next = rope.get_char(s.head);
506            let prev = s.head.checked_sub(1).and_then(|i| rope.get_char(i));
507            let at = |p: usize, d: isize| p.wrapping_add_signed(d);
508            if s.is_empty() && closes && next == Some(c) {
509                // Step over the closing char that is already there.
510                after.push(Selection::cursor(at(s.head, delta) + 1));
511                continue;
512            }
513            match &open_pair {
514                Some((open, close)) if !s.is_empty() => {
515                    edits.push(Edit::insert(s.start(), open.clone()));
516                    edits.push(Edit::insert(s.end(), close.clone()));
517                    let (a, b) = (at(s.start(), delta) + 1, at(s.end(), delta) + 1);
518                    after.push(if s.is_backward() { Selection::new(b, a) } else { Selection::new(a, b) });
519                    delta += 2;
520                }
521                Some((open, close)) => {
522                    let quote = open == close;
523                    let next_ok = next.is_none_or(|n| {
524                        n.is_whitespace() || pairs.iter().any(|(_, cl)| cl.starts_with(n)) || ",;".contains(n)
525                    });
526                    let prev_ok = !quote || prev.is_none_or(|p| !(p.is_alphanumeric() || p == '_' || p == c));
527                    if next_ok && prev_ok {
528                        edits.push(Edit::insert(s.head, format!("{open}{close}")));
529                        after.push(Selection::cursor(at(s.head, delta) + 1));
530                        delta += 2;
531                    } else {
532                        edits.push(Edit::insert(s.head, open.clone()));
533                        after.push(Selection::cursor(at(s.head, delta) + 1));
534                        delta += 1;
535                    }
536                }
537                None => {
538                    edits.push(Edit::new(s.start(), s.end(), typed));
539                    after.push(Selection::cursor(at(s.start(), delta) + 1));
540                    delta += 1 - s.len() as isize;
541                }
542            }
543        }
544        let after = Selections::new(after, self.cursors.selections.primary_index());
545        self.commit(ChangeSet::new(edits), after, EditKind::Typing);
546    }
547
548    /// Backspace that also removes the closing half of an empty auto-closing pair.
549    pub fn delete_backward_pair(&mut self) {
550        let pairs = self.model.editing.auto_closing.clone();
551        let rope = &self.model.rope;
552        let in_empty_pair = |s: &Selection| {
553            s.is_empty()
554                && s.head > 0
555                && pairs.iter().any(|(o, c)| {
556                    let (o, c) = (o.chars().collect::<Vec<_>>(), c.chars().collect::<Vec<_>>());
557                    o.len() == 1
558                        && c.len() == 1
559                        && rope.get_char(s.head - 1) == Some(o[0])
560                        && rope.get_char(s.head) == Some(c[0])
561                })
562        };
563        if !self.cursors.selections.iter().any(in_empty_pair) {
564            self.delete_backward();
565            return;
566        }
567        let flags: Vec<bool> = self.cursors.selections.iter().map(in_empty_pair).collect();
568        let mut i = 0;
569        self.delete_each_pub(EditKind::Deleting, |rope, s| {
570            let pair = flags[i];
571            i += 1;
572            if !s.is_empty() {
573                (s.start(), s.end())
574            } else if pair {
575                (s.head - 1, s.head + 1)
576            } else {
577                (prev_grapheme(rope, s.head), s.head)
578            }
579        });
580    }
581
582    /// Ctrl+D: selects the word at the cursor, or adds the next occurrence of the primary
583    /// selection's text as a new selection (wrapping at the end of the document).
584    pub fn add_next_occurrence(&mut self) {
585        let rope = self.model.rope.clone();
586        let primary = self.cursors.selections.primary();
587        if primary.is_empty() {
588            let (a, b) = word_at(&rope, primary.head);
589            if a < b {
590                let mut ranges = self.cursors.selections.as_slice().to_vec();
591                ranges[self.cursors.selections.primary_index()] = Selection::new(a, b);
592                self.set_selections(Selections::new(ranges, self.cursors.selections.primary_index()));
593            }
594            return;
595        }
596        let needle: String = rope.slice(primary.start()..primary.end()).to_string();
597        let text = rope.to_string();
598        let taken: Vec<(usize, usize)> = self.cursors.selections.iter().map(|s| (s.start(), s.end())).collect();
599        let last_end = taken.iter().map(|&(_, e)| e).max().unwrap_or(0);
600        let byte_of = |c: usize| rope.char_to_byte(c);
601        let from = byte_of(last_end);
602        let candidates = text[from..]
603            .match_indices(&needle)
604            .map(|(i, _)| i + from)
605            .chain(text[..from].match_indices(&needle).map(|(i, _)| i));
606        for b in candidates {
607            let start = rope.byte_to_char(b);
608            let end = start + primary.len();
609            if !taken.iter().any(|&(s, e)| s < end && start < e) {
610                let mut ranges = self.cursors.selections.as_slice().to_vec();
611                ranges.push(Selection::new(start, end));
612                let primary_index = ranges.len() - 1;
613                self.set_selections(Selections::new(ranges, primary_index));
614                return;
615            }
616        }
617    }
618
619    /// Ctrl+Shift+L: selects every occurrence of the primary selection's text (or of the word
620    /// at the cursor).
621    pub fn select_all_occurrences(&mut self) {
622        let rope = self.model.rope.clone();
623        let primary = self.cursors.selections.primary();
624        let (a, b) = if primary.is_empty() { word_at(&rope, primary.head) } else { (primary.start(), primary.end()) };
625        if a == b {
626            return;
627        }
628        let needle: String = rope.slice(a..b).to_string();
629        let text = rope.to_string();
630        let len = b - a;
631        let ranges: Vec<Selection> = text
632            .match_indices(&needle)
633            .map(|(i, _)| {
634                let start = rope.byte_to_char(i);
635                Selection::new(start, start + len)
636            })
637            .collect();
638        let primary_index = ranges.iter().position(|s| s.start() == a).unwrap_or(0);
639        self.set_selections(Selections::new(ranges, primary_index));
640    }
641
642    /// Expands the primary selection to the smallest of `ranges` (syntax node ranges from the
643    /// language module, innermost first) that contains it and is larger. The previous
644    /// selections are kept for [`Editor::shrink_selection`].
645    pub fn expand_selection(&mut self, ranges: &[Range<usize>]) -> bool {
646        let primary = self.cursors.selections.primary();
647        let (a, b) = (primary.start(), primary.end());
648        let Some(next) = ranges.iter().find(|r| r.start <= a && b <= r.end && r.len() > b - a) else { return false };
649        let before = self.cursors.selections.clone();
650        self.set_selections(Selections::single(Selection::new(next.start, next.end)));
651        self.cursors.expansions.push(before);
652        true
653    }
654
655    /// Goes back to the selections before the last [`Editor::expand_selection`].
656    pub fn shrink_selection(&mut self) -> bool {
657        match self.cursors.expansions.pop() {
658            Some(prev) => {
659                let expansions = std::mem::take(&mut self.cursors.expansions);
660                self.set_selections(prev);
661                self.cursors.expansions = expansions;
662                true
663            }
664            None => false,
665        }
666    }
667
668    /// Converts the selected text (or the word at each cursor) to upper or lower case.
669    pub fn transform_case(&mut self, upper: bool) {
670        let rope = self.model.rope.clone();
671        let mut edits = Vec::new();
672        let mut after = Vec::new();
673        let mut delta = 0isize;
674        for s in self.cursors.selections.iter() {
675            let (a, b) = if s.is_empty() { word_at(&rope, s.head) } else { (s.start(), s.end()) };
676            let text = rope.slice(a..b).to_string();
677            let new = if upper { text.to_uppercase() } else { text.to_lowercase() };
678            let new_len = new.chars().count();
679            let (na, nb) = (a.wrapping_add_signed(delta), a.wrapping_add_signed(delta) + new_len);
680            after.push(if s.is_empty() {
681                Selection::cursor(s.head.wrapping_add_signed(delta).min(nb))
682            } else if s.is_backward() {
683                Selection::new(nb, na)
684            } else {
685                Selection::new(na, nb)
686            });
687            delta += new_len as isize - (b - a) as isize;
688            edits.push(Edit::new(a, b, new));
689        }
690        let after = Selections::new(after, self.cursors.selections.primary_index());
691        self.commit(ChangeSet::new(edits), after, EditKind::Other);
692    }
693
694    /// Removes spaces and tabs at the end of every line.
695    pub fn trim_trailing_whitespace(&mut self) {
696        let rope = self.model.rope.clone();
697        let edits = (0..rope.len_lines())
698            .filter_map(|l| {
699                let end = line_end(&rope, l);
700                let start = rope.line_to_char(l);
701                let mut from = end;
702                while from > start && matches!(rope.char(from - 1), ' ' | '\t') {
703                    from -= 1;
704                }
705                (from < end).then(|| Edit::delete(from, end))
706            })
707            .collect();
708        let changes = ChangeSet::new(edits);
709        let after = self.cursors.selections.map(|s| Selection {
710            anchor: changes.map(s.anchor, Assoc::Before),
711            head: changes.map(s.head, Assoc::Before),
712            goal_column: None,
713        });
714        self.commit(changes, after, EditKind::Other);
715    }
716}
717
718impl Editor<'_> {
719    /// Replaces every match of `searcher` with `replacement` (capture groups in regex mode)
720    /// as one undo step. Returns the number of replacements.
721    pub fn replace_all(&mut self, searcher: &Searcher, replacement: &str, regex_mode: bool) -> usize {
722        let rope = self.model.rope.clone();
723        let matches = searcher.find_all(&rope, None);
724        let edits: Vec<Edit> = matches
725            .iter()
726            .map(|m| Edit::new(m.start, m.end, searcher.replacement_for(&rope, m.clone(), replacement, regex_mode)))
727            .collect();
728        let count = edits.len();
729        let changes = ChangeSet::new(edits);
730        let after = self.cursors.selections.map(|s| Selection::cursor(changes.map(s.head, Assoc::Before)));
731        self.commit(changes, after, EditKind::Other);
732        count
733    }
734
735    /// Selects every match of `searcher` (Alt+Enter in the find widget).
736    pub fn select_matches(&mut self, searcher: &Searcher) -> usize {
737        let matches = searcher.find_all(&self.model.rope, None);
738        if !matches.is_empty() {
739            let ranges = matches.iter().map(|m| Selection::new(m.start, m.end)).collect();
740            self.set_selections(Selections::new(ranges, 0));
741        }
742        matches.len()
743    }
744}
745
746impl Editor<'_> {
747    /// Runs a command by its id (VS Code's names). Returns false for ids the core does not
748    /// handle; frontends run those themselves (page movement needs the view, clipboard
749    /// commands need the platform clipboard).
750    pub fn run(&mut self, command: &str) -> bool {
751        match command {
752            "jumpToNextSnippetPlaceholder" => return self.next_snippet_stop(),
753            "jumpToPrevSnippetPlaceholder" => return self.prev_snippet_stop(),
754            "leaveSnippet" => {
755                let active = self.snippet().is_some();
756                self.end_snippet();
757                return active;
758            }
759            "cursorLeft" => self.move_left(false),
760            "cursorLeftSelect" => self.move_left(true),
761            "cursorRight" => self.move_right(false),
762            "cursorRightSelect" => self.move_right(true),
763            "cursorUp" => self.move_up(false),
764            "cursorUpSelect" => self.move_up(true),
765            "cursorDown" => self.move_down(false),
766            "cursorDownSelect" => self.move_down(true),
767            "cursorWordLeft" => self.move_word_left(false),
768            "cursorWordLeftSelect" => self.move_word_left(true),
769            "cursorWordRight" => self.move_word_right(false),
770            "cursorWordRightSelect" => self.move_word_right(true),
771            "cursorHome" => self.move_line_start(false),
772            "cursorHomeSelect" => self.move_line_start(true),
773            "cursorEnd" => self.move_line_end(false),
774            "cursorEndSelect" => self.move_line_end(true),
775            "cursorTop" => self.move_document_start(false),
776            "cursorTopSelect" => self.move_document_start(true),
777            "cursorBottom" => self.move_document_end(false),
778            "cursorBottomSelect" => self.move_document_end(true),
779            "deleteLeft" => self.delete_backward_pair(),
780            "deleteRight" => self.delete_forward(),
781            "deleteWordLeft" => self.delete_word_backward(),
782            "deleteWordRight" => self.delete_word_forward(),
783            "editor.action.newline" => self.newline(),
784            "tab" => self.tab(),
785            "outdent" | "editor.action.outdentLines" => self.outdent_lines(),
786            "editor.action.indentLines" => self.indent_lines(),
787            "editor.action.selectAll" => self.select_all(),
788            "undo" => {
789                self.undo();
790            }
791            "redo" => {
792                self.redo();
793            }
794            "removeSecondaryCursors" => {
795                let primary = self.cursors.selections.primary();
796                self.set_selections(Selections::single(primary));
797            }
798            "cancelSelection" => {
799                let primary = self.cursors.selections.primary();
800                self.set_selections(Selections::single(Selection::cursor(primary.head)));
801            }
802            "cursorUndo" => {
803                self.cursor_undo();
804            }
805            "editor.action.insertCursorAbove" => self.add_cursor_vertical(false),
806            "editor.action.insertCursorBelow" => self.add_cursor_vertical(true),
807            "editor.action.moveLinesUpAction" => self.move_lines(true),
808            "editor.action.moveLinesDownAction" => self.move_lines(false),
809            "editor.action.copyLinesUpAction" => self.copy_lines(true),
810            "editor.action.copyLinesDownAction" => self.copy_lines(false),
811            "editor.action.deleteLines" => self.delete_lines(),
812            "editor.action.insertLineAfter" => self.insert_line(true),
813            "editor.action.insertLineBefore" => self.insert_line(false),
814            "editor.action.commentLine" => self.toggle_line_comment(),
815            "editor.action.blockComment" => self.toggle_block_comment(),
816            "editor.action.addSelectionToNextFindMatch" => self.add_next_occurrence(),
817            "editor.action.selectHighlights" => self.select_all_occurrences(),
818            "editor.action.transformToUppercase" => self.transform_case(true),
819            "editor.action.transformToLowercase" => self.transform_case(false),
820            "editor.action.trimTrailingWhitespace" => self.trim_trailing_whitespace(),
821            _ => return false,
822        }
823        true
824    }
825}