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