Skip to main content

strata_editor/
buffer.rs

1//! Virtualized Balanced B-Tree Rope Line Buffer with O(log N) line indexing and fine-grained mutations.
2
3/// Maximum number of lines per leaf node before splitting.
4pub const CHUNK_CAPACITY: usize = 64;
5/// Minimum number of lines per leaf node.
6pub const MIN_CHUNK_SIZE: usize = 16;
7/// Maximum number of child nodes per internal B-Tree node before splitting.
8pub const MAX_INTERNAL_CHILDREN: usize = 8;
9/// Minimum number of child nodes per internal B-Tree node.
10pub const MIN_INTERNAL_CHILDREN: usize = 2;
11
12/// Subtree character, newline, and byte count metrics cached at each node in the B-Tree.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub struct SubtreeMetrics {
15    pub lines: usize,
16    pub chars: usize,
17    pub bytes: usize,
18}
19
20impl SubtreeMetrics {
21    pub const fn zero() -> Self {
22        Self {
23            lines: 0,
24            chars: 0,
25            bytes: 0,
26        }
27    }
28
29    pub fn from_lines(lines: &[String]) -> Self {
30        let mut chars = 0;
31        let mut bytes = 0;
32        for l in lines {
33            chars += l.chars().count();
34            bytes += l.len();
35        }
36        Self {
37            lines: lines.len(),
38            chars,
39            bytes,
40        }
41    }
42
43    #[inline]
44    pub fn add(&mut self, other: &SubtreeMetrics) {
45        self.lines += other.lines;
46        self.chars += other.chars;
47        self.bytes += other.bytes;
48    }
49}
50
51/// A leaf node containing a contiguous block of text lines in the B-Tree Rope.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct RopeLeaf {
54    pub lines: Vec<String>,
55    pub metrics: SubtreeMetrics,
56}
57
58impl RopeLeaf {
59    pub fn new(lines: Vec<String>) -> Self {
60        let metrics = SubtreeMetrics::from_lines(&lines);
61        Self { lines, metrics }
62    }
63
64    #[inline]
65    pub fn line_count(&self) -> usize {
66        self.lines.len()
67    }
68
69    pub fn recompute_metrics(&mut self) {
70        self.metrics = SubtreeMetrics::from_lines(&self.lines);
71    }
72}
73
74/// Alias for backwards compatibility with tests and callers expecting RopeChunk.
75pub type RopeChunk = RopeLeaf;
76
77/// An internal node in the B-Tree Rope maintaining balanced child references and aggregated metrics.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct RopeInternal {
80    pub children: Vec<RopeNode>,
81    pub metrics: SubtreeMetrics,
82}
83
84impl RopeInternal {
85    pub fn new(children: Vec<RopeNode>) -> Self {
86        let mut node = Self {
87            children,
88            metrics: SubtreeMetrics::zero(),
89        };
90        node.recompute_metrics();
91        node
92    }
93
94    #[inline]
95    pub fn recompute_metrics(&mut self) {
96        let mut m = SubtreeMetrics::zero();
97        for child in &self.children {
98            m.add(&child.metrics());
99        }
100        self.metrics = m;
101    }
102}
103
104/// Result of a B-Tree insertion or split propagation.
105pub enum SplitResult {
106    NoSplit,
107    Split(RopeNode),
108}
109
110/// A node in the balanced B-Tree Rope hierarchy (either an internal branch or a leaf node).
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub enum RopeNode {
113    Leaf(RopeLeaf),
114    Internal(RopeInternal),
115}
116
117impl RopeNode {
118    #[inline]
119    pub fn metrics(&self) -> SubtreeMetrics {
120        match self {
121            RopeNode::Leaf(leaf) => leaf.metrics,
122            RopeNode::Internal(internal) => internal.metrics,
123        }
124    }
125
126    #[inline]
127    pub fn line_count(&self) -> usize {
128        match self {
129            RopeNode::Leaf(leaf) => leaf.metrics.lines,
130            RopeNode::Internal(internal) => internal.metrics.lines,
131        }
132    }
133
134    #[inline]
135    pub fn char_count(&self) -> usize {
136        match self {
137            RopeNode::Leaf(leaf) => leaf.metrics.chars,
138            RopeNode::Internal(internal) => internal.metrics.chars,
139        }
140    }
141
142    #[inline]
143    pub fn byte_count(&self) -> usize {
144        match self {
145            RopeNode::Leaf(leaf) => leaf.metrics.bytes,
146            RopeNode::Internal(internal) => internal.metrics.bytes,
147        }
148    }
149
150    pub fn height(&self) -> usize {
151        match self {
152            RopeNode::Leaf(_) => 1,
153            RopeNode::Internal(internal) => 1 + internal.children.first().map_or(0, |c| c.height()),
154        }
155    }
156
157    pub fn get_line(&self, mut line_idx: usize) -> Option<&str> {
158        match self {
159            RopeNode::Leaf(leaf) => leaf.lines.get(line_idx).map(|s| s.as_str()),
160            RopeNode::Internal(internal) => {
161                for child in &internal.children {
162                    let c_lines = child.line_count();
163                    if line_idx < c_lines {
164                        return child.get_line(line_idx);
165                    }
166                    line_idx -= c_lines;
167                }
168                None
169            }
170        }
171    }
172
173    pub fn get_line_mut(&mut self, mut line_idx: usize) -> Option<&mut String> {
174        match self {
175            RopeNode::Leaf(leaf) => leaf.lines.get_mut(line_idx),
176            RopeNode::Internal(internal) => {
177                for child in &mut internal.children {
178                    let c_lines = child.line_count();
179                    if line_idx < c_lines {
180                        return child.get_line_mut(line_idx);
181                    }
182                    line_idx -= c_lines;
183                }
184                None
185            }
186        }
187    }
188
189    pub fn insert_char(&mut self, mut line_idx: usize, col: usize, ch: char) {
190        match self {
191            RopeNode::Leaf(leaf) => {
192                if let Some(l) = leaf.lines.get_mut(line_idx) {
193                    let byte_idx = char_to_byte(l, col);
194                    l.insert(byte_idx, ch);
195                    leaf.metrics.chars += 1;
196                    leaf.metrics.bytes += ch.len_utf8();
197                }
198            }
199            RopeNode::Internal(internal) => {
200                for child in &mut internal.children {
201                    let c_lines = child.line_count();
202                    if line_idx < c_lines {
203                        child.insert_char(line_idx, col, ch);
204                        internal.metrics.chars += 1;
205                        internal.metrics.bytes += ch.len_utf8();
206                        return;
207                    }
208                    line_idx -= c_lines;
209                }
210            }
211        }
212    }
213
214    pub fn insert_str_single_line(&mut self, mut line_idx: usize, col: usize, text: &str) {
215        match self {
216            RopeNode::Leaf(leaf) => {
217                if let Some(l) = leaf.lines.get_mut(line_idx) {
218                    let byte_idx = char_to_byte(l, col);
219                    l.insert_str(byte_idx, text);
220                    leaf.metrics.chars += text.chars().count();
221                    leaf.metrics.bytes += text.len();
222                }
223            }
224            RopeNode::Internal(internal) => {
225                let text_chars = text.chars().count();
226                let text_bytes = text.len();
227                for child in &mut internal.children {
228                    let c_lines = child.line_count();
229                    if line_idx < c_lines {
230                        child.insert_str_single_line(line_idx, col, text);
231                        internal.metrics.chars += text_chars;
232                        internal.metrics.bytes += text_bytes;
233                        return;
234                    }
235                    line_idx -= c_lines;
236                }
237            }
238        }
239    }
240
241    pub fn delete_char_at(&mut self, mut line_idx: usize, col: usize) -> Option<usize> {
242        match self {
243            RopeNode::Leaf(leaf) => {
244                let l = leaf.lines.get_mut(line_idx)?;
245                let byte_offset = char_to_byte(l, col);
246                if byte_offset > 0 {
247                    let prev_char = l[..byte_offset].chars().next_back()?;
248                    let prev_byte_offset = byte_offset - prev_char.len_utf8();
249                    let byte_len = prev_char.len_utf8();
250                    l.replace_range(prev_byte_offset..byte_offset, "");
251                    leaf.metrics.chars = leaf.metrics.chars.saturating_sub(1);
252                    leaf.metrics.bytes = leaf.metrics.bytes.saturating_sub(byte_len);
253                    Some(byte_len)
254                } else {
255                    None
256                }
257            }
258            RopeNode::Internal(internal) => {
259                for child in &mut internal.children {
260                    let c_lines = child.line_count();
261                    if line_idx < c_lines {
262                        if let Some(byte_len) = child.delete_char_at(line_idx, col) {
263                            internal.metrics.chars = internal.metrics.chars.saturating_sub(1);
264                            internal.metrics.bytes =
265                                internal.metrics.bytes.saturating_sub(byte_len);
266                            return Some(byte_len);
267                        }
268                        return None;
269                    }
270                    line_idx -= c_lines;
271                }
272                None
273            }
274        }
275    }
276
277    pub fn split_line(&mut self, mut line_idx: usize, col: usize) -> SplitResult {
278        match self {
279            RopeNode::Leaf(leaf) => {
280                if let Some(left) = leaf.lines.get_mut(line_idx) {
281                    let byte_idx = char_to_byte(left, col);
282                    let right = left[byte_idx..].to_string();
283                    left.truncate(byte_idx);
284                    leaf.lines.insert(line_idx + 1, right);
285                    leaf.metrics.lines += 1;
286                    if leaf.lines.len() > CHUNK_CAPACITY {
287                        let mid = leaf.lines.len() / 2;
288                        let right_lines = leaf.lines.split_off(mid);
289                        leaf.recompute_metrics();
290                        SplitResult::Split(RopeNode::Leaf(RopeLeaf::new(right_lines)))
291                    } else {
292                        SplitResult::NoSplit
293                    }
294                } else {
295                    SplitResult::NoSplit
296                }
297            }
298            RopeNode::Internal(internal) => {
299                let num_children = internal.children.len();
300                let mut target_child_idx = num_children.saturating_sub(1);
301                for (i, child) in internal.children.iter().enumerate() {
302                    let c_lines = child.line_count();
303                    if line_idx < c_lines || i == num_children - 1 {
304                        target_child_idx = i;
305                        break;
306                    }
307                    line_idx -= c_lines;
308                }
309
310                let split = internal.children[target_child_idx].split_line(line_idx, col);
311                if let SplitResult::Split(new_sibling) = split {
312                    internal.children.insert(target_child_idx + 1, new_sibling);
313                }
314                internal.recompute_metrics();
315
316                if internal.children.len() > MAX_INTERNAL_CHILDREN {
317                    let mid = internal.children.len() / 2;
318                    let right_children = internal.children.split_off(mid);
319                    let right_internal = RopeInternal::new(right_children);
320                    internal.recompute_metrics();
321                    SplitResult::Split(RopeNode::Internal(right_internal))
322                } else {
323                    SplitResult::NoSplit
324                }
325            }
326        }
327    }
328
329    pub fn append_to_line(&mut self, mut line_idx: usize, text: &str) {
330        match self {
331            RopeNode::Leaf(leaf) => {
332                if let Some(l) = leaf.lines.get_mut(line_idx) {
333                    l.push_str(text);
334                    leaf.metrics.chars += text.chars().count();
335                    leaf.metrics.bytes += text.len();
336                }
337            }
338            RopeNode::Internal(internal) => {
339                let text_chars = text.chars().count();
340                let text_bytes = text.len();
341                for child in &mut internal.children {
342                    let c_lines = child.line_count();
343                    if line_idx < c_lines {
344                        child.append_to_line(line_idx, text);
345                        internal.metrics.chars += text_chars;
346                        internal.metrics.bytes += text_bytes;
347                        return;
348                    }
349                    line_idx -= c_lines;
350                }
351            }
352        }
353    }
354
355    pub fn insert_line(&mut self, mut line_idx: usize, text: String) -> SplitResult {
356        match self {
357            RopeNode::Leaf(leaf) => {
358                let insert_pos = line_idx.min(leaf.lines.len());
359                let text_chars = text.chars().count();
360                let text_bytes = text.len();
361                leaf.lines.insert(insert_pos, text);
362                leaf.metrics.lines += 1;
363                leaf.metrics.chars += text_chars;
364                leaf.metrics.bytes += text_bytes;
365                if leaf.lines.len() > CHUNK_CAPACITY {
366                    let mid = leaf.lines.len() / 2;
367                    let right_lines = leaf.lines.split_off(mid);
368                    leaf.recompute_metrics();
369                    SplitResult::Split(RopeNode::Leaf(RopeLeaf::new(right_lines)))
370                } else {
371                    SplitResult::NoSplit
372                }
373            }
374            RopeNode::Internal(internal) => {
375                let num_children = internal.children.len();
376                let mut target_child_idx = num_children.saturating_sub(1);
377
378                for (i, child) in internal.children.iter().enumerate() {
379                    let c_lines = child.line_count();
380                    if line_idx <= c_lines || i == num_children - 1 {
381                        target_child_idx = i;
382                        break;
383                    }
384                    line_idx -= c_lines;
385                }
386
387                let split = internal.children[target_child_idx].insert_line(line_idx, text);
388                if let SplitResult::Split(new_sibling) = split {
389                    internal.children.insert(target_child_idx + 1, new_sibling);
390                }
391                internal.recompute_metrics();
392
393                if internal.children.len() > MAX_INTERNAL_CHILDREN {
394                    let mid = internal.children.len() / 2;
395                    let right_children = internal.children.split_off(mid);
396                    let right_internal = RopeInternal::new(right_children);
397                    internal.recompute_metrics();
398                    SplitResult::Split(RopeNode::Internal(right_internal))
399                } else {
400                    SplitResult::NoSplit
401                }
402            }
403        }
404    }
405
406    pub fn delete_line(&mut self, mut line_idx: usize) -> Option<String> {
407        match self {
408            RopeNode::Leaf(leaf) => {
409                if line_idx < leaf.lines.len() {
410                    let removed = leaf.lines.remove(line_idx);
411                    leaf.metrics.lines -= 1;
412                    leaf.metrics.chars = leaf.metrics.chars.saturating_sub(removed.chars().count());
413                    leaf.metrics.bytes = leaf.metrics.bytes.saturating_sub(removed.len());
414                    Some(removed)
415                } else {
416                    None
417                }
418            }
419            RopeNode::Internal(internal) => {
420                let mut target = None;
421                for (i, child) in internal.children.iter_mut().enumerate() {
422                    let c_lines = child.line_count();
423                    if line_idx < c_lines {
424                        target = Some((i, child.delete_line(line_idx)));
425                        break;
426                    }
427                    line_idx -= c_lines;
428                }
429
430                if let Some((idx, deleted)) = target {
431                    if internal.children[idx].line_count() == 0 && internal.children.len() > 1 {
432                        internal.children.remove(idx);
433                    }
434                    internal.recompute_metrics();
435                    deleted
436                } else {
437                    None
438                }
439            }
440        }
441    }
442
443    pub fn slice_lines<'a>(
444        &'a self,
445        line_offset: usize,
446        start: usize,
447        end: usize,
448        out: &mut Vec<(usize, &'a str)>,
449    ) {
450        let node_lines = self.line_count();
451        let node_start = line_offset;
452        let node_end = line_offset + node_lines;
453
454        if node_end <= start || node_start >= end {
455            return;
456        }
457
458        match self {
459            RopeNode::Leaf(leaf) => {
460                for (i, line) in leaf.lines.iter().enumerate() {
461                    let abs_line = node_start + i;
462                    if abs_line >= start && abs_line < end {
463                        out.push((abs_line, line.as_str()));
464                    }
465                }
466            }
467            RopeNode::Internal(internal) => {
468                let mut curr = line_offset;
469                for child in &internal.children {
470                    let child_lines = child.line_count();
471                    child.slice_lines(curr, start, end, out);
472                    curr += child_lines;
473                }
474            }
475        }
476    }
477
478    pub fn write_text(&self, out: &mut String, is_first: &mut bool) {
479        match self {
480            RopeNode::Leaf(leaf) => {
481                for line in &leaf.lines {
482                    if !*is_first {
483                        out.push('\n');
484                    }
485                    out.push_str(line);
486                    *is_first = false;
487                }
488            }
489            RopeNode::Internal(internal) => {
490                for child in &internal.children {
491                    child.write_text(out, is_first);
492                }
493            }
494        }
495    }
496}
497
498/// Converts a character-based column index to a byte offset within `s`.
499pub fn char_to_byte(s: &str, char_idx: usize) -> usize {
500    let mut byte_offset = 0;
501    for (i, ch) in s.chars().enumerate() {
502        if i == char_idx {
503            return byte_offset;
504        }
505        byte_offset += ch.len_utf8();
506    }
507    s.len()
508}
509
510/// Converts a byte offset within `s` to a character-based column index.
511pub fn byte_to_char(s: &str, byte_idx: usize) -> usize {
512    let clamped_byte = byte_idx.min(s.len());
513    let mut char_count = 0;
514    let mut curr_byte = 0;
515    for ch in s.chars() {
516        if curr_byte >= clamped_byte {
517            break;
518        }
519        curr_byte += ch.len_utf8();
520        char_count += 1;
521    }
522    char_count
523}
524
525/// Balanced B-Tree Rope text data structure for logarithmic-time
526/// line indexing, splitting, joining, and editing across massive documents (100,000+ lines).
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct TextRope {
529    root: RopeNode,
530}
531
532impl Default for TextRope {
533    fn default() -> Self {
534        Self::new()
535    }
536}
537
538impl TextRope {
539    /// Creates an empty rope containing a single empty line.
540    pub fn new() -> Self {
541        Self {
542            root: RopeNode::Leaf(RopeLeaf::new(vec![String::new()])),
543        }
544    }
545
546    /// Accesses the root node of the B-Tree.
547    pub fn root(&self) -> &RopeNode {
548        &self.root
549    }
550
551    /// Accesses the root node of the B-Tree mutably.
552    pub fn root_mut(&mut self) -> &mut RopeNode {
553        &mut self.root
554    }
555
556    /// Returns the tree height of the balanced B-Tree rope.
557    pub fn height(&self) -> usize {
558        self.root.height()
559    }
560
561    /// Constructs a TextRope by splitting an input string along linebreaks (`\n` or `\r\n`).
562    #[allow(clippy::should_implement_trait)]
563    pub fn from_str(text: &str) -> Self {
564        let raw_lines: Vec<String> = text
565            .split('\n')
566            .map(|l| l.strip_suffix('\r').unwrap_or(l).to_string())
567            .collect();
568        let lines = if raw_lines.is_empty() {
569            vec![String::new()]
570        } else {
571            raw_lines
572        };
573
574        let mut current_level: Vec<RopeNode> = lines
575            .chunks(CHUNK_CAPACITY / 2)
576            .map(|chunk| RopeNode::Leaf(RopeLeaf::new(chunk.to_vec())))
577            .collect();
578
579        if current_level.is_empty() {
580            current_level.push(RopeNode::Leaf(RopeLeaf::new(vec![String::new()])));
581        }
582
583        while current_level.len() > 1 {
584            let mut next_level = Vec::new();
585            for chunk in current_level.chunks(MAX_INTERNAL_CHILDREN) {
586                next_level.push(RopeNode::Internal(RopeInternal::new(chunk.to_vec())));
587            }
588            current_level = next_level;
589        }
590
591        Self {
592            root: current_level.remove(0),
593        }
594    }
595
596    /// Total number of lines in the buffer.
597    #[inline]
598    pub fn line_count(&self) -> usize {
599        self.root.line_count()
600    }
601
602    /// Total number of characters in the buffer.
603    #[inline]
604    pub fn total_char_count(&self) -> usize {
605        self.root.char_count()
606    }
607
608    /// Total number of bytes in the buffer.
609    #[inline]
610    pub fn total_byte_count(&self) -> usize {
611        self.root.byte_count()
612    }
613
614    /// Inserts a new line into the B-Tree at index `line_idx`, maintaining B-Tree balance.
615    pub fn insert_line(&mut self, line_idx: usize, text: String) {
616        if let SplitResult::Split(sibling) = self.root.insert_line(line_idx, text) {
617            let old_root =
618                std::mem::replace(&mut self.root, RopeNode::Leaf(RopeLeaf::new(Vec::new())));
619            self.root = RopeNode::Internal(RopeInternal::new(vec![old_root, sibling]));
620        }
621    }
622
623    /// Deletes the line at index `line_idx`, collapsing internal nodes if necessary.
624    pub fn delete_line(&mut self, line_idx: usize) -> Option<String> {
625        let deleted = self.root.delete_line(line_idx);
626        if let RopeNode::Internal(ref mut internal) = self.root {
627            if internal.children.len() == 1 {
628                self.root = internal.children.remove(0);
629            }
630        }
631        deleted
632    }
633
634    /// Returns a reference to the line at the specified 0-based index.
635    pub fn line(&self, idx: usize) -> Option<&str> {
636        self.root.get_line(idx)
637    }
638
639    /// Returns a mutable reference to the line at the specified 0-based index.
640    pub fn line_mut(&mut self, idx: usize) -> Option<&mut String> {
641        self.root.get_line_mut(idx)
642    }
643
644    /// Returns the character length of the line at the specified index.
645    pub fn line_len(&self, idx: usize) -> usize {
646        self.line(idx).map_or(0, |l| l.chars().count())
647    }
648
649    /// Returns the character count of the line at the specified index.
650    pub fn line_char_count(&self, idx: usize) -> usize {
651        self.line_len(idx)
652    }
653
654    /// Returns the byte length of the line at the specified index.
655    pub fn line_byte_len(&self, idx: usize) -> usize {
656        self.line(idx).map_or(0, |l| l.len())
657    }
658
659    /// Inserts a character at the specified line and character column.
660    pub fn insert_char(&mut self, line: usize, col: usize, ch: char) {
661        if ch == '\n' {
662            self.split_line(line, col);
663            return;
664        }
665
666        self.root.insert_char(line, col, ch);
667    }
668
669    /// Inserts a string at the specified line and character column, automatically handling multiline breaks.
670    pub fn insert_str(&mut self, line: usize, col: usize, text: &str) {
671        if text.is_empty() {
672            return;
673        }
674
675        if !text.contains('\n') {
676            self.root.insert_str_single_line(line, col, text);
677            return;
678        }
679
680        let parts: Vec<&str> = text.split('\n').collect();
681        let remainder = if let Some(l) = self.line_mut(line) {
682            let byte_idx = char_to_byte(l, col);
683            let rem = l[byte_idx..].to_string();
684            l.truncate(byte_idx);
685            l.push_str(parts[0]);
686            rem
687        } else {
688            return;
689        };
690
691        let mut insert_idx = line + 1;
692        for part in &parts[1..parts.len() - 1] {
693            self.insert_line(insert_idx, part.to_string());
694            insert_idx += 1;
695        }
696
697        let mut last_line = parts[parts.len() - 1].to_string();
698        last_line.push_str(&remainder);
699        self.insert_line(insert_idx, last_line);
700    }
701
702    /// Splits a line into two lines at the given character column index.
703    pub fn split_line(&mut self, line: usize, col: usize) {
704        if let SplitResult::Split(sibling) = self.root.split_line(line, col) {
705            let old_root =
706                std::mem::replace(&mut self.root, RopeNode::Leaf(RopeLeaf::new(Vec::new())));
707            self.root = RopeNode::Internal(RopeInternal::new(vec![old_root, sibling]));
708        }
709    }
710
711    /// Joins the specified line with the subsequent line.
712    pub fn join_line_with_next(&mut self, line: usize) {
713        if line + 1 < self.line_count() {
714            if let Some(next_line) = self.delete_line(line + 1) {
715                self.root.append_to_line(line, &next_line);
716            }
717        }
718    }
719
720    /// Deletes a character before the specified position (backspace).
721    pub fn delete_backwards(&mut self, line: usize, col: usize) -> Option<(usize, usize)> {
722        if col > 0 {
723            if self.root.delete_char_at(line, col).is_some() {
724                return Some((line, col - 1));
725            }
726        } else if line > 0 {
727            let prev_line_len = self.line_len(line - 1);
728            self.join_line_with_next(line - 1);
729            return Some((line - 1, prev_line_len));
730        }
731        None
732    }
733
734    /// Deletes text within the given bounding character range and returns the deleted substring.
735    pub fn delete_range(
736        &mut self,
737        start_line: usize,
738        start_col: usize,
739        end_line: usize,
740        end_col: usize,
741    ) -> String {
742        if start_line > end_line || (start_line == end_line && start_col >= end_col) {
743            return String::new();
744        }
745
746        if start_line == end_line {
747            if let Some(line) = self.line_mut(start_line) {
748                let sc = char_to_byte(line, start_col);
749                let ec = char_to_byte(line, end_col);
750                let deleted = line[sc..ec].to_string();
751                line.replace_range(sc..ec, "");
752                return deleted;
753            }
754            return String::new();
755        }
756
757        let mut deleted = String::new();
758
759        // 1. First line
760        let remainder = if let Some(first) = self.line_mut(start_line) {
761            let sc = char_to_byte(first, start_col);
762            deleted.push_str(&first[sc..]);
763            deleted.push('\n');
764            first.truncate(sc);
765            true
766        } else {
767            false
768        };
769
770        // 2. Middle lines
771        let remove_count = end_line - start_line - 1;
772        for _ in 0..remove_count {
773            if start_line + 1 < self.line_count() {
774                if let Some(mid) = self.delete_line(start_line + 1) {
775                    deleted.push_str(&mid);
776                    deleted.push('\n');
777                }
778            }
779        }
780
781        // 3. Last line
782        if remainder && start_line + 1 < self.line_count() {
783            if let Some(last) = self.delete_line(start_line + 1) {
784                let ec = char_to_byte(&last, end_col);
785                deleted.push_str(&last[..ec]);
786                let tail = &last[ec..];
787                if let Some(first) = self.line_mut(start_line) {
788                    first.push_str(tail);
789                }
790            }
791        }
792
793        deleted
794    }
795
796    /// Returns a slice of lines for virtual viewport rendering in logarithmic time.
797    pub fn slice_lines(&self, start: usize, count: usize) -> Vec<(usize, &str)> {
798        let total = self.line_count();
799        let end = (start + count).min(total);
800        if start >= end {
801            return Vec::new();
802        }
803
804        let mut out = Vec::with_capacity(end - start);
805        self.root.slice_lines(0, start, end, &mut out);
806        out
807    }
808
809    /// Serializes entire rope back into a single newline-separated String.
810    pub fn to_text(&self) -> String {
811        let mut out = String::with_capacity(self.root.byte_count() + self.line_count());
812        let mut is_first = true;
813        self.root.write_text(&mut out, &mut is_first);
814        out
815    }
816}
817
818/// Fast, indexed line-based text buffer backed by a balanced B-Tree Rope.
819#[derive(Debug, Clone, PartialEq, Eq, Default)]
820pub struct LineBuffer {
821    rope: TextRope,
822}
823
824impl LineBuffer {
825    /// Creates an empty buffer containing a single empty line.
826    pub fn new() -> Self {
827        Self {
828            rope: TextRope::new(),
829        }
830    }
831
832    /// Constructs a LineBuffer by splitting an input string along linebreaks (`\n` or `\r\n`).
833    #[allow(clippy::should_implement_trait)]
834    pub fn from_str(text: &str) -> Self {
835        Self {
836            rope: TextRope::from_str(text),
837        }
838    }
839
840    /// Accesses the underlying balanced B-Tree TextRope.
841    pub fn rope(&self) -> &TextRope {
842        &self.rope
843    }
844
845    /// Accesses the underlying balanced B-Tree TextRope mutably.
846    pub fn rope_mut(&mut self) -> &mut TextRope {
847        &mut self.rope
848    }
849
850    /// Total number of lines in the buffer.
851    pub fn line_count(&self) -> usize {
852        self.rope.line_count()
853    }
854
855    /// Total number of characters in the buffer.
856    pub fn total_char_count(&self) -> usize {
857        self.rope.total_char_count()
858    }
859
860    /// Total number of bytes in the buffer.
861    pub fn total_byte_count(&self) -> usize {
862        self.rope.total_byte_count()
863    }
864
865    /// Tree height of the B-Tree rope.
866    pub fn height(&self) -> usize {
867        self.rope.height()
868    }
869
870    /// Returns a reference to the line at the specified 0-based index.
871    pub fn line(&self, idx: usize) -> Option<&str> {
872        self.rope.line(idx)
873    }
874
875    /// Returns a mutable reference to the line at the specified 0-based index.
876    pub fn line_mut(&mut self, idx: usize) -> Option<&mut String> {
877        self.rope.line_mut(idx)
878    }
879
880    /// Returns the character length of the line at the specified index.
881    pub fn line_len(&self, idx: usize) -> usize {
882        self.rope.line_len(idx)
883    }
884
885    /// Returns the character count of the line at the specified index.
886    pub fn line_char_count(&self, idx: usize) -> usize {
887        self.rope.line_char_count(idx)
888    }
889
890    /// Returns the byte length of the line at the specified index.
891    pub fn line_byte_len(&self, idx: usize) -> usize {
892        self.rope.line_byte_len(idx)
893    }
894
895    /// Inserts a character at the specified line and character column.
896    pub fn insert_char(&mut self, line: usize, col: usize, ch: char) {
897        self.rope.insert_char(line, col, ch);
898    }
899
900    /// Inserts a string at the specified line and character column, automatically handling multiline breaks.
901    pub fn insert_str(&mut self, line: usize, col: usize, text: &str) {
902        self.rope.insert_str(line, col, text);
903    }
904
905    /// Splits a line into two lines at the given character column index.
906    pub fn split_line(&mut self, line: usize, col: usize) {
907        self.rope.split_line(line, col);
908    }
909
910    /// Joins the specified line with the subsequent line.
911    pub fn join_line_with_next(&mut self, line: usize) {
912        self.rope.join_line_with_next(line);
913    }
914
915    /// Deletes a character before the specified position (backspace).
916    pub fn delete_backwards(&mut self, line: usize, col: usize) -> Option<(usize, usize)> {
917        self.rope.delete_backwards(line, col)
918    }
919
920    /// Deletes text within the given bounding character range and returns the deleted substring.
921    pub fn delete_range(
922        &mut self,
923        start_line: usize,
924        start_col: usize,
925        end_line: usize,
926        end_col: usize,
927    ) -> String {
928        self.rope
929            .delete_range(start_line, start_col, end_line, end_col)
930    }
931
932    /// Returns a slice of lines for virtual viewport rendering in logarithmic time.
933    pub fn slice_lines(&self, start: usize, count: usize) -> Vec<(usize, &str)> {
934        self.rope.slice_lines(start, count)
935    }
936
937    /// Serializes entire buffer back into a single newline-separated String.
938    pub fn to_text(&self) -> String {
939        self.rope.to_text()
940    }
941}
942
943impl std::str::FromStr for LineBuffer {
944    type Err = std::convert::Infallible;
945
946    fn from_str(text: &str) -> Result<Self, Self::Err> {
947        Ok(Self::from_str(text))
948    }
949}
950
951impl std::fmt::Display for LineBuffer {
952    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
953        write!(f, "{}", self.to_text())
954    }
955}