Debian Codegraph @

helix-stdx/src/rope.rs

raw symbols SCIP
1 //! Functions and types for working with [RopeSlice]
2 use std::fmt;
3 use std::ops::{Bound, RangeBounds};
4
5 pub use regex_cursor::engines::meta::{Builder as RegexBuilder, Regex};
6 pub use regex_cursor::regex_automata::util::syntax::Config;
7 use regex_cursor::{Input as RegexInput, RopeyCursor};
8 use ropey::iter::Chunks;
9 use ropey::RopeSlice;
10 use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
11
12 /// Additional utility functions for [RopeSlice]
13 pub trait RopeSliceExt<'a>: Sized {
14 fn ends_with(self, text: &str) -> bool;
15 fn starts_with(self, text: &str) -> bool;
16 #[must_use]
17 fn regex_input(self) -> RegexInput<RopeyCursor<'a>>;
18 #[must_use]
19 fn regex_input_at_bytes<R: RangeBounds<usize>>(
20 self,
21 byte_range: R,
22 ) -> RegexInput<RopeyCursor<'a>>;
23 #[must_use]
24 fn regex_input_at<R: RangeBounds<usize>>(self, char_range: R) -> RegexInput<RopeyCursor<'a>>;
25 fn first_non_whitespace_char(self) -> Option<usize>;
26 fn last_non_whitespace_char(self) -> Option<usize>;
27 /// Finds the closest byte index not exceeding `byte_idx` which lies on a character boundary.
28 ///
29 /// If `byte_idx` already lies on a character boundary then it is returned as-is. When
30 /// `byte_idx` lies between two character boundaries, this function returns the byte index of
31 /// the lesser / earlier / left-hand-side boundary.
32 ///
33 /// # Example
34 ///
35 /// ```
36 /// # use ropey::RopeSlice;
37 /// # use helix_stdx::rope::RopeSliceExt;
38 /// let text = RopeSlice::from("⌚"); // three bytes: e2 8c 9a
39 /// assert_eq!(text.floor_char_boundary(0), 0);
40 /// assert_eq!(text.floor_char_boundary(1), 0);
41 /// assert_eq!(text.floor_char_boundary(2), 0);
42 /// assert_eq!(text.floor_char_boundary(3), 3);
43 /// ```
44 fn floor_char_boundary(self, byte_idx: usize) -> usize;
45 /// Finds the closest byte index not below `byte_idx` which lies on a character boundary.
46 ///
47 /// If `byte_idx` already lies on a character boundary then it is returned as-is. When
48 /// `byte_idx` lies between two character boundaries, this function returns the byte index of
49 /// the greater / later / right-hand-side boundary.
50 ///
51 /// # Example
52 ///
53 /// ```
54 /// # use ropey::RopeSlice;
55 /// # use helix_stdx::rope::RopeSliceExt;
56 /// let text = RopeSlice::from("⌚"); // three bytes: e2 8c 9a
57 /// assert_eq!(text.ceil_char_boundary(0), 0);
58 /// assert_eq!(text.ceil_char_boundary(1), 3);
59 /// assert_eq!(text.ceil_char_boundary(2), 3);
60 /// assert_eq!(text.ceil_char_boundary(3), 3);
61 /// ```
62 fn ceil_char_boundary(self, byte_idx: usize) -> usize;
63 /// Checks whether the given `byte_idx` lies on a character boundary.
64 ///
65 /// # Example
66 ///
67 /// ```
68 /// # use ropey::RopeSlice;
69 /// # use helix_stdx::rope::RopeSliceExt;
70 /// let text = RopeSlice::from("⌚"); // three bytes: e2 8c 9a
71 /// assert!(text.is_char_boundary(0));
72 /// assert!(!text.is_char_boundary(1));
73 /// assert!(!text.is_char_boundary(2));
74 /// assert!(text.is_char_boundary(3));
75 /// ```
76 #[allow(clippy::wrong_self_convention)]
77 fn is_char_boundary(self, byte_idx: usize) -> bool;
78 /// Finds the closest byte index not exceeding `byte_idx` which lies on a grapheme cluster
79 /// boundary.
80 ///
81 /// If `byte_idx` already lies on a grapheme cluster boundary then it is returned as-is. When
82 /// `byte_idx` lies between two grapheme cluster boundaries, this function returns the byte
83 /// index of the lesser / earlier / left-hand-side boundary.
84 ///
85 /// `byte_idx` does not need to be aligned to a character boundary.
86 ///
87 /// # Example
88 ///
89 /// ```
90 /// # use ropey::RopeSlice;
91 /// # use helix_stdx::rope::RopeSliceExt;
92 /// let text = RopeSlice::from("\r\n"); // U+000D U+000A, hex: 0d 0a
93 /// assert_eq!(text.floor_grapheme_boundary(0), 0);
94 /// assert_eq!(text.floor_grapheme_boundary(1), 0);
95 /// assert_eq!(text.floor_grapheme_boundary(2), 2);
96 /// ```
97 fn floor_grapheme_boundary(self, byte_idx: usize) -> usize;
98 /// Finds the closest byte index not exceeding `byte_idx` which lies on a grapheme cluster
99 /// boundary.
100 ///
101 /// If `byte_idx` already lies on a grapheme cluster boundary then it is returned as-is. When
102 /// `byte_idx` lies between two grapheme cluster boundaries, this function returns the byte
103 /// index of the greater / later / right-hand-side boundary.
104 ///
105 /// `byte_idx` does not need to be aligned to a character boundary.
106 ///
107 /// # Example
108 ///
109 /// ```
110 /// # use ropey::RopeSlice;
111 /// # use helix_stdx::rope::RopeSliceExt;
112 /// let text = RopeSlice::from("\r\n"); // U+000D U+000A, hex: 0d 0a
113 /// assert_eq!(text.ceil_grapheme_boundary(0), 0);
114 /// assert_eq!(text.ceil_grapheme_boundary(1), 2);
115 /// assert_eq!(text.ceil_grapheme_boundary(2), 2);
116 /// ```
117 fn ceil_grapheme_boundary(self, byte_idx: usize) -> usize;
118 /// Checks whether the `byte_idx` lies on a grapheme cluster boundary.
119 ///
120 /// # Example
121 ///
122 /// ```
123 /// # use ropey::RopeSlice;
124 /// # use helix_stdx::rope::RopeSliceExt;
125 /// let text = RopeSlice::from("\r\n"); // U+000D U+000A, hex: 0d 0a
126 /// assert!(text.is_grapheme_boundary(0));
127 /// assert!(!text.is_grapheme_boundary(1));
128 /// assert!(text.is_grapheme_boundary(2));
129 /// ```
130 #[allow(clippy::wrong_self_convention)]
131 fn is_grapheme_boundary(self, byte_idx: usize) -> bool;
132 /// Returns an iterator over the grapheme clusters in the slice.
133 ///
134 /// # Example
135 ///
136 /// ```
137 /// # use ropey::RopeSlice;
138 /// # use helix_stdx::rope::RopeSliceExt;
139 /// let text = RopeSlice::from("πŸ˜Άβ€πŸŒ«οΈπŸ΄β€β˜ οΈπŸ–ΌοΈ");
140 /// let graphemes: Vec<_> = text.graphemes().collect();
141 /// assert_eq!(graphemes.as_slice(), &["πŸ˜Άβ€πŸŒ«οΈ", "πŸ΄β€β˜ οΈ", "πŸ–ΌοΈ"]);
142 /// ```
143 #[inline]
144 #[must_use]
145 fn graphemes(self) -> RopeGraphemes<'a> {
146 self.graphemes_at(0)
147 }
148 /// Returns an iterator over the grapheme clusters in the slice, reversed.
149 ///
150 /// The returned iterator starts at the end of the slice and ends at the beginning of the
151 /// slice.
152 ///
153 /// # Example
154 ///
155 /// ```
156 /// # use ropey::RopeSlice;
157 /// # use helix_stdx::rope::RopeSliceExt;
158 /// let text = RopeSlice::from("πŸ˜Άβ€πŸŒ«οΈπŸ΄β€β˜ οΈπŸ–ΌοΈ");
159 /// let graphemes: Vec<_> = text.graphemes_rev().collect();
160 /// assert_eq!(graphemes.as_slice(), &["πŸ–ΌοΈ", "πŸ΄β€β˜ οΈ", "πŸ˜Άβ€πŸŒ«οΈ"]);
161 /// ```
162 #[must_use]
163 fn graphemes_rev(self) -> RopeGraphemes<'a>;
164 /// Returns an iterator over the grapheme clusters in the slice at the given byte index.
165 ///
166 /// # Example
167 ///
168 /// ```
169 /// # use ropey::Rope;
170 /// # use helix_stdx::rope::RopeSliceExt;
171 /// let text = Rope::from_str("πŸ˜Άβ€πŸŒ«οΈπŸ΄β€β˜ οΈπŸ–ΌοΈ");
172 /// // 14 is the byte index of the pirate flag's starting cluster boundary.
173 /// let graphemes: Vec<_> = text.slice(..).graphemes_at(14).collect();
174 /// assert_eq!(graphemes.as_slice(), &["πŸ΄β€β˜ οΈ", "πŸ–ΌοΈ"]);
175 /// // 27 is the byte index of the pirate flag's ending cluster boundary.
176 /// let graphemes: Vec<_> = text.slice(..).graphemes_at(27).reversed().collect();
177 /// assert_eq!(graphemes.as_slice(), &["πŸ΄β€β˜ οΈ", "πŸ˜Άβ€πŸŒ«οΈ"]);
178 /// ```
179 #[must_use]
180 fn graphemes_at(self, byte_idx: usize) -> RopeGraphemes<'a>;
181 /// Returns an iterator over the grapheme clusters in a rope and the byte index where each
182 /// grapheme cluster starts.
183 ///
184 /// Same as `grapheme_indices_at(0)`.
185 #[inline]
186 #[must_use]
187 fn grapheme_indices(self) -> RopeGraphemeIndices<'a> {
188 self.grapheme_indices_at(0)
189 }
190 /// Returns an iterator over the grapheme clusters in a rope and the byte index where each
191 /// grapheme cluster starts.
192 ///
193 /// # Example
194 ///
195 /// ```
196 /// # use ropey::Rope;
197 /// # use helix_stdx::rope::RopeSliceExt;
198 /// let text = Rope::from_str("πŸ˜Άβ€πŸŒ«οΈπŸ΄β€β˜ οΈπŸ–ΌοΈ");
199 /// let slice = text.slice(..);
200 /// let graphemes: Vec<_> = slice.grapheme_indices_at(0).collect();
201 /// assert_eq!(
202 /// graphemes.as_slice(),
203 /// &[(0, "πŸ˜Άβ€πŸŒ«οΈ".into()), (14, "πŸ΄β€β˜ οΈ".into()), (27, "πŸ–ΌοΈ".into())]
204 /// );
205 /// let graphemes: Vec<_> = slice.grapheme_indices_at(slice.len_bytes()).reversed().collect();
206 /// assert_eq!(
207 /// graphemes.as_slice(),
208 /// &[(27, "πŸ–ΌοΈ".into()), (14, "πŸ΄β€β˜ οΈ".into()), (0, "πŸ˜Άβ€πŸŒ«οΈ".into())]
209 /// );
210 /// ```
211 #[must_use]
212 fn grapheme_indices_at(self, byte_idx: usize) -> RopeGraphemeIndices<'a>;
213 /// Finds the byte index of the next grapheme boundary after `byte_idx`.
214 ///
215 /// If the byte index lies on the last grapheme cluster in the slice then this function
216 /// returns `RopeSlice::len_bytes`.
217 ///
218 /// # Example
219 ///
220 /// ```
221 /// # use ropey::Rope;
222 /// # use helix_stdx::rope::RopeSliceExt;
223 /// let text = Rope::from_str("πŸ˜Άβ€πŸŒ«οΈπŸ΄β€β˜ οΈπŸ–ΌοΈ");
224 /// let slice = text.slice(..);
225 /// let mut byte_idx = 0;
226 /// assert_eq!(slice.graphemes_at(byte_idx).next(), Some("πŸ˜Άβ€πŸŒ«οΈ".into()));
227 /// byte_idx = slice.next_grapheme_boundary(byte_idx);
228 /// assert_eq!(slice.graphemes_at(byte_idx).next(), Some("πŸ΄β€β˜ οΈ".into()));
229 ///
230 /// // If `byte_idx` does not lie on a character or grapheme boundary then this function is
231 /// // functionally the same as `ceil_grapheme_boundary`.
232 /// assert_eq!(slice.next_grapheme_boundary(byte_idx - 1), byte_idx);
233 /// assert_eq!(slice.next_grapheme_boundary(byte_idx - 2), byte_idx);
234 /// assert_eq!(slice.next_grapheme_boundary(byte_idx + 1), slice.next_grapheme_boundary(byte_idx));
235 /// assert_eq!(slice.next_grapheme_boundary(byte_idx + 2), slice.next_grapheme_boundary(byte_idx));
236 ///
237 /// byte_idx = slice.next_grapheme_boundary(byte_idx);
238 /// assert_eq!(slice.graphemes_at(byte_idx).next(), Some("πŸ–ΌοΈ".into()));
239 /// byte_idx = slice.next_grapheme_boundary(byte_idx);
240 /// assert_eq!(slice.graphemes_at(byte_idx).next(), None);
241 /// assert_eq!(byte_idx, slice.len_bytes());
242 /// ```
243 fn next_grapheme_boundary(self, byte_idx: usize) -> usize {
244 self.nth_next_grapheme_boundary(byte_idx, 1)
245 }
246 /// Finds the byte index of the `n`th grapheme cluster after the given `byte_idx`.
247 ///
248 /// If there are fewer than `n` grapheme clusters after `byte_idx` in the rope then this
249 /// function returns `RopeSlice::len_bytes`.
250 ///
251 /// This is functionally equivalent to calling `next_grapheme_boundary` `n` times but is more
252 /// efficient.
253 fn nth_next_grapheme_boundary(self, byte_idx: usize, n: usize) -> usize;
254 /// Finds the byte index of the previous grapheme boundary before `byte_idx`.
255 ///
256 /// If the byte index lies on the first grapheme cluster in the slice then this function
257 /// returns zero.
258 ///
259 /// # Example
260 ///
261 /// ```
262 /// # use ropey::Rope;
263 /// # use helix_stdx::rope::RopeSliceExt;
264 /// let text = Rope::from_str("πŸ˜Άβ€πŸŒ«οΈπŸ΄β€β˜ οΈπŸ–ΌοΈ");
265 /// let slice = text.slice(..);
266 /// let mut byte_idx = text.len_bytes();
267 /// assert_eq!(slice.graphemes_at(byte_idx).prev(), Some("πŸ–ΌοΈ".into()));
268 /// byte_idx = slice.prev_grapheme_boundary(byte_idx);
269 /// assert_eq!(slice.graphemes_at(byte_idx).prev(), Some("πŸ΄β€β˜ οΈ".into()));
270 ///
271 /// // If `byte_idx` does not lie on a character or grapheme boundary then this function is
272 /// // functionally the same as `floor_grapheme_boundary`.
273 /// assert_eq!(slice.prev_grapheme_boundary(byte_idx + 1), byte_idx);
274 /// assert_eq!(slice.prev_grapheme_boundary(byte_idx + 2), byte_idx);
275 /// assert_eq!(slice.prev_grapheme_boundary(byte_idx - 1), slice.prev_grapheme_boundary(byte_idx));
276 /// assert_eq!(slice.prev_grapheme_boundary(byte_idx - 2), slice.prev_grapheme_boundary(byte_idx));
277 ///
278 /// byte_idx = slice.prev_grapheme_boundary(byte_idx);
279 /// assert_eq!(slice.graphemes_at(byte_idx).prev(), Some("πŸ˜Άβ€πŸŒ«οΈ".into()));
280 /// byte_idx = slice.prev_grapheme_boundary(byte_idx);
281 /// assert_eq!(slice.graphemes_at(byte_idx).prev(), None);
282 /// assert_eq!(byte_idx, 0);
283 /// ```
284 fn prev_grapheme_boundary(self, byte_idx: usize) -> usize {
285 self.nth_prev_grapheme_boundary(byte_idx, 1)
286 }
287 /// Finds the byte index of the `n`th grapheme cluster before the given `byte_idx`.
288 ///
289 /// If there are fewer than `n` grapheme clusters before `byte_idx` in the rope then this
290 /// function returns zero.
291 ///
292 /// This is functionally equivalent to calling `prev_grapheme_boundary` `n` times but is more
293 /// efficient.
294 fn nth_prev_grapheme_boundary(self, byte_idx: usize, n: usize) -> usize;
295 }
296
297 impl<'a> RopeSliceExt<'a> for RopeSlice<'a> {
298 fn ends_with(self, text: &str) -> bool {
299 let len = self.len_bytes();
300 if len < text.len() {
301 return false;
302 }
303 self.get_byte_slice(len - text.len()..)
304 .is_some_and(|end| end == text)
305 }
306
307 fn starts_with(self, text: &str) -> bool {
308 let len = self.len_bytes();
309 if len < text.len() {
310 return false;
311 }
312 self.get_byte_slice(..text.len())
313 .is_some_and(|start| start == text)
314 }
315
316 fn regex_input(self) -> RegexInput<RopeyCursor<'a>> {
317 RegexInput::new(self)
318 }
319
320 fn regex_input_at<R: RangeBounds<usize>>(self, char_range: R) -> RegexInput<RopeyCursor<'a>> {
321 let start_bound = match char_range.start_bound() {
322 Bound::Included(&val) => Bound::Included(self.char_to_byte(val)),
323 Bound::Excluded(&val) => Bound::Excluded(self.char_to_byte(val)),
324 Bound::Unbounded => Bound::Unbounded,
325 };
326 let end_bound = match char_range.end_bound() {
327 Bound::Included(&val) => Bound::Included(self.char_to_byte(val)),
328 Bound::Excluded(&val) => Bound::Excluded(self.char_to_byte(val)),
329 Bound::Unbounded => Bound::Unbounded,
330 };
331 self.regex_input_at_bytes((start_bound, end_bound))
332 }
333 fn regex_input_at_bytes<R: RangeBounds<usize>>(
334 self,
335 byte_range: R,
336 ) -> RegexInput<RopeyCursor<'a>> {
337 let input = match byte_range.start_bound() {
338 Bound::Included(&pos) | Bound::Excluded(&pos) => {
339 RegexInput::new(RopeyCursor::at(self, pos))
340 }
341 Bound::Unbounded => RegexInput::new(self),
342 };
343 input.range(byte_range)
344 }
345 fn first_non_whitespace_char(self) -> Option<usize> {
346 self.chars().position(|ch| !ch.is_whitespace())
347 }
348 fn last_non_whitespace_char(self) -> Option<usize> {
349 self.chars_at(self.len_chars())
350 .reversed()
351 .position(|ch| !ch.is_whitespace())
352 .map(|pos| self.len_chars() - pos - 1)
353 }
354
355 // These three are adapted from std:
356
357 fn floor_char_boundary(self, byte_idx: usize) -> usize {
358 if byte_idx >= self.len_bytes() {
359 self.len_bytes()
360 } else {
361 let offset = self
362 .bytes_at(byte_idx + 1)
363 .reversed()
364 .take(4)
365 .position(is_utf8_char_boundary)
366 // A char can only be four bytes long so we are guaranteed to find a boundary.
367 .unwrap();
368
369 byte_idx - offset
370 }
371 }
372
373 fn ceil_char_boundary(self, byte_idx: usize) -> usize {
374 if byte_idx > self.len_bytes() {
375 self.len_bytes()
376 } else {
377 let upper_bound = self.len_bytes().min(byte_idx + 4);
378 self.bytes_at(byte_idx)
379 .position(is_utf8_char_boundary)
380 .map_or(upper_bound, |pos| pos + byte_idx)
381 }
382 }
383
384 fn is_char_boundary(self, byte_idx: usize) -> bool {
385 if byte_idx == 0 {
386 return true;
387 }
388
389 if byte_idx >= self.len_bytes() {
390 byte_idx == self.len_bytes()
391 } else {
392 is_utf8_char_boundary(self.bytes_at(byte_idx).next().unwrap())
393 }
394 }
395
396 fn floor_grapheme_boundary(self, mut byte_idx: usize) -> usize {
397 if byte_idx >= self.len_bytes() {
398 return self.len_bytes();
399 }
400
401 byte_idx = self.ceil_char_boundary(byte_idx + 1);
402
403 let (mut chunk, mut chunk_byte_idx, _, _) = self.chunk_at_byte(byte_idx);
404
405 let mut cursor = GraphemeCursor::new(byte_idx, self.len_bytes(), true);
406
407 loop {
408 match cursor.prev_boundary(chunk, chunk_byte_idx) {
409 Ok(None) => return 0,
410 Ok(Some(boundary)) => return boundary,
411 Err(GraphemeIncomplete::PrevChunk) => {
412 let (ch, ch_byte_idx, _, _) = self.chunk_at_byte(chunk_byte_idx - 1);
413 chunk = ch;
414 chunk_byte_idx = ch_byte_idx;
415 }
416 Err(GraphemeIncomplete::PreContext(n)) => {
417 let ctx_chunk = self.chunk_at_byte(n - 1).0;
418 cursor.provide_context(ctx_chunk, n - ctx_chunk.len());
419 }
420 _ => unreachable!(),
421 }
422 }
423 }
424
425 fn ceil_grapheme_boundary(self, mut byte_idx: usize) -> usize {
426 if byte_idx >= self.len_bytes() {
427 return self.len_bytes();
428 }
429
430 if byte_idx == 0 {
431 return 0;
432 }
433
434 byte_idx = self.floor_char_boundary(byte_idx - 1);
435
436 let (mut chunk, mut chunk_byte_idx, _, _) = self.chunk_at_byte(byte_idx);
437
438 let mut cursor = GraphemeCursor::new(byte_idx, self.len_bytes(), true);
439
440 loop {
441 match cursor.next_boundary(chunk, chunk_byte_idx) {
442 Ok(None) => return self.len_bytes(),
443 Ok(Some(boundary)) => return boundary,
444 Err(GraphemeIncomplete::NextChunk) => {
445 chunk_byte_idx += chunk.len();
446 chunk = self.chunk_at_byte(chunk_byte_idx).0;
447 }
448 Err(GraphemeIncomplete::PreContext(n)) => {
449 let ctx_chunk = self.chunk_at_byte(n - 1).0;
450 cursor.provide_context(ctx_chunk, n - ctx_chunk.len());
451 }
452 _ => unreachable!(),
453 }
454 }
455 }
456
457 fn is_grapheme_boundary(self, byte_idx: usize) -> bool {
458 // The byte must lie on a character boundary to lie on a grapheme cluster boundary.
459 if !self.is_char_boundary(byte_idx) {
460 return false;
461 }
462
463 let (chunk, chunk_byte_idx, _, _) = self.chunk_at_byte(byte_idx);
464
465 let mut cursor = GraphemeCursor::new(byte_idx, self.len_bytes(), true);
466
467 loop {
468 match cursor.is_boundary(chunk, chunk_byte_idx) {
469 Ok(n) => return n,
470 Err(GraphemeIncomplete::PreContext(n)) => {
471 let (ctx_chunk, ctx_byte_start, _, _) = self.chunk_at_byte(n - 1);
472 cursor.provide_context(ctx_chunk, ctx_byte_start);
473 }
474 Err(_) => unreachable!(),
475 }
476 }
477 }
478
479 fn graphemes_rev(self) -> RopeGraphemes<'a> {
480 self.graphemes_at(self.len_bytes()).reversed()
481 }
482
483 fn graphemes_at(self, byte_idx: usize) -> RopeGraphemes<'a> {
484 // Bounds check
485 assert!(byte_idx <= self.len_bytes());
486
487 let (mut chunks, chunk_byte_idx, _, _) = self.chunks_at_byte(byte_idx);
488 let current_chunk = chunks.next().unwrap_or("");
489
490 RopeGraphemes {
491 text: self,
492 chunks,
493 current_chunk,
494 chunk_byte_idx,
495 cursor: GraphemeCursor::new(byte_idx, self.len_bytes(), true),
496 is_reversed: false,
497 }
498 }
499
500 fn grapheme_indices_at(self, byte_idx: usize) -> RopeGraphemeIndices<'a> {
501 // Bounds check
502 assert!(byte_idx <= self.len_bytes());
503 RopeGraphemeIndices {
504 front_offset: byte_idx,
505 iter: self.graphemes_at(byte_idx),
506 is_reversed: false,
507 }
508 }
509
510 fn nth_next_grapheme_boundary(self, mut byte_idx: usize, n: usize) -> usize {
511 // Bounds check
512 assert!(byte_idx <= self.len_bytes());
513
514 byte_idx = self.floor_char_boundary(byte_idx);
515
516 // Get the chunk with our byte index in it.
517 let (mut chunk, mut chunk_byte_idx, _, _) = self.chunk_at_byte(byte_idx);
518
519 // Set up the grapheme cursor.
520 let mut gc = GraphemeCursor::new(byte_idx, self.len_bytes(), true);
521
522 // Find the nth next grapheme cluster boundary.
523 for _ in 0..n {
524 loop {
525 match gc.next_boundary(chunk, chunk_byte_idx) {
526 Ok(None) => return self.len_bytes(),
527 Ok(Some(boundary)) => {
528 byte_idx = boundary;
529 break;
530 }
531 Err(GraphemeIncomplete::NextChunk) => {
532 chunk_byte_idx += chunk.len();
533 let (a, _, _, _) = self.chunk_at_byte(chunk_byte_idx);
534 chunk = a;
535 }
536 Err(GraphemeIncomplete::PreContext(n)) => {
537 let ctx_chunk = self.chunk_at_byte(n - 1).0;
538 gc.provide_context(ctx_chunk, n - ctx_chunk.len());
539 }
540 _ => unreachable!(),
541 }
542 }
543 }
544
545 byte_idx
546 }
547
548 fn nth_prev_grapheme_boundary(self, mut byte_idx: usize, n: usize) -> usize {
549 // Bounds check
550 assert!(byte_idx <= self.len_bytes());
551
552 byte_idx = self.ceil_char_boundary(byte_idx);
553
554 // Get the chunk with our byte index in it.
555 let (mut chunk, mut chunk_byte_idx, _, _) = self.chunk_at_byte(byte_idx);
556
557 // Set up the grapheme cursor.
558 let mut gc = GraphemeCursor::new(byte_idx, self.len_bytes(), true);
559
560 for _ in 0..n {
561 loop {
562 match gc.prev_boundary(chunk, chunk_byte_idx) {
563 Ok(None) => return 0,
564 Ok(Some(boundary)) => {
565 byte_idx = boundary;
566 break;
567 }
568 Err(GraphemeIncomplete::PrevChunk) => {
569 let (a, b, _, _) = self.chunk_at_byte(chunk_byte_idx - 1);
570 chunk = a;
571 chunk_byte_idx = b;
572 }
573 Err(GraphemeIncomplete::PreContext(n)) => {
574 let ctx_chunk = self.chunk_at_byte(n - 1).0;
575 gc.provide_context(ctx_chunk, n - ctx_chunk.len());
576 }
577 _ => unreachable!(),
578 }
579 }
580 }
581
582 byte_idx
583 }
584 }
585
586 // copied from std
587 #[inline]
588 const fn is_utf8_char_boundary(b: u8) -> bool {
589 // This is bit magic equivalent to: b < 128 || b >= 192
590 (b as i8) >= -0x40
591 }
592
593 /// An iterator over the graphemes of a `RopeSlice`.
594 ///
595 /// This iterator is cursor-like: rather than implementing DoubleEndedIterator it can be reversed
596 /// like a cursor. This style matches `Bytes` and `Chars` iterator types in Ropey and is more
597 /// natural and useful for wrapping `GraphemeCursor`.
598 #[derive(Clone)]
599 pub struct RopeGraphemes<'a> {
600 text: RopeSlice<'a>,
601 chunks: Chunks<'a>,
602 current_chunk: &'a str,
603 /// Byte index of the start of the current chunk.
604 chunk_byte_idx: usize,
605 cursor: GraphemeCursor,
606 is_reversed: bool,
607 }
608
609 impl fmt::Debug for RopeGraphemes<'_> {
610 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
611 f.debug_struct("RopeGraphemes")
612 .field("text", &self.text)
613 .field("chunks", &self.chunks)
614 .field("current_chunk", &self.current_chunk)
615 .field("chunk_byte_idx", &self.chunk_byte_idx)
616 // .field("cursor", &self.cursor)
617 .field("is_reversed", &self.is_reversed)
618 .finish()
619 }
620 }
621
622 impl<'a> RopeGraphemes<'a> {
623 #[allow(clippy::should_implement_trait)]
624 pub fn next(&mut self) -> Option<RopeSlice<'a>> {
625 if self.is_reversed {
626 self.prev_impl()
627 } else {
628 self.next_impl()
629 }
630 }
631
632 pub fn prev(&mut self) -> Option<RopeSlice<'a>> {
633 if self.is_reversed {
634 self.next_impl()
635 } else {
636 self.prev_impl()
637 }
638 }
639
640 pub fn reverse(&mut self) {
641 self.is_reversed = !self.is_reversed;
642 }
643
644 #[must_use]
645 pub fn reversed(mut self) -> Self {
646 self.reverse();
647 self
648 }
649
650 fn next_impl(&mut self) -> Option<RopeSlice<'a>> {
651 let a = self.cursor.cur_cursor();
652 let b;
653 loop {
654 match self
655 .cursor
656 .next_boundary(self.current_chunk, self.chunk_byte_idx)
657 {
658 Ok(None) => return None,
659 Ok(Some(boundary)) => {
660 b = boundary;
661 break;
662 }
663 Err(GraphemeIncomplete::NextChunk) => {
664 self.chunk_byte_idx += self.current_chunk.len();
665 self.current_chunk = self.chunks.next().unwrap_or("");
666 }
667 Err(GraphemeIncomplete::PreContext(idx)) => {
668 let (chunk, byte_idx, _, _) = self.text.chunk_at_byte(idx.saturating_sub(1));
669 self.cursor.provide_context(chunk, byte_idx);
670 }
671 _ => unreachable!(),
672 }
673 }
674
675 if a < self.chunk_byte_idx {
676 Some(self.text.byte_slice(a..b))
677 } else {
678 let a2 = a - self.chunk_byte_idx;
679 let b2 = b - self.chunk_byte_idx;
680 Some((&self.current_chunk[a2..b2]).into())
681 }
682 }
683
684 fn prev_impl(&mut self) -> Option<RopeSlice<'a>> {
685 let a = self.cursor.cur_cursor();
686 let b;
687 loop {
688 match self
689 .cursor
690 .prev_boundary(self.current_chunk, self.chunk_byte_idx)
691 {
692 Ok(None) => return None,
693 Ok(Some(boundary)) => {
694 b = boundary;
695 break;
696 }
697 Err(GraphemeIncomplete::PrevChunk) => {
698 self.current_chunk = self.chunks.prev().unwrap_or("");
699 self.chunk_byte_idx -= self.current_chunk.len();
700 }
701 Err(GraphemeIncomplete::PreContext(idx)) => {
702 let (chunk, byte_idx, _, _) = self.text.chunk_at_byte(idx.saturating_sub(1));
703 self.cursor.provide_context(chunk, byte_idx);
704 }
705 _ => unreachable!(),
706 }
707 }
708
709 if a >= self.chunk_byte_idx + self.current_chunk.len() {
710 Some(self.text.byte_slice(b..a))
711 } else {
712 let a2 = a - self.chunk_byte_idx;
713 let b2 = b - self.chunk_byte_idx;
714 Some((&self.current_chunk[b2..a2]).into())
715 }
716 }
717 }
718
719 impl<'a> Iterator for RopeGraphemes<'a> {
720 type Item = RopeSlice<'a>;
721
722 fn next(&mut self) -> Option<Self::Item> {
723 RopeGraphemes::next(self)
724 }
725 }
726
727 /// An iterator over the grapheme clusters in a rope and the byte indices where each grapheme
728 /// cluster starts.
729 ///
730 /// This iterator wraps `RopeGraphemes` and is also cursor-like. Use `reverse` or `reversed` to
731 /// toggle the direction of the iterator. See [RopeGraphemes].
732 #[derive(Debug, Clone)]
733 pub struct RopeGraphemeIndices<'a> {
734 front_offset: usize,
735 iter: RopeGraphemes<'a>,
736 is_reversed: bool,
737 }
738
739 impl<'a> RopeGraphemeIndices<'a> {
740 #[allow(clippy::should_implement_trait)]
741 pub fn next(&mut self) -> Option<(usize, RopeSlice<'a>)> {
742 if self.is_reversed {
743 self.prev_impl()
744 } else {
745 self.next_impl()
746 }
747 }
748
749 pub fn prev(&mut self) -> Option<(usize, RopeSlice<'a>)> {
750 if self.is_reversed {
751 self.next_impl()
752 } else {
753 self.prev_impl()
754 }
755 }
756
757 pub fn reverse(&mut self) {
758 self.is_reversed = !self.is_reversed;
759 }
760
761 #[must_use]
762 pub fn reversed(mut self) -> Self {
763 self.reverse();
764 self
765 }
766
767 fn next_impl(&mut self) -> Option<(usize, RopeSlice<'a>)> {
768 let slice = self.iter.next()?;
769 let idx = self.front_offset;
770 self.front_offset += slice.len_bytes();
771 Some((idx, slice))
772 }
773
774 fn prev_impl(&mut self) -> Option<(usize, RopeSlice<'a>)> {
775 let slice = self.iter.prev()?;
776 self.front_offset -= slice.len_bytes();
777 Some((self.front_offset, slice))
778 }
779 }
780
781 impl<'a> Iterator for RopeGraphemeIndices<'a> {
782 type Item = (usize, RopeSlice<'a>);
783
784 fn next(&mut self) -> Option<Self::Item> {
785 RopeGraphemeIndices::next(self)
786 }
787 }
788
789 #[cfg(test)]
790 mod tests {
791 use ropey::RopeSlice;
792
793 use crate::rope::RopeSliceExt;
794
795 #[test]
796 fn starts_with() {
797 assert!(RopeSlice::from("asdf").starts_with("a"));
798 }
799
800 #[test]
801 fn ends_with() {
802 assert!(RopeSlice::from("asdf").ends_with("f"));
803 }
804
805 #[test]
806 fn char_boundaries() {
807 let ascii = RopeSlice::from("ascii");
808 // When the given index lies on a character boundary, the index should not change.
809 for byte_idx in 0..=ascii.len_bytes() {
810 assert_eq!(ascii.floor_char_boundary(byte_idx), byte_idx);
811 assert_eq!(ascii.ceil_char_boundary(byte_idx), byte_idx);
812 assert!(ascii.is_char_boundary(byte_idx));
813 }
814
815 // This is a polyfill of a method of this trait which was replaced by ceil_char_boundary.
816 // It returns the _character index_ of the given byte index, rounding up if it does not
817 // already lie on a character boundary.
818 fn byte_to_next_char(slice: RopeSlice, byte_idx: usize) -> usize {
819 slice.byte_to_char(slice.ceil_char_boundary(byte_idx))
820 }
821
822 for i in 0..=6 {
823 assert_eq!(byte_to_next_char(RopeSlice::from("foobar"), i), i);
824 }
825 for char_idx in 0..10 {
826 let len = "πŸ˜†".len();
827 assert_eq!(
828 byte_to_next_char(RopeSlice::from("πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†"), char_idx * len),
829 char_idx
830 );
831 for i in 1..=len {
832 assert_eq!(
833 byte_to_next_char(RopeSlice::from("πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†πŸ˜†"), char_idx * len + i),
834 char_idx + 1
835 );
836 }
837 }
838 }
839
840 #[test]
841 fn grapheme_boundaries() {
842 let ascii = RopeSlice::from("ascii");
843 // When the given index lies on a grapheme boundary, the index should not change.
844 for byte_idx in 0..=ascii.len_bytes() {
845 assert_eq!(ascii.floor_char_boundary(byte_idx), byte_idx);
846 assert_eq!(ascii.ceil_char_boundary(byte_idx), byte_idx);
847 assert!(ascii.is_grapheme_boundary(byte_idx));
848 }
849
850 // πŸ΄β€β˜ οΈ: U+1F3F4 U+200D U+2620 U+FE0F
851 // 13 bytes, hex: f0 9f 8f b4 + e2 80 8d + e2 98 a0 + ef b8 8f
852 let g = RopeSlice::from("πŸ΄β€β˜ οΈ\r\n");
853 let emoji_len = "πŸ΄β€β˜ οΈ".len();
854 let end = g.len_bytes();
855
856 for byte_idx in 0..emoji_len {
857 assert_eq!(g.floor_grapheme_boundary(byte_idx), 0);
858 }
859 for byte_idx in emoji_len..end {
860 assert_eq!(g.floor_grapheme_boundary(byte_idx), emoji_len);
861 }
862 assert_eq!(g.floor_grapheme_boundary(end), end);
863
864 assert_eq!(g.ceil_grapheme_boundary(0), 0);
865 for byte_idx in 1..=emoji_len {
866 assert_eq!(g.ceil_grapheme_boundary(byte_idx), emoji_len);
867 }
868 for byte_idx in emoji_len + 1..=end {
869 assert_eq!(g.ceil_grapheme_boundary(byte_idx), end);
870 }
871
872 assert!(g.is_grapheme_boundary(0));
873 assert!(g.is_grapheme_boundary(emoji_len));
874 assert!(g.is_grapheme_boundary(end));
875 for byte_idx in (1..emoji_len).chain(emoji_len + 1..end) {
876 assert!(!g.is_grapheme_boundary(byte_idx));
877 }
878 }
879 }