rsvim_core 0.1.3-alpha.2

The core library for RSVIM text editor.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Text content backend for buffer.

pub mod cache;
pub mod cidx;

#[cfg(test)]
mod cache_tests;
#[cfg(test)]
mod cidx_tests;

use crate::buf::opt::BufferOptions;
use crate::buf::opt::EndOfLineOption;
use crate::buf::unicode;
use crate::prelude::*;
use arcstr::ArcStr;
use cache::CachedLines;
use cache::CachedLinesKey;
use cache::CachedWidth;
pub use cidx::ColumnIndex;
use compact_str::CompactString;
use compact_str::ToCompactString;
use ropey::Rope;
use ropey::RopeSlice;
use std::cell::RefCell;
use std::ops::Range;

#[derive(Debug)]
/// Text content backend.
pub struct Text {
  rope: Rope,
  options: BufferOptions,

  // Caches for:
  // 1. Lines width
  // 2. Cloned lines, this is only used when `wrap=true,line_break=true`.
  cached_width: RefCell<CachedWidth>,
  cached_lines: RefCell<CachedLines>,
}

arc_mutex_ptr!(Text);

impl Text {
  pub fn new(opts: BufferOptions, canvas_size: U16Size, rope: Rope) -> Self {
    Self {
      rope,
      options: opts,
      cached_width: RefCell::new(CachedWidth::new(canvas_size)),
      cached_lines: RefCell::new(CachedLines::new(canvas_size)),
    }
  }
}

#[cfg(test)]
impl Drop for Text {
  fn drop(&mut self) {
    let cached_width = self.cached_width.borrow();
    if cached_width.stats().total() > 0 {
      trace!("|drop| cached_width {}", cached_width.stats());
    }
    let cached_lines = self.cached_lines.borrow();
    if cached_lines.stats().total() > 0 {
      trace!("|drop| cached_lines {}", cached_lines.stats());
    }
  }
}

// Unicode {
impl Text {
  /// Get the display width for a `char`, supports both ASCI control codes and unicode.
  ///
  /// The char display width follows the
  /// [Unicode Standard Annex #11](https://www.unicode.org/reports/tr11/).
  pub fn char_width(&self, c: char) -> usize {
    unicode::char_width(&self.options, c)
  }

  /// Get the printable cell symbol.
  pub fn char_symbol(&self, c: char) -> CompactString {
    unicode::char_symbol(&self.options, c)
  }

  /// Get both cell symbol and its display width.
  pub fn char_symbol_and_width(&self, c: char) -> (CompactString, usize) {
    (
      unicode::char_symbol(&self.options, c),
      unicode::char_width(&self.options, c),
    )
  }
}
// Unicode }

// Rope {
impl Text {
  /// Get rope.
  pub fn rope(&self) -> &Rope {
    &self.rope
  }

  // Get mutable rope.
  //
  // NOTE:
  // Directly get mutable `&mut Rope` is disabled, while `Text` provides all kinds of mutable
  // operations to correctly reset internal cached display width.
  // and hide these details.
  fn rope_mut(&mut self) -> &mut Rope {
    &mut self.rope
  }

  fn _clone_line_impl(
    &self,
    line_idx: usize,
    start_char_idx: usize,
    max_chars_width: usize,
  ) -> Option<ArcStr> {
    match self.rope.get_line(line_idx) {
      Some(buffer_line) => match buffer_line.get_chars_at(start_char_idx) {
        Some(chars_iter) => {
          let mut w: usize = 0;
          let mut builder = String::with_capacity(max_chars_width);
          for c in chars_iter {
            w += unicode::char_width(self.options(), c);
            if w >= max_chars_width {
              return Some(ArcStr::from(builder));
            }
            builder.push(c);
          }
          Some(ArcStr::from(builder))
        }
        None => None,
      },
      None => None,
    }
  }

  fn _clone_line_impl_wrap(
    &self,
    line_idx: usize,
    start_char_idx: usize,
    max_chars_width: usize,
    skip_cache: bool,
  ) -> Option<ArcStr> {
    let mut cached_lines = self.cached_lines.borrow_mut();

    let key = CachedLinesKey {
      line_idx,
      start_char_idx,
      max_chars: max_chars_width,
    };

    if skip_cache {
      self._clone_line_impl(line_idx, start_char_idx, max_chars_width)
    } else {
      cached_lines
        .get_or_insert(&key, || {
          self._clone_line_impl(line_idx, start_char_idx, max_chars_width)
        })
        .cloned()
    }
  }

  /// Similar to [`Rope::get_line`], but collect and clone a normal string with
  /// limited length, for performance reason when the line is too long to clone.
  pub fn clone_line(
    &self,
    line_idx: usize,
    start_char_idx: usize,
    max_chars_width: usize,
  ) -> Option<ArcStr> {
    let result1 = self._clone_line_impl_wrap(
      line_idx,
      start_char_idx,
      max_chars_width,
      false,
    );

    // Ensure cached version and non-cached version have same results.
    if cfg!(debug_assertions) {
      let result2 = self._clone_line_impl_wrap(
        line_idx,
        start_char_idx,
        max_chars_width,
        true,
      );
      debug_assert_eq!(result1, result2);
    }

    result1
  }

  // NOTE: Actually here we use a specified algorithm that keeps compatible with the `ropey`
  // library since we heavily rely on it, and cannot do anything without it. But anyway it works
  // great, so let's keep it.
  pub fn is_eol_on_rope_line(line: &RopeSlice, char_idx: usize) -> bool {
    let len_chars = line.len_chars();

    // The eol detection logic (NOTE: We don't check the file format option):
    //
    // 1. If the last two chars are CRLF (`\r\n`), and the `char_idx` is one of them, then it is
    //    (one of) the eol. Usually for Windows/Dos.
    // 2. If the last char is CR (`\r`) or LF (`\n`), and `char_idx` is it, then it is the eol.

    let is_crlf = len_chars >= 2
      && char_idx >= len_chars - 2
      && char_idx < len_chars
      && format!("{}{}", line.char(len_chars - 2), line.char(len_chars - 1))
        == EndOfLineOption::Crlf.to_compact_string();
    let is_cr_or_lf = len_chars >= 1
      && char_idx == len_chars - 1
      && (format!("{}", line.char(len_chars - 1))
        == EndOfLineOption::Cr.to_compact_string()
        || format!("{}", line.char(len_chars - 1))
          == EndOfLineOption::Lf.to_compact_string());

    is_crlf || is_cr_or_lf
  }

  // Same logic with `is_eol_on_rope_line`, except the `absolute_char_idx` is
  // an absolute char index on whole rope.
  pub fn is_eol_on_rope(rope: &Rope, absolute_char_idx: usize) -> bool {
    let len_chars = rope.len_chars();

    let is_crlf = len_chars >= 2
      && absolute_char_idx >= len_chars - 2
      && absolute_char_idx < len_chars
      && format!("{}{}", rope.char(len_chars - 2), rope.char(len_chars - 1))
        == EndOfLineOption::Crlf.to_compact_string();
    let is_cr_or_lf = len_chars >= 1
      && absolute_char_idx == len_chars - 1
      && (format!("{}", rope.char(len_chars - 1))
        == EndOfLineOption::Cr.to_compact_string()
        || format!("{}", rope.char(len_chars - 1))
          == EndOfLineOption::Lf.to_compact_string());

    is_crlf || is_cr_or_lf
  }

  /// Get last char index on line, include invisible end-of-line chars.
  ///
  /// It returns the char index if exists, returns `None` if line not exists or line is empty.
  pub fn last_char_idx_on_line_include_eol(
    &self,
    line_idx: usize,
  ) -> Option<usize> {
    match self.rope.get_line(line_idx) {
      Some(line) => {
        let line_len_chars = line.len_chars();
        if line_len_chars > 0 {
          Some(line_len_chars - 1)
        } else {
          None
        }
      }
      None => None,
    }
  }

  /// Get last visible char index on line, it takes below scenarios into considerations:
  ///
  /// - The `\r\n` is eol.
  /// - The `\n` is eol.
  /// - The `\r` is eol. NOTE: This is a legacy on Mac, which is actually not used in
  ///   today's computer.
  ///
  /// It returns the char index if exists, returns `None` if line not exists or line is
  /// empty/blank.
  pub fn last_char_idx_on_line_exclude_eol(
    &self,
    line_idx: usize,
  ) -> Option<usize> {
    match self.rope.get_line(line_idx) {
      Some(line) => match self.last_char_idx_on_line_include_eol(line_idx) {
        Some(last_char) => {
          let mut c = last_char;
          while c > 0 && Self::is_eol_on_rope_line(&line, c) {
            c = c.saturating_sub(1);
          }
          if Self::is_eol_on_rope_line(&line, c) {
            None
          } else {
            Some(c)
          }
        }
        None => None,
      },
      None => None,
    }
  }

  /// Whether the `line_idx`/`char_idx` is eol (end-of-line).
  pub fn is_eol(&self, line_idx: usize, char_idx: usize) -> bool {
    match self.rope.get_line(line_idx) {
      Some(line) => Self::is_eol_on_rope_line(&line, char_idx),
      None => false,
    }
  }

  /// Whether the `line_idx`/`char_idx` is eol (end-of-line), or line end.
  pub fn is_eol_or_line_end(&self, line_idx: usize, char_idx: usize) -> bool {
    match self.rope.get_line(line_idx) {
      Some(line) => {
        char_idx >= line.len_chars()
          || Self::is_eol_on_rope_line(&line, char_idx)
      }
      None => false,
    }
  }
}
// Rope }

// Options {
impl Text {
  pub fn options(&self) -> &BufferOptions {
    &self.options
  }

  pub fn set_options(&mut self, options: &BufferOptions) {
    self.options = *options;
  }
}
// Options }

// Display Width {
impl Text {
  fn with_cached_column_idx<U, F>(
    &self,
    line_idx: usize,
    rope_line: &RopeSlice,
    f: F,
  ) -> U
  where
    F: FnOnce(&mut ColumnIndex) -> U,
  {
    f(self
      .cached_width
      .borrow_mut()
      .get_or_insert_mut(&line_idx, || {
        Some(ColumnIndex::with_capacity(rope_line.len_chars()))
      })
      .unwrap())
  }

  /// See [`ColumnIndex::width_before`].
  ///
  /// # Panics
  ///
  /// It panics if the `line_idx` doesn't exist in rope.
  pub fn width_before(&self, line_idx: usize, char_idx: usize) -> usize {
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.width_before(&self.options, &rope_line, char_idx)
    })
  }

  /// See [`ColumnIndex::width_until`].
  ///
  /// # Panics
  ///
  /// It panics if the `line_idx` doesn't exist in rope.
  pub fn width_until(&self, line_idx: usize, char_idx: usize) -> usize {
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.width_until(&self.options, &rope_line, char_idx)
    })
  }

  /// See [`ColumnIndex::char_before`].
  ///
  /// # Panics
  ///
  /// It panics if the `line_idx` doesn't exist in rope.
  pub fn char_before(&self, line_idx: usize, width: usize) -> Option<usize> {
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.char_before(&self.options, &rope_line, width)
    })
  }

  /// See [`ColumnIndex::char_at`].
  ///
  /// # Panics
  ///
  /// It panics if the `line_idx` doesn't exist in rope.
  pub fn char_at(&self, line_idx: usize, width: usize) -> Option<usize> {
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.char_at(&self.options, &rope_line, width)
    })
  }

  /// See [`ColumnIndex::char_after`].
  ///
  /// # Panics
  ///
  /// It panics if the `line_idx` doesn't exist in rope.
  pub fn char_after(&self, line_idx: usize, width: usize) -> Option<usize> {
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.char_after(&self.options, &rope_line, width)
    })
  }

  /// See [`ColumnIndex::last_char_until`].
  ///
  /// # Panics
  ///
  /// It panics if the `line_idx` doesn't exist in rope.
  pub fn last_char_until(
    &self,
    line_idx: usize,
    width: usize,
  ) -> Option<usize> {
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.last_char_until(&self.options, &rope_line, width)
    })
  }

  /// See [`ColumnIndex::truncate_since_char`].
  fn truncate_cached_line_since_char(&self, line_idx: usize, char_idx: usize) {
    // cached cloned lines
    self
      .cached_lines
      .borrow_mut()
      .retain(|key| key.line_idx != line_idx);

    // cached lines width
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.truncate_since_char(char_idx)
    })
  }

  #[allow(dead_code)]
  /// See [`ColumnIndex::truncate_since_width`].
  fn truncate_cached_line_since_width(&self, line_idx: usize, width: usize) {
    // cached cloned lines
    self
      .cached_lines
      .borrow_mut()
      .retain(|key| key.line_idx != line_idx);

    // cached lines width
    let rope_line = self.rope.line(line_idx);
    self.with_cached_column_idx(line_idx, &rope_line, |col| {
      col.truncate_since_width(width)
    })
  }

  #[allow(dead_code)]
  /// Remove one cached line.
  fn remove_cached_line(&self, line_idx: usize) {
    // cached cloned lines
    self
      .cached_lines
      .borrow_mut()
      .retain(|key| key.line_idx != line_idx);

    // cached lines width
    self
      .cached_width
      .borrow_mut()
      .retain(|line| *line != line_idx);
  }

  /// Retain multiple cached lines by lambda function `f`.
  fn retain_cached_lines<F>(&self, f: F)
  where
    F: Fn(/* line_idx */ &usize) -> bool,
  {
    // cached clone lines
    self
      .cached_lines
      .borrow_mut()
      .retain(|key| f(&key.line_idx));

    // cached lines width
    self
      .cached_width
      .borrow_mut()
      .retain(|line_idx| f(line_idx));
  }

  /// Clear cache.
  fn clear_cached_lines(&self) {
    self.cached_lines.borrow_mut().clear();
    self.cached_width.borrow_mut().clear();
  }

  #[allow(dead_code)]
  /// Resize cache.
  fn resize_cached_lines(&self, canvas_size: U16Size) {
    self.cached_lines.borrow_mut().resize(canvas_size);
    self.cached_width.borrow_mut().resize(canvas_size);
  }
}
// Display Width }

#[cfg(test)]
fn _ropeline_to_string(bufline: &ropey::RopeSlice) -> String {
  let mut builder = String::with_capacity(bufline.len_chars());
  for c in bufline.chars() {
    builder.push(c);
  }
  builder
}

impl Text {
  #[cfg(not(test))]
  fn dbg_print_textline_absolutely(
    &mut self,
    _line_idx: usize,
    _absolute_char_idx: usize,
    _msg: &str,
  ) {
  }

  #[cfg(test)]
  fn dbg_print_textline_absolutely(
    &mut self,
    line_idx: usize,
    absolute_char_idx: usize,
    msg: &str,
  ) {
    trace!(
      "{} text line:{},absolute_char:{}",
      msg, line_idx, absolute_char_idx
    );

    match self.rope().get_line(line_idx) {
      Some(line) => {
        trace!("len_chars:{}", line.len_chars());
        let start_char_on_line = self.rope().line_to_char(line_idx);

        let mut builder1 = String::new();
        let mut builder2 = String::new();
        for (i, c) in line.chars().enumerate() {
          let w = self.char_width(c);
          if w > 0 {
            builder1.push(c);
          }
          let s: String = std::iter::repeat_n(
            if i + start_char_on_line == absolute_char_idx {
              '^'
            } else {
              ' '
            },
            w,
          )
          .collect();
          builder2.push_str(s.as_str());
        }
        trace!("-{}-", builder1);
        trace!("-{}-", builder2);
      }
      None => trace!("line not exist"),
    }

    trace!("{} whole text:", msg);
    for i in 0..self.rope().len_lines() {
      trace!("{i}:{:?}", _ropeline_to_string(&self.rope().line(i)));
    }
  }

  #[cfg(not(test))]
  fn dbg_print_textline(&self, _line_idx: usize, _char_idx: usize, _msg: &str) {
  }

  #[cfg(test)]
  fn dbg_print_textline(&self, line_idx: usize, char_idx: usize, msg: &str) {
    trace!("{} text line:{},char:{}", msg, line_idx, char_idx);

    match self.rope().get_line(line_idx) {
      Some(bufline) => {
        trace!("len_chars:{}", bufline.len_chars());
        let mut builder1 = String::new();
        let mut builder2 = String::new();
        for (i, c) in bufline.chars().enumerate() {
          let w = self.char_width(c);
          if w > 0 {
            builder1.push(c);
          }
          let s: String =
            std::iter::repeat_n(if i == char_idx { '^' } else { ' ' }, w)
              .collect();
          builder2.push_str(s.as_str());
        }
        trace!("-{}-", builder1);
        trace!("-{}-", builder2);
      }
      None => trace!("line not exist"),
    }

    trace!("{}, whole buffer:", msg);
    for i in 0..self.rope().len_lines() {
      trace!("{i}:{:?}", _ropeline_to_string(&self.rope().line(i)));
    }
  }
}

// Edit {
impl Text {
  /// Restore the `EOL` at the end of text file.
  fn restore_eol_at_end_if_not_exist(&mut self) {
    let eol = Into::<EndOfLineOption>::into(self.options().file_format());

    let buffer_len_chars = self.rope.len_chars();
    let last_char_on_buf = buffer_len_chars.saturating_sub(1);
    match self.rope.get_char(last_char_on_buf) {
      Some(_c) => {
        let c_is_eol = Self::is_eol_on_rope(self.rope(), last_char_on_buf);
        // Only append eol when the whole text rope doesn't have it at end.
        if !c_is_eol {
          self
            .rope_mut()
            .insert(buffer_len_chars, eol.to_compact_string().as_str());
          let inserted_line_idx = self.rope.char_to_line(buffer_len_chars);
          self.retain_cached_lines(|line_idx| *line_idx < inserted_line_idx);
          self.dbg_print_textline_absolutely(
            inserted_line_idx,
            buffer_len_chars,
            "Eol appended(non-empty)",
          );
        }
      }
      None => {
        self
          .rope_mut()
          .insert(0_usize, eol.to_compact_string().as_str());
        self.clear_cached_lines();
        self.dbg_print_textline_absolutely(
          0_usize,
          buffer_len_chars,
          "Eol appended(empty)",
        );
      }
    }
  }

  /// Convert 2-dimensional `(line_idx, char_idx)` into 1-dimensional absolute
  /// `char_idx`.
  pub fn to_absolute_char_idx(
    &self,
    line_idx: usize,
    char_idx: usize,
  ) -> usize {
    // debug_assert!(!payload.is_empty());
    debug_assert!(self.rope.get_line(line_idx).is_some());
    debug_assert!(char_idx <= self.rope.line(line_idx).len_chars());

    let absolute_line_idx = self.rope.line_to_char(line_idx);
    absolute_line_idx + char_idx
  }

  /// Convert 1-dimensional absolute `char_idx` into 2-dimensional
  /// `(line_idx, char_idx)`.
  pub fn to_line_idx_and_char_idx(
    &self,
    absolute_char_idx: usize,
  ) -> (/* line_idx */ usize, /* char_idx*/ usize) {
    // debug_assert!(!payload.is_empty());
    debug_assert!(absolute_char_idx <= self.rope.len_chars());

    let line_idx = self.rope.char_to_line(absolute_char_idx);
    let line_absolute_char_idx = self.rope.line_to_char(line_idx);
    let char_idx = absolute_char_idx - line_absolute_char_idx;
    (line_idx, char_idx)
  }

  fn reset_cache_after_edit(
    &mut self,
    line_idx: usize,
    char_idx: usize,
    line_idx_after_edit: usize,
    char_idx_after_edit: usize,
  ) {
    if line_idx == line_idx_after_edit {
      // If before/after insert, the cursor line doesn't change, it means the
      // inserted text doesn't contain line break, i.e. it is still the same
      // line. Thus only need to truncate chars after insert position on the
      // same line.

      // debug_assert!(char_idx_after_edit >= char_idx);
      let truncate_char_idx = std::cmp::min(char_idx_after_edit, char_idx);
      self.truncate_cached_line_since_char(
        line_idx,
        truncate_char_idx.saturating_sub(1),
      );
    } else {
      // Otherwise the inserted text contains line breaks, and we have to
      // truncate all the cached lines below the cursor line, because we have
      // new lines.
      let truncate_line_idx = std::cmp::min(line_idx_after_edit, line_idx);
      self.retain_cached_lines(|line_idx| *line_idx < truncate_line_idx);
    }
  }

  /// Insert text payload at position `line_idx`/`char_idx`, insert nothing if
  /// text payload is empty.
  ///
  /// # Returns
  /// 1. It returns the new position `(line_idx,char_idx)` after text inserted.
  /// 2. It returns the same `line_idx`/`char_idx` if the text payload is empty.
  ///
  /// # Panics
  /// If the position doesn't exist on text rope.
  pub fn insert(
    &mut self,
    line_idx: usize,
    char_idx: usize,
    payload: CompactString,
  ) -> (usize, usize) {
    let absolute_char_idx = self.to_absolute_char_idx(line_idx, char_idx);
    debug_assert_eq!(
      self.to_line_idx_and_char_idx(absolute_char_idx).0,
      line_idx
    );
    debug_assert_eq!(
      self.to_line_idx_and_char_idx(absolute_char_idx).1,
      char_idx
    );

    self.dbg_print_textline(line_idx, char_idx, "Before insert");

    self.rope_mut().insert(absolute_char_idx, payload.as_str());

    // The `text` may contains line break '\n', which can interrupts the
    // `line_idx` and we need to recalculate it.
    let absolute_char_idx_after_inserted =
      absolute_char_idx + payload.chars().count();
    let (line_idx_after_inserted, char_idx_after_inserted) =
      self.to_line_idx_and_char_idx(absolute_char_idx_after_inserted);

    self.reset_cache_after_edit(
      line_idx,
      char_idx,
      line_idx_after_inserted,
      char_idx_after_inserted,
    );

    // Try restore eol if `fix_end_of_line` is on.
    if self.options().fix_end_of_line() {
      self.restore_eol_at_end_if_not_exist();
    }

    self.dbg_print_textline(
      line_idx_after_inserted,
      char_idx_after_inserted,
      "After inserted",
    );

    (line_idx_after_inserted, char_idx_after_inserted)
  }

  fn n_chars_to_left(&self, absolute_char_idx: usize, n: usize) -> usize {
    debug_assert!(n > 0);
    let mut i = absolute_char_idx as isize;
    let mut acc = 0;

    while acc < n && i >= 0 {
      let c1 = self.rope.get_char(i as usize);
      let c2 = if i > 0 {
        self.rope.get_char((i - 1) as usize)
      } else {
        None
      };
      if c1.is_some()
        && c2.is_some()
        && format!("{}{}", c2.unwrap(), c1.unwrap())
          == EndOfLineOption::Crlf.to_compact_string()
      {
        i -= 2;
      } else {
        i -= 1;
      }
      acc += 1;
    }
    std::cmp::max(i, 0) as usize
  }

  fn n_chars_to_right(&self, absolute_char_idx: usize, n: usize) -> usize {
    debug_assert!(n > 0);

    let len_chars = self.rope.len_chars();
    let mut i = absolute_char_idx;
    let mut acc = 0;

    while acc < n && i <= len_chars {
      let c1 = self.rope.get_char(i);
      let c2 = self.rope.get_char(i + 1);
      if c1.is_some()
        && c2.is_some()
        && format!("{}{}", c1.unwrap(), c2.unwrap())
          == EndOfLineOption::Crlf.to_compact_string()
      {
        i += 2;
      } else {
        i += 1;
      }
      acc += 1;
    }
    std::cmp::min(i, len_chars)
  }

  /// Calculate the absolute char index range that will be deleted, by line
  /// index and its char index on the line.
  ///
  /// NOTE: This API only removes char range in 1 line, it cannot remove char
  /// range cross multiple lines.
  pub fn get_removable_char_idx_range(
    &self,
    line_idx: usize,
    char_idx: usize,
    n: isize,
  ) -> Option<Range<usize>> {
    if line_idx >= self.rope.len_lines() {
      return None;
    }
    if char_idx > self.rope.line(line_idx).len_chars() {
      return None;
    }
    debug_assert!(char_idx <= self.rope.line(line_idx).len_chars());

    let absolute_char_idx = self.to_absolute_char_idx(line_idx, char_idx);
    debug_assert_eq!(
      self.to_line_idx_and_char_idx(absolute_char_idx).0,
      line_idx
    );
    debug_assert_eq!(
      self.to_line_idx_and_char_idx(absolute_char_idx).1,
      char_idx
    );

    self.dbg_print_textline(line_idx, char_idx, "Before delete");

    // NOTE: We also need to handle the windows-style line break `\r\n`, i.e.
    // we treat `\r\n` as 1 single char when deleting it.
    let result = if n > 0 {
      // Delete to right side, on range `[cursor..cursor+n)`.
      let upper = self.n_chars_to_right(absolute_char_idx, n as usize);
      debug_assert!(
        upper <= self.rope.len_chars(),
        "upper ({}) <= self.rope.len_chars() ({})",
        upper,
        self.rope.len_chars()
      );
      absolute_char_idx..upper
    } else {
      // Delete to left side, on range `[cursor-n,cursor)`.
      let lower = self.n_chars_to_left(absolute_char_idx, (-n) as usize);
      lower..absolute_char_idx
    };
    Some(result)
  }

  /// Delete `n` text chars at position `line_idx`/`char_idx`, to either left
  /// or right direction.
  ///
  /// 1. If `n<0`, delete to the left direction, i.e. delete the range
  ///    `[char_idx-n, char_idx)`.
  /// 2. If `n>0`, delete to the right direction, i.e. delete the range
  ///    `[char_idx, char_idx+n)`.
  /// 3. If `n=0`, delete nothing.
  ///
  /// # Returns
  /// 1. It returns the new position `(line_idx,char_idx)` after deleted.
  /// 2. It returns `None` if delete nothing.
  ///
  /// # Panics
  /// It panics if the position doesn't exist on text rope.
  pub fn remove(
    &mut self,
    line_idx: usize,
    char_idx: usize,
    n: isize,
  ) -> Option<(usize, usize)> {
    let delete_range = self.get_removable_char_idx_range(line_idx, char_idx, n);
    if delete_range.is_none() || delete_range.as_ref().unwrap().is_empty() {
      return None;
    }
    let delete_range = delete_range.unwrap();

    self.rope_mut().remove(delete_range.clone());

    let absolute_char_idx_after_deleted = delete_range.start;
    let absolute_char_idx_after_deleted =
      std::cmp::min(absolute_char_idx_after_deleted, self.rope.len_chars());
    let (line_idx_after_deleted, char_idx_after_deleted) =
      self.to_line_idx_and_char_idx(absolute_char_idx_after_deleted);

    self.reset_cache_after_edit(
      line_idx,
      char_idx,
      line_idx_after_deleted,
      char_idx_after_deleted,
    );

    // Try restore eol if `fix_end_of_line` is on.
    if self.options().fix_end_of_line() {
      self.restore_eol_at_end_if_not_exist();
    }

    self.dbg_print_textline(
      line_idx_after_deleted,
      char_idx_after_deleted,
      "After deleted",
    );

    Some((line_idx_after_deleted, char_idx_after_deleted))
  }

  /// Clear all text payload in current content.
  pub fn clear(&mut self) {
    self.rope_mut().remove(0..);
    self.clear_cached_lines();
  }
}
// Edit }