1pub const CHUNK_CAPACITY: usize = 64;
5pub const MIN_CHUNK_SIZE: usize = 16;
7pub const MAX_INTERNAL_CHILDREN: usize = 8;
9pub const MIN_INTERNAL_CHILDREN: usize = 2;
11
12#[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#[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
74pub type RopeChunk = RopeLeaf;
76
77#[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
104pub enum SplitResult {
106 NoSplit,
107 Split(RopeNode),
108}
109
110#[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 mutate_line<R>(
481 &mut self,
482 mut line_idx: usize,
483 f: impl FnOnce(&mut String) -> R,
484 ) -> Option<(R, isize, isize)> {
485 match self {
486 RopeNode::Leaf(leaf) => {
487 let line = leaf.lines.get_mut(line_idx)?;
488 let old_chars = line.chars().count() as isize;
489 let old_bytes = line.len() as isize;
490 let res = f(line);
491 let new_chars = line.chars().count() as isize;
492 let new_bytes = line.len() as isize;
493 let d_chars = new_chars - old_chars;
494 let d_bytes = new_bytes - old_bytes;
495 leaf.metrics.chars = (leaf.metrics.chars as isize + d_chars).max(0) as usize;
496 leaf.metrics.bytes = (leaf.metrics.bytes as isize + d_bytes).max(0) as usize;
497 Some((res, d_chars, d_bytes))
498 }
499 RopeNode::Internal(internal) => {
500 for child in &mut internal.children {
501 let c_lines = child.line_count();
502 if line_idx < c_lines {
503 let (res, d_chars, d_bytes) = child.mutate_line(line_idx, f)?;
504 internal.metrics.chars =
505 (internal.metrics.chars as isize + d_chars).max(0) as usize;
506 internal.metrics.bytes =
507 (internal.metrics.bytes as isize + d_bytes).max(0) as usize;
508 return Some((res, d_chars, d_bytes));
509 }
510 line_idx -= c_lines;
511 }
512 None
513 }
514 }
515 }
516
517 pub fn position_to_byte(&self, mut line_idx: usize, char_col: usize) -> usize {
520 match self {
521 RopeNode::Leaf(leaf) => {
522 let mut offset = 0usize;
523 for (i, line) in leaf.lines.iter().enumerate() {
524 if i == line_idx {
525 return offset + char_to_byte(line, char_col);
526 }
527 offset += line.len() + 1;
528 }
529 offset.saturating_sub(1)
531 }
532 RopeNode::Internal(internal) => {
533 let mut offset = 0usize;
534 for child in &internal.children {
535 let m = child.metrics();
536 if line_idx < m.lines {
537 return offset + child.position_to_byte(line_idx, char_col);
538 }
539 offset += m.bytes + m.lines;
540 line_idx -= m.lines;
541 }
542 offset.saturating_sub(1)
543 }
544 }
545 }
546
547 pub fn byte_to_position(&self, mut byte_offset: usize, line_base: usize) -> (usize, usize) {
549 match self {
550 RopeNode::Leaf(leaf) => {
551 for (i, line) in leaf.lines.iter().enumerate() {
552 let line_bytes = line.len();
553 if byte_offset <= line_bytes {
554 return (line_base + i, byte_to_char(line, byte_offset));
555 }
556 byte_offset = byte_offset.saturating_sub(line_bytes + 1);
558 }
559 let last_idx = leaf.lines.len().saturating_sub(1);
560 let last_chars = leaf.lines.get(last_idx).map_or(0, |l| l.chars().count());
561 (line_base + last_idx, last_chars)
562 }
563 RopeNode::Internal(internal) => {
564 let mut cur_line = line_base;
565 let last_child_idx = internal.children.len().saturating_sub(1);
566 for (i, child) in internal.children.iter().enumerate() {
567 let m = child.metrics();
568 let span_with_newlines = m.bytes + m.lines;
569 if byte_offset < span_with_newlines || i == last_child_idx {
570 return child.byte_to_position(byte_offset, cur_line);
571 }
572 byte_offset -= span_with_newlines;
573 cur_line += m.lines;
574 }
575 (cur_line, 0)
576 }
577 }
578 }
579
580 pub fn write_text(&self, out: &mut String, is_first: &mut bool) {
581 match self {
582 RopeNode::Leaf(leaf) => {
583 for line in &leaf.lines {
584 if !*is_first {
585 out.push('\n');
586 }
587 out.push_str(line);
588 *is_first = false;
589 }
590 }
591 RopeNode::Internal(internal) => {
592 for child in &internal.children {
593 child.write_text(out, is_first);
594 }
595 }
596 }
597 }
598}
599
600pub fn char_to_byte(s: &str, char_idx: usize) -> usize {
602 let mut byte_offset = 0;
603 for (i, ch) in s.chars().enumerate() {
604 if i == char_idx {
605 return byte_offset;
606 }
607 byte_offset += ch.len_utf8();
608 }
609 s.len()
610}
611
612pub fn byte_to_char(s: &str, byte_idx: usize) -> usize {
614 let clamped_byte = byte_idx.min(s.len());
615 let mut char_count = 0;
616 let mut curr_byte = 0;
617 for ch in s.chars() {
618 if curr_byte >= clamped_byte {
619 break;
620 }
621 curr_byte += ch.len_utf8();
622 char_count += 1;
623 }
624 char_count
625}
626
627#[derive(Debug, Clone, PartialEq, Eq)]
630pub struct TextRope {
631 root: RopeNode,
632}
633
634impl Default for TextRope {
635 fn default() -> Self {
636 Self::new()
637 }
638}
639
640impl TextRope {
641 pub fn new() -> Self {
643 Self {
644 root: RopeNode::Leaf(RopeLeaf::new(vec![String::new()])),
645 }
646 }
647
648 pub fn root(&self) -> &RopeNode {
650 &self.root
651 }
652
653 pub fn root_mut(&mut self) -> &mut RopeNode {
655 &mut self.root
656 }
657
658 pub fn height(&self) -> usize {
660 self.root.height()
661 }
662
663 #[allow(clippy::should_implement_trait)]
665 pub fn from_str(text: &str) -> Self {
666 let raw_lines: Vec<String> = text
667 .split('\n')
668 .map(|l| l.strip_suffix('\r').unwrap_or(l).to_string())
669 .collect();
670 let lines = if raw_lines.is_empty() {
671 vec![String::new()]
672 } else {
673 raw_lines
674 };
675
676 let mut current_level: Vec<RopeNode> = lines
677 .chunks(CHUNK_CAPACITY / 2)
678 .map(|chunk| RopeNode::Leaf(RopeLeaf::new(chunk.to_vec())))
679 .collect();
680
681 if current_level.is_empty() {
682 current_level.push(RopeNode::Leaf(RopeLeaf::new(vec![String::new()])));
683 }
684
685 while current_level.len() > 1 {
686 let mut next_level = Vec::new();
687 for chunk in current_level.chunks(MAX_INTERNAL_CHILDREN) {
688 next_level.push(RopeNode::Internal(RopeInternal::new(chunk.to_vec())));
689 }
690 current_level = next_level;
691 }
692
693 Self {
694 root: current_level.remove(0),
695 }
696 }
697
698 #[inline]
700 pub fn line_count(&self) -> usize {
701 self.root.line_count()
702 }
703
704 #[inline]
706 pub fn total_char_count(&self) -> usize {
707 self.root.char_count()
708 }
709
710 #[inline]
712 pub fn total_byte_count(&self) -> usize {
713 self.root.byte_count()
714 }
715
716 pub fn insert_line(&mut self, line_idx: usize, text: String) {
718 if let SplitResult::Split(sibling) = self.root.insert_line(line_idx, text) {
719 let old_root =
720 std::mem::replace(&mut self.root, RopeNode::Leaf(RopeLeaf::new(Vec::new())));
721 self.root = RopeNode::Internal(RopeInternal::new(vec![old_root, sibling]));
722 }
723 }
724
725 pub fn delete_line(&mut self, line_idx: usize) -> Option<String> {
727 let deleted = self.root.delete_line(line_idx);
728 if let RopeNode::Internal(ref mut internal) = self.root {
729 if internal.children.len() == 1 {
730 self.root = internal.children.remove(0);
731 }
732 }
733 deleted
734 }
735
736 pub fn line(&self, idx: usize) -> Option<&str> {
738 self.root.get_line(idx)
739 }
740
741 pub fn line_mut(&mut self, idx: usize) -> Option<&mut String> {
743 self.root.get_line_mut(idx)
744 }
745
746 pub fn line_len(&self, idx: usize) -> usize {
748 self.line(idx).map_or(0, |l| l.chars().count())
749 }
750
751 pub fn line_char_count(&self, idx: usize) -> usize {
753 self.line_len(idx)
754 }
755
756 pub fn line_byte_len(&self, idx: usize) -> usize {
758 self.line(idx).map_or(0, |l| l.len())
759 }
760
761 pub fn insert_char(&mut self, line: usize, col: usize, ch: char) {
763 if ch == '\n' {
764 self.split_line(line, col);
765 return;
766 }
767
768 self.root.insert_char(line, col, ch);
769 }
770
771 pub fn insert_str(&mut self, line: usize, col: usize, text: &str) {
773 if text.is_empty() {
774 return;
775 }
776
777 if !text.contains('\n') {
778 self.root.insert_str_single_line(line, col, text);
779 return;
780 }
781
782 let parts: Vec<&str> = text.split('\n').collect();
783 let remainder = match self.root.mutate_line(line, |l| {
784 let byte_idx = char_to_byte(l, col);
785 let rem = l[byte_idx..].to_string();
786 l.truncate(byte_idx);
787 l.push_str(parts[0]);
788 rem
789 }) {
790 Some((rem, _, _)) => rem,
791 None => return,
792 };
793
794 let mut insert_idx = line + 1;
795 for part in &parts[1..parts.len() - 1] {
796 self.insert_line(insert_idx, part.to_string());
797 insert_idx += 1;
798 }
799
800 let mut last_line = parts[parts.len() - 1].to_string();
801 last_line.push_str(&remainder);
802 self.insert_line(insert_idx, last_line);
803 }
804
805 pub fn split_line(&mut self, line: usize, col: usize) {
807 if let SplitResult::Split(sibling) = self.root.split_line(line, col) {
808 let old_root =
809 std::mem::replace(&mut self.root, RopeNode::Leaf(RopeLeaf::new(Vec::new())));
810 self.root = RopeNode::Internal(RopeInternal::new(vec![old_root, sibling]));
811 }
812 }
813
814 pub fn join_line_with_next(&mut self, line: usize) {
816 if line + 1 < self.line_count() {
817 if let Some(next_line) = self.delete_line(line + 1) {
818 self.root.append_to_line(line, &next_line);
819 }
820 }
821 }
822
823 pub fn delete_backwards(&mut self, line: usize, col: usize) -> Option<(usize, usize)> {
825 if col > 0 {
826 if self.root.delete_char_at(line, col).is_some() {
827 return Some((line, col - 1));
828 }
829 } else if line > 0 {
830 let prev_line_len = self.line_len(line - 1);
831 self.join_line_with_next(line - 1);
832 return Some((line - 1, prev_line_len));
833 }
834 None
835 }
836
837 pub fn delete_range(
839 &mut self,
840 start_line: usize,
841 start_col: usize,
842 end_line: usize,
843 end_col: usize,
844 ) -> String {
845 if start_line > end_line || (start_line == end_line && start_col >= end_col) {
846 return String::new();
847 }
848
849 if start_line == end_line {
850 return self
851 .root
852 .mutate_line(start_line, |line| {
853 let sc = char_to_byte(line, start_col);
854 let ec = char_to_byte(line, end_col);
855 let deleted = line[sc..ec].to_string();
856 line.replace_range(sc..ec, "");
857 deleted
858 })
859 .map(|(d, _, _)| d)
860 .unwrap_or_default();
861 }
862
863 let mut deleted = String::new();
864
865 let remainder = if let Some((first_tail, _, _)) = self.root.mutate_line(start_line, |first| {
867 let sc = char_to_byte(first, start_col);
868 let tail = first[sc..].to_string();
869 first.truncate(sc);
870 tail
871 }) {
872 deleted.push_str(&first_tail);
873 deleted.push('\n');
874 true
875 } else {
876 false
877 };
878
879 let remove_count = end_line - start_line - 1;
881 for _ in 0..remove_count {
882 if start_line + 1 < self.line_count() {
883 if let Some(mid) = self.delete_line(start_line + 1) {
884 deleted.push_str(&mid);
885 deleted.push('\n');
886 }
887 }
888 }
889
890 if remainder && start_line + 1 < self.line_count() {
892 if let Some(last) = self.delete_line(start_line + 1) {
893 let ec = char_to_byte(&last, end_col);
894 deleted.push_str(&last[..ec]);
895 let tail = &last[ec..];
896 if !tail.is_empty() {
897 self.root.append_to_line(start_line, tail);
898 }
899 }
900 }
901
902 deleted
903 }
904
905 #[inline]
907 pub fn total_text_byte_len(&self) -> usize {
908 self.root.byte_count() + self.line_count().saturating_sub(1)
909 }
910
911 pub fn position_to_byte(&self, line: usize, char_col: usize) -> usize {
913 let clamped_line = line.min(self.line_count().saturating_sub(1));
914 self.root.position_to_byte(clamped_line, char_col)
915 }
916
917 pub fn position_to_point(&self, line: usize, char_col: usize) -> tree_sitter::Point {
919 let clamped_line = line.min(self.line_count().saturating_sub(1));
920 let byte_col = self
921 .line(clamped_line)
922 .map_or(0, |l| char_to_byte(l, char_col));
923 tree_sitter::Point {
924 row: clamped_line,
925 column: byte_col,
926 }
927 }
928
929 pub fn byte_to_position(&self, byte_offset: usize) -> (usize, usize) {
931 self.root.byte_to_position(byte_offset, 0)
932 }
933
934 pub fn compute_input_edit(
937 &self,
938 start: crate::cursor::Position,
939 old_end: crate::cursor::Position,
940 inserted_text: &str,
941 ) -> (tree_sitter::InputEdit, crate::cursor::Position) {
942 let start_byte = self.position_to_byte(start.line, start.col);
943 let old_end_byte = self.position_to_byte(old_end.line, old_end.col);
944 let new_end_byte = start_byte + inserted_text.len();
945
946 let start_position = self.position_to_point(start.line, start.col);
947 let old_end_position = self.position_to_point(old_end.line, old_end.col);
948
949 let (new_end_position, new_end_char_pos) = if let Some(last_nl) = inserted_text.rfind('\n') {
950 let added_rows = inserted_text.bytes().filter(|&b| b == b'\n').count();
951 let tail = &inserted_text[last_nl + 1..];
952 (
953 tree_sitter::Point {
954 row: start_position.row + added_rows,
955 column: tail.len(),
956 },
957 crate::cursor::Position::new(start.line + added_rows, tail.chars().count()),
958 )
959 } else {
960 (
961 tree_sitter::Point {
962 row: start_position.row,
963 column: start_position.column + inserted_text.len(),
964 },
965 crate::cursor::Position::new(start.line, start.col + inserted_text.chars().count()),
966 )
967 };
968
969 (
970 tree_sitter::InputEdit {
971 start_byte,
972 old_end_byte,
973 new_end_byte,
974 start_position,
975 old_end_position,
976 new_end_position,
977 },
978 new_end_char_pos,
979 )
980 }
981
982 pub fn slice_lines(&self, start: usize, count: usize) -> Vec<(usize, &str)> {
984 let total = self.line_count();
985 let end = (start + count).min(total);
986 if start >= end {
987 return Vec::new();
988 }
989
990 let mut out = Vec::with_capacity(end - start);
991 self.root.slice_lines(0, start, end, &mut out);
992 out
993 }
994
995 pub fn to_text(&self) -> String {
997 let mut out = String::with_capacity(self.root.byte_count() + self.line_count());
998 let mut is_first = true;
999 self.root.write_text(&mut out, &mut is_first);
1000 out
1001 }
1002}
1003
1004#[derive(Debug, Clone, PartialEq, Eq, Default)]
1006pub struct LineBuffer {
1007 rope: TextRope,
1008}
1009
1010impl LineBuffer {
1011 pub fn new() -> Self {
1013 Self {
1014 rope: TextRope::new(),
1015 }
1016 }
1017
1018 #[allow(clippy::should_implement_trait)]
1020 pub fn from_str(text: &str) -> Self {
1021 Self {
1022 rope: TextRope::from_str(text),
1023 }
1024 }
1025
1026 pub fn rope(&self) -> &TextRope {
1028 &self.rope
1029 }
1030
1031 pub fn rope_mut(&mut self) -> &mut TextRope {
1033 &mut self.rope
1034 }
1035
1036 pub fn line_count(&self) -> usize {
1038 self.rope.line_count()
1039 }
1040
1041 pub fn total_char_count(&self) -> usize {
1043 self.rope.total_char_count()
1044 }
1045
1046 pub fn total_byte_count(&self) -> usize {
1048 self.rope.total_byte_count()
1049 }
1050
1051 pub fn total_text_byte_len(&self) -> usize {
1053 self.rope.total_text_byte_len()
1054 }
1055
1056 pub fn position_to_byte(&self, pos: crate::cursor::Position) -> usize {
1058 self.rope.position_to_byte(pos.line, pos.col)
1059 }
1060
1061 pub fn position_to_point(&self, pos: crate::cursor::Position) -> tree_sitter::Point {
1063 self.rope.position_to_point(pos.line, pos.col)
1064 }
1065
1066 pub fn byte_to_position(&self, byte_offset: usize) -> crate::cursor::Position {
1068 let (line, col) = self.rope.byte_to_position(byte_offset);
1069 crate::cursor::Position::new(line, col)
1070 }
1071
1072 pub fn compute_input_edit(
1075 &self,
1076 start: crate::cursor::Position,
1077 old_end: crate::cursor::Position,
1078 inserted_text: &str,
1079 ) -> (tree_sitter::InputEdit, crate::cursor::Position) {
1080 self.rope.compute_input_edit(start, old_end, inserted_text)
1081 }
1082
1083 pub fn height(&self) -> usize {
1085 self.rope.height()
1086 }
1087
1088 pub fn line(&self, idx: usize) -> Option<&str> {
1090 self.rope.line(idx)
1091 }
1092
1093 pub fn line_mut(&mut self, idx: usize) -> Option<&mut String> {
1095 self.rope.line_mut(idx)
1096 }
1097
1098 pub fn line_len(&self, idx: usize) -> usize {
1100 self.rope.line_len(idx)
1101 }
1102
1103 pub fn line_char_count(&self, idx: usize) -> usize {
1105 self.rope.line_char_count(idx)
1106 }
1107
1108 pub fn line_byte_len(&self, idx: usize) -> usize {
1110 self.rope.line_byte_len(idx)
1111 }
1112
1113 pub fn insert_char(&mut self, line: usize, col: usize, ch: char) {
1115 self.rope.insert_char(line, col, ch);
1116 }
1117
1118 pub fn insert_str(&mut self, line: usize, col: usize, text: &str) {
1120 self.rope.insert_str(line, col, text);
1121 }
1122
1123 pub fn split_line(&mut self, line: usize, col: usize) {
1125 self.rope.split_line(line, col);
1126 }
1127
1128 pub fn join_line_with_next(&mut self, line: usize) {
1130 self.rope.join_line_with_next(line);
1131 }
1132
1133 pub fn delete_backwards(&mut self, line: usize, col: usize) -> Option<(usize, usize)> {
1135 self.rope.delete_backwards(line, col)
1136 }
1137
1138 pub fn delete_range(
1140 &mut self,
1141 start_line: usize,
1142 start_col: usize,
1143 end_line: usize,
1144 end_col: usize,
1145 ) -> String {
1146 self.rope
1147 .delete_range(start_line, start_col, end_line, end_col)
1148 }
1149
1150 pub fn slice_lines(&self, start: usize, count: usize) -> Vec<(usize, &str)> {
1152 self.rope.slice_lines(start, count)
1153 }
1154
1155 pub fn to_text(&self) -> String {
1157 self.rope.to_text()
1158 }
1159}
1160
1161impl std::str::FromStr for LineBuffer {
1162 type Err = std::convert::Infallible;
1163
1164 fn from_str(text: &str) -> Result<Self, Self::Err> {
1165 Ok(Self::from_str(text))
1166 }
1167}
1168
1169impl std::fmt::Display for LineBuffer {
1170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171 write!(f, "{}", self.to_text())
1172 }
1173}