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 } => self.do_insert_str(at, ch.to_string()),
153            Edit::InsertStr { at, text } => self.do_insert_str(at, text),
154            Edit::DeleteRange { start, end, kind } => self.do_delete_range(start, end, kind),
155            Edit::JoinLines {
156                row,
157                count,
158                with_space,
159            } => self.do_join_lines(row, count, with_space),
160            Edit::SplitLines {
161                row,
162                cols,
163                inserted_spaces,
164            } => self.do_split_lines(row, cols, inserted_spaces),
165            Edit::Replace { start, end, with } => self.do_replace(start, end, with),
166            Edit::InsertBlock { at, chunks } => self.do_insert_block(at, chunks),
167            Edit::DeleteBlockChunks { at, widths, pads } => {
168                self.do_delete_block_chunks(at, widths, pads)
169            }
170        }
171    }
172
173    fn do_insert_block(&mut self, at: Position, chunks: Vec<String>) -> Edit {
174        let mut widths: Vec<usize> = Vec::with_capacity(chunks.len());
175        let mut pads: Vec<usize> = Vec::with_capacity(chunks.len());
176        for (i, chunk) in chunks.into_iter().enumerate() {
177            let row = at.row + i;
178            // Pad short rows with spaces so the column position exists
179            // before splicing — same semantics as the old Vec<String> impl.
180            // Recorded in `pads` so the returned DeleteBlockChunks inverse
181            // can remove this padding too, not just the chunk (audit-r2
182            // fix 6): otherwise undoing an InsertBlock that padded a
183            // ragged row leaves the padding behind.
184            let mut pad = 0usize;
185            {
186                let mut c = self.content.lock().unwrap();
187                let n = c.text.len_lines();
188                if row < n {
189                    let lc = rope_line_char_count(&c.text, row);
190                    if lc < at.col {
191                        pad = at.col - lc;
192                        let insert_char_idx = pos_to_char_idx(&c.text, row, lc);
193                        c.text.insert(insert_char_idx, &" ".repeat(pad));
194                    }
195                }
196            }
197            pads.push(pad);
198            widths.push(chunk.chars().count());
199            // Insert chunk at (row, at.col).
200            {
201                let mut c = self.content.lock().unwrap();
202                let n = c.text.len_lines();
203                if row < n {
204                    let char_idx = pos_to_char_idx(&c.text, row, at.col);
205                    c.text.insert(char_idx, &chunk);
206                }
207            }
208        }
209        self.dirty_gen_bump();
210        self.set_cursor(at);
211        Edit::DeleteBlockChunks { at, widths, pads }
212    }
213
214    fn do_delete_block_chunks(
215        &mut self,
216        at: Position,
217        widths: Vec<usize>,
218        pads: Vec<usize>,
219    ) -> Edit {
220        let mut chunks: Vec<String> = Vec::with_capacity(widths.len());
221        for (i, w) in widths.into_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: String) -> 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, new_cursor, lo) = {
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(rope_line_str_locked(&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                    c.text.remove(remove_start..remove_end);
333                    // ropey guarantees len_lines() >= 1 (empty rope = 1 line).
334
335                    let n2 = c.text.len_lines();
336                    let target_row = lo.min(n2.saturating_sub(1));
337                    let removed_joined = {
338                        let mut s = removed_lines.join("\n");
339                        // Add trailing '\n' so the inverse InsertStr re-inserts
340                        // correctly (pushes surviving rows down).
341                        s.push('\n');
342                        s
343                    };
344                    (removed_joined, Position::new(target_row, 0), lo)
345                };
346                self.dirty_gen_bump();
347                self.set_cursor(new_cursor);
348                Edit::InsertStr {
349                    at: Position::new(lo, 0),
350                    text: removed_text,
351                }
352            }
353            MotionKind::Block => {
354                let (left, right) = (start.col.min(end.col), start.col.max(end.col));
355                let mut chunks: Vec<String> = Vec::with_capacity(end.row - start.row + 1);
356                for row in start.row..=end.row {
357                    let removed = {
358                        let mut c = self.content.lock().unwrap();
359                        let n = c.text.len_lines();
360                        if row >= n {
361                            String::new()
362                        } else {
363                            let row_start_pos = Position::new(row, left);
364                            let row_end_pos = Position::new(row, right + 1);
365                            rope_cut_chars(&mut c.text, row_start_pos, row_end_pos)
366                        }
367                    };
368                    chunks.push(removed);
369                }
370                self.dirty_gen_bump();
371                self.set_cursor(Position::new(start.row, left));
372                Edit::InsertBlock {
373                    at: Position::new(start.row, left),
374                    chunks,
375                }
376            }
377        }
378    }
379
380    fn do_join_lines(&mut self, row: usize, count: usize, with_space: bool) -> Edit {
381        let count = count.max(1);
382        let (actual_row, split_cols, inserted_spaces) = {
383            let mut c = self.content.lock().unwrap();
384            let n = c.text.len_lines();
385            let row = row.min(n.saturating_sub(1));
386            let mut split_cols: Vec<usize> = Vec::with_capacity(count);
387            // Per-join outcome (did THIS join actually insert a space),
388            // NOT the uniform `with_space` intent — see the field doc on
389            // `Edit::SplitLines::inserted_spaces` (audit-r2 fix 6).
390            let mut inserted_spaces: Vec<bool> = Vec::with_capacity(count);
391
392            for _ in 0..count {
393                let n2 = c.text.len_lines();
394                if row + 1 >= n2 {
395                    break;
396                }
397                // Current length of row (in chars, sans '\n').
398                let join_col = rope_line_char_count(&c.text, row);
399                split_cols.push(join_col);
400
401                // The '\n' that ends row is at char index line_to_char(row) + join_col.
402                let newline_char = c.text.line_to_char(row) + join_col;
403                // Remove the '\n'.
404                c.text.remove(newline_char..newline_char + 1);
405
406                // Now row and (what was row+1) are merged. Insert space if needed.
407                let mut this_inserted_space = false;
408                if with_space {
409                    // After removing '\n', the join_col chars of original row are
410                    // followed immediately by the next row's content.
411                    // Insert space only if both sides are non-empty.
412                    let merged_len = rope_line_char_count(&c.text, row);
413                    let prefix_empty = join_col == 0;
414                    let suffix_empty = join_col >= merged_len;
415                    if !prefix_empty && !suffix_empty {
416                        // Insert space at newline_char (now the join point).
417                        c.text.insert_char(newline_char, ' ');
418                        this_inserted_space = true;
419                        // Adjust future split_cols: the space shifts subsequent
420                        // join points by 1, but split_cols[i] is the char count
421                        // of the original row *before* this join, which doesn't
422                        // need adjustment — the SplitLines inverse uses it to
423                        // split the joined line at the right position.
424                    }
425                }
426                inserted_spaces.push(this_inserted_space);
427            }
428            (row, split_cols, inserted_spaces)
429        };
430        self.dirty_gen_bump();
431        self.set_cursor(Position::new(actual_row, 0));
432        Edit::SplitLines {
433            row: actual_row,
434            cols: split_cols,
435            inserted_spaces,
436        }
437    }
438
439    fn do_split_lines(&mut self, row: usize, cols: Vec<usize>, inserted_spaces: Vec<bool>) -> Edit {
440        let actual_row = {
441            let mut c = self.content.lock().unwrap();
442            let n = c.text.len_lines();
443            let row = row.min(n.saturating_sub(1));
444
445            // Split right-to-left so each col still indexes into the
446            // original char positions on the surviving prefix.
447            for (idx, &col) in cols.iter().enumerate().rev() {
448                let mut split_col = col;
449                // Per-col: did the ORIGINAL join at this position actually
450                // insert a space? (Not a uniform flag — see the
451                // `Edit::SplitLines` field doc, audit-r2 fix 6.)
452                if inserted_spaces.get(idx).copied().unwrap_or(false) {
453                    // The original join inserted a space at `col`, so the
454                    // current content has a space at position `col` which
455                    // we need to remove before inserting the '\n'.
456                    let lc = rope_line_char_count(&c.text, row);
457                    if split_col < lc {
458                        let space_char_idx = c.text.line_to_char(row) + split_col;
459                        // Check if char at split_col is a space.
460                        let ch = c.text.char(space_char_idx);
461                        if ch == ' ' {
462                            c.text.remove(space_char_idx..space_char_idx + 1);
463                        }
464                    }
465                    // split_col stays the same — the '\n' goes at the same
466                    // position (we removed the space, so col is still correct).
467                } else {
468                    let lc = rope_line_char_count(&c.text, row);
469                    split_col = split_col.min(lc);
470                }
471
472                // Insert '\n' at (row, split_col).
473                let char_idx = c.text.line_to_char(row) + split_col;
474                c.text.insert_char(char_idx, '\n');
475            }
476
477            row
478        };
479        self.dirty_gen_bump();
480        self.set_cursor(Position::new(actual_row, 0));
481        Edit::JoinLines {
482            row: actual_row,
483            count: cols.len(),
484            // Reconstructing a single with_space intent for redo: true iff
485            // ANY col in this batch actually inserted a space. When none
486            // did, redoing with with_space=false reproduces the identical
487            // result anyway (do_join_lines would skip every space here
488            // too), so this is a safe, behavior-preserving collapse.
489            with_space: inserted_spaces.iter().any(|&b| b),
490        }
491    }
492
493    fn do_replace(&mut self, start: Position, end: Position, with: String) -> Edit {
494        let (start, end) = order(start, end);
495        let removed = {
496            let mut c = self.content.lock().unwrap();
497            rope_cut_chars(&mut c.text, start, end)
498        };
499        let normalised = self.clamp_position(start);
500        let inserted_chars = with.chars().count();
501        let inserted_lines = with.split('\n').count();
502        let new_end = if inserted_lines > 1 {
503            let last_chars = with.rsplit('\n').next().unwrap_or("").chars().count();
504            Position::new(normalised.row + inserted_lines - 1, last_chars)
505        } else {
506            Position::new(normalised.row, normalised.col + inserted_chars)
507        };
508        {
509            let mut c = self.content.lock().unwrap();
510            let char_idx = pos_to_char_idx(&c.text, normalised.row, normalised.col);
511            c.text.insert(char_idx, &with);
512        }
513        self.dirty_gen_bump();
514        self.set_cursor(new_end);
515        Edit::Replace {
516            start: normalised,
517            end: new_end,
518            with: removed,
519        }
520    }
521}
522
523// ── Internals — char surgery (free functions over &mut ropey::Rope) ──
524
525/// Get logical line `row` as a `String`, stripping trailing `\n`.
526/// Identical to `rope_line_str` but takes a lock guard's rope by ref
527/// (avoids re-importing the pub(crate) helper from buffer.rs inside this module).
528fn rope_line_str_locked(rope: &ropey::Rope, row: usize) -> String {
529    let slice = rope.line(row);
530    let s = slice.to_string();
531    if s.ends_with('\n') {
532        s[..s.len() - 1].to_string()
533    } else {
534        s
535    }
536}
537
538/// Remove `[start, end)` (charwise) from the rope and return the
539/// removed text as a `String` (with `\n` between rows).
540///
541/// `start` and `end` carry `(row, col)` where `col` is a char index
542/// within the line. The function converts them to absolute char indices,
543/// removes the range, and returns the removed text.
544fn rope_cut_chars(rope: &mut ropey::Rope, start: Position, end: Position) -> String {
545    let (start, end) = order(start, end);
546    let n = rope.len_lines();
547
548    // Clamp to rope bounds.
549    let start_row = start.row.min(n.saturating_sub(1));
550    let start_col = {
551        let lc = crate::buffer::rope_line_char_count(rope, start_row);
552        start.col.min(lc)
553    };
554    let end_row = end.row.min(n.saturating_sub(1));
555    let end_col = {
556        let lc = crate::buffer::rope_line_char_count(rope, end_row);
557        end.col.min(lc)
558    };
559
560    let char_start = rope.line_to_char(start_row) + start_col;
561    let char_end = rope.line_to_char(end_row) + end_col;
562
563    if char_start >= char_end {
564        return String::new();
565    }
566
567    let removed: String = rope.slice(char_start..char_end).to_string();
568    rope.remove(char_start..char_end);
569    removed
570}
571
572fn order(a: Position, b: Position) -> (Position, Position) {
573    if a <= b { (a, b) } else { (b, a) }
574}
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579    use crate::buffer::rope_line_str;
580
581    fn round_trip_check(initial: &str, edit: Edit) {
582        let mut b = View::from_str(initial);
583        let snapshot_before = b.as_string();
584        let inverse = b.apply_edit(edit);
585        b.apply_edit(inverse);
586        assert_eq!(b.as_string(), snapshot_before);
587    }
588
589    #[test]
590    fn insert_char_round_trip() {
591        round_trip_check(
592            "abc",
593            Edit::InsertChar {
594                at: Position::new(0, 1),
595                ch: 'X',
596            },
597        );
598    }
599
600    #[test]
601    fn insert_str_multiline_round_trip() {
602        round_trip_check(
603            "abc\ndef",
604            Edit::InsertStr {
605                at: Position::new(0, 2),
606                text: "X\nY\nZ".into(),
607            },
608        );
609    }
610
611    #[test]
612    fn delete_charwise_single_row_round_trip() {
613        round_trip_check(
614            "alpha bravo charlie",
615            Edit::DeleteRange {
616                start: Position::new(0, 6),
617                end: Position::new(0, 11),
618                kind: MotionKind::Char,
619            },
620        );
621    }
622
623    #[test]
624    fn delete_charwise_multi_row_round_trip() {
625        round_trip_check(
626            "row0\nrow1\nrow2",
627            Edit::DeleteRange {
628                start: Position::new(0, 2),
629                end: Position::new(2, 2),
630                kind: MotionKind::Char,
631            },
632        );
633    }
634
635    #[test]
636    fn delete_linewise_round_trip() {
637        round_trip_check(
638            "a\nb\nc\nd",
639            Edit::DeleteRange {
640                start: Position::new(1, 0),
641                end: Position::new(2, 0),
642                kind: MotionKind::Line,
643            },
644        );
645    }
646
647    #[test]
648    fn delete_blockwise_round_trip() {
649        round_trip_check(
650            "abcdef\nghijkl\nmnopqr",
651            Edit::DeleteRange {
652                start: Position::new(0, 1),
653                end: Position::new(2, 3),
654                kind: MotionKind::Block,
655            },
656        );
657    }
658
659    #[test]
660    fn join_lines_with_space_round_trip() {
661        round_trip_check(
662            "first\nsecond\nthird",
663            Edit::JoinLines {
664                row: 0,
665                count: 2,
666                with_space: true,
667            },
668        );
669    }
670
671    #[test]
672    fn join_lines_no_space_round_trip() {
673        round_trip_check(
674            "first\nsecond",
675            Edit::JoinLines {
676                row: 0,
677                count: 1,
678                with_space: false,
679            },
680        );
681    }
682
683    #[test]
684    fn replace_round_trip() {
685        round_trip_check(
686            "foo bar baz",
687            Edit::Replace {
688                start: Position::new(0, 4),
689                end: Position::new(0, 7),
690                with: "QUUX".into(),
691            },
692        );
693    }
694
695    // ── Block-op / split-lines round trips (audit-r2 fix 6) ──────────────────
696    //
697    // These inverses are dead today — nothing currently chains
698    // apply(edit) -> apply(inverse) for InsertBlock/DeleteBlockChunks or a
699    // JoinLines/SplitLines pair with mixed per-join outcomes — but the
700    // contract (`apply_edit` returns an inverse that restores the pre-edit
701    // text exactly) must hold the day something does.
702
703    #[test]
704    fn insert_block_round_trip_uniform_rows() {
705        round_trip_check(
706            "ab\ncd\nef",
707            Edit::InsertBlock {
708                at: Position::new(0, 1),
709                chunks: vec!["X".into(), "Y".into(), "Z".into()],
710            },
711        );
712    }
713
714    /// `do_insert_block` space-pads a row shorter than `at.col` before
715    /// splicing the chunk in. Round-tripping must remove that padding too,
716    /// not just the chunk — pre-fix, `DeleteBlockChunks`'s inverse only
717    /// carried the chunk width, leaving the padding behind.
718    #[test]
719    fn insert_block_round_trip_pads_short_row() {
720        // Row 1 ("x") is only 1 char; at.col=3 needs 2 chars of padding
721        // before the "Q" chunk lands.
722        round_trip_check(
723            "abcd\nx\nefgh",
724            Edit::InsertBlock {
725                at: Position::new(0, 3),
726                chunks: vec!["P".into(), "Q".into(), "R".into()],
727            },
728        );
729    }
730
731    /// Same as above but EVERY row needs padding, and by different amounts.
732    #[test]
733    fn insert_block_round_trip_ragged_pads_vary_per_row() {
734        round_trip_check(
735            "\na\nab\nabc",
736            Edit::InsertBlock {
737                at: Position::new(0, 3),
738                chunks: vec!["W".into(), "X".into(), "Y".into(), "Z".into()],
739            },
740        );
741    }
742
743    #[test]
744    fn delete_block_chunks_round_trip() {
745        // Constructed directly (DeleteBlockChunks only ever appears in
746        // practice as InsertBlock's returned inverse — see the variant's
747        // doc comment) to round-trip the OTHER direction: does re-inserting
748        // (InsertBlock) restore what DeleteBlockChunks removed?
749        round_trip_check(
750            "abcdef\nghijkl",
751            Edit::DeleteBlockChunks {
752                at: Position::new(0, 1),
753                widths: vec![2, 2],
754                pads: vec![0, 0],
755            },
756        );
757    }
758
759    /// Regression for the exact scenario fix 6 describes: a join with an
760    /// EMPTY prefix (row 0 is blank) skips inserting a space, but the
761    /// pulled-up row legitimately STARTS with its own, unrelated space.
762    /// Pre-fix, `SplitLines`'s single uniform `inserted_space` flag
763    /// couldn't tell "this join skipped the space" from "this join
764    /// inserted one", so splitting back mistook the legitimate leading
765    /// space for the (never-inserted) join space and ate it.
766    #[test]
767    fn join_then_split_empty_prefix_preserves_legitimate_leading_space() {
768        round_trip_check(
769            "\n bar",
770            Edit::JoinLines {
771                row: 0,
772                count: 1,
773                with_space: true,
774            },
775        );
776    }
777
778    /// Same failure mode from the empty-SUFFIX side: the row being joined
779    /// INTO legitimately ends with a space of its own, and the incoming
780    /// (pulled-up) row is empty, so the join skips inserting one.
781    #[test]
782    fn join_then_split_empty_suffix_preserves_legitimate_trailing_space() {
783        round_trip_check(
784            "foo \n",
785            Edit::JoinLines {
786                row: 0,
787                count: 1,
788                with_space: true,
789            },
790        );
791    }
792
793    /// count > 1 with an empty middle line mixes a skipped-space join and a
794    /// real one in the SAME batch — the scenario `content_edit_shape_tests`
795    /// (hjkl-engine) exercises for byte-exactness; here we check the
796    /// simpler round-trip-restores-original-text property instead.
797    #[test]
798    fn join_then_split_multi_count_mixed_spaces_round_trip() {
799        round_trip_check(
800            "foo\n\nbar",
801            Edit::JoinLines {
802                row: 0,
803                count: 2,
804                with_space: true,
805            },
806        );
807    }
808
809    /// Regression: a linewise delete whose START row lies past the last
810    /// buffer row used to underflow `hi - lo + 1` (capacity math) and panic
811    /// `line_to_char(lo)`. Both endpoints must clamp to the last row.
812    #[test]
813    fn delete_linewise_start_past_end_is_clamped() {
814        let mut b = View::from_str("a\nb\nc");
815        b.apply_edit(Edit::DeleteRange {
816            start: Position::new(10, 0),
817            end: Position::new(20, 0),
818            kind: MotionKind::Line,
819        });
820        // Clamps to the last row and removes it.
821        assert_eq!(b.as_string(), "a\nb");
822    }
823
824    #[test]
825    fn delete_clearing_buffer_keeps_one_empty_row() {
826        let mut b = View::from_str("only");
827        b.apply_edit(Edit::DeleteRange {
828            start: Position::new(0, 0),
829            end: Position::new(0, 0),
830            kind: MotionKind::Line,
831        });
832        assert_eq!(b.row_count(), 1);
833        assert_eq!(rope_line_str(&b.rope(), 0), "");
834    }
835
836    #[test]
837    fn insert_char_lands_cursor_after() {
838        let mut b = View::from_str("abc");
839        b.set_cursor(Position::new(0, 1));
840        b.apply_edit(Edit::InsertChar {
841            at: Position::new(0, 1),
842            ch: 'X',
843        });
844        assert_eq!(b.cursor(), Position::new(0, 2));
845        assert_eq!(rope_line_str(&b.rope(), 0), "aXbc");
846    }
847
848    #[test]
849    fn block_delete_on_ragged_rows_handles_short_lines() {
850        // Row 1 is shorter than the block right edge — only the
851        // chars that exist get removed.
852        let mut b = View::from_str("longline\nhi\nthird row");
853        let inv = b.apply_edit(Edit::DeleteRange {
854            start: Position::new(0, 2),
855            end: Position::new(2, 5),
856            kind: MotionKind::Block,
857        });
858        b.apply_edit(inv);
859        assert_eq!(b.as_string(), "longline\nhi\nthird row");
860    }
861
862    #[test]
863    fn dirty_gen_bumps_per_edit() {
864        let mut b = View::from_str("abc");
865        let g0 = b.dirty_gen();
866        b.apply_edit(Edit::InsertChar {
867            at: Position::new(0, 0),
868            ch: 'X',
869        });
870        assert_eq!(b.dirty_gen(), g0 + 1);
871        b.apply_edit(Edit::DeleteRange {
872            start: Position::new(0, 0),
873            end: Position::new(0, 1),
874            kind: MotionKind::Char,
875        });
876        assert_eq!(b.dirty_gen(), g0 + 2);
877    }
878
879    /// Regression: a 60 k-row multi-line `InsertStr` into a 60 k-row buffer
880    /// used to call `Vec::insert(insert_at + i, …)` per row → O(N²) memmove.
881    /// With ropey, InsertStr is O(log N + edit_size) — this test confirms it
882    /// stays comfortably under the 200 ms budget.
883    #[test]
884    fn splice_at_60k_paste_at_row_zero_is_under_200ms() {
885        // View with 60 k rows of empty content.
886        let initial = "\n".repeat(60_000);
887        let mut b = View::from_str(&initial);
888        // Multi-line payload: 60 k "x" lines glued by \n.
889        let payload = vec!["x"; 60_000].join("\n");
890        let t = std::time::Instant::now();
891        b.apply_edit(Edit::InsertStr {
892            at: Position::new(0, 0),
893            text: payload,
894        });
895        let elapsed = t.elapsed();
896        assert!(
897            elapsed.as_millis() < 200,
898            "60k-row InsertStr took {elapsed:?}; budget 200 ms"
899        );
900    }
901}