rgpui 1.3.0

GUI UI framework
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
use std::ops::Range;

use crate::sum_tree::Bias;
use ropey::{LineType, Rope, RopeSlice};

/// 树点(行列坐标)类型,替代 tree-sitter 的 Point。
/// 行和列均为 0 起始,列为字节偏移。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point {
    /// 0 起始的行号。
    pub row: usize,
    /// 0 起始的列号(字节偏移)。
    pub column: usize,
}

impl Point {
    /// 创建新的点。
    pub fn new(row: usize, column: usize) -> Self {
        Self { row, column }
    }
}

/// 编辑记录类型,替代 tree-sitter 的 InputEdit。
#[derive(Debug, Clone, Copy)]
pub struct InputEdit {
    /// 起始字节偏移。
    pub start_byte: usize,
    /// 旧文本结束字节偏移。
    pub old_end_byte: usize,
    /// 新文本结束字节偏移。
    pub new_end_byte: usize,
    /// 起始位置。
    pub start_position: Point,
    /// 旧文本结束位置。
    pub old_end_position: Point,
    /// 新文本结束位置。
    pub new_end_position: Point,
}

/// 字符位置(行 + 字符索引),0 起始。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
    /// 0 起始的行号。
    pub line: u32,
    /// 0 起始的字符索引。
    pub character: u32,
}

impl Position {
    /// 创建新的位置。
    pub fn new(line: u32, character: u32) -> Self {
        Self { line, character }
    }
}

/// 遍历 `Rope` 行的迭代器。
pub struct RopeLines<'a> {
    rope: &'a Rope,
    row: usize,
    end_row: usize,
}

impl<'a> RopeLines<'a> {
    /// 创建新的 `RopeLines` 迭代器。
    pub fn new(rope: &'a Rope) -> Self {
        let end_row = rope.lines_len();
        Self {
            row: 0,
            end_row,
            rope,
        }
    }
}
impl<'a> Iterator for RopeLines<'a> {
    type Item = RopeSlice<'a>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.row >= self.end_row {
            return None;
        }

        let line = self.rope.slice_line(self.row);
        self.row += 1;
        Some(line)
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.row = self.row.saturating_add(n);
        self.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.end_row - self.row;
        (len, Some(len))
    }
}

impl std::iter::ExactSizeIterator for RopeLines<'_> {}
impl std::iter::FusedIterator for RopeLines<'_> {}

/// [`Rope`] 的扩展 trait,提供额外的实用方法。
pub trait RopeExt {
    /// 获取指定行(0 起始)的起始字节偏移。
    ///
    /// # 示例
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    ///
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// assert_eq!(rope.line_start_offset(0), 0);
    /// assert_eq!(rope.line_start_offset(1), 6);
    /// ```
    fn line_start_offset(&self, row: usize) -> usize;

    /// 获取指定行(0 起始)的结束字节偏移(不包含换行符)。
    ///
    /// 如果行超出范围则返回绳子的末尾。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// assert_eq!(rope.line_end_offset(0), 5); // "Hello\n"
    /// assert_eq!(rope.line_end_offset(1), 12); // "World\r\n"
    /// ```
    fn line_end_offset(&self, row: usize) -> usize;

    /// 返回指定行(0 起始)的行切片。包含 `\r`(如果存在),但不包含 `\n`。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// assert_eq!(rope.slice_line(0).to_string(), "Hello");
    /// assert_eq!(rope.slice_line(1).to_string(), "World\r");
    /// assert_eq!(rope.slice_line(2).to_string(), "This is a test 测试");
    /// assert_eq!(rope.slice_line(6).to_string(), ""); // out of bounds
    /// ```
    fn slice_line(&self, row: usize) -> RopeSlice<'_>;

    /// 返回给定范围内的行切片(0 起始,结束不包含)。
    ///
    /// 如果范围超出边界,将被裁剪到有效范围。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// assert_eq!(rope.slice_lines(0..2).to_string(), "Hello\nWorld\r");
    /// assert_eq!(rope.slice_lines(1..3).to_string(), "World\r\nThis is a test 测试");
    /// assert_eq!(rope.slice_lines(2..5).to_string(), "This is a test 测试\nRope");
    /// assert_eq!(rope.slice_lines(3..10).to_string(), "Rope");
    /// assert_eq!(rope.slice_lines(5..10).to_string(), ""); // out of bounds
    /// ```
    fn slice_lines(&self, rows_range: Range<usize>) -> RopeSlice<'_>;

    /// 返回遍历所有行的迭代器。
    ///
    /// 每个行切片包含 `\r`(如果存在),但不包含 `\n`。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// let lines: Vec<_> = rope.iter_lines().map(|r| r.to_string()).collect();
    /// assert_eq!(lines, vec!["Hello", "World\r", "This is a test 测试", "Rope"]);
    /// ```
    fn iter_lines(&self) -> RopeLines<'_>;

    /// 返回绳子中的行数。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// assert_eq!(rope.lines_len(), 4);
    /// ```
    fn lines_len(&self) -> usize;

    /// 返回指定行(0 起始)的字符长度,包含 `\r`(如果存在),但不包含 `\n`。
    ///
    /// 如果行超出范围,返回 0。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// assert_eq!(rope.line_len(0), 5); // "Hello"
    /// assert_eq!(rope.line_len(1), 6); // "World\r"
    /// assert_eq!(rope.line_len(2), 19); // "This is a test 测试"
    /// assert_eq!(rope.line_len(4), 0); // out of bounds
    /// ```
    fn line_len(&self, row: usize) -> usize;

    /// 用新文本替换给定字节范围。
    ///
    /// # Panics
    ///
    /// - 如果范围不在字符边界上。
    /// - 如果范围超出边界。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let mut rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
    /// rope.replace(6..11, "Universe");
    /// assert_eq!(rope.to_string(), "Hello\nUniverse\r\nThis is a test 测试\nRope");
    /// ```
    fn replace(&mut self, range: Range<usize>, new_text: &str);

    /// 获取给定字节偏移处的字符。
    ///
    /// - 如果偏移在多字节字符中间将会 panic。
    /// - 如果偏移超出边界,返回 None。
    fn char_at(&self, offset: usize) -> Option<char>;

    /// 从给定的行、列 [`Position`](0 起始)获取字节偏移。
    ///
    /// 列以字符为单位。
    fn position_to_offset(&self, line_col: &Position) -> usize;

    /// 从给定字节偏移获取行、列 [`Position`](0 起始)。
    ///
    /// 列以字符为单位。
    fn offset_to_position(&self, offset: usize) -> Position;

    /// 从给定字节偏移获取点(行、列)。
    ///
    /// 列以字节为单位。
    fn offset_to_point(&self, offset: usize) -> Point;

    /// 从给定点(行、列)获取字节偏移。
    ///
    /// 列以字节为单位,0 起始。
    fn point_to_offset(&self, point: Point) -> usize;

    /// 获取给定字节偏移处的单词字节范围(0 起始)。
    fn word_range(&self, offset: usize) -> Option<Range<usize>>;

    /// 获取给定字节偏移处的单词(0 起始)。
    fn word_at(&self, offset: usize) -> String;

    /// 将 UTF-16 偏移转换为字节偏移(0 起始)。
    ///
    /// 时间复杂度 O(log N)。
    fn offset_utf16_to_offset(&self, offset_utf16: usize) -> usize;

    /// 将字节偏移(0 起始)转换为 UTF-16 偏移。
    ///
    /// 时间复杂度 O(log N)。
    fn offset_to_offset_utf16(&self, offset: usize) -> usize;

    /// 获取裁剪后的偏移(避免在字符边界内)。
    ///
    /// - 如果 Bias::Left 且在字符边界内,返回 ix - 1;
    /// - 如果 Bias::Right 且在字符边界内,返回 ix + 1;
    /// - 否则返回 ix。
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// use rgpui::sum_tree::Bias;
    ///
    /// let rope = Rope::from("Hello 测试?? test\nRope");
    /// assert_eq!(rope.clip_offset(5, Bias::Left), 5);
    /// // Inside multi-byte character '测' (3 bytes)
    /// assert_eq!(rope.clip_offset(7, Bias::Left), 6);
    /// assert_eq!(rope.clip_offset(7, Bias::Right), 9);
    /// ```
    fn clip_offset(&self, offset: usize, bias: Bias) -> usize;

    /// 将字符偏移转换为字节偏移(0 起始)。
    ///
    /// 时间复杂度 O(n)。
    ///
    /// # 示例
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("a 测试?? test\nRope");
    /// assert_eq!(rope.char_index_to_offset(0), 0);
    /// assert_eq!(rope.char_index_to_offset(1), 1);
    /// assert_eq!(rope.char_index_to_offset(3), "a 测".len());
    /// assert_eq!(rope.char_index_to_offset(5), "a 测试??".len());
    /// ```
    fn char_index_to_offset(&self, char_index: usize) -> usize;

    /// 将字节偏移(0 起始)转换为字符偏移。
    ///
    /// 时间复杂度 O(n)。
    ///
    /// # 示例
    ///
    /// ```
    /// use rgpui::{Rope, RopeExt};
    /// let rope = Rope::from("a 测试?? test\nRope");
    /// assert_eq!(rope.offset_to_char_index(0), 0);
    /// assert_eq!(rope.offset_to_char_index(1), 1);
    /// assert_eq!(rope.offset_to_char_index(3), 3);
    /// assert_eq!(rope.offset_to_char_index(4), 3);
    /// ```
    fn offset_to_char_index(&self, offset: usize) -> usize;
}

impl RopeExt for Rope {
    fn slice_line(&self, row: usize) -> RopeSlice<'_> {
        let total_lines = self.lines_len();
        if row >= total_lines {
            return self.slice(0..0);
        }

        let line = self.line(row, LineType::LF);
        if line.len() > 0 {
            let line_end = line.len() - 1;
            if line.is_char_boundary(line_end) && line.char(line_end) == '\n' {
                return line.slice(..line_end);
            }
        }

        line
    }

    fn slice_lines(&self, rows_range: Range<usize>) -> RopeSlice<'_> {
        let start = self.line_start_offset(rows_range.start);
        let end = self.line_end_offset(rows_range.end.saturating_sub(1));
        self.slice(start..end)
    }

    fn iter_lines(&self) -> RopeLines<'_> {
        RopeLines::new(&self)
    }

    fn line_len(&self, row: usize) -> usize {
        self.slice_line(row).len()
    }

    fn line_start_offset(&self, row: usize) -> usize {
        self.point_to_offset(Point::new(row, 0))
    }

    fn offset_to_point(&self, offset: usize) -> Point {
        let offset = self.clip_offset(offset, Bias::Left);
        let row = self.byte_to_line_idx(offset, LineType::LF);
        let line_start = self.line_to_byte_idx(row, LineType::LF);
        let column = offset.saturating_sub(line_start);
        Point::new(row, column)
    }

    fn point_to_offset(&self, point: Point) -> usize {
        if point.row >= self.lines_len() {
            return self.len();
        }

        let line_start = self.line_to_byte_idx(point.row, LineType::LF);
        line_start + point.column
    }

    fn position_to_offset(&self, pos: &Position) -> usize {
        let line = self.slice_line(pos.line as usize);
        self.line_start_offset(pos.line as usize)
            + line
                .chars()
                .take(pos.character as usize)
                .map(|c| c.len_utf8())
                .sum::<usize>()
    }

    fn offset_to_position(&self, offset: usize) -> Position {
        let point = self.offset_to_point(offset);
        let line = self.slice_line(point.row);
        let offset = line.utf16_to_byte_idx(line.byte_to_utf16_idx(point.column));
        let character = line.slice(..offset).chars().count();
        Position::new(point.row as u32, character as u32)
    }

    fn line_end_offset(&self, row: usize) -> usize {
        if row > self.lines_len() {
            return self.len();
        }

        self.line_start_offset(row) + self.line_len(row)
    }

    fn lines_len(&self) -> usize {
        self.len_lines(LineType::LF)
    }

    fn char_at(&self, offset: usize) -> Option<char> {
        if offset > self.len() {
            return None;
        }

        self.get_char(offset).ok()
    }

    fn word_range(&self, offset: usize) -> Option<Range<usize>> {
        if offset >= self.len() {
            return None;
        }

        let mut left = String::new();
        let offset = self.clip_offset(offset, Bias::Left);
        for c in self.chars_at(offset).reversed() {
            if c.is_alphanumeric() || c == '_' {
                left.insert(0, c);
            } else {
                break;
            }
        }
        let start = offset.saturating_sub(left.len());

        let right = self
            .chars_at(offset)
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect::<String>();

        let end = offset + right.len();

        if start == end { None } else { Some(start..end) }
    }

    fn word_at(&self, offset: usize) -> String {
        if let Some(range) = self.word_range(offset) {
            self.slice(range).to_string()
        } else {
            String::new()
        }
    }

    #[inline]
    fn offset_utf16_to_offset(&self, offset_utf16: usize) -> usize {
        if offset_utf16 > self.len_utf16() {
            return self.len();
        }

        self.utf16_to_byte_idx(offset_utf16)
    }

    #[inline]
    fn offset_to_offset_utf16(&self, offset: usize) -> usize {
        if offset > self.len() {
            return self.len_utf16();
        }

        self.byte_to_utf16_idx(offset)
    }

    fn replace(&mut self, range: Range<usize>, new_text: &str) {
        let range =
            self.clip_offset(range.start, Bias::Left)..self.clip_offset(range.end, Bias::Right);
        self.remove(range.clone());
        self.insert(range.start, new_text);
    }

    fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
        if offset > self.len() {
            return self.len();
        }

        if self.is_char_boundary(offset) {
            return offset;
        }

        if bias == Bias::Left {
            self.floor_char_boundary(offset)
        } else {
            self.ceil_char_boundary(offset)
        }
    }

    fn char_index_to_offset(&self, char_offset: usize) -> usize {
        self.chars().take(char_offset).map(|c| c.len_utf8()).sum()
    }

    fn offset_to_char_index(&self, offset: usize) -> usize {
        let offset = self.clip_offset(offset, Bias::Right);
        self.slice(..offset).chars().count()
    }
}

#[cfg(test)]
mod tests {
    use ropey::Rope;

    use super::{Point, Position};
    use crate::input_ui::RopeExt;
    use crate::sum_tree::Bias;

    #[test]
    fn test_slice_line() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
        assert_eq!(rope.slice_line(0).to_string(), "Hello");
        assert_eq!(rope.slice_line(1).to_string(), "World\r");
        assert_eq!(rope.slice_line(2).to_string(), "This is a test 测试");
        assert_eq!(rope.slice_line(3).to_string(), "Rope");

        // over bounds
        assert_eq!(rope.slice_line(6).to_string(), "");

        // only have \r end
        let rope = Rope::from("Hello\r");
        assert_eq!(rope.slice_line(0).to_string(), "Hello\r");
        assert_eq!(rope.slice_line(1).to_string(), "");
    }

    #[test]
    fn test_lines_len() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
        assert_eq!(rope.lines_len(), 4);
        let rope = Rope::from("");
        assert_eq!(rope.lines_len(), 1);
        let rope = Rope::from("Single line");
        assert_eq!(rope.lines_len(), 1);

        // only have \r end
        let rope = Rope::from("Hello\r");
        assert_eq!(rope.lines_len(), 1);
    }

    #[test]
    fn test_lines() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope\r");
        let lines: Vec<_> = rope.iter_lines().map(|r| r.to_string()).collect();
        assert_eq!(
            lines,
            vec!["Hello", "World\r", "This is a test 测试", "Rope\r"]
        );
    }

    #[test]
    fn test_eq() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
        assert!(rope.eq(&Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope")));
        assert!(!rope.eq(&Rope::from("Hello\nWorld")));

        let rope1 = rope.clone();
        assert!(rope.eq(&rope1));
    }

    #[test]
    fn test_iter_lines() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
        let lines: Vec<_> = rope
            .iter_lines()
            .skip(1)
            .take(2)
            .map(|r| r.to_string())
            .collect();
        assert_eq!(lines, vec!["World\r", "This is a test 测试"]);
    }

    #[test]
    fn test_line_start_end_offset() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 测试\nRope");
        assert_eq!(rope.line_start_offset(0), 0);
        assert_eq!(rope.line_end_offset(0), 5);

        assert_eq!(rope.line_start_offset(1), 6);
        assert_eq!(rope.line_end_offset(1), 12);

        assert_eq!(rope.line_start_offset(2), 13);
        assert_eq!(rope.line_end_offset(2), 34);

        assert_eq!(rope.line_start_offset(3), 35);
        assert_eq!(rope.line_end_offset(3), 39);

        assert_eq!(rope.line_start_offset(4), 39);
        assert_eq!(rope.line_end_offset(4), 39);
    }

    #[test]
    fn test_line_column() {
        let rope = Rope::from("a 中文🎉 test\nRope");
        assert_eq!(rope.position_to_offset(&Position::new(0, 3)), "a 中".len());
        assert_eq!(
            rope.position_to_offset(&Position::new(0, 5)),
            "a 中文🎉".len()
        );
        assert_eq!(
            rope.position_to_offset(&Position::new(1, 1)),
            "a 中文🎉 test\nR".len()
        );

        assert_eq!(
            rope.offset_to_position("a 中文🎉 test\nR".len()),
            Position::new(1, 1)
        );
        assert_eq!(
            rope.offset_to_position("a 中文🎉".len()),
            Position::new(0, 5)
        );
    }

    #[test]
    fn test_offset_to_point() {
        let rope = Rope::from("a 中文🎉 test\nRope");
        assert_eq!(rope.offset_to_point(0), Point::new(0, 0));
        assert_eq!(rope.offset_to_point(1), Point::new(0, 1));
        assert_eq!(rope.offset_to_point("a 中".len()), Point::new(0, 5));
        assert_eq!(rope.offset_to_point("a 中文🎉".len()), Point::new(0, 12));
        assert_eq!(
            rope.offset_to_point("a 中文🎉 test\nR".len()),
            Point::new(1, 1)
        );
    }

    #[test]
    fn test_point_to_offset() {
        let rope = Rope::from("a 中文🎉 test\nRope");
        assert_eq!(rope.point_to_offset(Point::new(0, 0)), 0);
        assert_eq!(rope.point_to_offset(Point::new(0, 1)), 1);
        assert_eq!(rope.point_to_offset(Point::new(0, 5)), "a 中".len());
        assert_eq!(rope.point_to_offset(Point::new(0, 12)), "a 中文🎉".len());
        assert_eq!(
            rope.point_to_offset(Point::new(1, 1)),
            "a 中文🎉 test\nR".len()
        );
    }

    #[test]
    fn test_char_at() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文🎉\nRope");
        assert_eq!(rope.char_at(0), Some('H'));
        assert_eq!(rope.char_at(5), Some('\n'));
        assert_eq!(rope.char_at(13), Some('T'));
        assert_eq!(rope.char_at(28), Some(''));
        assert_eq!(rope.char_at(34), Some('🎉'));
        assert_eq!(rope.char_at(38), Some('\n'));
        assert_eq!(rope.char_at(50), None);
    }

    #[test]
    fn test_word_at() {
        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文 世界\nRope");
        assert_eq!(rope.word_at(0), "Hello");
        assert_eq!(rope.word_range(0), Some(0..5));
        assert_eq!(rope.word_at(8), "World");
        assert_eq!(rope.word_range(8), Some(6..11));
        assert_eq!(rope.word_at(12), "");
        assert_eq!(rope.word_range(12), None);
        assert_eq!(rope.word_at(13), "This");
        assert_eq!(rope.word_range(13), Some(13..17));
        assert_eq!(rope.word_at(31), "中文");
        assert_eq!(rope.word_range(31), Some(28..34));
        assert_eq!(rope.word_at(38), "世界");
        assert_eq!(rope.word_range(38), Some(35..41));
        assert_eq!(rope.word_at(44), "Rope");
        assert_eq!(rope.word_range(44), Some(42..46));
        assert_eq!(rope.word_at(45), "Rope");
    }

    #[test]
    fn test_offset_utf16_conversion() {
        let rope = Rope::from("hello 中文🎉 test\nRope");
        assert_eq!(rope.offset_to_offset_utf16("hello".len()), 5);
        assert_eq!(rope.offset_to_offset_utf16("hello 中".len()), 7);
        assert_eq!(rope.offset_to_offset_utf16("hello 中文".len()), 8);
        assert_eq!(rope.offset_to_offset_utf16("hello 中文🎉".len()), 10);
        assert_eq!(rope.offset_to_offset_utf16(100), 20);

        assert_eq!(rope.offset_utf16_to_offset(5), "hello".len());
        assert_eq!(rope.offset_utf16_to_offset(7), "hello 中".len());
        assert_eq!(rope.offset_utf16_to_offset(8), "hello 中文".len());
        assert_eq!(rope.offset_utf16_to_offset(10), "hello 中文🎉".len());
        assert_eq!(rope.offset_utf16_to_offset(100), rope.len());
    }

    #[test]
    fn test_replace() {
        let mut rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
        rope.replace(6..11, "Universe");
        assert_eq!(
            rope.to_string(),
            "Hello\nUniverse\r\nThis is a test 中文\nRope"
        );

        rope.replace(0..5, "Hi");
        assert_eq!(
            rope.to_string(),
            "Hi\nUniverse\r\nThis is a test 中文\nRope"
        );

        rope.replace(rope.len() - 4..rope.len(), "String");
        assert_eq!(
            rope.to_string(),
            "Hi\nUniverse\r\nThis is a test 中文\nString"
        );

        // Test for not on a char boundary
        let mut rope = Rope::from("中文");
        rope.replace(0..1, "New");
        assert_eq!(rope.to_string(), "New文");
        let mut rope = Rope::from("中文");
        rope.replace(0..2, "New");
        assert_eq!(rope.to_string(), "New文");
        let mut rope = Rope::from("中文");
        rope.replace(0..3, "New");
        assert_eq!(rope.to_string(), "New文");
        let mut rope = Rope::from("中文");
        rope.replace(1..4, "New");
        assert_eq!(rope.to_string(), "New");
    }

    #[test]
    fn test_clip_offset() {
        let rope = Rope::from("Hello 中文🎉 test\nRope");
        // Inside multi-byte character '中' (3 bytes)
        assert_eq!(rope.clip_offset(5, Bias::Left), 5);
        assert_eq!(rope.clip_offset(7, Bias::Left), 6);
        assert_eq!(rope.clip_offset(7, Bias::Right), 9);
        assert_eq!(rope.clip_offset(9, Bias::Left), 9);

        // Inside multi-byte character '🎉' (4 bytes)
        assert_eq!(rope.clip_offset(13, Bias::Left), 12);
        assert_eq!(rope.clip_offset(13, Bias::Right), 16);
        assert_eq!(rope.clip_offset(16, Bias::Left), 16);

        // At character boundary
        assert_eq!(rope.clip_offset(5, Bias::Left), 5);
        assert_eq!(rope.clip_offset(5, Bias::Right), 5);

        // Out of bounds
        assert_eq!(rope.clip_offset(26, Bias::Left), 26);
        assert_eq!(rope.clip_offset(100, Bias::Left), 26);
    }

    #[test]
    fn test_char_index_to_offset() {
        let rope = Rope::from("a 中文🎉 test\nRope");
        assert_eq!(rope.char_index_to_offset(0), 0);
        assert_eq!(rope.char_index_to_offset(1), 1);
        assert_eq!(rope.char_index_to_offset(3), "a 中".len());
        assert_eq!(rope.char_index_to_offset(5), "a 中文🎉".len());
        assert_eq!(rope.char_index_to_offset(6), "a 中文🎉 ".len());

        assert_eq!(rope.offset_to_char_index(0), 0);
        assert_eq!(rope.offset_to_char_index(1), 1);
        assert_eq!(rope.offset_to_char_index(3), 3);
        assert_eq!(rope.offset_to_char_index(4), 3);
        assert_eq!(rope.offset_to_char_index(5), 3);
        assert_eq!(rope.offset_to_char_index(6), 4);
        assert_eq!(rope.offset_to_char_index(10), 5);
    }
}