Skip to main content

gpui_deck/input/base/
rope_ext.rs

1// Modified for GPUI Deck: update references to the extracted crate.
2use std::ops::Range;
3
4use ropey::{LineType, Rope, RopeSlice};
5use sum_tree::Bias;
6use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
7
8/// Parser-independent byte/row/column position used for incremental edits.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub struct Point {
11    pub row: usize,
12    pub column: usize,
13}
14
15impl Point {
16    pub fn new(row: usize, column: usize) -> Self {
17        Self { row, column }
18    }
19}
20
21/// Parser-independent description of an incremental text replacement.
22#[derive(Debug, Clone, Copy)]
23pub struct InputEdit {
24    pub start_byte: usize,
25    pub old_end_byte: usize,
26    pub new_end_byte: usize,
27    pub start_position: Point,
28    pub old_end_position: Point,
29    pub new_end_position: Point,
30}
31
32use lsp_types::Position;
33
34/// An iterator over the lines of a `Rope`.
35pub struct RopeLines<'a> {
36    rope: &'a Rope,
37    row: usize,
38    end_row: usize,
39}
40
41impl<'a> RopeLines<'a> {
42    /// Create a new `RopeLines` iterator.
43    pub fn new(rope: &'a Rope) -> Self {
44        let end_row = rope.lines_len();
45        Self {
46            row: 0,
47            end_row,
48            rope,
49        }
50    }
51}
52impl<'a> Iterator for RopeLines<'a> {
53    type Item = RopeSlice<'a>;
54
55    #[inline]
56    fn next(&mut self) -> Option<Self::Item> {
57        if self.row >= self.end_row {
58            return None;
59        }
60
61        let line = self.rope.slice_line(self.row);
62        self.row += 1;
63        Some(line)
64    }
65
66    #[inline]
67    fn nth(&mut self, n: usize) -> Option<Self::Item> {
68        self.row = self.row.saturating_add(n).min(self.end_row);
69        self.next()
70    }
71
72    #[inline]
73    fn size_hint(&self) -> (usize, Option<usize>) {
74        let len = self.end_row - self.row;
75        (len, Some(len))
76    }
77}
78
79impl std::iter::ExactSizeIterator for RopeLines<'_> {}
80impl std::iter::FusedIterator for RopeLines<'_> {}
81
82/// An extension trait for [`Rope`] to provide additional utility methods.
83pub trait RopeExt {
84    /// Start offset of the line at the given row (0-based) index.
85    ///
86    /// # Example
87    ///
88    /// ```
89    /// use gpui_deck::input::{Rope, RopeExt};
90    ///
91    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
92    /// assert_eq!(rope.line_start_offset(0), 0);
93    /// assert_eq!(rope.line_start_offset(1), 6);
94    /// ```
95    fn line_start_offset(&self, row: usize) -> usize;
96
97    /// Line the end offset (including `\n`) of the line at the given row (0-based) index.
98    ///
99    /// Return the end of the rope if the row is out of bounds.
100    ///
101    /// ```
102    /// use gpui_deck::input::{Rope, RopeExt};
103    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
104    /// assert_eq!(rope.line_end_offset(0), 5); // "Hello\n"
105    /// assert_eq!(rope.line_end_offset(1), 12); // "World\r\n"
106    /// ```
107    fn line_end_offset(&self, row: usize) -> usize;
108
109    /// Return a line slice at the given row (0-based) index. including `\r` if present, but not `\n`.
110    ///
111    /// ```
112    /// use gpui_deck::input::{Rope, RopeExt};
113    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
114    /// assert_eq!(rope.slice_line(0).to_string(), "Hello");
115    /// assert_eq!(rope.slice_line(1).to_string(), "World\r");
116    /// assert_eq!(rope.slice_line(2).to_string(), "This is a test 中文");
117    /// assert_eq!(rope.slice_line(6).to_string(), ""); // out of bounds
118    /// ```
119    fn slice_line(&self, row: usize) -> RopeSlice<'_>;
120
121    /// Return a slice of rows in the given range (0-based, end exclusive).
122    ///
123    /// If the range is out of bounds, it will be clamped to the valid range.
124    ///
125    /// ```
126    /// use gpui_deck::input::{Rope, RopeExt};
127    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
128    /// assert_eq!(rope.slice_lines(0..2).to_string(), "Hello\nWorld\r");
129    /// assert_eq!(rope.slice_lines(1..3).to_string(), "World\r\nThis is a test 中文");
130    /// assert_eq!(rope.slice_lines(2..5).to_string(), "This is a test 中文\nRope");
131    /// assert_eq!(rope.slice_lines(3..10).to_string(), "Rope");
132    /// assert_eq!(rope.slice_lines(5..10).to_string(), ""); // out of bounds
133    /// ```
134    fn slice_lines(&self, rows_range: Range<usize>) -> RopeSlice<'_>;
135
136    /// Return an iterator over all lines in the rope.
137    ///
138    /// Each line slice includes `\r` if present, but not `\n`.
139    ///
140    /// ```
141    /// use gpui_deck::input::{Rope, RopeExt};
142    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
143    /// let lines: Vec<_> = rope.iter_lines().map(|r| r.to_string()).collect();
144    /// assert_eq!(lines, vec!["Hello", "World\r", "This is a test 中文", "Rope"]);
145    /// ```
146    fn iter_lines(&self) -> RopeLines<'_>;
147
148    /// Return the number of lines in the rope.
149    ///
150    /// ```
151    /// use gpui_deck::input::{Rope, RopeExt};
152    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
153    /// assert_eq!(rope.lines_len(), 4);
154    /// ```
155    fn lines_len(&self) -> usize;
156
157    /// Return the length of the row (0-based) in characters, including `\r` if present, but not `\n`.
158    ///
159    /// If the row is out of bounds, return 0.
160    ///
161    /// ```
162    /// use gpui_deck::input::{Rope, RopeExt};
163    /// let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
164    /// assert_eq!(rope.line_len(0), 5); // "Hello"
165    /// assert_eq!(rope.line_len(1), 6); // "World\r"
166    /// assert_eq!(rope.line_len(2), 21); // "This is a test 中文"
167    /// assert_eq!(rope.line_len(4), 0); // out of bounds
168    /// ```
169    fn line_len(&self, row: usize) -> usize;
170
171    /// Replace the text in the given byte range with new text.
172    ///
173    /// # Panics
174    ///
175    /// - If the range is not on char boundary.
176    /// - If the range is out of bounds.
177    ///
178    /// ```
179    /// use gpui_deck::input::{Rope, RopeExt};
180    /// let mut rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
181    /// rope.replace(6..11, "Universe");
182    /// assert_eq!(rope.to_string(), "Hello\nUniverse\r\nThis is a test 中文\nRope");
183    /// ```
184    fn replace(&mut self, range: Range<usize>, new_text: &str);
185
186    /// Get char at the given offset (byte).
187    ///
188    /// - If the offset is in the middle of a multi-byte character will panic.
189    /// - If the offset is out of bounds, return None.
190    fn char_at(&self, offset: usize) -> Option<char>;
191
192    /// Get the byte offset from the given line, column [`Position`] (0-based).
193    ///
194    /// The column is in characters.
195    fn position_to_offset(&self, line_col: &Position) -> usize;
196
197    /// Get the line, column [`Position`] (0-based) from the given byte offset.
198    ///
199    /// The column is in characters.
200    fn offset_to_position(&self, offset: usize) -> Position;
201
202    /// Get point (row, column) from the given byte offset.
203    ///
204    /// The column is in bytes.
205    fn offset_to_point(&self, offset: usize) -> Point;
206
207    /// Get byte offset from the given point (row, column).
208    ///
209    /// The column is 0-based in bytes.
210    fn point_to_offset(&self, point: Point) -> usize;
211
212    /// Get the word byte range at the given byte offset (0-based).
213    fn word_range(&self, offset: usize) -> Option<Range<usize>>;
214
215    /// Get word at the given byte offset (0-based).
216    fn word_at(&self, offset: usize) -> String;
217
218    /// Convert offset in UTF-16 to byte offset (0-based).
219    ///
220    /// Runs in O(log N) time.
221    fn offset_utf16_to_offset(&self, offset_utf16: usize) -> usize;
222
223    /// Convert byte offset (0-based) to offset in UTF-16.
224    ///
225    /// Runs in O(log N) time.
226    fn offset_to_offset_utf16(&self, offset: usize) -> usize;
227
228    /// Get a clipped offset (avoid in a char boundary).
229    ///
230    /// - If Bias::Left and inside the char boundary, return the ix - 1;
231    /// - If Bias::Right and in inside char boundary, return the ix + 1;
232    /// - Otherwise return the ix.
233    ///
234    /// ```
235    /// use gpui_deck::input::{Rope, RopeExt};
236    /// use sum_tree::Bias;
237    ///
238    /// let rope = Rope::from("Hello 中文🎉 test\nRope");
239    /// assert_eq!(rope.clip_offset(5, Bias::Left), 5);
240    /// // Inside multi-byte character '中' (3 bytes)
241    /// assert_eq!(rope.clip_offset(7, Bias::Left), 6);
242    /// assert_eq!(rope.clip_offset(7, Bias::Right), 9);
243    /// ```
244    fn clip_offset(&self, offset: usize, bias: Bias) -> usize;
245
246    /// Convert offset in characters to byte offset (0-based).
247    ///
248    /// Run in O(n) time.
249    ///
250    /// # Example
251    ///
252    /// ```
253    /// use gpui_deck::input::{Rope, RopeExt};
254    /// let rope = Rope::from("a 中文🎉 test\nRope");
255    /// assert_eq!(rope.char_index_to_offset(0), 0);
256    /// assert_eq!(rope.char_index_to_offset(1), 1);
257    /// assert_eq!(rope.char_index_to_offset(3), "a 中".len());
258    /// assert_eq!(rope.char_index_to_offset(5), "a 中文🎉".len());
259    /// ```
260    fn char_index_to_offset(&self, char_index: usize) -> usize;
261
262    /// Convert byte offset (0-based) to offset in characters.
263    ///
264    /// Run in O(n) time.
265    ///
266    /// # Example
267    ///
268    /// ```
269    /// use gpui_deck::input::{Rope, RopeExt};
270    /// let rope = Rope::from("a 中文🎉 test\nRope");
271    /// assert_eq!(rope.offset_to_char_index(0), 0);
272    /// assert_eq!(rope.offset_to_char_index(1), 1);
273    /// assert_eq!(rope.offset_to_char_index(3), 3);
274    /// assert_eq!(rope.offset_to_char_index(4), 3);
275    /// ```
276    fn offset_to_char_index(&self, offset: usize) -> usize;
277}
278
279impl RopeExt for Rope {
280    fn slice_line(&self, row: usize) -> RopeSlice<'_> {
281        let total_lines = self.lines_len();
282        if row >= total_lines {
283            return self.slice(0..0);
284        }
285
286        let line = self.line(row, LineType::LF);
287        if line.len() > 0 {
288            let line_end = line.len() - 1;
289            if line.is_char_boundary(line_end) && line.char(line_end) == '\n' {
290                return line.slice(..line_end);
291            }
292        }
293
294        line
295    }
296
297    fn slice_lines(&self, rows_range: Range<usize>) -> RopeSlice<'_> {
298        let start = self.line_start_offset(rows_range.start);
299        let end = self.line_end_offset(rows_range.end.saturating_sub(1));
300        self.slice(start..end)
301    }
302
303    fn iter_lines(&self) -> RopeLines<'_> {
304        RopeLines::new(&self)
305    }
306
307    fn line_len(&self, row: usize) -> usize {
308        self.slice_line(row).len()
309    }
310
311    fn line_start_offset(&self, row: usize) -> usize {
312        self.point_to_offset(Point::new(row, 0))
313    }
314
315    fn offset_to_point(&self, offset: usize) -> Point {
316        let offset = self.clip_offset(offset, Bias::Left);
317        let row = self.byte_to_line_idx(offset, LineType::LF);
318        let line_start = self.line_to_byte_idx(row, LineType::LF);
319        let column = offset.saturating_sub(line_start);
320        Point::new(row, column)
321    }
322
323    fn point_to_offset(&self, point: Point) -> usize {
324        if point.row >= self.lines_len() {
325            return self.len();
326        }
327
328        let line_start = self.line_to_byte_idx(point.row, LineType::LF);
329        line_start + point.column
330    }
331
332    fn position_to_offset(&self, pos: &Position) -> usize {
333        let line = self.slice_line(pos.line as usize);
334        // Clamp out-of-range columns, then use Ropey's index to avoid rescanning long lines.
335        self.line_start_offset(pos.line as usize)
336            + line.char_to_byte_idx((pos.character as usize).min(line.len_chars()))
337    }
338
339    fn offset_to_position(&self, offset: usize) -> Position {
340        let point = self.offset_to_point(offset);
341        let line = self.slice_line(point.row);
342        let offset = line.utf16_to_byte_idx(line.byte_to_utf16_idx(point.column));
343        let character = line.slice(..offset).chars().count();
344        Position::new(point.row as u32, character as u32)
345    }
346
347    fn line_end_offset(&self, row: usize) -> usize {
348        if row > self.lines_len() {
349            return self.len();
350        }
351
352        self.line_start_offset(row) + self.line_len(row)
353    }
354
355    fn lines_len(&self) -> usize {
356        self.len_lines(LineType::LF)
357    }
358
359    fn char_at(&self, offset: usize) -> Option<char> {
360        if offset > self.len() {
361            return None;
362        }
363
364        self.get_char(offset).ok()
365    }
366
367    fn word_range(&self, offset: usize) -> Option<Range<usize>> {
368        if offset >= self.len() {
369            return None;
370        }
371
372        let mut left = String::new();
373        let offset = self.clip_offset(offset, Bias::Left);
374        for c in self.chars_at(offset).reversed() {
375            if c.is_alphanumeric() || c == '_' {
376                left.insert(0, c);
377            } else {
378                break;
379            }
380        }
381        let start = offset.saturating_sub(left.len());
382
383        let right = self
384            .chars_at(offset)
385            .take_while(|c| c.is_alphanumeric() || *c == '_')
386            .collect::<String>();
387
388        let end = offset + right.len();
389
390        if start == end { None } else { Some(start..end) }
391    }
392
393    fn word_at(&self, offset: usize) -> String {
394        if let Some(range) = self.word_range(offset) {
395            self.slice(range).to_string()
396        } else {
397            String::new()
398        }
399    }
400
401    #[inline]
402    fn offset_utf16_to_offset(&self, offset_utf16: usize) -> usize {
403        if offset_utf16 > self.len_utf16() {
404            return self.len();
405        }
406
407        self.utf16_to_byte_idx(offset_utf16)
408    }
409
410    #[inline]
411    fn offset_to_offset_utf16(&self, offset: usize) -> usize {
412        if offset > self.len() {
413            return self.len_utf16();
414        }
415
416        self.byte_to_utf16_idx(offset)
417    }
418
419    fn replace(&mut self, range: Range<usize>, new_text: &str) {
420        let range =
421            self.clip_offset(range.start, Bias::Left)..self.clip_offset(range.end, Bias::Right);
422        self.remove(range.clone());
423        self.insert(range.start, new_text);
424    }
425
426    fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
427        if offset > self.len() {
428            return self.len();
429        }
430
431        if self.is_char_boundary(offset) {
432            return offset;
433        }
434
435        if bias == Bias::Left {
436            self.floor_char_boundary(offset)
437        } else {
438            self.ceil_char_boundary(offset)
439        }
440    }
441
442    fn char_index_to_offset(&self, char_offset: usize) -> usize {
443        self.chars().take(char_offset).map(|c| c.len_utf8()).sum()
444    }
445
446    fn offset_to_char_index(&self, offset: usize) -> usize {
447        let offset = self.clip_offset(offset, Bias::Right);
448        self.slice(..offset).chars().count()
449    }
450}
451
452/// The start of the grapheme cluster before `offset`, or of the cluster `offset` is inside.
453pub(crate) fn previous_grapheme_boundary(rope: &Rope, offset: usize) -> usize {
454    let offset = rope.clip_offset(offset, Bias::Right);
455    if offset == 0 {
456        return 0;
457    }
458    let mut cursor = GraphemeCursor::new(offset, rope.len(), true);
459    let (mut chunk, mut chunk_start) = rope.chunk(offset - 1);
460    loop {
461        match cursor.prev_boundary(chunk, chunk_start) {
462            Ok(boundary) => return boundary.unwrap_or(0),
463            Err(GraphemeIncomplete::PrevChunk) => {
464                (chunk, chunk_start) = rope.chunk(chunk_start - 1);
465            }
466            Err(GraphemeIncomplete::PreContext(end)) => {
467                let (context, context_start) = rope.chunk(end - 1);
468                cursor.provide_context(context, context_start);
469            }
470            Err(_) => return rope.clip_offset(offset - 1, Bias::Left),
471        }
472    }
473}
474
475/// The end of the grapheme cluster at `offset`, or of the cluster `offset` is inside.
476pub(crate) fn next_grapheme_boundary(rope: &Rope, offset: usize) -> usize {
477    let offset = rope.clip_offset(offset, Bias::Left);
478    if offset >= rope.len() {
479        return rope.len();
480    }
481    let mut cursor = GraphemeCursor::new(offset, rope.len(), true);
482    let (mut chunk, mut chunk_start) = rope.chunk(offset);
483    loop {
484        match cursor.next_boundary(chunk, chunk_start) {
485            Ok(boundary) => return boundary.unwrap_or(rope.len()),
486            Err(GraphemeIncomplete::NextChunk) => {
487                (chunk, chunk_start) = rope.chunk(chunk_start + chunk.len());
488            }
489            Err(GraphemeIncomplete::PreContext(end)) => {
490                let (context, context_start) = rope.chunk(end - 1);
491                cursor.provide_context(context, context_start);
492            }
493            Err(_) => return rope.clip_offset(offset + 1, Bias::Right),
494        }
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::{Point, next_grapheme_boundary, previous_grapheme_boundary};
501    use ropey::Rope;
502    use sum_tree::Bias;
503
504    use crate::input::{Position, RopeExt};
505
506    #[test]
507    fn test_slice_line() {
508        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
509        assert_eq!(rope.slice_line(0).to_string(), "Hello");
510        assert_eq!(rope.slice_line(1).to_string(), "World\r");
511        assert_eq!(rope.slice_line(2).to_string(), "This is a test 中文");
512        assert_eq!(rope.slice_line(3).to_string(), "Rope");
513
514        // over bounds
515        assert_eq!(rope.slice_line(6).to_string(), "");
516
517        // only have \r end
518        let rope = Rope::from("Hello\r");
519        assert_eq!(rope.slice_line(0).to_string(), "Hello\r");
520        assert_eq!(rope.slice_line(1).to_string(), "");
521    }
522
523    #[test]
524    fn test_lines_len() {
525        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
526        assert_eq!(rope.lines_len(), 4);
527        let rope = Rope::from("");
528        assert_eq!(rope.lines_len(), 1);
529        let rope = Rope::from("Single line");
530        assert_eq!(rope.lines_len(), 1);
531
532        // only have \r end
533        let rope = Rope::from("Hello\r");
534        assert_eq!(rope.lines_len(), 1);
535    }
536
537    #[test]
538    fn test_lines() {
539        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope\r");
540        let lines: Vec<_> = rope.iter_lines().map(|r| r.to_string()).collect();
541        assert_eq!(
542            lines,
543            vec!["Hello", "World\r", "This is a test 中文", "Rope\r"]
544        );
545    }
546
547    #[test]
548    fn test_eq() {
549        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
550        assert!(rope.eq(&Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope")));
551        assert!(!rope.eq(&Rope::from("Hello\nWorld")));
552
553        let rope1 = rope.clone();
554        assert!(rope.eq(&rope1));
555    }
556
557    #[test]
558    fn test_iter_lines() {
559        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
560        let lines: Vec<_> = rope
561            .iter_lines()
562            .skip(1)
563            .take(2)
564            .map(|r| r.to_string())
565            .collect();
566        assert_eq!(lines, vec!["World\r", "This is a test 中文"]);
567    }
568
569    #[test]
570    fn test_iter_lines_nth_reports_remaining_length() {
571        let rope = Rope::from("first\nsecond\nthird");
572        let mut lines = rope.iter_lines();
573
574        assert_eq!(lines.nth(1).unwrap().to_string(), "second");
575        assert_eq!(lines.len(), 1);
576        assert_eq!(lines.size_hint(), (1, Some(1)));
577        assert_eq!(lines.nth(0).unwrap().to_string(), "third");
578        assert_eq!(lines.len(), 0);
579        assert_eq!(lines.size_hint(), (0, Some(0)));
580        assert!(lines.next().is_none());
581    }
582
583    #[test]
584    fn test_iter_lines_nth_past_end_stays_exhausted() {
585        let rope = Rope::from("first\nsecond\nthird");
586        for skip in [2, 3, usize::MAX] {
587            let mut lines = rope.iter_lines();
588            assert_eq!(lines.next().unwrap().to_string(), "first");
589            assert_eq!(lines.len(), 2);
590
591            assert!(lines.nth(skip).is_none());
592            assert_eq!(lines.len(), 0);
593            assert_eq!(lines.size_hint(), (0, Some(0)));
594            assert!(lines.next().is_none());
595            assert!(lines.nth(usize::MAX).is_none());
596            assert_eq!(lines.len(), 0);
597            assert_eq!(lines.size_hint(), (0, Some(0)));
598        }
599    }
600
601    #[test]
602    fn test_line_start_end_offset() {
603        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
604        assert_eq!(rope.line_start_offset(0), 0);
605        assert_eq!(rope.line_end_offset(0), 5);
606
607        assert_eq!(rope.line_start_offset(1), 6);
608        assert_eq!(rope.line_end_offset(1), 12);
609
610        assert_eq!(rope.line_start_offset(2), 13);
611        assert_eq!(rope.line_end_offset(2), 34);
612
613        assert_eq!(rope.line_start_offset(3), 35);
614        assert_eq!(rope.line_end_offset(3), 39);
615
616        assert_eq!(rope.line_start_offset(4), 39);
617        assert_eq!(rope.line_end_offset(4), 39);
618    }
619
620    #[test]
621    fn test_line_column() {
622        let rope = Rope::from("a 中文🎉 test\nRope");
623        assert_eq!(rope.position_to_offset(&Position::new(0, 3)), "a 中".len());
624        assert_eq!(
625            rope.position_to_offset(&Position::new(0, 5)),
626            "a 中文🎉".len()
627        );
628        assert_eq!(
629            rope.position_to_offset(&Position::new(1, 1)),
630            "a 中文🎉 test\nR".len()
631        );
632        assert_eq!(
633            rope.position_to_offset(&Position::new(0, u32::MAX)),
634            "a 中文🎉 test".len()
635        );
636
637        assert_eq!(
638            rope.offset_to_position("a 中文🎉 test\nR".len()),
639            Position::new(1, 1)
640        );
641        assert_eq!(
642            rope.offset_to_position("a 中文🎉".len()),
643            Position::new(0, 5)
644        );
645    }
646
647    #[test]
648    fn test_offset_to_point() {
649        let rope = Rope::from("a 中文🎉 test\nRope");
650        assert_eq!(rope.offset_to_point(0), Point::new(0, 0));
651        assert_eq!(rope.offset_to_point(1), Point::new(0, 1));
652        assert_eq!(rope.offset_to_point("a 中".len()), Point::new(0, 5));
653        assert_eq!(rope.offset_to_point("a 中文🎉".len()), Point::new(0, 12));
654        assert_eq!(
655            rope.offset_to_point("a 中文🎉 test\nR".len()),
656            Point::new(1, 1)
657        );
658    }
659
660    #[test]
661    fn test_point_to_offset() {
662        let rope = Rope::from("a 中文🎉 test\nRope");
663        assert_eq!(rope.point_to_offset(Point::new(0, 0)), 0);
664        assert_eq!(rope.point_to_offset(Point::new(0, 1)), 1);
665        assert_eq!(rope.point_to_offset(Point::new(0, 5)), "a 中".len());
666        assert_eq!(rope.point_to_offset(Point::new(0, 12)), "a 中文🎉".len());
667        assert_eq!(
668            rope.point_to_offset(Point::new(1, 1)),
669            "a 中文🎉 test\nR".len()
670        );
671    }
672
673    #[test]
674    fn test_char_at() {
675        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文🎉\nRope");
676        assert_eq!(rope.char_at(0), Some('H'));
677        assert_eq!(rope.char_at(5), Some('\n'));
678        assert_eq!(rope.char_at(13), Some('T'));
679        assert_eq!(rope.char_at(28), Some('中'));
680        assert_eq!(rope.char_at(34), Some('🎉'));
681        assert_eq!(rope.char_at(38), Some('\n'));
682        assert_eq!(rope.char_at(50), None);
683    }
684
685    #[test]
686    fn test_word_at() {
687        let rope = Rope::from("Hello\nWorld\r\nThis is a test 中文 世界\nRope");
688        assert_eq!(rope.word_at(0), "Hello");
689        assert_eq!(rope.word_range(0), Some(0..5));
690        assert_eq!(rope.word_at(8), "World");
691        assert_eq!(rope.word_range(8), Some(6..11));
692        assert_eq!(rope.word_at(12), "");
693        assert_eq!(rope.word_range(12), None);
694        assert_eq!(rope.word_at(13), "This");
695        assert_eq!(rope.word_range(13), Some(13..17));
696        assert_eq!(rope.word_at(31), "中文");
697        assert_eq!(rope.word_range(31), Some(28..34));
698        assert_eq!(rope.word_at(38), "世界");
699        assert_eq!(rope.word_range(38), Some(35..41));
700        assert_eq!(rope.word_at(44), "Rope");
701        assert_eq!(rope.word_range(44), Some(42..46));
702        assert_eq!(rope.word_at(45), "Rope");
703    }
704
705    #[test]
706    fn test_offset_utf16_conversion() {
707        let rope = Rope::from("hello 中文🎉 test\nRope");
708        assert_eq!(rope.offset_to_offset_utf16("hello".len()), 5);
709        assert_eq!(rope.offset_to_offset_utf16("hello 中".len()), 7);
710        assert_eq!(rope.offset_to_offset_utf16("hello 中文".len()), 8);
711        assert_eq!(rope.offset_to_offset_utf16("hello 中文🎉".len()), 10);
712        assert_eq!(rope.offset_to_offset_utf16(100), 20);
713
714        assert_eq!(rope.offset_utf16_to_offset(5), "hello".len());
715        assert_eq!(rope.offset_utf16_to_offset(7), "hello 中".len());
716        assert_eq!(rope.offset_utf16_to_offset(8), "hello 中文".len());
717        assert_eq!(rope.offset_utf16_to_offset(10), "hello 中文🎉".len());
718        assert_eq!(rope.offset_utf16_to_offset(100), rope.len());
719    }
720
721    #[test]
722    fn test_replace() {
723        let mut rope = Rope::from("Hello\nWorld\r\nThis is a test 中文\nRope");
724        rope.replace(6..11, "Universe");
725        assert_eq!(
726            rope.to_string(),
727            "Hello\nUniverse\r\nThis is a test 中文\nRope"
728        );
729
730        rope.replace(0..5, "Hi");
731        assert_eq!(
732            rope.to_string(),
733            "Hi\nUniverse\r\nThis is a test 中文\nRope"
734        );
735
736        rope.replace(rope.len() - 4..rope.len(), "String");
737        assert_eq!(
738            rope.to_string(),
739            "Hi\nUniverse\r\nThis is a test 中文\nString"
740        );
741
742        // Test for not on a char boundary
743        let mut rope = Rope::from("中文");
744        rope.replace(0..1, "New");
745        // autocorrect-disable
746        assert_eq!(rope.to_string(), "New文");
747        let mut rope = Rope::from("中文");
748        rope.replace(0..2, "New");
749        assert_eq!(rope.to_string(), "New文");
750        let mut rope = Rope::from("中文");
751        rope.replace(0..3, "New");
752        assert_eq!(rope.to_string(), "New文");
753        // autocorrect-enable
754        let mut rope = Rope::from("中文");
755        rope.replace(1..4, "New");
756        assert_eq!(rope.to_string(), "New");
757    }
758
759    #[test]
760    fn test_clip_offset() {
761        let rope = Rope::from("Hello 中文🎉 test\nRope");
762        // Inside multi-byte character '中' (3 bytes)
763        assert_eq!(rope.clip_offset(5, Bias::Left), 5);
764        assert_eq!(rope.clip_offset(7, Bias::Left), 6);
765        assert_eq!(rope.clip_offset(7, Bias::Right), 9);
766        assert_eq!(rope.clip_offset(9, Bias::Left), 9);
767
768        // Inside multi-byte character '🎉' (4 bytes)
769        assert_eq!(rope.clip_offset(13, Bias::Left), 12);
770        assert_eq!(rope.clip_offset(13, Bias::Right), 16);
771        assert_eq!(rope.clip_offset(16, Bias::Left), 16);
772
773        // At character boundary
774        assert_eq!(rope.clip_offset(5, Bias::Left), 5);
775        assert_eq!(rope.clip_offset(5, Bias::Right), 5);
776
777        // Out of bounds
778        assert_eq!(rope.clip_offset(26, Bias::Left), 26);
779        assert_eq!(rope.clip_offset(100, Bias::Left), 26);
780    }
781
782    #[test]
783    fn test_grapheme_boundaries_match_unicode_segmentation() {
784        use unicode_segmentation::UnicodeSegmentation as _;
785
786        let text = "x".repeat(1500) + "🇸🇪🇸🇪🇸🇪" + "👨‍👩‍👧".repeat(200).as_str() + "e\u{301}\r\nend";
787        let rope = Rope::from(text.as_str());
788        let mut boundaries: Vec<usize> = text.grapheme_indices(true).map(|(ix, _)| ix).collect();
789        boundaries.push(text.len());
790
791        for pair in boundaries.windows(2) {
792            assert_eq!(next_grapheme_boundary(&rope, pair[0]), pair[1]);
793            assert_eq!(previous_grapheme_boundary(&rope, pair[1]), pair[0]);
794            for inside in pair[0] + 1..pair[1] {
795                assert_eq!(previous_grapheme_boundary(&rope, inside), pair[0]);
796            }
797        }
798        assert_eq!(previous_grapheme_boundary(&rope, 0), 0);
799        assert_eq!(next_grapheme_boundary(&rope, text.len()), text.len());
800    }
801
802    #[test]
803    fn test_char_index_to_offset() {
804        let rope = Rope::from("a 中文🎉 test\nRope");
805        assert_eq!(rope.char_index_to_offset(0), 0);
806        assert_eq!(rope.char_index_to_offset(1), 1);
807        assert_eq!(rope.char_index_to_offset(3), "a 中".len());
808        assert_eq!(rope.char_index_to_offset(5), "a 中文🎉".len());
809        assert_eq!(rope.char_index_to_offset(6), "a 中文🎉 ".len());
810
811        assert_eq!(rope.offset_to_char_index(0), 0);
812        assert_eq!(rope.offset_to_char_index(1), 1);
813        assert_eq!(rope.offset_to_char_index(3), 3);
814        assert_eq!(rope.offset_to_char_index(4), 3);
815        assert_eq!(rope.offset_to_char_index(5), 3);
816        assert_eq!(rope.offset_to_char_index(6), 4);
817        assert_eq!(rope.offset_to_char_index(10), 5);
818    }
819}