sl_liner/
buffer.rs

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
918
919
920
921
922
923
924
925
926
927
928
use crate::grapheme_iter::GraphemeIter;
use std::fmt::{self, Write as FmtWrite};
use std::io::{self, Write};
use std::iter::FromIterator;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

/// A modification performed on a `Buffer`. These are used for the purpose of undo/redo.
#[derive(Debug, Clone)]
pub enum Action {
    Insert { start: usize, text: String },
    Remove { start: usize, text: String },
    Noop { start: usize },
    StartGroup,
    EndGroup,
}

impl Action {
    pub fn do_on(&self, buf: &mut Buffer) -> Option<usize> {
        match *self {
            Action::Insert { start, ref text } => {
                buf.insert_raw(start, text);
                Some(start)
            }
            Action::Remove { start, ref text } => {
                let len = text.len();
                buf.remove_raw(start, start + len, false);
                if len > start {
                    Some(0)
                } else {
                    Some(start - len)
                }
            }
            Action::Noop { start } => Some(start),
            Action::StartGroup | Action::EndGroup => None,
        }
    }

    pub fn undo(&self, buf: &mut Buffer) -> Option<usize> {
        match *self {
            Action::Insert { start, ref text } => {
                buf.remove_raw(start, start + text.len(), false);
                Some(start)
            }
            Action::Remove { start, ref text } => {
                buf.insert_raw(start, text);
                Some(start)
            }
            Action::Noop { start } => Some(start),
            Action::StartGroup | Action::EndGroup => None,
        }
    }
}

/// A buffer for text in the line editor.
///
/// It keeps track of each action performed on it for use with undo/redo.
#[derive(Debug, Clone)]
pub struct Buffer {
    data: String,
    actions: Vec<Action>,
    undone_actions: Vec<Action>,
    register: Option<String>,
    curr_num_graphemes: usize,
    grapheme_indices: Vec<usize>,
}

impl PartialEq for Buffer {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl Eq for Buffer {}

impl From<Buffer> for String {
    fn from(buf: Buffer) -> Self {
        buf.data
    }
}

impl From<String> for Buffer {
    fn from(s: String) -> Self {
        s.chars().collect()
    }
}

impl<'a> From<&'a str> for Buffer {
    fn from(s: &'a str) -> Self {
        s.chars().collect()
    }
}

impl fmt::Display for Buffer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let chars = self.data.chars();
        for c in chars {
            f.write_char(c)?;
        }
        Ok(())
    }
}

impl FromIterator<char> for Buffer {
    fn from_iter<T: IntoIterator<Item = char>>(t: T) -> Self {
        let str = t.into_iter().collect::<String>();
        let g_idxs = Buffer::string_to_grapheme_indices(&str);
        Buffer {
            data: str,
            actions: Vec::new(),
            undone_actions: Vec::new(),
            register: None,
            curr_num_graphemes: g_idxs.len(),
            grapheme_indices: g_idxs,
        }
    }
}

impl Default for Buffer {
    fn default() -> Self {
        Self::new()
    }
}

impl Buffer {
    pub fn new() -> Self {
        Buffer {
            data: String::new(),
            actions: Vec::new(),
            undone_actions: Vec::new(),
            register: None,
            curr_num_graphemes: 0,
            grapheme_indices: Vec::new(),
        }
    }

    pub fn clear_actions(&mut self) {
        self.actions.clear();
        self.undone_actions.clear();
    }

    pub fn start_undo_group(&mut self) {
        self.actions.push(Action::StartGroup);
    }

    pub fn end_undo_group(&mut self) {
        self.actions.push(Action::EndGroup);
    }

    pub fn undo(&mut self) -> Option<usize> {
        use Action::*;

        let mut old_cursor_pos = None;
        let mut group_nest = 0;
        let mut group_count = 0;
        while let Some(act) = self.actions.pop() {
            self.undone_actions.push(act.clone());
            if let Some(pos) = act.undo(self) {
                old_cursor_pos = Some(pos)
            }
            match act {
                EndGroup => {
                    group_nest += 1;
                    group_count = 0;
                }
                StartGroup => group_nest -= 1,
                // count the actions in this group so we can ignore empty groups below
                _ => group_count += 1,
            }

            // if we aren't in a group, and the last group wasn't empty
            if group_nest == 0 && group_count > 0 {
                break;
            }
        }
        old_cursor_pos
    }

    pub fn redo(&mut self) -> Option<usize> {
        use Action::*;

        let mut old_cursor_pos = None;
        let mut group_nest = 0;
        let mut group_count = 0;
        while let Some(act) = self.undone_actions.pop() {
            if let Some(pos) = act.do_on(self) {
                old_cursor_pos = Some(pos)
            }
            self.actions.push(act.clone());
            match act {
                StartGroup => {
                    group_nest += 1;
                    group_count = 0;
                }
                EndGroup => group_nest -= 1,
                // count the actions in this group so we can ignore empty groups below
                _ => group_count += 1,
            }

            // if we aren't in a group, and the last group wasn't empty
            if group_nest == 0 && group_count > 0 {
                break;
            }
        }
        old_cursor_pos
    }

    pub fn revert(&mut self) -> bool {
        if self.actions.is_empty() {
            return false;
        }

        while self.undo().is_some() {}
        true
    }

    fn push_action(&mut self, act: Action) {
        self.actions.push(act);
        self.undone_actions.clear();
    }

    pub fn is_last_arg_newline(&self) -> bool {
        let mut iter = self
            .data
            .split_word_bounds()
            .filter(|s| !s.is_empty())
            .rev();
        let last = iter.next().map_or("", |s| s);
        let next_last = iter.next().map_or("", |s| s);
        last == "\n" || (last == "\r" && next_last == "\n")
    }

    pub fn last_arg(&self) -> Option<&str> {
        self.data
            .split_word_bounds()
            .filter(|s| !s.trim().is_empty())
            .last()
    }

    pub fn num_lines(&self) -> usize {
        self.lines().count()
    }

    pub fn num_graphemes(&self) -> usize {
        self.curr_num_graphemes
    }

    pub fn lines(&self) -> impl Iterator<Item = &str> + '_ {
        self.data.split('\n')
    }

    pub fn num_bytes(&self) -> usize {
        self.data.as_bytes().len()
    }

    fn get_grapheme(&self, cursor: usize) -> Option<&str> {
        GraphemeIter::new(&self.data, &self.grapheme_indices, 0, self.num_graphemes()).get(cursor)
    }

    pub fn grapheme_before(&self, cursor: usize) -> Option<&str> {
        self.get_grapheme(cursor - 1)
    }

    pub fn grapheme_after(&self, cursor: usize) -> Option<&str> {
        self.get_grapheme(cursor)
    }

    /// Returns the graphemes removed. Does not register as an action in the undo/redo
    /// buffer or in the buffer's register.
    pub fn remove_unrecorded(&mut self, start: usize, end: usize) {
        self.remove_raw(start, end, false);
    }

    /// Returns the number of graphemes removed.
    pub fn remove(&mut self, start: usize, end: usize) -> usize {
        let orig_len = self.num_graphemes();
        self.remove_raw(start, end, true);
        let new_len = self.num_graphemes();
        orig_len - new_len
    }

    /// Insert contents of register to the right or to the left of the provided start index in the
    /// current buffer
    /// and return length of text inserted.
    pub fn insert_register_around_idx(
        &mut self,
        mut idx: usize,
        count: usize,
        right: bool,
    ) -> usize {
        let mut inserted = 0;
        if let Some(text) = self.register.as_ref() {
            if !text.is_empty() {
                let orig_len = self.num_graphemes();
                if orig_len > idx && right {
                    // insert to right of cursor
                    idx += 1;
                }

                let text = if count > 1 {
                    let mut full_text = String::with_capacity(text.len() * count);
                    for _i in 0..count {
                        full_text.push_str(text);
                    }
                    full_text
                } else {
                    text.to_owned()
                };
                self.insert_action(Action::Insert { start: idx, text });
                let new_len = self.num_graphemes();
                inserted = new_len - orig_len;
            }
        }
        inserted
    }

    pub fn insert_str(&mut self, start: usize, text: &str) -> usize {
        let orig_len = self.num_graphemes();
        let text = text.to_owned();
        let act = Action::Insert { start, text };
        self.insert_action(act);
        let new_len = self.num_graphemes();
        new_len - orig_len
    }

    pub fn insert<'a, I>(&mut self, start: usize, text: I) -> usize
    where
        I: Iterator<Item = &'a char>,
    {
        let text: String = text.collect::<String>();
        self.insert_str(start, &text)
    }

    pub fn insert_action(&mut self, act: Action) {
        act.do_on(self);
        self.push_action(act);
    }

    pub fn append_buffer(&mut self, other: &Buffer) -> usize {
        let start = self.num_graphemes();
        let other_data_offset = other.grapheme_indices.get(start).map_or(0, |o| *o);
        self.insert_str(start, &other.data[other_data_offset..])
    }

    pub fn copy_buffer(&mut self, other: &Buffer) -> usize {
        self.remove(0, self.curr_num_graphemes);
        self.insert_str(0, &other.data)
    }

    pub fn range_graphemes_all(&self) -> GraphemeIter {
        GraphemeIter::new(&self.data, &self.grapheme_indices, 0, self.num_graphemes())
    }

    pub fn range_graphemes_until(&self, until: usize) -> GraphemeIter {
        GraphemeIter::new(&self.data, &self.grapheme_indices, 0, until)
    }

    pub fn range_graphemes_from(&self, start: usize) -> GraphemeIter {
        GraphemeIter::new(
            &self.data,
            &self.grapheme_indices,
            start,
            self.num_graphemes(),
        )
    }

    pub fn range(&self, start: usize, end: usize) -> &str {
        if start == 0 && end >= self.curr_num_graphemes {
            self.range_graphemes_all().slice()
        } else if self.data.is_empty() || start == end {
            GraphemeIter::default().slice()
        } else {
            GraphemeIter::new(&self.data, &self.grapheme_indices, start, end).slice()
        }
    }

    pub fn range_graphemes(&self, start: usize, end: usize) -> GraphemeIter {
        if start == 0 && end >= self.curr_num_graphemes {
            self.range_graphemes_all()
        } else if self.data.is_empty() || start == end {
            GraphemeIter::default()
        } else {
            GraphemeIter::new(&self.data, &self.grapheme_indices, start, end)
        }
    }

    pub fn line_width_until(&self, until: usize) -> impl Iterator<Item = usize> + '_ {
        self.range_graphemes(0, until)
            .slice()
            .lines()
            .map(|line| line.width())
    }

    pub fn line_widths(&self) -> impl Iterator<Item = usize> + '_ {
        self.range_graphemes_all()
            .slice()
            .lines()
            .map(|line| line.width())
    }

    pub fn truncate(&mut self, num: usize) {
        self.remove(num, self.num_graphemes());
    }

    pub fn print<W>(&self, out: &mut W) -> io::Result<()>
    where
        W: Write,
    {
        out.write_all(self.as_bytes())
    }

    fn as_bytes(&self) -> &[u8] {
        self.data.as_bytes()
    }

    /// Takes other buffer, measures its length and prints this buffer from the point where
    /// the other stopped.
    /// Used to implement autosuggestions.
    pub fn print_rest<W>(&self, out: &mut W, after: usize) -> io::Result<usize>
    where
        W: Write,
    {
        let mut ret = 0;
        if self.curr_num_graphemes != 0 {
            if let Some(&offset) = self.grapheme_indices.get(after) {
                let bytes = &self.data.as_bytes()[offset..];
                out.write_all(bytes)?;
                ret = bytes.len();
            }
        }
        Ok(ret)
    }

    pub fn yank(&mut self, start: usize, end: usize) {
        let slice = self.range_graphemes(start, end).collect::<String>();
        self.register = Some(slice);
    }

    fn string_to_grapheme_indices(str: &str) -> Vec<usize> {
        str.grapheme_indices(true)
            .map(|o| o.0)
            .collect::<Vec<usize>>()
    }

    fn to_graphemes_indices(&self) -> Vec<usize> {
        Self::string_to_grapheme_indices(&self.data)
    }

    /// done after an insert/remove for two reasons:
    /// 1. the number of graphemes may change
    /// 2. knowing the length of the buffer in graphemes is an important
    /// constant for callers to reference.
    fn recompute_size(&mut self) {
        if self.data.is_empty() {
            self.curr_num_graphemes = 0;
            self.grapheme_indices.clear();
        } else {
            self.grapheme_indices = self.to_graphemes_indices();
            self.curr_num_graphemes = self.grapheme_indices.len();
        }
    }

    /// Push ch onto the end of the buffer.
    pub fn push(&mut self, ch: char) {
        self.data.push(ch);
        self.recompute_size();
    }

    fn remove_raw(&mut self, start: usize, end: usize, save_action: bool) {
        let mut logged_action = false;
        if !self.data.is_empty() && start != end {
            if start == 0 && end == self.num_graphemes() {
                let str = self.data.to_owned();
                self.data.clear();
                if save_action {
                    self.register = Some(str.to_owned());
                    self.push_action(Action::Remove { start, text: str });
                    logged_action = true;
                }
            } else {
                let start_opt = self.grapheme_indices.get(start);
                let len = self.data.len();
                let end_opt = if end >= self.num_graphemes() {
                    Some(&len)
                } else {
                    self.grapheme_indices.get(end)
                };

                if let (Some(start_idx), Some(end_idx)) = (start_opt, end_opt) {
                    let drain = self.data.drain(start_idx..end_idx);
                    if save_action {
                        let str = drain.collect::<String>();
                        self.register = Some(str.to_owned());
                        self.push_action(Action::Remove { start, text: str });
                        logged_action = true;
                    }
                }
            }
        }
        if !logged_action && save_action {
            self.push_action(Action::Noop { start });
        } else {
            self.recompute_size();
        }
    }

    fn insert_raw(&mut self, start: usize, new_graphemes: &str) {
        if start >= self.num_graphemes() {
            let len = self.data.len();
            self.data.insert_str(len, new_graphemes);
        } else {
            let offset = self.grapheme_indices.get(start);
            if let Some(offset) = offset {
                self.data.insert_str(*offset, new_graphemes);
            }
        }
        self.recompute_size();
    }

    /// Check if the other buffer starts with the same content as this one.
    /// Used to implement autosuggestions.
    pub fn starts_with(&self, other: &Buffer) -> bool {
        let other = &other.data;
        let this = &self.data;
        let other_len = other.len();
        let self_len = this.len();
        if !other.is_empty() && self_len != other_len {
            this.starts_with(other)
        } else {
            false
        }
    }

    /// Check if the buffer contains pattern.
    /// Used to implement history search.
    pub fn contains(&self, other: &Buffer) -> bool {
        let other = &other.data;
        if other.is_empty() {
            false
        } else {
            self.data.contains(other)
        }
    }

    /// Return true if the buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Returns the first grapheme of the buffer or None if empty.
    pub fn first(&self) -> Option<&str> {
        let mut ret = None;
        if !self.data.is_empty() {
            if let Some(str) = self.range_graphemes_all().next() {
                ret = Some(str)
            }
        }
        ret
    }

    /// Returns the last grapheme of the buffer or None if empty.
    pub fn last(&self) -> Option<&str> {
        let mut ret = None;
        if !self.data.is_empty() {
            if let Some(str) = self.range_graphemes_all().rev().next() {
                ret = Some(str)
            }
        }
        ret
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_truncate_empty() {
        let mut buf = Buffer::new();
        buf.truncate(0);
        assert_eq!(String::from(buf), "");
    }

    #[test]
    fn test_truncate_all() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.truncate(0);
        assert_eq!(String::from(buf), "");
    }

    #[test]
    fn test_truncate_end() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let end = buf.num_graphemes();
        buf.truncate(end);
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_truncate_part() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.truncate(3);
        assert_eq!(String::from(buf), "abc");
    }

    #[test]
    fn test_truncate_empty_undo() {
        let mut buf = Buffer::new();
        buf.truncate(0);
        buf.undo();
        assert_eq!(String::from(buf), "");
    }

    #[test]
    fn test_truncate_all_then_undo() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.truncate(0);
        buf.undo();
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_truncate_end_then_undo() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let end = buf.num_graphemes();
        buf.truncate(end);
        buf.undo();
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_truncate_part_then_undo() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.truncate(3);
        buf.undo();
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_revert_undo_group() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.end_undo_group();
        assert_eq!(String::from(buf.clone()), "defg");
        assert!(buf.revert());
        assert_eq!(String::from(buf), "");
    }

    #[test]
    fn test_clear_undo_group() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.end_undo_group();
        buf.clear_actions();
        buf.revert();
        assert!(buf.undo().is_none());
        assert_eq!(String::from(buf), "defg");
    }

    #[test]
    fn test_undo_group() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.end_undo_group();
        assert!(buf.undo().is_some());
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_redo_group() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.remove(0, 1);
        buf.end_undo_group();
        assert!(buf.undo().is_some());
        assert!(buf.redo().is_some());
        assert_eq!(String::from(buf), "defg");
    }

    #[test]
    fn test_nested_undo_group() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.end_undo_group();
        buf.remove(0, 1);
        buf.end_undo_group();
        assert!(buf.undo().is_some());
        assert_eq!(String::from(buf), "abcdefg");
    }

    #[test]
    fn test_nested_redo_group() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.start_undo_group();
        buf.remove(0, 1);
        buf.end_undo_group();
        buf.remove(0, 1);
        buf.end_undo_group();
        assert!(buf.undo().is_some());
        assert!(buf.redo().is_some());
        assert_eq!(String::from(buf), "defg");
    }

    #[test]
    fn test_starts_with() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['a', 'b', 'c'].iter());
        assert_eq!(buf.starts_with(&buf2), true);
    }

    #[test]
    fn test_does_not_start_with() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['a', 'b', 'c'].iter());
        assert_eq!(buf.starts_with(&buf2), false);
    }

    #[test]
    fn test_is_not_match2() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['x', 'y', 'z'].iter());
        assert_eq!(buf.starts_with(&buf2), false);
    }

    #[test]
    fn test_partial_eq() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['x', 'y', 'z'].iter());
        assert_eq!(buf.eq(&buf2), false);
        let mut buf3 = Buffer::new();
        buf3.insert(0, ['x', 'y', 'z'].iter());
        assert_eq!(buf2.eq(&buf3), true);
    }

    #[test]
    fn test_contains() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['a', 'b', 'c'].iter());
        assert_eq!(buf.contains(&buf2), true);
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['c', 'd', 'e'].iter());
        assert_eq!(buf.contains(&buf2), true);
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['e', 'f', 'g'].iter());
        assert_eq!(buf.contains(&buf2), true);
        let empty_buf = Buffer::default();
        assert_eq!(buf.contains(&empty_buf), false);
    }

    #[test]
    fn test_does_not_contain() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['x', 'b', 'c'].iter());
        assert_eq!(buf.contains(&buf2), false);
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['a', 'b', 'd'].iter());
        assert_eq!(buf.contains(&buf2), false);
    }

    #[test]
    fn test_print() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut out: Vec<u8> = vec![];
        buf.print(&mut out).unwrap();
        assert_eq!(out.len(), 7);
        let mut str = String::new();
        for x in out {
            str.push(x as char);
        }
        assert_eq!(str, String::from("abcdefg"));
    }

    #[test]
    fn test_print_rest() {
        let mut buf = Buffer::new();
        buf.insert(0, ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter());
        let mut buf2 = Buffer::new();
        buf2.insert(0, ['a', 'b', 'c'].iter());
        let mut out: Vec<u8> = vec![];
        buf.print_rest(&mut out, buf2.data.len()).unwrap();
        assert_eq!(out.len(), 4);
    }

    #[test]
    fn test_append() {
        let orig = String::from("hello string \u{938}\u{94d}\u{924}\u{947}");
        let mut buf0 = Buffer::from(orig.clone());
        let append = "\u{938}\u{94d}\u{924}\u{947}a";
        let buf1 = Buffer::from(append);
        buf0.append_buffer(&buf1);
        assert_eq!(Buffer::from(orig + append), buf0);
    }

    #[test]
    fn test_first() {
        let s = "\u{938}\u{94d}\u{924}\u{947} hello string";
        let buf = Buffer::from(s);
        let first = buf.first();
        assert!(first.is_some());
        let s = "\u{938}\u{94d}";
        assert_eq!(s, first.unwrap());
    }

    #[test]
    fn test_push() {
        let s = "hello string \u{938}\u{94d}\u{924}\u{947}";
        let mut buf = Buffer::from(s);
        buf.push('a');
        let last_arg = buf.last_arg();
        assert!(last_arg.is_some());
        let s = "\u{938}\u{94d}\u{924}\u{947}a";
        assert_eq!(s, last_arg.unwrap());
        let buf = Buffer::from(s);
        let v = buf.as_bytes();
        assert_eq!(
            vec![224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135, 97],
            v
        );
    }

    #[test]
    fn test_range_chars() {
        let orig = "('\u{928}' '\u{92e}' '\u{938}\u{94d}' '\u{924}\u{947}')";
        let buf = Buffer::from(orig);
        let trim = "('\u{928}' '\u{92e}' '\u{938}\u{94d}' '";
        let str: String = buf.range_graphemes(0, 14).into();
        assert_eq!(trim, str);

        let str: &str = buf.range(0, 14).into();
        assert_eq!(trim, str);
    }

    #[test]
    fn test_whole_range_chars() {
        let orig = "('\u{928}' '\u{92e}' '\u{938}\u{94d}' '\u{924}\u{947}')";
        let buf = Buffer::from(orig);
        let str: String = buf.range_graphemes(0, 42).into();
        assert_eq!(orig, str);

        let str: &str = buf.range(0, 42).into();
        assert_eq!(orig, str);
    }

    #[test]
    fn test_range_graphemes_on_empty() {
        let orig = "";
        let buf = Buffer::from(orig);
        let str: String = buf.range_graphemes(5, 14).into();
        assert_eq!(orig, str);

        let str: &str = buf.range(5, 14);
        assert_eq!(orig, str);
    }

    #[test]
    fn test_noop() {
        let orig = "";
        let mut buf = Buffer::from(orig);
        let start = 0;
        let act = Action::Noop { start };
        let ret = act.do_on(&mut buf);
        assert_eq!(start, ret.unwrap());
    }

    #[test]
    fn test_newlines() {
        let orig = "elemeno\\\n";
        let buf = Buffer::from(orig);
        assert_eq!(2, buf.num_lines());
        for (i, line) in buf.lines().enumerate() {
            if i == 0 {
                assert_eq!("elemeno\\", line);
            } else if i == 1 {
                assert_eq!("", line);
            } else {
                panic!("There should only be two elements in the buffer!");
            }
        }
    }
}