Skip to main content

hjkl_buffer/
edit.rs

1//! Edit operations on [`crate::View`].
2//!
3//! Every mutation goes through [`View::apply_edit`] and returns
4//! the inverse `Edit` so the host can build an undo stack without
5//! snapshotting the whole buffer. Cursor follows edits the way vim
6//! does: insertions land the cursor at the end of the inserted
7//! text; deletions clamp the cursor to the deletion start.
8
9use crate::buffer::{pos_to_char_idx, rope_line_char_count};
10use crate::{Position, View};
11
12/// Granularity of a delete; preserved through undo so a linewise
13/// delete doesn't come back as a charwise one.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum MotionKind {
16    /// Charwise — `[start, end)` byte range, possibly wrapping rows.
17    Char,
18    /// Linewise — whole rows from `start.row..=end.row`. Endpoint
19    /// columns are ignored.
20    Line,
21    /// Blockwise — rectangle `[start.row..=end.row] × [min_col..=max_col]`.
22    Block,
23}
24
25/// One unit of buffer mutation. Constructed by the caller (vim
26/// engine, ex command, …) and handed to [`View::apply_edit`].
27///
28/// ## Invariants
29///
30/// All `Position` arguments must satisfy the bounds documented on
31/// [`Position`] before the edit is applied. Out-of-bounds positions
32/// are clamped by [`View::clamp_position`] inside
33/// [`View::apply_edit`]; if the clamped form changes the edit's
34/// meaning the result is implementation-defined.
35///
36/// See [`View::apply_edit`] for post-conditions that hold after
37/// every variant.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum Edit {
40    /// Insert one char at `at`. Cursor lands one position past it.
41    ///
42    /// `at` must be a valid [`Position`]. `ch` must be a single Unicode
43    /// scalar. Multi-grapheme content must use [`Edit::InsertStr`].
44    InsertChar { at: Position, ch: char },
45    /// Insert `text` (possibly multi-line) at `at`. Cursor lands at
46    /// the end of the inserted content.
47    ///
48    /// `at` must be a valid [`Position`]. `text` may contain `\n` — the
49    /// buffer splits on newline. CR (`\r`) is preserved as-is; the host
50    /// is responsible for CRLF normalization before insert.
51    InsertStr { at: Position, text: String },
52    /// Delete `[start, end)` with the given kind.
53    ///
54    /// `start <= end` in document order. [`MotionKind`] controls whether
55    /// trailing newlines are consumed:
56    ///
57    /// - [`MotionKind::Char`][]: byte-precise; preserves enclosing newlines.
58    /// - [`MotionKind::Line`][]: whole rows from `start.row..=end.row`;
59    ///   endpoint columns are ignored.
60    /// - [`MotionKind::Block`][]: rectangle
61    ///   `[start.row..=end.row] × [min_col..=max_col]`.
62    DeleteRange {
63        start: Position,
64        end: Position,
65        kind: MotionKind,
66    },
67    /// `J` (`with_space = true`) / `gJ` (`false`) — fold `count` rows
68    /// after `row` into `row`.
69    ///
70    /// `row + count - 1` must be a valid row. `count >= 1`.
71    JoinLines {
72        row: usize,
73        count: usize,
74        with_space: bool,
75    },
76    /// Inverse of `JoinLines`. Splits `row` back at each char column
77    /// in `cols`.
78    ///
79    /// `inserted_spaces[i]` records whether the join that produced
80    /// `cols[i]` ACTUALLY inserted a space there — NOT the caller's
81    /// `with_space` intent passed to `JoinLines`, which is uniform for
82    /// the whole (possibly multi-join) batch while the per-join outcome
83    /// is not: `do_join_lines` skips the space whenever either side of
84    /// that specific join is empty. A single bool here (matching the
85    /// original, uniform `with_space` intent) can't tell those joins
86    /// apart from ones that DID insert a space, so `do_split_lines` would
87    /// misidentify — and delete — an unrelated, legitimately-present
88    /// space character that happens to sit at that col (audit-r2 fix 6).
89    /// Parallel to `cols`.
90    SplitLines {
91        row: usize,
92        cols: Vec<usize>,
93        inserted_spaces: Vec<bool>,
94    },
95    /// Replace `[start, end)` with `with` (charwise, may span rows).
96    ///
97    /// Same constraints as [`Edit::DeleteRange`] with
98    /// [`MotionKind::Char`] for the deleted range, plus the insert
99    /// constraints from [`Edit::InsertStr`] for `with`.
100    Replace {
101        start: Position,
102        end: Position,
103        with: String,
104    },
105    /// Insert one chunk per row, each at `(at.row + i, at.col)`.
106    /// Inverse of a blockwise delete; preserves the rectangle even
107    /// when rows are ragged shorter than `at.col`.
108    InsertBlock { at: Position, chunks: Vec<String> },
109    /// Inverse of [`Edit::InsertBlock`]. Removes `widths[i]` chars
110    /// starting at `(at.row + i, at.col)`, plus `pads[i]` more chars
111    /// immediately BEFORE `at.col` on that row. Carrying widths instead
112    /// of recomputing means a ragged-row block delete round-trips
113    /// exactly.
114    ///
115    /// `pads` exists because `do_insert_block` space-pads a row that's
116    /// shorter than `at.col` before splicing the chunk in, so that the
117    /// chunk lands at the intended column; without recording that pad
118    /// width here too, this inverse would remove the chunk but leave the
119    /// padding behind (audit-r2 fix 6). `pads[i]` is always `0` for a row
120    /// that didn't need padding. `DeleteBlockChunks` only ever appears as
121    /// `InsertBlock`'s inverse (never constructed by a "forward" edit —
122    /// see `do_delete_range`'s `MotionKind::Block` arm, which builds its
123    /// own inverse `InsertBlock` directly via `rope_cut_chars`), so this
124    /// field has no bearing on any other call site's semantics.
125    DeleteBlockChunks {
126        at: Position,
127        widths: Vec<usize>,
128        pads: Vec<usize>,
129    },
130}
131
132impl View {
133    /// Apply `edit` and return the inverse. Pushing the inverse back
134    /// through `apply_edit` restores the previous state, making it the
135    /// single hook for undo-stack integration.
136    ///
137    /// `apply_edit` is the **only** way to mutate buffer text.
138    ///
139    /// ## Post-conditions
140    ///
141    /// After any [`Edit`] variant:
142    ///
143    /// - [`View::dirty_gen`] is incremented exactly once.
144    /// - The cursor is repositioned to a sensible place for the edit kind
145    ///   (insert lands past the inserted content; delete lands at the
146    ///   start). Callers that need to override the new cursor must call
147    ///   [`View::set_cursor`] immediately after.
148    /// - All [`Position`] values the caller held from before the edit may
149    ///   be invalid. Re-derive from row / col deltas; do not cache.
150    pub fn apply_edit(&mut self, edit: Edit) -> Edit {
151        match edit {
152            Edit::InsertChar { at, ch } => {
153                // Encode in place — a per-keystroke `String` allocation for a
154                // single char is pure overhead on the insert-mode hot path.
155                let mut buf = [0u8; 4];
156                self.do_insert_str(at, ch.encode_utf8(&mut buf))
157            }
158            Edit::InsertStr { at, text } => self.do_insert_str(at, &text),
159            Edit::DeleteRange { start, end, kind } => self.do_delete_range(start, end, kind),
160            Edit::JoinLines {
161                row,
162                count,
163                with_space,
164            } => self.do_join_lines(row, count, with_space),
165            Edit::SplitLines {
166                row,
167                cols,
168                inserted_spaces,
169            } => self.do_split_lines(row, &cols, &inserted_spaces),
170            Edit::Replace { start, end, with } => self.do_replace(start, end, &with),
171            Edit::InsertBlock { at, chunks } => self.do_insert_block(at, chunks),
172            Edit::DeleteBlockChunks { at, widths, pads } => {
173                self.do_delete_block_chunks(at, &widths, &pads)
174            }
175        }
176    }
177
178    fn do_insert_block(&mut self, at: Position, chunks: Vec<String>) -> Edit {
179        let mut widths: Vec<usize> = Vec::with_capacity(chunks.len());
180        let mut pads: Vec<usize> = Vec::with_capacity(chunks.len());
181        for (i, chunk) in chunks.into_iter().enumerate() {
182            let row = at.row + i;
183            // Pad short rows with spaces so the column position exists
184            // before splicing — same semantics as the old Vec<String> impl.
185            // Recorded in `pads` so the returned DeleteBlockChunks inverse
186            // can remove this padding too, not just the chunk (audit-r2
187            // fix 6): otherwise undoing an InsertBlock that padded a
188            // ragged row leaves the padding behind.
189            let mut pad = 0usize;
190            {
191                let mut c = self.content.lock().unwrap();
192                let n = c.text.len_lines();
193                if row < n {
194                    let lc = rope_line_char_count(&c.text, row);
195                    if lc < at.col {
196                        pad = at.col - lc;
197                        let insert_char_idx = pos_to_char_idx(&c.text, row, lc);
198                        c.text.insert(insert_char_idx, &" ".repeat(pad));
199                    }
200                }
201            }
202            pads.push(pad);
203            widths.push(chunk.chars().count());
204            // Insert chunk at (row, at.col).
205            {
206                let mut c = self.content.lock().unwrap();
207                let n = c.text.len_lines();
208                if row < n {
209                    let char_idx = pos_to_char_idx(&c.text, row, at.col);
210                    c.text.insert(char_idx, &chunk);
211                }
212            }
213        }
214        self.dirty_gen_bump();
215        self.set_cursor(at);
216        Edit::DeleteBlockChunks { at, widths, pads }
217    }
218
219    fn do_delete_block_chunks(&mut self, at: Position, widths: &[usize], pads: &[usize]) -> Edit {
220        let mut chunks: Vec<String> = Vec::with_capacity(widths.len());
221        for (i, &w) in widths.iter().enumerate() {
222            let pad = pads.get(i).copied().unwrap_or(0);
223            let row = at.row + i;
224            let removed = {
225                let mut c = self.content.lock().unwrap();
226                let n = c.text.len_lines();
227                if row >= n {
228                    String::new()
229                } else {
230                    let lc = rope_line_char_count(&c.text, row);
231                    // Remove the pad (immediately before at.col) together
232                    // with the chunk (at.col..at.col+w) in one contiguous
233                    // span — do_insert_block always places them adjacently.
234                    let col_start = at.col.saturating_sub(pad).min(lc);
235                    let col_end = (at.col + w).min(lc);
236                    if col_start >= col_end {
237                        String::new()
238                    } else {
239                        let char_start = pos_to_char_idx(&c.text, row, col_start);
240                        let char_end = pos_to_char_idx(&c.text, row, col_end);
241                        let removed_span: String = c.text.slice(char_start..char_end).to_string();
242                        c.text.remove(char_start..char_end);
243                        // Discard the pad portion from the returned chunk —
244                        // it's regenerated automatically by do_insert_block
245                        // if this inverse is itself later undone (redo).
246                        let pad_end = at.col.min(lc);
247                        let pad_len = pad_end.saturating_sub(col_start);
248                        removed_span.chars().skip(pad_len).collect()
249                    }
250                }
251            };
252            chunks.push(removed);
253        }
254        self.dirty_gen_bump();
255        self.set_cursor(at);
256        Edit::InsertBlock { at, chunks }
257    }
258
259    fn do_insert_str(&mut self, at: Position, text: &str) -> Edit {
260        let normalised = self.clamp_position(at);
261        let inserted_chars = text.chars().count();
262        let inserted_lines = text.split('\n').count();
263        let end = if inserted_lines > 1 {
264            let last_chars = text.rsplit('\n').next().unwrap_or("").chars().count();
265            Position::new(normalised.row + inserted_lines - 1, last_chars)
266        } else {
267            Position::new(normalised.row, normalised.col + inserted_chars)
268        };
269        {
270            let mut c = self.content.lock().unwrap();
271            let char_idx = pos_to_char_idx(&c.text, normalised.row, normalised.col);
272            c.text.insert(char_idx, text);
273        }
274        self.dirty_gen_bump();
275        self.set_cursor(end);
276        Edit::DeleteRange {
277            start: normalised,
278            end,
279            kind: MotionKind::Char,
280        }
281    }
282
283    fn do_delete_range(&mut self, start: Position, end: Position, kind: MotionKind) -> Edit {
284        let (start, end) = order(start, end);
285        match kind {
286            MotionKind::Char => {
287                let removed = {
288                    let mut c = self.content.lock().unwrap();
289                    rope_cut_chars(&mut c.text, start, end)
290                };
291                self.dirty_gen_bump();
292                self.set_cursor(start);
293                Edit::InsertStr {
294                    at: start,
295                    text: removed,
296                }
297            }
298            MotionKind::Line => {
299                let (_removed_text, inverse_at, inverse_text, new_cursor) = {
300                    let mut c = self.content.lock().unwrap();
301                    let n = c.text.len_lines();
302                    // Clamp BOTH endpoints. An unclamped `lo` past the last
303                    // row underflows the `hi - lo + 1` capacity below and
304                    // panics `line_to_char(lo)`.
305                    let lo = start.row.min(n.saturating_sub(1));
306                    let hi = end.row.min(n.saturating_sub(1));
307
308                    // Collect the removed rows as a joined string (needed for inverse).
309                    let mut removed_lines: Vec<String> = Vec::with_capacity(hi - lo + 1);
310                    for r in lo..=hi {
311                        removed_lines.push(crate::buffer::rope_line_str(&c.text, r));
312                    }
313
314                    // Compute char range to remove.
315                    // When hi is not the last row, we take [line_to_char(lo), line_to_char(hi+1)).
316                    // When hi IS the last row and lo>0, we also remove the '\n' that ends
317                    // row lo-1 so we don't leave a trailing newline orphan.
318                    // When removing everything (lo==0, hi==last), take [0, len_chars()).
319                    let (remove_start, remove_end) = if hi + 1 < n {
320                        // Normal case: rows lo..=hi followed by more rows.
321                        // char range = [line_to_char(lo), line_to_char(hi+1))
322                        (c.text.line_to_char(lo), c.text.line_to_char(hi + 1))
323                    } else if lo > 0 {
324                        // hi is the last row AND there are rows before lo.
325                        // Remove the '\n' that ended row lo-1 as well.
326                        (c.text.line_to_char(lo) - 1, c.text.len_chars())
327                    } else {
328                        // Removing everything (lo==0, hi==last).
329                        (0, c.text.len_chars())
330                    };
331
332                    // Capture the exact removed span BEFORE removing. The
333                    // inverse must re-insert byte-for-byte what was cut, and
334                    // ropey's unicode line splitting separates on `\r`,
335                    // `\r\n`, U+000B, U+000C, U+0085, U+2028 and U+2029 as
336                    // well as `\n` — a join rebuilt with `'\n'` would rewrite
337                    // those separators and undo would restore a different
338                    // buffer. (`removed_joined` below keeps the `\n`-joined
339                    // register form, which vim-style registers expect.)
340                    let removed_span: String = if remove_start == remove_end {
341                        String::new()
342                    } else {
343                        c.text.slice(remove_start..remove_end).to_string()
344                    };
345                    c.text.remove(remove_start..remove_end);
346                    // ropey guarantees len_lines() >= 1 (empty rope = 1 line).
347
348                    let n2 = c.text.len_lines();
349                    let target_row = lo.min(n2.saturating_sub(1));
350                    let removed_joined = if remove_start == remove_end {
351                        // True no-op: zero chars removed (linewise delete on
352                        // an already-empty buffer — the only shape where the
353                        // range collapses). Joining the lone empty row and
354                        // appending the '\n' terminator would fabricate "\n"
355                        // out of nothing; callers then record that phantom
356                        // text into the unnamed register, where vim leaves
357                        // registers untouched (#280 follow-up).
358                        String::new()
359                    } else {
360                        let mut s = removed_lines.join("\n");
361                        // Add trailing '\n' so the register form reads like
362                        // vim's `dd` register (lines joined with '\n').
363                        s.push('\n');
364                        s
365                    };
366                    // The inverse text is the exact removed span, so its
367                    // shape follows the three `(remove_start, remove_end)`
368                    // branches above:
369                    //
370                    // - `lo > 0 && hi + 1 == n` (last-row delete with rows
371                    //   above): the removed span starts with the separator
372                    //   that ended row lo-1 (its trailing `\n` for a CRLF
373                    //   row — the `\r` stays in the surviving row), so the
374                    //   inverse is a leading-separator insert at the end of
375                    //   the new last row (row lo-1). The trailing-separator
376                    //   form targeted at (lo, 0) would reference a row that
377                    //   no longer exists.
378                    // - `lo == 0 && hi + 1 == n` (whole buffer): the removed
379                    //   span is the entire rope; re-inserting it at (0, 0)
380                    //   restores it exactly, separators included.
381                    // - `hi + 1 < n` (rows survive below): the surviving rows
382                    //   must be pushed back down, so inserting the span at
383                    //   (lo, 0) is exact.
384                    let (inverse_at, inverse_text) = if lo > 0 && hi + 1 == n {
385                        let last_row_chars = c.text.line(lo - 1).len_chars();
386                        (Position::new(lo - 1, last_row_chars), removed_span)
387                    } else if hi + 1 == n {
388                        (Position::new(0, 0), removed_span)
389                    } else {
390                        (Position::new(lo, 0), removed_span)
391                    };
392                    (
393                        removed_joined,
394                        inverse_at,
395                        inverse_text,
396                        Position::new(target_row, 0),
397                    )
398                };
399                self.dirty_gen_bump();
400                self.set_cursor(new_cursor);
401                Edit::InsertStr {
402                    at: inverse_at,
403                    text: inverse_text,
404                }
405            }
406            MotionKind::Block => {
407                let (left, right) = (start.col.min(end.col), start.col.max(end.col));
408                let mut chunks: Vec<String> = Vec::with_capacity(end.row - start.row + 1);
409                for row in start.row..=end.row {
410                    let removed = {
411                        let mut c = self.content.lock().unwrap();
412                        let n = c.text.len_lines();
413                        if row >= n {
414                            String::new()
415                        } else {
416                            let row_start_pos = Position::new(row, left);
417                            let row_end_pos = Position::new(row, right + 1);
418                            rope_cut_chars(&mut c.text, row_start_pos, row_end_pos)
419                        }
420                    };
421                    chunks.push(removed);
422                }
423                self.dirty_gen_bump();
424                self.set_cursor(Position::new(start.row, left));
425                Edit::InsertBlock {
426                    at: Position::new(start.row, left),
427                    chunks,
428                }
429            }
430        }
431    }
432
433    fn do_join_lines(&mut self, row: usize, count: usize, with_space: bool) -> Edit {
434        let count = count.max(1);
435        let (actual_row, split_cols, inserted_spaces) = {
436            let mut c = self.content.lock().unwrap();
437            let n = c.text.len_lines();
438            let row = row.min(n.saturating_sub(1));
439            let mut split_cols: Vec<usize> = Vec::with_capacity(count);
440            // Per-join outcome (did THIS join actually insert a space),
441            // NOT the uniform `with_space` intent — see the field doc on
442            // `Edit::SplitLines::inserted_spaces` (audit-r2 fix 6).
443            let mut inserted_spaces: Vec<bool> = Vec::with_capacity(count);
444
445            for _ in 0..count {
446                let n2 = c.text.len_lines();
447                if row + 1 >= n2 {
448                    break;
449                }
450                // Current length of row (in chars, sans '\n').
451                let join_col = rope_line_char_count(&c.text, row);
452                split_cols.push(join_col);
453
454                // The '\n' that ends row is at char index line_to_char(row) + join_col.
455                let newline_char = c.text.line_to_char(row) + join_col;
456                // Remove the '\n'.
457                c.text.remove(newline_char..newline_char + 1);
458
459                // Now row and (what was row+1) are merged. Insert space if needed.
460                let mut this_inserted_space = false;
461                if with_space {
462                    // After removing '\n', the join_col chars of original row are
463                    // followed immediately by the next row's content.
464                    // Insert space only if both sides are non-empty.
465                    let merged_len = rope_line_char_count(&c.text, row);
466                    let prefix_empty = join_col == 0;
467                    let suffix_empty = join_col >= merged_len;
468                    if !prefix_empty && !suffix_empty {
469                        // Insert space at newline_char (now the join point).
470                        c.text.insert_char(newline_char, ' ');
471                        this_inserted_space = true;
472                        // Adjust future split_cols: the space shifts subsequent
473                        // join points by 1, but split_cols[i] is the char count
474                        // of the original row *before* this join, which doesn't
475                        // need adjustment — the SplitLines inverse uses it to
476                        // split the joined line at the right position.
477                    }
478                }
479                inserted_spaces.push(this_inserted_space);
480            }
481            (row, split_cols, inserted_spaces)
482        };
483        self.dirty_gen_bump();
484        self.set_cursor(Position::new(actual_row, 0));
485        Edit::SplitLines {
486            row: actual_row,
487            cols: split_cols,
488            inserted_spaces,
489        }
490    }
491
492    fn do_split_lines(&mut self, row: usize, cols: &[usize], inserted_spaces: &[bool]) -> Edit {
493        let actual_row = {
494            let mut c = self.content.lock().unwrap();
495            let n = c.text.len_lines();
496            let row = row.min(n.saturating_sub(1));
497
498            // Split right-to-left so each col still indexes into the
499            // original char positions on the surviving prefix.
500            for (idx, &col) in cols.iter().enumerate().rev() {
501                let mut split_col = col;
502                // Per-col: did the ORIGINAL join at this position actually
503                // insert a space? (Not a uniform flag — see the
504                // `Edit::SplitLines` field doc, audit-r2 fix 6.)
505                if inserted_spaces.get(idx).copied().unwrap_or(false) {
506                    // The original join inserted a space at `col`, so the
507                    // current content has a space at position `col` which
508                    // we need to remove before inserting the '\n'.
509                    let lc = rope_line_char_count(&c.text, row);
510                    if split_col < lc {
511                        let space_char_idx = c.text.line_to_char(row) + split_col;
512                        // Check if char at split_col is a space.
513                        let ch = c.text.char(space_char_idx);
514                        if ch == ' ' {
515                            c.text.remove(space_char_idx..space_char_idx + 1);
516                        }
517                    }
518                    // split_col stays the same — the '\n' goes at the same
519                    // position (we removed the space, so col is still correct).
520                } else {
521                    let lc = rope_line_char_count(&c.text, row);
522                    split_col = split_col.min(lc);
523                }
524
525                // Insert '\n' at (row, split_col).
526                let char_idx = c.text.line_to_char(row) + split_col;
527                c.text.insert_char(char_idx, '\n');
528            }
529
530            row
531        };
532        self.dirty_gen_bump();
533        self.set_cursor(Position::new(actual_row, 0));
534        Edit::JoinLines {
535            row: actual_row,
536            count: cols.len(),
537            // Reconstructing a single with_space intent for redo: true iff
538            // ANY col in this batch actually inserted a space. When none
539            // did, redoing with with_space=false reproduces the identical
540            // result anyway (do_join_lines would skip every space here
541            // too), so this is a safe, behavior-preserving collapse.
542            with_space: inserted_spaces.iter().any(|&b| b),
543        }
544    }
545
546    fn do_replace(&mut self, start: Position, end: Position, with: &str) -> Edit {
547        let (start, end) = order(start, end);
548        let removed = {
549            let mut c = self.content.lock().unwrap();
550            rope_cut_chars(&mut c.text, start, end)
551        };
552        let normalised = self.clamp_position(start);
553        let inserted_chars = with.chars().count();
554        let inserted_lines = with.split('\n').count();
555        let new_end = if inserted_lines > 1 {
556            let last_chars = with.rsplit('\n').next().unwrap_or("").chars().count();
557            Position::new(normalised.row + inserted_lines - 1, last_chars)
558        } else {
559            Position::new(normalised.row, normalised.col + inserted_chars)
560        };
561        {
562            let mut c = self.content.lock().unwrap();
563            let char_idx = pos_to_char_idx(&c.text, normalised.row, normalised.col);
564            c.text.insert(char_idx, with);
565        }
566        self.dirty_gen_bump();
567        self.set_cursor(new_end);
568        Edit::Replace {
569            start: normalised,
570            end: new_end,
571            with: removed,
572        }
573    }
574}
575
576// ── Internals — char surgery (free functions over &mut ropey::Rope) ──
577
578/// Remove `[start, end)` (charwise) from the rope and return the
579/// removed text as a `String` (with `\n` between rows).
580///
581/// `start` and `end` carry `(row, col)` where `col` is a char index
582/// within the line. The function converts them to absolute char indices,
583/// removes the range, and returns the removed text.
584fn rope_cut_chars(rope: &mut ropey::Rope, start: Position, end: Position) -> String {
585    let (start, end) = order(start, end);
586    let n = rope.len_lines();
587
588    // Clamp to rope bounds.
589    let start_row = start.row.min(n.saturating_sub(1));
590    let start_col = {
591        let lc = crate::buffer::rope_line_char_count(rope, start_row);
592        start.col.min(lc)
593    };
594    let end_row = end.row.min(n.saturating_sub(1));
595    let end_col = {
596        let lc = crate::buffer::rope_line_char_count(rope, end_row);
597        end.col.min(lc)
598    };
599
600    let char_start = rope.line_to_char(start_row) + start_col;
601    let char_end = rope.line_to_char(end_row) + end_col;
602
603    if char_start >= char_end {
604        return String::new();
605    }
606
607    let removed: String = rope.slice(char_start..char_end).to_string();
608    rope.remove(char_start..char_end);
609    removed
610}
611
612fn order(a: Position, b: Position) -> (Position, Position) {
613    if a <= b { (a, b) } else { (b, a) }
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619    use crate::buffer::rope_line_str;
620
621    fn round_trip_check(initial: &str, edit: Edit) {
622        let mut b = View::from_str(initial);
623        let snapshot_before = b.as_string();
624        let inverse = b.apply_edit(edit);
625        b.apply_edit(inverse);
626        assert_eq!(b.as_string(), snapshot_before);
627    }
628
629    #[test]
630    fn insert_char_round_trip() {
631        round_trip_check(
632            "abc",
633            Edit::InsertChar {
634                at: Position::new(0, 1),
635                ch: 'X',
636            },
637        );
638    }
639
640    #[test]
641    fn insert_str_multiline_round_trip() {
642        round_trip_check(
643            "abc\ndef",
644            Edit::InsertStr {
645                at: Position::new(0, 2),
646                text: "X\nY\nZ".into(),
647            },
648        );
649    }
650
651    #[test]
652    fn delete_charwise_single_row_round_trip() {
653        round_trip_check(
654            "alpha bravo charlie",
655            Edit::DeleteRange {
656                start: Position::new(0, 6),
657                end: Position::new(0, 11),
658                kind: MotionKind::Char,
659            },
660        );
661    }
662
663    #[test]
664    fn delete_charwise_multi_row_round_trip() {
665        round_trip_check(
666            "row0\nrow1\nrow2",
667            Edit::DeleteRange {
668                start: Position::new(0, 2),
669                end: Position::new(2, 2),
670                kind: MotionKind::Char,
671            },
672        );
673    }
674
675    #[test]
676    fn delete_linewise_round_trip() {
677        round_trip_check(
678            "a\nb\nc\nd",
679            Edit::DeleteRange {
680                start: Position::new(1, 0),
681                end: Position::new(2, 0),
682                kind: MotionKind::Line,
683            },
684        );
685    }
686
687    #[test]
688    fn delete_blockwise_round_trip() {
689        round_trip_check(
690            "abcdef\nghijkl\nmnopqr",
691            Edit::DeleteRange {
692                start: Position::new(0, 1),
693                end: Position::new(2, 3),
694                kind: MotionKind::Block,
695            },
696        );
697    }
698
699    #[test]
700    fn join_lines_with_space_round_trip() {
701        round_trip_check(
702            "first\nsecond\nthird",
703            Edit::JoinLines {
704                row: 0,
705                count: 2,
706                with_space: true,
707            },
708        );
709    }
710
711    #[test]
712    fn join_lines_no_space_round_trip() {
713        round_trip_check(
714            "first\nsecond",
715            Edit::JoinLines {
716                row: 0,
717                count: 1,
718                with_space: false,
719            },
720        );
721    }
722
723    #[test]
724    fn replace_round_trip() {
725        round_trip_check(
726            "foo bar baz",
727            Edit::Replace {
728                start: Position::new(0, 4),
729                end: Position::new(0, 7),
730                with: "QUUX".into(),
731            },
732        );
733    }
734
735    // ── Block-op / split-lines round trips (audit-r2 fix 6) ──────────────────
736    //
737    // These inverses are dead today — nothing currently chains
738    // apply(edit) -> apply(inverse) for InsertBlock/DeleteBlockChunks or a
739    // JoinLines/SplitLines pair with mixed per-join outcomes — but the
740    // contract (`apply_edit` returns an inverse that restores the pre-edit
741    // text exactly) must hold the day something does.
742
743    #[test]
744    fn insert_block_round_trip_uniform_rows() {
745        round_trip_check(
746            "ab\ncd\nef",
747            Edit::InsertBlock {
748                at: Position::new(0, 1),
749                chunks: vec!["X".into(), "Y".into(), "Z".into()],
750            },
751        );
752    }
753
754    /// `do_insert_block` space-pads a row shorter than `at.col` before
755    /// splicing the chunk in. Round-tripping must remove that padding too,
756    /// not just the chunk — pre-fix, `DeleteBlockChunks`'s inverse only
757    /// carried the chunk width, leaving the padding behind.
758    #[test]
759    fn insert_block_round_trip_pads_short_row() {
760        // Row 1 ("x") is only 1 char; at.col=3 needs 2 chars of padding
761        // before the "Q" chunk lands.
762        round_trip_check(
763            "abcd\nx\nefgh",
764            Edit::InsertBlock {
765                at: Position::new(0, 3),
766                chunks: vec!["P".into(), "Q".into(), "R".into()],
767            },
768        );
769    }
770
771    /// Same as above but EVERY row needs padding, and by different amounts.
772    #[test]
773    fn insert_block_round_trip_ragged_pads_vary_per_row() {
774        round_trip_check(
775            "\na\nab\nabc",
776            Edit::InsertBlock {
777                at: Position::new(0, 3),
778                chunks: vec!["W".into(), "X".into(), "Y".into(), "Z".into()],
779            },
780        );
781    }
782
783    #[test]
784    fn delete_block_chunks_round_trip() {
785        // Constructed directly (DeleteBlockChunks only ever appears in
786        // practice as InsertBlock's returned inverse — see the variant's
787        // doc comment) to round-trip the OTHER direction: does re-inserting
788        // (InsertBlock) restore what DeleteBlockChunks removed?
789        round_trip_check(
790            "abcdef\nghijkl",
791            Edit::DeleteBlockChunks {
792                at: Position::new(0, 1),
793                widths: vec![2, 2],
794                pads: vec![0, 0],
795            },
796        );
797    }
798
799    /// Regression for the exact scenario fix 6 describes: a join with an
800    /// EMPTY prefix (row 0 is blank) skips inserting a space, but the
801    /// pulled-up row legitimately STARTS with its own, unrelated space.
802    /// Pre-fix, `SplitLines`'s single uniform `inserted_space` flag
803    /// couldn't tell "this join skipped the space" from "this join
804    /// inserted one", so splitting back mistook the legitimate leading
805    /// space for the (never-inserted) join space and ate it.
806    #[test]
807    fn join_then_split_empty_prefix_preserves_legitimate_leading_space() {
808        round_trip_check(
809            "\n bar",
810            Edit::JoinLines {
811                row: 0,
812                count: 1,
813                with_space: true,
814            },
815        );
816    }
817
818    /// Same failure mode from the empty-SUFFIX side: the row being joined
819    /// INTO legitimately ends with a space of its own, and the incoming
820    /// (pulled-up) row is empty, so the join skips inserting one.
821    #[test]
822    fn join_then_split_empty_suffix_preserves_legitimate_trailing_space() {
823        round_trip_check(
824            "foo \n",
825            Edit::JoinLines {
826                row: 0,
827                count: 1,
828                with_space: true,
829            },
830        );
831    }
832
833    /// count > 1 with an empty middle line mixes a skipped-space join and a
834    /// real one in the SAME batch — the scenario `content_edit_shape_tests`
835    /// (hjkl-engine) exercises for byte-exactness; here we check the
836    /// simpler round-trip-restores-original-text property instead.
837    #[test]
838    fn join_then_split_multi_count_mixed_spaces_round_trip() {
839        round_trip_check(
840            "foo\n\nbar",
841            Edit::JoinLines {
842                row: 0,
843                count: 2,
844                with_space: true,
845            },
846        );
847    }
848
849    /// Regression: a linewise delete whose START row lies past the last
850    /// buffer row used to underflow `hi - lo + 1` (capacity math) and panic
851    /// `line_to_char(lo)`. Both endpoints must clamp to the last row.
852    #[test]
853    fn delete_linewise_start_past_end_is_clamped() {
854        let mut b = View::from_str("a\nb\nc");
855        b.apply_edit(Edit::DeleteRange {
856            start: Position::new(10, 0),
857            end: Position::new(20, 0),
858            kind: MotionKind::Line,
859        });
860        // Clamps to the last row and removes it.
861        assert_eq!(b.as_string(), "a\nb");
862    }
863
864    #[test]
865    fn delete_clearing_buffer_keeps_one_empty_row() {
866        let mut b = View::from_str("only");
867        b.apply_edit(Edit::DeleteRange {
868            start: Position::new(0, 0),
869            end: Position::new(0, 0),
870            kind: MotionKind::Line,
871        });
872        assert_eq!(b.row_count(), 1);
873        assert_eq!(rope_line_str(&b.rope(), 0), "");
874    }
875
876    /// Regression (#280 follow-up): a linewise delete on an ALREADY-EMPTY
877    /// buffer removes zero chars, so the inverse must carry empty text.
878    /// The old code fabricated "\n" (joined the lone empty row and appended
879    /// a terminator), which callers then recorded into the unnamed register
880    /// — vim leaves registers untouched on a true no-op delete.
881    #[test]
882    fn noop_linewise_delete_on_empty_buffer_has_empty_inverse() {
883        let mut b = View::from_str("");
884        let inv = b.apply_edit(Edit::DeleteRange {
885            start: Position::new(0, 0),
886            end: Position::new(0, 0),
887            kind: MotionKind::Line,
888        });
889        match inv {
890            Edit::InsertStr { text, .. } => {
891                assert_eq!(text, "", "no-op delete must not fabricate \"\\n\"");
892            }
893            other => panic!("expected InsertStr inverse, got {other:?}"),
894        }
895        assert_eq!(b.row_count(), 1);
896        assert_eq!(rope_line_str(&b.rope(), 0), "");
897    }
898
899    /// Regression (non-`\n` line separators): ropey's unicode line splitting
900    /// treats `\r`, U+000B, U+000C, U+0085, U+2028 and U+2029 as line
901    /// separators too, and the linewise-delete inverse used to rebuild the
902    /// removed text from per-row strings joined with `'\n'` — fabricating a
903    /// phantom extra line break after a U+2028 separator (and rewriting `\r`
904    /// as `\n`). The inverse must be the exact removed span so undo restores
905    /// the buffer byte-for-byte.
906    #[test]
907    fn delete_linewise_inverse_is_exact_removed_span_for_non_nl_separators() {
908        for (initial, removed_span) in [
909            ("a\u{2028}b", "a\u{2028}"),
910            ("a\rb", "a\r"),
911            ("a\r\nb", "a\r\n"),
912        ] {
913            let mut b = View::from_str(initial);
914            let inv = b.apply_edit(Edit::DeleteRange {
915                start: Position::new(0, 0),
916                end: Position::new(0, 0),
917                kind: MotionKind::Line,
918            });
919            match &inv {
920                Edit::InsertStr { text, .. } => assert_eq!(
921                    text.as_str(),
922                    removed_span,
923                    "inverse must be the exact removed span for {initial:?}"
924                ),
925                other => panic!("expected InsertStr inverse, got {other:?}"),
926            }
927            b.apply_edit(inv);
928            assert_eq!(b.as_string(), initial, "undo must restore {initial:?}");
929        }
930    }
931
932    /// Same regression from the whole-buffer side: `dd`ing every row must
933    /// restore a U+2028-separated buffer exactly — the old inverse joined the
934    /// rows with `'\n'`, rewriting the separator.
935    #[test]
936    fn delete_linewise_whole_buffer_restores_unicode_separator() {
937        let initial = "a\u{2028}b\u{2028}c";
938        let mut b = View::from_str(initial);
939        let inv = b.apply_edit(Edit::DeleteRange {
940            start: Position::new(0, 0),
941            end: Position::new(2, 0),
942            kind: MotionKind::Line,
943        });
944        match &inv {
945            Edit::InsertStr { text, .. } => assert_eq!(text.as_str(), initial),
946            other => panic!("expected InsertStr inverse, got {other:?}"),
947        }
948        b.apply_edit(inv);
949        assert_eq!(b.as_string(), initial);
950    }
951
952    #[test]
953    fn insert_char_lands_cursor_after() {
954        let mut b = View::from_str("abc");
955        b.set_cursor(Position::new(0, 1));
956        b.apply_edit(Edit::InsertChar {
957            at: Position::new(0, 1),
958            ch: 'X',
959        });
960        assert_eq!(b.cursor(), Position::new(0, 2));
961        assert_eq!(rope_line_str(&b.rope(), 0), "aXbc");
962    }
963
964    #[test]
965    fn block_delete_on_ragged_rows_handles_short_lines() {
966        // Row 1 is shorter than the block right edge — only the
967        // chars that exist get removed.
968        let mut b = View::from_str("longline\nhi\nthird row");
969        let inv = b.apply_edit(Edit::DeleteRange {
970            start: Position::new(0, 2),
971            end: Position::new(2, 5),
972            kind: MotionKind::Block,
973        });
974        b.apply_edit(inv);
975        assert_eq!(b.as_string(), "longline\nhi\nthird row");
976    }
977
978    #[test]
979    fn dirty_gen_bumps_per_edit() {
980        let mut b = View::from_str("abc");
981        let g0 = b.dirty_gen();
982        b.apply_edit(Edit::InsertChar {
983            at: Position::new(0, 0),
984            ch: 'X',
985        });
986        assert_eq!(b.dirty_gen(), g0 + 1);
987        b.apply_edit(Edit::DeleteRange {
988            start: Position::new(0, 0),
989            end: Position::new(0, 1),
990            kind: MotionKind::Char,
991        });
992        assert_eq!(b.dirty_gen(), g0 + 2);
993    }
994
995    /// Regression: a 60 k-row multi-line `InsertStr` into a 60 k-row buffer
996    /// used to call `Vec::insert(insert_at + i, …)` per row → O(N²) memmove.
997    /// With ropey, InsertStr is O(log N + edit_size) — this test confirms it
998    /// stays comfortably under the 200 ms budget.
999    #[test]
1000    // miri interprets rather than executes, so a 60 k-row splice takes orders
1001    // of magnitude longer than the 200 ms budget and would both stall the
1002    // weekly miri job and fail an assertion that says nothing about UB.
1003    #[cfg_attr(miri, ignore = "wall-clock budget is meaningless under miri")]
1004    fn splice_at_60k_paste_at_row_zero_is_under_200ms() {
1005        // View with 60 k rows of empty content.
1006        let initial = "\n".repeat(60_000);
1007        let mut b = View::from_str(&initial);
1008        // Multi-line payload: 60 k "x" lines glued by \n.
1009        let payload = vec!["x"; 60_000].join("\n");
1010        let t = std::time::Instant::now();
1011        b.apply_edit(Edit::InsertStr {
1012            at: Position::new(0, 0),
1013            text: payload,
1014        });
1015        let elapsed = t.elapsed();
1016        assert!(
1017            elapsed.as_millis() < 200,
1018            "60k-row InsertStr took {elapsed:?}; budget 200 ms"
1019        );
1020    }
1021}