Skip to main content

hjkl_engine/
buffer_impl.rs

1//! Canonical [`View`] trait impl over [`hjkl_buffer::View`].
2//!
3//! Wires the engine trait surface (`Cursor` / `Query` / `BufferEdit` /
4//! `Search`, sealed via [`crate::types::sealed::Sealed`]) onto the
5//! in-tree rope-backed buffer. Pos⇄Position conversion lives at this
6//! boundary — engine code (FSM, editor) keeps using `hjkl_buffer`'s
7//! concrete API directly until the motion / fold relocation lands;
8//! external trait users see the engine trait surface.
9//!
10//! # Why concrete-Editor today
11//!
12//! The trait surface here is 13 methods. The engine FSM today calls
13//! ~46 distinct methods on `hjkl_buffer::View` — most of them are
14//! motion / fold / viewport helpers that don't belong on `View`
15//! (they're computed over the buffer, not delegated to it). Generic-ifying
16//! `Editor<B: View, H: Host>` therefore requires relocating those
17//! ~33 helpers from `hjkl-buffer` into `hjkl-engine` as free functions
18//! over `B: Cursor + Query`. That's a separate, multi-thousand-LOC
19//! patch tracked for the 0.1.0 cut.
20//!
21//! Until then this module ships the canonical impl + a compile-time
22//! assertion that `hjkl_buffer::View` satisfies the trait, so
23//! downstream callers can write `fn f<B: hjkl_engine::View>(…)`
24//! today and the engine's own `Editor` becomes generic over `B` in a
25//! follow-up patch without breaking the trait contract.
26
27use std::borrow::Cow;
28
29use hjkl_buffer::Position;
30use hjkl_buffer::View as RopeBuffer;
31use regex::Regex;
32
33use crate::types::sealed::Sealed;
34use crate::types::{BufferEdit, Cursor, FoldOp, FoldProvider, Pos, Query, Search, View};
35
36// ── Pos ⇄ Position conversion ──────────────────────────────────────
37
38/// Engine [`Pos`] → buffer [`Position`].
39///
40/// Engine `Pos` is `(line: u32, col: u32)` grapheme-indexed; buffer
41/// [`Position`] is `(row: usize, col: usize)` char-indexed. The two
42/// indexings happen to match for the in-tree rope today (graphemes
43/// without combining marks == chars); future grapheme-aware backends
44/// will need to thread a real grapheme→char map through this fn.
45#[inline]
46pub fn pos_to_position(p: Pos) -> Position {
47    Position {
48        row: p.line as usize,
49        col: p.col as usize,
50    }
51}
52
53/// View [`Position`] → engine [`Pos`].
54#[inline]
55pub fn position_to_pos(p: Position) -> Pos {
56    Pos {
57        line: p.row as u32,
58        col: p.col as u32,
59    }
60}
61
62// ── Sealed marker ──────────────────────────────────────────────────
63
64impl Sealed for RopeBuffer {}
65
66// ── Cursor ─────────────────────────────────────────────────────────
67
68impl Cursor for RopeBuffer {
69    fn cursor(&self) -> Pos {
70        position_to_pos(Self::cursor(self))
71    }
72
73    fn set_cursor(&mut self, pos: Pos) {
74        Self::set_cursor(self, pos_to_position(pos));
75    }
76
77    fn byte_offset(&self, pos: Pos) -> usize {
78        let p = pos_to_position(pos);
79        let rope = self.rope();
80        let n = rope.len_lines();
81        // O(log N) rope index — no per-row String materialization.
82        let row = p.row.min(n);
83        let line_start = rope.line_to_byte(row);
84        if p.row < n {
85            // Only the cursor's own line needs to materialize for the
86            // col→byte offset translation.
87            let line = hjkl_buffer::rope_line_str(&rope, p.row);
88            line_start + p.byte_offset(&line)
89        } else {
90            line_start
91        }
92    }
93
94    fn pos_at_byte(&self, byte: usize) -> Pos {
95        let rope = self.rope();
96        let total = rope.len_bytes();
97        if total == 0 {
98            return Pos { line: 0, col: 0 };
99        }
100        // Clamp into [0, total]; `byte_to_line` panics on OOB.
101        let byte_clamped = byte.min(total);
102        // O(log N) rope index — no per-row scan.
103        let row = rope.byte_to_line(byte_clamped);
104        let line_start = rope.line_to_byte(row);
105        let line = hjkl_buffer::rope_line_str(&rope, row);
106        let mut col_byte = byte_clamped.saturating_sub(line_start);
107        // Clamp to the line body (exclude the trailing `\n` if any).
108        col_byte = col_byte.min(line.len());
109        // Round down to the nearest char boundary so a byte index
110        // landing inside a multi-byte codepoint maps to the column
111        // of the char that contains it (not a slice panic).
112        while col_byte > 0 && !line.is_char_boundary(col_byte) {
113            col_byte -= 1;
114        }
115        let col = line[..col_byte].chars().count();
116        Pos {
117            line: row as u32,
118            col: col as u32,
119        }
120    }
121}
122
123// ── Query ──────────────────────────────────────────────────────────
124
125impl Query for RopeBuffer {
126    fn line_count(&self) -> u32 {
127        self.row_count() as u32
128    }
129
130    fn line(&self, idx: u32) -> String {
131        let row = idx as usize;
132        let rope = self.rope();
133        // SPEC: panic on OOB rather than silently return empty.
134        if row >= rope.len_lines() {
135            panic!(
136                "Query::line: index {idx} out of bounds (line_count = {})",
137                self.row_count()
138            );
139        }
140        hjkl_buffer::rope_line_str(&rope, row)
141    }
142
143    fn len_bytes(&self) -> usize {
144        // Use cached byte_len — O(1), no allocation.
145        Self::byte_len(self)
146    }
147
148    fn dirty_gen(&self) -> u64 {
149        Self::dirty_gen(self)
150    }
151
152    fn content_joined(&self) -> std::sync::Arc<String> {
153        Self::content_joined(self)
154    }
155
156    fn line_bytes(&self, row: usize) -> usize {
157        // One lock, zero allocations via rope API.
158        let rope = self.rope();
159        // `Query::line_bytes` contracts out-of-range rows to 0, but
160        // `ropey::Rope::line` *panics* past the last line — guard here
161        // rather than at each call site. `len_lines()` is O(1) on the
162        // already-cloned rope, so this costs nothing extra.
163        if row >= rope.len_lines() {
164            return 0;
165        }
166        hjkl_buffer::rope_line_bytes(&rope, row)
167    }
168
169    fn rope(&self) -> ropey::Rope {
170        // O(1): Arc-clone of the rope root — no byte copying.
171        Self::rope(self)
172    }
173
174    fn slice(&self, range: core::ops::Range<Pos>) -> Cow<'_, str> {
175        let start = pos_to_position(range.start);
176        let end = pos_to_position(range.end);
177        if start >= end {
178            return Cow::Borrowed("");
179        }
180        let rope = self.rope();
181        let n = rope.len_lines();
182        // Single-line slice — allocate since View::rope_line_str returns owned String.
183        if start.row == end.row {
184            if start.row < n {
185                let line = hjkl_buffer::rope_line_str(&rope, start.row);
186                let lo = start.byte_offset(&line).min(line.len());
187                let hi = end.byte_offset(&line).min(line.len());
188                return Cow::Owned(line[lo..hi].to_owned());
189            }
190            return Cow::Borrowed("");
191        }
192        // Multi-line: allocate.
193        let mut out = String::new();
194        // The buffer's true last row — it never has a trailing newline
195        // (vim invariant), so a row equal to `last_row` must never get
196        // a fabricated `\n` appended.
197        let last_row = self.row_count().saturating_sub(1);
198        // Clamp the end row for iteration, but remember whether the
199        // *original* end row was in-bounds: only an in-bounds end row
200        // is a genuine mid-line cut. An out-of-bounds (past-end
201        // sentinel) end row means "through the end of the buffer",
202        // which must fall through to the full-line branch below
203        // instead of comparing against a phantom row that can never
204        // be reached by the clamped loop.
205        let end_row = end.row.min(last_row);
206        let end_in_bounds = end.row <= last_row;
207        for r in start.row..=end_row {
208            let line = if r < n {
209                hjkl_buffer::rope_line_str(&rope, r)
210            } else {
211                String::new()
212            };
213            let lo = if r == start.row {
214                start.byte_offset(&line).min(line.len())
215            } else {
216                0
217            };
218            if r == end_row && end_in_bounds {
219                let hi = end.byte_offset(&line).min(line.len()).max(lo);
220                out.push_str(&line[lo..hi]);
221            } else {
222                out.push_str(&line[lo..]);
223                if r < last_row {
224                    out.push('\n');
225                }
226            }
227        }
228        Cow::Owned(out)
229    }
230}
231
232// ── BufferEdit ─────────────────────────────────────────────────────
233
234impl BufferEdit for RopeBuffer {
235    fn insert_at(&mut self, pos: Pos, text: &str) {
236        let at = clamp_to_buf(self, pos_to_position(pos));
237        let _ = self.apply_edit(hjkl_buffer::Edit::InsertStr {
238            at,
239            text: text.to_string(),
240        });
241    }
242
243    fn delete_range(&mut self, range: core::ops::Range<Pos>) {
244        let start = clamp_to_buf(self, pos_to_position(range.start));
245        let end = clamp_to_buf(self, pos_to_position(range.end));
246        if start >= end {
247            return;
248        }
249        let _ = self.apply_edit(hjkl_buffer::Edit::DeleteRange {
250            start,
251            end,
252            kind: hjkl_buffer::MotionKind::Char,
253        });
254    }
255
256    fn replace_range(&mut self, range: core::ops::Range<Pos>, replacement: &str) {
257        let start = clamp_to_buf(self, pos_to_position(range.start));
258        let end = clamp_to_buf(self, pos_to_position(range.end));
259        if start >= end {
260            // Treat as pure insert at `start`.
261            let _ = self.apply_edit(hjkl_buffer::Edit::InsertStr {
262                at: start,
263                text: replacement.to_string(),
264            });
265            return;
266        }
267        let _ = self.apply_edit(hjkl_buffer::Edit::Replace {
268            start,
269            end,
270            with: replacement.to_string(),
271        });
272    }
273
274    fn replace_all(&mut self, text: &str) {
275        // Forward to the inherent in-tree fast path which rebuilds
276        // the line vector in one pass + bumps `dirty_gen`.
277        Self::replace_all(self, text);
278    }
279}
280
281#[inline]
282fn clamp_to_buf(buf: &RopeBuffer, p: Position) -> Position {
283    buf.clamp_position(p)
284}
285
286// ── Search ─────────────────────────────────────────────────────────
287
288impl Search for RopeBuffer {
289    fn find_next(&self, from: Pos, pat: &Regex) -> Option<core::ops::Range<Pos>> {
290        let start = pos_to_position(from);
291        let total = self.row_count();
292        if total == 0 {
293            return None;
294        }
295        // Scan the from-row from `start.col` onward, then every row
296        // after, then wrap to rows before. SPEC: "first match
297        // at-or-after `from`". 0.0.37: wrap policy now lives on the
298        // engine's `SearchState::wrap_around` (see
299        // `DESIGN_33_METHOD_CLASSIFICATION.md` step 3); the trait
300        // impl always wraps and the engine's `search_*` free
301        // functions are responsible for honouring `wrapscan` by
302        // wrapping or not invoking the trait at all.
303        let wrap = true;
304        let rope = self.rope();
305        let from_line = crate::viewport_math::rope_line_slice(&rope, start.row);
306        let from_byte = start.byte_offset(&from_line).min(from_line.len());
307        if let Some(m) = pat.find_at(&from_line, from_byte) {
308            return Some(byte_range_to_pos_range(
309                start.row,
310                m.start(),
311                start.row,
312                m.end(),
313                &from_line,
314            ));
315        }
316        // `..=total`: the last step wraps back onto the starting row, whose
317        // part BEFORE `from` the scan above never looked at — a match behind
318        // the cursor on its own line (in a one-line buffer, the only line).
319        for offset in 1..=total {
320            let row = start.row + offset;
321            if row >= total && !wrap {
322                break;
323            }
324            let row = row % total;
325            if !wrap && row <= start.row {
326                break;
327            }
328            let line = crate::viewport_math::rope_line_slice(&rope, row);
329            if let Some(m) = pat.find(&line) {
330                return Some(byte_range_to_pos_range(row, m.start(), row, m.end(), &line));
331            }
332            if row == start.row {
333                break;
334            }
335        }
336        None
337    }
338
339    fn find_prev(&self, from: Pos, pat: &Regex) -> Option<core::ops::Range<Pos>> {
340        let start = pos_to_position(from);
341        let total = self.row_count();
342        if total == 0 {
343            return None;
344        }
345        // 0.0.37: wrap moved to engine SearchState; trait impl always wraps.
346        let wrap = true;
347        // Last match at-or-before `from`. We can't run the regex
348        // backwards, so iterate matches and pick the last one with
349        // start <= from-byte on the from-row, then walk previous rows
350        // taking the last match per row.
351        let rope = self.rope();
352        let from_line = crate::viewport_math::rope_line_slice(&rope, start.row);
353        let from_byte = start.byte_offset(&from_line).min(from_line.len());
354        let mut best: Option<(usize, usize)> = None;
355        for m in pat.find_iter(&from_line) {
356            if m.start() <= from_byte {
357                best = Some((m.start(), m.end()));
358            } else {
359                break;
360            }
361        }
362        if let Some((s, e)) = best {
363            return Some(byte_range_to_pos_range(
364                start.row, s, start.row, e, &from_line,
365            ));
366        }
367        // `..=total`: as in `find_next`, the last step wraps back onto the
368        // starting row and takes its last match AFTER `from`.
369        for offset in 1..=total {
370            // Walk backwards.
371            let row = if offset > start.row {
372                if !wrap {
373                    break;
374                }
375                total - (offset - start.row)
376            } else {
377                start.row - offset
378            };
379            if !wrap && row >= start.row {
380                break;
381            }
382            let line = crate::viewport_math::rope_line_slice(&rope, row);
383            let last = pat.find_iter(&line).last();
384            if let Some(m) = last {
385                return Some(byte_range_to_pos_range(row, m.start(), row, m.end(), &line));
386            }
387            if row == start.row {
388                break;
389            }
390        }
391        None
392    }
393}
394
395#[inline]
396fn byte_range_to_pos_range(
397    s_row: usize,
398    s_byte: usize,
399    e_row: usize,
400    e_byte: usize,
401    line: &str,
402) -> core::ops::Range<Pos> {
403    let s_col = line[..s_byte.min(line.len())].chars().count();
404    let e_col = line[..e_byte.min(line.len())].chars().count();
405    Pos {
406        line: s_row as u32,
407        col: s_col as u32,
408    }..Pos {
409        line: e_row as u32,
410        col: e_col as u32,
411    }
412}
413
414// ── View super-trait ─────────────────────────────────────────────
415
416impl View for RopeBuffer {}
417
418// ── Fold provider ──────────────────────────────────────────────────
419
420/// [`FoldProvider`] adapter wrapping a `&hjkl_buffer::View`. Lets
421/// engine call sites ask the buffer's fold storage about visible
422/// rows without reaching into `View::next_visible_row` &c. directly.
423///
424/// Construct with [`BufferFoldProvider::new`]. Hosts that want to
425/// expose their own fold model (a separate fold tree, LSP-derived
426/// folding ranges, …) can implement `FoldProvider` against their own
427/// state and skip this adapter entirely.
428///
429/// Introduced in 0.0.32 (Patch C-β) as part of the fold-iteration
430/// relocation. Fold *storage* still lives on the buffer for
431/// `dirty_gen` / render-cache reasons; only the iteration API moved.
432pub struct BufferFoldProvider<'a> {
433    buffer: &'a RopeBuffer,
434}
435
436impl<'a> BufferFoldProvider<'a> {
437    pub fn new(buffer: &'a RopeBuffer) -> Self {
438        Self { buffer }
439    }
440}
441
442impl FoldProvider for BufferFoldProvider<'_> {
443    fn next_visible_row(&self, row: usize, _row_count: usize) -> Option<usize> {
444        // View ignores the row_count hint — it knows its own size.
445        RopeBuffer::next_visible_row(self.buffer, row)
446    }
447
448    fn prev_visible_row(&self, row: usize) -> Option<usize> {
449        RopeBuffer::prev_visible_row(self.buffer, row)
450    }
451
452    fn is_row_hidden(&self, row: usize) -> bool {
453        RopeBuffer::is_row_hidden(self.buffer, row)
454    }
455
456    fn fold_at_row(&self, row: usize) -> Option<(usize, usize, bool)> {
457        let f = self.buffer.fold_at_row(row)?;
458        Some((f.start_row, f.end_row, f.closed))
459    }
460
461    // `apply` / `invalidate_range` use the trait's default no-op impl
462    // because `BufferFoldProvider` only borrows the buffer immutably.
463    // For fold mutation, use [`BufferFoldProviderMut`] instead.
464}
465
466/// Mutable [`FoldProvider`] adapter wrapping a `&mut hjkl_buffer::View`.
467/// Engine call sites that need to dispatch a [`FoldOp`] (vim's `z…`
468/// keystrokes, the `:fold*` Ex commands, edit-pipeline invalidation)
469/// construct this on the fly from `&mut self.buffer` and call
470/// [`FoldProvider::apply`] / [`FoldProvider::invalidate_range`] on it.
471///
472/// Introduced in 0.0.38 (Patch C-δ.4) as part of routing fold mutation
473/// through the [`FoldProvider`] surface. Fold *storage* still lives
474/// on [`hjkl_buffer::View`] for `dirty_gen` / render-cache reasons;
475/// only the dispatch path moved.
476pub struct BufferFoldProviderMut<'a> {
477    buffer: &'a mut RopeBuffer,
478}
479
480impl<'a> BufferFoldProviderMut<'a> {
481    pub fn new(buffer: &'a mut RopeBuffer) -> Self {
482        Self { buffer }
483    }
484}
485
486impl FoldProvider for BufferFoldProviderMut<'_> {
487    fn next_visible_row(&self, row: usize, _row_count: usize) -> Option<usize> {
488        RopeBuffer::next_visible_row(self.buffer, row)
489    }
490
491    fn prev_visible_row(&self, row: usize) -> Option<usize> {
492        RopeBuffer::prev_visible_row(self.buffer, row)
493    }
494
495    fn is_row_hidden(&self, row: usize) -> bool {
496        RopeBuffer::is_row_hidden(self.buffer, row)
497    }
498
499    fn fold_at_row(&self, row: usize) -> Option<(usize, usize, bool)> {
500        let f = self.buffer.fold_at_row(row)?;
501        Some((f.start_row, f.end_row, f.closed))
502    }
503
504    fn apply(&mut self, op: FoldOp) {
505        match op {
506            FoldOp::Add {
507                start_row,
508                end_row,
509                closed,
510            } => {
511                self.buffer.add_fold(start_row, end_row, closed);
512            }
513            FoldOp::RemoveAt(row) => {
514                self.buffer.remove_fold_at(row);
515            }
516            FoldOp::OpenAt(row) => {
517                self.buffer.open_fold_at(row);
518            }
519            FoldOp::CloseAt(row) => {
520                self.buffer.close_fold_at(row);
521            }
522            FoldOp::ToggleAt(row) => {
523                self.buffer.toggle_fold_at(row);
524            }
525            FoldOp::OpenRecursivelyAt(row) => {
526                self.buffer.open_folds_recursively_at(row);
527            }
528            FoldOp::CloseRecursivelyAt(row) => {
529                self.buffer.close_folds_recursively_at(row);
530            }
531            FoldOp::ToggleRecursivelyAt(row) => {
532                self.buffer.toggle_folds_recursively_at(row);
533            }
534            FoldOp::OpenAll => {
535                self.buffer.open_all_folds();
536            }
537            FoldOp::CloseAll => {
538                self.buffer.close_all_folds();
539            }
540            FoldOp::ClearAll => {
541                self.buffer.clear_all_folds();
542            }
543            FoldOp::Invalidate { start_row, end_row } => {
544                self.buffer.invalidate_folds_in_range(start_row, end_row);
545            }
546            // FoldOp is #[non_exhaustive] — new variants added in hjkl-buffer
547            // are silently ignored here until buffer_impl is updated.
548            _ => {}
549        }
550    }
551
552    fn invalidate_range(&mut self, start_row: usize, end_row: usize) {
553        self.buffer.invalidate_folds_in_range(start_row, end_row);
554    }
555}
556
557/// Owned-snapshot [`FoldProvider`] adapter. Carries a copy of the
558/// buffer's fold list (one `Vec<Fold>` clone — fold lists are tiny in
559/// practice) plus the buffer's `row_count`, so the call site can hold
560/// the snapshot for fold queries while passing `&mut hjkl_buffer::View`
561/// to a motion function that needs cursor mutation.
562///
563/// Introduced in 0.0.40 (Patch C-δ.5) so the lifted motion fns can
564/// take `&dyn FoldProvider` separately from `&mut B: Cursor + Query`
565/// without the call site running into the immutable-vs-mutable
566/// borrow conflict that arises with [`BufferFoldProvider`] /
567/// [`BufferFoldProviderMut`] (both of which hold a buffer borrow).
568///
569/// The snapshot is read-only — `apply` and `invalidate_range` are
570/// no-ops (any fold mutation must go through the canonical
571/// [`BufferFoldProviderMut`] adapter against the live buffer).
572pub struct SnapshotFoldProvider {
573    folds: Vec<hjkl_buffer::Fold>,
574    /// Merged hidden-range index over `folds` — per-row "is this row
575    /// hidden" queries in the walks below are O(log F) instead of a
576    /// linear scan per row (this provider is rebuilt per `j`/`k` and per
577    /// frame). Built once here from the snapshot, whose folds are the
578    /// buffer's sorted-by-`start_row` list.
579    fold_index: hjkl_buffer::FoldIndex,
580    row_count: usize,
581}
582
583impl SnapshotFoldProvider {
584    /// Snapshot the current fold list + row-count from `buffer`.
585    /// The snapshot is decoupled from the buffer's lifetime, so the
586    /// caller can immediately re-borrow the buffer mutably.
587    ///
588    /// `row_count` is clamped to skip vim's single phantom trailing
589    /// empty row — `ropey`'s `len_lines()` always synthesizes one
590    /// extra empty final "line" when the buffer text ends in `\n`.
591    /// Without this, `j`/`k` (which route through this snapshot, not
592    /// [`hjkl_buffer::View::next_visible_row`] directly) could step
593    /// the cursor onto that phantom row. Mirrors
594    /// `hjkl_engine::motions::move_bottom`'s clamp (`G`).
595    ///
596    /// The clamp defers to [`hjkl_buffer::View::last_content_row`] — the
597    /// same helper `next_visible_row` / `prev_visible_row` use — instead
598    /// of re-deriving it by materializing the last line as a `String`
599    /// just to ask whether it is empty (this runs per `j`/`k` and per
600    /// `cursor_screen_pos`, i.e. per frame).
601    pub fn from_buffer(buffer: &RopeBuffer) -> Self {
602        let folds = buffer.folds();
603        let fold_index = hjkl_buffer::FoldIndex::new(&folds);
604        Self {
605            folds,
606            fold_index,
607            row_count: buffer.last_content_row() + 1,
608        }
609    }
610
611    /// True iff `row` is hidden by any closed fold in the snapshot.
612    /// Mirrors [`hjkl_buffer::View::is_row_hidden`] over the
613    /// snapshotted fold list.
614    fn snapshot_is_row_hidden(&self, row: usize) -> bool {
615        self.fold_index.hides_row(row)
616    }
617}
618
619impl FoldProvider for SnapshotFoldProvider {
620    fn next_visible_row(&self, row: usize, _row_count: usize) -> Option<usize> {
621        // Mirrors [`hjkl_buffer::View::next_visible_row`]: walk
622        // forward, skipping closed-fold-hidden rows, stop at end.
623        let last = self.row_count.saturating_sub(1);
624        if last == 0 && row == 0 {
625            return None;
626        }
627        let mut r = row.checked_add(1)?;
628        while r <= last && self.snapshot_is_row_hidden(r) {
629            r += 1;
630        }
631        (r <= last).then_some(r)
632    }
633
634    fn prev_visible_row(&self, row: usize) -> Option<usize> {
635        // Mirrors [`hjkl_buffer::View::prev_visible_row`].
636        let mut r = row.checked_sub(1)?;
637        while self.snapshot_is_row_hidden(r) {
638            r = r.checked_sub(1)?;
639        }
640        Some(r)
641    }
642
643    fn is_row_hidden(&self, row: usize) -> bool {
644        self.snapshot_is_row_hidden(row)
645    }
646
647    fn fold_at_row(&self, row: usize) -> Option<(usize, usize, bool)> {
648        self.folds
649            .iter()
650            .find(|f| f.contains(row))
651            .map(|f| (f.start_row, f.end_row, f.closed))
652    }
653
654    // `apply` / `invalidate_range` use the trait's default no-op impl.
655}
656
657// ── Tests ──────────────────────────────────────────────────────────
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662
663    /// Compile-time check: the in-tree `hjkl_buffer::View` satisfies
664    /// the SPEC `View` super-trait (and therefore all four sub-traits).
665    /// If this stops compiling, the trait surface diverged from the
666    /// canonical impl — fix the impl, not this assertion.
667    #[test]
668    fn rope_buffer_implements_spec_buffer() {
669        fn assert_buffer<B: View>() {}
670        fn assert_cursor<B: Cursor>() {}
671        fn assert_query<B: Query>() {}
672        fn assert_edit<B: BufferEdit>() {}
673        fn assert_search<B: Search>() {}
674        assert_buffer::<RopeBuffer>();
675        assert_cursor::<RopeBuffer>();
676        assert_query::<RopeBuffer>();
677        assert_edit::<RopeBuffer>();
678        assert_search::<RopeBuffer>();
679    }
680
681    #[test]
682    fn cursor_roundtrip() {
683        let mut b = RopeBuffer::from_str("hello\nworld");
684        Cursor::set_cursor(&mut b, Pos::new(1, 3));
685        assert_eq!(Cursor::cursor(&b), Pos::new(1, 3));
686    }
687
688    #[test]
689    fn query_line_count_and_line() {
690        let b = RopeBuffer::from_str("a\nb\nc");
691        assert_eq!(Query::line_count(&b), 3);
692        assert_eq!(Query::line(&b, 0), "a");
693        assert_eq!(Query::line(&b, 2), "c");
694    }
695
696    /// `Query::line_bytes` is the allocation-free stand-in for
697    /// `line(row).len()`. Both are BYTE counts and the hot paths that
698    /// swapped one for the other (syntax-span clamping) depend on that being
699    /// exact, so pin the equivalence over the shapes that reach a real
700    /// buffer: ASCII, multi-byte UTF-8, tabs, empty rows, trailing newline,
701    /// CRLF, and out-of-range rows (contract: 0, never a panic).
702    #[test]
703    fn line_bytes_matches_line_len() {
704        let corpus = [
705            "",
706            "a",
707            "a\n",
708            "a\nbb\nccc",
709            "héllo\nwörld",
710            "emoji 🎉 tail\nnext",
711            "tabs\there\nx",
712            "a\r\nb\r\nc",
713            "trailing\n\n",
714        ];
715        for text in corpus {
716            let b = RopeBuffer::from_str(text);
717            let n = Query::line_count(&b) as usize;
718            for row in 0..n {
719                assert_eq!(
720                    Query::line_bytes(&b, row),
721                    Query::line(&b, row as u32).len(),
722                    "row {row} of {text:?}"
723                );
724            }
725            // Out of range: 0, and no panic (ropey's `Rope::line` panics
726            // past the last line — the impl must guard).
727            for row in n..n + 3 {
728                assert_eq!(Query::line_bytes(&b, row), 0, "oob row {row} of {text:?}");
729            }
730        }
731    }
732
733    /// A row terminated by a non-LF break that ropey still counts as a line
734    /// break (lone CR, NEL, U+2028/9) reports only its own content.
735    ///
736    /// This test previously pinned a divergence here as deliberate: `line()`
737    /// kept the terminator while `line_bytes` dropped it. Neither half of the
738    /// rationale survived measurement. `line_bytes` subtracted a hard-coded
739    /// ONE byte, so on `"a\u{2028}b"` it answered 3 for a row whose content is
740    /// the single byte `a` — it kept two of the separator's three bytes — and
741    /// it therefore did not "match `rope_line_char_count`", which answered 1.
742    /// The `line()` half is what let a `\r`-terminated row read one char wide
743    /// than it is, which the debug curswant invariant caught via the
744    /// `handle_key` fuzz target. All three helpers now share one rule.
745    #[test]
746    fn line_helpers_exclude_a_non_lf_line_break() {
747        for text in ["a\rb", "a\u{2028}b", "a\u{0085}b", "a\u{0b}b", "a\u{0c}b"] {
748            let b = RopeBuffer::from_str(text);
749            assert_eq!(Query::line(&b, 0), "a", "{text:?}");
750            assert_eq!(Query::line_bytes(&b, 0), 1, "{text:?}");
751        }
752    }
753
754    /// `\r\n` is the one break whose `\r` stays in the row's content — ropey
755    /// makes it a single break, and stripping back to the `\r` would silently
756    /// rewrite CRLF text. Pinned so the shared rule cannot drift into it.
757    #[test]
758    fn crlf_keeps_its_carriage_return() {
759        let b = RopeBuffer::from_str("a\r\nb");
760        assert_eq!(Query::line(&b, 0), "a\r");
761        assert_eq!(Query::line_bytes(&b, 0), 2);
762    }
763
764    #[test]
765    fn query_len_bytes_matches_join() {
766        let b = RopeBuffer::from_str("foo\nbar\nbaz");
767        assert_eq!(Query::len_bytes(&b), b.as_string().len());
768    }
769
770    #[test]
771    fn query_slice_single_line_borrows() {
772        let b = RopeBuffer::from_str("hello world");
773        let s = Query::slice(&b, Pos::new(0, 0)..Pos::new(0, 5));
774        assert_eq!(&*s, "hello");
775        // View::line now returns owned String; single-line slice is Owned.
776        assert!(matches!(s, Cow::Owned(_)));
777    }
778
779    #[test]
780    fn query_slice_multiline_allocates() {
781        let b = RopeBuffer::from_str("ab\ncd\nef");
782        let s = Query::slice(&b, Pos::new(0, 1)..Pos::new(2, 1));
783        assert_eq!(&*s, "b\ncd\ne");
784        assert!(matches!(s, Cow::Owned(_)));
785    }
786
787    /// Regression for audit finding A9: an end row past the buffer's
788    /// last row (a "through end of buffer" sentinel, e.g. `u32::MAX`
789    /// as used by `BufferEdit::replace_all`'s default range) used to
790    /// compare against the *unclamped* end row, so the clamped loop
791    /// never hit the mid-line-cut branch and instead fell through to
792    /// the "full line + \n" branch on the buffer's real last row —
793    /// fabricating a trailing newline that isn't in the source text
794    /// (the last line of a buffer never has one). The slice must stop
795    /// exactly at the end of the real content, with no spurious `\n`.
796    #[test]
797    fn query_slice_past_end_sentinel_row_has_no_spurious_trailing_newline() {
798        let b = RopeBuffer::from_str("ab\ncd\nef");
799        let s = Query::slice(&b, Pos::new(0, 1)..Pos::new(u32::MAX, u32::MAX));
800        assert_eq!(&*s, "b\ncd\nef");
801        assert!(!s.ends_with('\n'));
802    }
803
804    #[test]
805    fn cursor_byte_offset_and_inverse() {
806        let b = RopeBuffer::from_str("hello\nworld");
807        // Start of row 1 = 6 bytes ('h','e','l','l','o','\n').
808        let p = Pos::new(1, 0);
809        assert_eq!(Cursor::byte_offset(&b, p), 6);
810        assert_eq!(Cursor::pos_at_byte(&b, 6), p);
811        // Roundtrip mid-line.
812        let p2 = Pos::new(1, 3);
813        let off = Cursor::byte_offset(&b, p2);
814        assert_eq!(Cursor::pos_at_byte(&b, off), p2);
815    }
816
817    #[test]
818    fn buffer_edit_insert_delete_replace() {
819        let mut b = RopeBuffer::from_str("hello");
820        BufferEdit::insert_at(&mut b, Pos::new(0, 5), " world");
821        assert_eq!(b.as_string(), "hello world");
822        BufferEdit::delete_range(&mut b, Pos::new(0, 5)..Pos::new(0, 11));
823        assert_eq!(b.as_string(), "hello");
824        BufferEdit::replace_range(&mut b, Pos::new(0, 0)..Pos::new(0, 5), "HI");
825        assert_eq!(b.as_string(), "HI");
826    }
827
828    /// Default `BufferEdit::replace_all` impl forwards to
829    /// `replace_range(ORIGIN..MAX, text)`. Non-canonical backends that
830    /// don't override `replace_all` rely on this; locked in here with
831    /// a minimal mock that records the calls.
832    #[test]
833    fn buffer_edit_default_replace_all_routes_through_replace_range() {
834        struct MockBuf {
835            cursor: Pos,
836            lines: Vec<String>,
837            last_replace_range: Option<core::ops::Range<Pos>>,
838        }
839        impl Sealed for MockBuf {}
840        impl Cursor for MockBuf {
841            fn cursor(&self) -> Pos {
842                self.cursor
843            }
844            fn set_cursor(&mut self, p: Pos) {
845                self.cursor = p;
846            }
847            fn byte_offset(&self, _p: Pos) -> usize {
848                0
849            }
850            fn pos_at_byte(&self, _b: usize) -> Pos {
851                Pos::ORIGIN
852            }
853        }
854        impl Query for MockBuf {
855            fn line_count(&self) -> u32 {
856                self.lines.len() as u32
857            }
858            fn line(&self, idx: u32) -> String {
859                self.lines[idx as usize].clone()
860            }
861            fn len_bytes(&self) -> usize {
862                0
863            }
864            fn slice(&self, _r: core::ops::Range<Pos>) -> Cow<'_, str> {
865                Cow::Borrowed("")
866            }
867        }
868        impl BufferEdit for MockBuf {
869            fn insert_at(&mut self, _p: Pos, _t: &str) {}
870            fn delete_range(&mut self, _r: core::ops::Range<Pos>) {}
871            fn replace_range(&mut self, range: core::ops::Range<Pos>, _t: &str) {
872                self.last_replace_range = Some(range);
873            }
874        }
875        impl Search for MockBuf {
876            fn find_next(&self, _f: Pos, _p: &Regex) -> Option<core::ops::Range<Pos>> {
877                None
878            }
879            fn find_prev(&self, _f: Pos, _p: &Regex) -> Option<core::ops::Range<Pos>> {
880                None
881            }
882        }
883        impl View for MockBuf {}
884
885        let mut m = MockBuf {
886            cursor: Pos::ORIGIN,
887            lines: vec!["hi".into()],
888            last_replace_range: None,
889        };
890        BufferEdit::replace_all(&mut m, "new content");
891        let r = m
892            .last_replace_range
893            .expect("default impl must hit replace_range");
894        assert_eq!(r.start, Pos::ORIGIN);
895        assert_eq!(r.end.line, u32::MAX);
896        assert_eq!(r.end.col, u32::MAX);
897    }
898
899    #[test]
900    fn buffer_edit_replace_all_rebuilds_content() {
901        let mut b = RopeBuffer::from_str("hello\nworld");
902        Cursor::set_cursor(&mut b, Pos::new(1, 3));
903        BufferEdit::replace_all(&mut b, "alpha\nbeta\ngamma");
904        assert_eq!(b.as_string(), "alpha\nbeta\ngamma");
905        assert_eq!(Query::line_count(&b), 3);
906        // Cursor clamped to surviving content (`replace_all` invariant).
907        let c = Cursor::cursor(&b);
908        assert!((c.line as usize) < Query::line_count(&b) as usize);
909    }
910
911    #[test]
912    fn search_find_next_same_row() {
913        let b = RopeBuffer::from_str("abc def abc");
914        let pat = Regex::new("abc").unwrap();
915        let r = Search::find_next(&b, Pos::new(0, 0), &pat).unwrap();
916        assert_eq!(r, Pos::new(0, 0)..Pos::new(0, 3));
917        let r2 = Search::find_next(&b, Pos::new(0, 1), &pat).unwrap();
918        assert_eq!(r2, Pos::new(0, 8)..Pos::new(0, 11));
919    }
920
921    #[test]
922    fn search_find_next_wraps() {
923        let b = RopeBuffer::from_str("foo\nbar\nfoo");
924        // 0.0.37: wrap policy moved to engine `SearchState::wrap_around`.
925        // The trait impl always wraps; engine code that wants
926        // non-wrap semantics short-circuits before invoking the trait.
927        let pat = Regex::new("foo").unwrap();
928        // Starting on row 1: should find row 2's "foo".
929        let r = Search::find_next(&b, Pos::new(1, 0), &pat).unwrap();
930        assert_eq!(r, Pos::new(2, 0)..Pos::new(2, 3));
931    }
932
933    #[test]
934    fn search_find_prev_same_row() {
935        let b = RopeBuffer::from_str("abc def abc");
936        let pat = Regex::new("abc").unwrap();
937        let r = Search::find_prev(&b, Pos::new(0, 11), &pat).unwrap();
938        assert_eq!(r, Pos::new(0, 8)..Pos::new(0, 11));
939    }
940
941    /// Regression for the borrow swap in `find_next`/`find_prev`: the
942    /// per-row `String` became a `Cow<str>` borrow of the rope chunk
943    /// (`crate::viewport_math::rope_line_slice`). Content is identical,
944    /// but the byte→char column translation in
945    /// `byte_range_to_pos_range` must survive — a match on a row past
946    /// the from-row with multibyte content (whose byte offsets differ
947    /// from char columns) must resolve to the same char range as the
948    /// old `String` path.
949    #[test]
950    fn search_cross_row_multibyte_borrow_swap() {
951        let b = RopeBuffer::from_str("héllo\nwörld\n🎉 fóo\nbar");
952        let pat = Regex::new("fóo").unwrap();
953        // Match on row 2, at-or-after (0, 0): "🎉 fóo" is 5 chars
954        // ('🎉',' ','f','ó','o'); 'f' sits at byte 5, and the prefix
955        // `line[..5]` ("🎉 ") is 2 chars, so the match spans cols 2..5.
956        let r = Search::find_next(&b, Pos::new(0, 0), &pat).unwrap();
957        assert_eq!(r, Pos::new(2, 2)..Pos::new(2, 5));
958        // find_prev from a row past the match.
959        let r = Search::find_prev(&b, Pos::new(3, 0), &pat).unwrap();
960        assert_eq!(r, Pos::new(2, 2)..Pos::new(2, 5));
961    }
962
963    #[test]
964    fn pos_position_roundtrip() {
965        let p = Pos::new(7, 3);
966        assert_eq!(position_to_pos(pos_to_position(p)), p);
967    }
968
969    // ── BufferFoldProviderMut dispatch (0.0.38, Patch C-δ.4) ───────
970
971    #[test]
972    fn fold_provider_mut_apply_add_open_close_toggle() {
973        let mut buf = RopeBuffer::from_str("a\nb\nc\nd\ne");
974        {
975            let mut p = BufferFoldProviderMut::new(&mut buf);
976            p.apply(FoldOp::Add {
977                start_row: 1,
978                end_row: 3,
979                closed: true,
980            });
981            assert_eq!(p.fold_at_row(2), Some((1, 3, true)));
982            p.apply(FoldOp::OpenAt(2));
983            assert_eq!(p.fold_at_row(2), Some((1, 3, false)));
984            p.apply(FoldOp::CloseAt(2));
985            assert_eq!(p.fold_at_row(2), Some((1, 3, true)));
986            p.apply(FoldOp::ToggleAt(2));
987            assert_eq!(p.fold_at_row(2), Some((1, 3, false)));
988        }
989        assert_eq!(buf.folds().len(), 1);
990    }
991
992    #[test]
993    fn fold_provider_mut_apply_recursive_operations() {
994        let mut buf = RopeBuffer::from_str("a\nb\nc\nd\ne");
995        buf.add_fold(0, 4, false);
996        buf.add_fold(0, 2, false);
997        {
998            let mut p = BufferFoldProviderMut::new(&mut buf);
999            p.apply(FoldOp::CloseRecursivelyAt(0));
1000        }
1001        assert!(buf.folds().iter().all(|fold| fold.closed));
1002        {
1003            let mut p = BufferFoldProviderMut::new(&mut buf);
1004            p.apply(FoldOp::OpenRecursivelyAt(0));
1005            p.apply(FoldOp::ToggleRecursivelyAt(0));
1006        }
1007        assert!(buf.folds().iter().all(|fold| fold.closed));
1008    }
1009
1010    #[test]
1011    fn fold_provider_mut_apply_open_close_clear_all() {
1012        let mut buf = RopeBuffer::from_str("a\nb\nc\nd\ne");
1013        buf.add_fold(0, 1, false);
1014        buf.add_fold(2, 3, true);
1015        {
1016            let mut p = BufferFoldProviderMut::new(&mut buf);
1017            p.apply(FoldOp::CloseAll);
1018        }
1019        assert!(buf.folds().iter().all(|f| f.closed));
1020        {
1021            let mut p = BufferFoldProviderMut::new(&mut buf);
1022            p.apply(FoldOp::OpenAll);
1023        }
1024        assert!(buf.folds().iter().all(|f| !f.closed));
1025        {
1026            let mut p = BufferFoldProviderMut::new(&mut buf);
1027            p.apply(FoldOp::ClearAll);
1028        }
1029        assert!(buf.folds().is_empty());
1030    }
1031
1032    #[test]
1033    fn fold_provider_mut_invalidate_range_drops_overlapping() {
1034        let mut buf = RopeBuffer::from_str("a\nb\nc\nd\ne");
1035        buf.add_fold(0, 1, true);
1036        buf.add_fold(2, 3, true);
1037        buf.add_fold(4, 4, true);
1038        {
1039            let mut p = BufferFoldProviderMut::new(&mut buf);
1040            p.invalidate_range(2, 3);
1041        }
1042        let starts: Vec<usize> = buf.folds().iter().map(|f| f.start_row).collect();
1043        assert_eq!(starts, vec![0, 4]);
1044    }
1045
1046    #[test]
1047    fn fold_provider_mut_apply_remove_at() {
1048        let mut buf = RopeBuffer::from_str("a\nb\nc\nd\ne");
1049        buf.add_fold(1, 3, true);
1050        {
1051            let mut p = BufferFoldProviderMut::new(&mut buf);
1052            p.apply(FoldOp::RemoveAt(2));
1053        }
1054        assert!(buf.folds().is_empty());
1055    }
1056
1057    #[test]
1058    fn noop_fold_provider_apply_is_noop() {
1059        // The default `apply` impl on the trait is a no-op; verify
1060        // NoopFoldProvider inherits it without panicking.
1061        let mut p = crate::types::NoopFoldProvider;
1062        FoldProvider::apply(&mut p, FoldOp::OpenAll);
1063        FoldProvider::invalidate_range(&mut p, 0, 5);
1064        // Read methods unaffected.
1065        assert!(!FoldProvider::is_row_hidden(&p, 3));
1066    }
1067}