Skip to main content

gpui_base/input/base/
rope_ext.rs

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