Skip to main content

egui/text_selection/
text_cursor_state.rs

1//! Text cursor changes/interaction, without modifying the text.
2
3use epaint::text::{ByteIndex, ByteRangeExt as _, CharIndex, Galley, cursor::CCursor};
4use unicode_segmentation::UnicodeSegmentation as _;
5
6use crate::{NumExt as _, Rect, Response, Ui, epaint};
7
8use super::CCursorRange;
9
10/// The unit by which a click or mouse-drag extends a text selection:
11/// characters after a single click, whole words after a double-click,
12/// whole lines after a triple-click.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(crate) enum SelectGranularity {
15    Char,
16    Word,
17    Line,
18}
19
20/// A selection that started with a double- or triple-click,
21/// remembered so that dragging and shift-clicking extend it by whole words or lines
22/// while always keeping the originally clicked word or line selected.
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub(crate) struct GranularDragSelect {
25    /// The unit of the current gesture (e.g. a shift-click extends by characters).
26    pub granularity: SelectGranularity,
27
28    /// The word or line that was initially double- or triple-clicked.
29    ///
30    /// Extending the selection before this range keeps its end fixed,
31    /// and extending it after this range keeps its start fixed,
32    /// so the anchor word or line always stays selected (like on macOS).
33    ///
34    /// For a shift-double-click (or triple-click) of a selection
35    /// that did not start with a double- or triple-click,
36    /// this is instead the (empty) far end of the selection that is being extended.
37    pub anchor: CCursorRange,
38}
39
40impl SelectGranularity {
41    /// The granularity of the current press: by characters, words, or lines.
42    pub(crate) fn of_press(ui: &Ui) -> Self {
43        match ui.input(|i| i.pointer.press_click_count()) {
44            0 | 1 => Self::Char,
45            2 => Self::Word,
46            _ => Self::Line,
47        }
48    }
49}
50
51/// The state of a text cursor selection.
52///
53/// Used for [`crate::TextEdit`] and [`crate::Label`].
54#[derive(Clone, Copy, Debug, Default)]
55#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
56#[cfg_attr(feature = "serde", serde(default))]
57pub struct TextCursorState {
58    ccursor_range: Option<CCursorRange>,
59
60    /// Transient state of the current mouse gesture, so not serialized.
61    #[cfg_attr(feature = "serde", serde(skip))]
62    granular_drag: Option<GranularDragSelect>,
63}
64
65impl From<CCursorRange> for TextCursorState {
66    fn from(ccursor_range: CCursorRange) -> Self {
67        Self {
68            ccursor_range: Some(ccursor_range),
69            granular_drag: None,
70        }
71    }
72}
73
74impl TextCursorState {
75    pub fn is_empty(&self) -> bool {
76        self.ccursor_range.is_none()
77    }
78
79    /// The currently selected range of characters.
80    pub fn char_range(&self) -> Option<CCursorRange> {
81        self.ccursor_range
82    }
83
84    /// The currently selected range of characters, clamped within the character
85    /// range of the given [`Galley`].
86    pub fn range(&self, galley: &Galley) -> Option<CCursorRange> {
87        self.ccursor_range.map(|mut range| {
88            range.primary = galley.clamp_cursor(&range.primary);
89            range.secondary = galley.clamp_cursor(&range.secondary);
90            range
91        })
92    }
93
94    /// Sets the currently selected range of characters.
95    pub fn set_char_range(&mut self, ccursor_range: Option<CCursorRange>) {
96        let sorted_indices =
97            |range: Option<CCursorRange>| range.map(|r| r.sorted_cursors().map(|c| c.index));
98        if sorted_indices(ccursor_range) != sorted_indices(self.ccursor_range) {
99            // The selection was changed by something else than the mouse (e.g. typing),
100            // so forget the double- or triple-clicked word or line that anchored it:
101            self.granular_drag = None;
102        }
103        self.ccursor_range = ccursor_range;
104    }
105
106    /// If the selection started with a double- or triple-click, the word or line that anchors it.
107    pub(crate) fn granular_drag(&self) -> Option<GranularDragSelect> {
108        self.granular_drag
109    }
110
111    /// Restore the anchor of a selection that started with a double- or triple-click.
112    ///
113    /// Used by labels, whose [`TextCursorState`] is recreated each pass.
114    pub(crate) fn set_granular_drag(&mut self, granular_drag: Option<GranularDragSelect>) {
115        self.granular_drag = granular_drag;
116    }
117
118    /// The remembered double- or triple-clicked word or line,
119    /// if it is still non-empty and part of the given selection.
120    fn anchor_range_within(&self, selection: CCursorRange, text: &str) -> Option<CCursorRange> {
121        let anchor = self.granular_drag?.anchor;
122        let [anchor_min, anchor_max] = anchor.sorted_cursors();
123        let [sel_min, sel_max] = selection.sorted_cursors();
124        let num_chars = text.chars().count();
125        (!anchor.is_empty()
126            && anchor_max.index.0 <= num_chars
127            && sel_min.index <= anchor_min.index
128            && anchor_max.index <= sel_max.index)
129            .then_some(anchor)
130    }
131}
132
133impl TextCursorState {
134    /// Handle clicking and/or dragging text.
135    ///
136    /// Returns `true` if there was interaction.
137    pub fn pointer_interaction(
138        &mut self,
139        ui: &Ui,
140        response: &Response,
141        cursor_at_pointer: CCursor,
142        galley: &Galley,
143        is_being_dragged: bool,
144    ) -> bool {
145        let text = galley.text();
146
147        // Shift-click extends the existing selection (handled on press, below),
148        // so don't replace it with the clicked word/line when the click is released:
149        let shift = ui.input(|i| i.modifiers.shift);
150
151        if response.double_clicked() && !shift {
152            // Select word:
153            let ccursor_range = select_word_at(text, cursor_at_pointer);
154            self.set_char_range(Some(ccursor_range));
155            true
156        } else if response.triple_clicked() && !shift {
157            // Select line:
158            let ccursor_range = select_line_at(text, cursor_at_pointer);
159            self.set_char_range(Some(ccursor_range));
160            true
161        } else if response.sense.senses_drag() {
162            if response.hovered() && ui.input(|i| i.pointer.any_pressed()) {
163                // The start of a drag (or a click).
164                // Clicks are counted on release, but for double-click-and-drag
165                // we need to select the word (or line) already on the second (or third) press:
166                let granularity = SelectGranularity::of_press(ui);
167                let existing_range = if shift { self.range(galley) } else { None };
168
169                if let Some(mut cursor_range) = existing_range {
170                    // Shift-click: extend the selection, by characters, words, or lines.
171                    // If the selection started with a double- or triple-click,
172                    // the clicked word/line stays selected, even if we now extend the selection
173                    // in the other direction (like on macOS).
174                    // Otherwise the far end (secondary) of the selection stays fixed.
175                    let anchor = self
176                        .anchor_range_within(cursor_range, text)
177                        .unwrap_or_else(|| CCursorRange::one(cursor_range.secondary));
178
179                    if granularity == SelectGranularity::Char && anchor.is_empty() {
180                        // Plain shift-click of a plain selection:
181                        self.granular_drag = None;
182                        cursor_range.primary = cursor_at_pointer;
183                        self.ccursor_range = Some(cursor_range);
184                    } else {
185                        // A subsequent drag continues extending by the same granularity:
186                        self.granular_drag = Some(GranularDragSelect {
187                            granularity,
188                            anchor,
189                        });
190                        self.ccursor_range = Some(extend_granular_select(
191                            granularity,
192                            anchor,
193                            text,
194                            cursor_at_pointer,
195                        ));
196                    }
197                } else if granularity == SelectGranularity::Char {
198                    self.granular_drag = None;
199                    self.ccursor_range = Some(CCursorRange::one(cursor_at_pointer));
200                } else {
201                    self.begin_granular_drag(granularity, text, cursor_at_pointer);
202                }
203                true
204            } else if is_being_dragged {
205                // Drag to select text:
206                if let Some(granular) = self.granular_drag {
207                    // Extend the selection by whole words or lines:
208                    let new_range = extend_granular_select(
209                        granular.granularity,
210                        granular.anchor,
211                        text,
212                        cursor_at_pointer,
213                    );
214                    self.ccursor_range = Some(new_range);
215                } else if let Some(mut cursor_range) = self.range(galley) {
216                    cursor_range.primary = cursor_at_pointer;
217                    self.set_char_range(Some(cursor_range));
218                }
219                true
220            } else {
221                false
222            }
223        } else {
224            false
225        }
226    }
227
228    /// Start a double- or triple-click selection: select the whole word (or line) at the pointer,
229    /// and remember it so that a subsequent drag extends the selection by that granularity.
230    fn begin_granular_drag(
231        &mut self,
232        granularity: SelectGranularity,
233        text: &str,
234        cursor_at_pointer: CCursor,
235    ) {
236        let anchor = select_unit_at(granularity, text, cursor_at_pointer);
237        self.granular_drag = Some(GranularDragSelect {
238            granularity,
239            anchor,
240        });
241        self.ccursor_range = Some(anchor);
242    }
243}
244
245/// The whole word or line at the given position.
246pub(crate) fn select_unit_at(
247    granularity: SelectGranularity,
248    text: &str,
249    ccursor: CCursor,
250) -> CCursorRange {
251    match granularity {
252        SelectGranularity::Char => CCursorRange::one(ccursor),
253        SelectGranularity::Word => select_word_at(text, ccursor),
254        SelectGranularity::Line => select_line_at(text, ccursor),
255    }
256}
257
258/// Extend a selection to also cover the character, word, or line at the pointer.
259///
260/// Returns the union of the anchor and the character/word/line at the pointer,
261/// with `primary` at the pointer end.
262///
263/// The anchor is usually the word/line that was double/triple-clicked,
264/// but for a shift-double-click it may be the (empty) far end of the previous selection.
265pub(crate) fn extend_granular_select(
266    granularity: SelectGranularity,
267    anchor: CCursorRange,
268    text: &str,
269    cursor_at_pointer: CCursor,
270) -> CCursorRange {
271    let unit = select_unit_at(granularity, text, cursor_at_pointer);
272    let [anchor_min, anchor_max] = anchor.sorted_cursors();
273    let [unit_min, unit_max] = unit.sorted_cursors();
274
275    if cursor_at_pointer.index < anchor_min.index {
276        // Dragging backwards, before the anchor:
277        CCursorRange {
278            primary: unit_min,
279            secondary: anchor_max,
280            h_pos: None,
281        }
282    } else if anchor_max.index < cursor_at_pointer.index || anchor.is_empty() {
283        // Dragging forwards, after the anchor:
284        CCursorRange {
285            primary: unit_max,
286            secondary: anchor_min,
287            h_pos: None,
288        }
289    } else {
290        // The pointer is inside the anchor word/line:
291        anchor
292    }
293}
294
295fn select_word_at(text: &str, ccursor: CCursor) -> CCursorRange {
296    if text.is_empty() {
297        return CCursorRange::one(ccursor);
298    }
299
300    let line_start = find_line_start(text, ccursor);
301    let line_end = ccursor_next_line(text, line_start);
302
303    let line_range = line_start.index..line_end.index;
304    let current_line_text = slice_char_range(text, line_range.clone());
305
306    let relative_idx = ccursor.index - line_start.index;
307    let relative_ccursor = CCursor::new(relative_idx);
308
309    let min = ccursor_previous_word(current_line_text, relative_ccursor);
310    let max = ccursor_next_word(current_line_text, relative_ccursor);
311
312    CCursorRange::two(
313        CCursor::new(line_start.index + min.index),
314        CCursor::new(line_start.index + max.index),
315    )
316}
317
318fn select_line_at(text: &str, ccursor: CCursor) -> CCursorRange {
319    if ccursor.index == CharIndex::ZERO {
320        CCursorRange::two(ccursor, ccursor_next_line(text, ccursor))
321    } else {
322        let it = text.chars();
323        let mut it = it.skip(ccursor.index.0 - 1);
324        if let Some(char_before_cursor) = it.next() {
325            if let Some(char_after_cursor) = it.next() {
326                if (!is_linebreak(char_before_cursor)) && (!is_linebreak(char_after_cursor)) {
327                    let min = ccursor_previous_line(text, ccursor + 1);
328                    let max = ccursor_next_line(text, min);
329                    CCursorRange::two(min, max)
330                } else if !is_linebreak(char_before_cursor) {
331                    let min = ccursor_previous_line(text, ccursor);
332                    let max = ccursor_next_line(text, min);
333                    CCursorRange::two(min, max)
334                } else if is_linebreak(char_after_cursor) {
335                    let min = ccursor_previous_line(text, ccursor);
336                    let max = ccursor_next_line(text, ccursor);
337                    CCursorRange::two(min, max)
338                } else {
339                    let max = ccursor_next_line(text, ccursor);
340                    CCursorRange::two(ccursor, max)
341                }
342            } else {
343                let min = ccursor_previous_line(text, ccursor);
344                CCursorRange::two(min, ccursor)
345            }
346        } else {
347            let max = ccursor_next_line(text, ccursor);
348            CCursorRange::two(ccursor, max)
349        }
350    }
351}
352
353pub fn ccursor_next_word(text: &str, ccursor: CCursor) -> CCursor {
354    CCursor {
355        index: next_word_boundary_char_index(text, ccursor.index),
356        prefer_next_row: false,
357    }
358}
359
360fn ccursor_next_line(text: &str, ccursor: CCursor) -> CCursor {
361    CCursor {
362        index: next_line_boundary_char_index(text.chars(), ccursor.index),
363        prefer_next_row: false,
364    }
365}
366
367pub fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor {
368    let num_chars = CharIndex(text.chars().count());
369    let reversed: String = text.graphemes(true).rev().collect();
370    let boundary = next_word_boundary_char_index(&reversed, num_chars - ccursor.index);
371    CCursor {
372        index: num_chars - boundary.min(num_chars),
373        prefer_next_row: true,
374    }
375}
376
377fn ccursor_previous_line(text: &str, ccursor: CCursor) -> CCursor {
378    let num_chars = CharIndex(text.chars().count());
379    let boundary = next_line_boundary_char_index(text.chars().rev(), num_chars - ccursor.index);
380    CCursor {
381        index: num_chars - boundary,
382        prefer_next_row: true,
383    }
384}
385
386fn next_word_boundary_char_index(text: &str, cursor_ci: CharIndex) -> CharIndex {
387    let mut current_char_idx = CharIndex::ZERO;
388
389    for (_word_byte_index, word) in text.split_word_bound_indices() {
390        let word_ci = current_char_idx;
391
392        // We consider `.` a word boundary.
393        // At least that's how Mac works when navigating something like `www.example.com`.
394        let mut word_char_count = 0;
395        for chr in word.chars() {
396            let dot_ci = word_ci + word_char_count;
397            if chr == '.' && cursor_ci < dot_ci {
398                return dot_ci;
399            }
400            word_char_count += 1;
401        }
402
403        // Splitting considers contiguous whitespace as one word, such words must be skipped,
404        // this handles cases for example ' abc' (a space and a word), the cursor is at the beginning
405        // (before space) - this jumps at the end of 'abc' (this is consistent with text editors
406        // or browsers)
407        if cursor_ci < word_ci && !all_word_chars(word) {
408            return word_ci;
409        }
410
411        current_char_idx += word_char_count;
412    }
413
414    current_char_idx
415}
416
417fn all_word_chars(text: &str) -> bool {
418    text.chars().all(is_word_char)
419}
420
421fn next_line_boundary_char_index(
422    it: impl Iterator<Item = char>,
423    mut index: CharIndex,
424) -> CharIndex {
425    let mut it = it.skip(index.0);
426    if let Some(_first) = it.next() {
427        index += 1;
428
429        if let Some(second) = it.next() {
430            index += 1;
431            for next in it {
432                if is_linebreak(next) != is_linebreak(second) {
433                    break;
434                }
435                index += 1;
436            }
437        }
438    }
439    index
440}
441
442pub fn is_word_char(c: char) -> bool {
443    c.is_alphanumeric() || c == '_'
444}
445
446fn is_linebreak(c: char) -> bool {
447    c == '\r' || c == '\n'
448}
449
450/// Accepts and returns character offset (NOT byte offset!).
451pub fn find_line_start(text: &str, current_index: CCursor) -> CCursor {
452    let byte_idx = byte_index_from_char_index(text, current_index.index);
453    let text_before = (ByteIndex::ZERO..byte_idx).slice(text);
454
455    if let Some(last_newline_byte) = text_before.rfind('\n') {
456        let char_idx = char_index_from_byte_index(text, ByteIndex(last_newline_byte + 1));
457        CCursor::new(char_idx)
458    } else {
459        CCursor::new(0)
460    }
461}
462
463pub fn byte_index_from_char_index(s: &str, char_index: CharIndex) -> ByteIndex {
464    for (ci, (bi, _)) in s.char_indices().enumerate() {
465        if ci == char_index.0 {
466            return ByteIndex(bi);
467        }
468    }
469    ByteIndex(s.len())
470}
471
472pub fn char_index_from_byte_index(input: &str, byte_index: ByteIndex) -> CharIndex {
473    for (ci, (bi, _)) in input.char_indices().enumerate() {
474        if bi == byte_index.0 {
475            return CharIndex(ci);
476        }
477    }
478
479    // `byte_index` is at or past the end of the string (or not on a char boundary):
480    // return the total number of characters.
481    CharIndex(input.chars().count())
482}
483
484pub fn slice_char_range(s: &str, char_range: core::ops::Range<CharIndex>) -> &str {
485    assert!(
486        char_range.start <= char_range.end,
487        "Invalid range, start must be less than end, but start = {}, end = {}",
488        char_range.start,
489        char_range.end
490    );
491    let start_byte = byte_index_from_char_index(s, char_range.start);
492    let end_byte = byte_index_from_char_index(s, char_range.end);
493    (start_byte..end_byte).slice(s)
494}
495
496/// The thin rectangle of one end of the selection, e.g. the primary cursor, in local galley coordinates.
497pub fn cursor_rect(galley: &Galley, cursor: &CCursor, row_height: f32) -> Rect {
498    let mut cursor_pos = galley.pos_from_cursor(*cursor);
499
500    // Handle completely empty galleys
501    cursor_pos.max.y = cursor_pos.max.y.at_least(cursor_pos.min.y + row_height);
502
503    cursor_pos = cursor_pos.expand(1.5); // slightly above/below row
504
505    cursor_pos
506}
507
508#[cfg(test)]
509mod test {
510    use super::*;
511
512    #[test]
513    fn test_next_word_boundary_char_index() {
514        // ASCII only
515        let text = "abc d3f g_h i-j";
516        assert_eq!(next_word_boundary_char_index(text, CharIndex(1)).0, 3);
517        assert_eq!(next_word_boundary_char_index(text, CharIndex(3)).0, 7);
518        assert_eq!(next_word_boundary_char_index(text, CharIndex(9)).0, 11);
519        assert_eq!(next_word_boundary_char_index(text, CharIndex(12)).0, 13);
520        assert_eq!(next_word_boundary_char_index(text, CharIndex(13)).0, 15);
521        assert_eq!(next_word_boundary_char_index(text, CharIndex(15)).0, 15);
522
523        assert_eq!(next_word_boundary_char_index("", CharIndex(0)).0, 0);
524        assert_eq!(next_word_boundary_char_index("", CharIndex(1)).0, 0);
525
526        // ASCII only
527        let text = "abc.def.ghi";
528        assert_eq!(next_word_boundary_char_index(text, CharIndex(1)).0, 3);
529        assert_eq!(next_word_boundary_char_index(text, CharIndex(3)).0, 7);
530        assert_eq!(next_word_boundary_char_index(text, CharIndex(7)).0, 11);
531
532        // Unicode graphemes, some of which consist of multiple Unicode characters,
533        // !!! Unicode character is not always what is tranditionally considered a character,
534        // the values below are correct despite not seeming that way on the first look,
535        // handling of and around emojis is kind of weird and is not consistent across
536        // text editors and browsers
537        let text = "β€οΈπŸ‘ skvΔ›lΓ‘ knihovna πŸ‘β€οΈ";
538        assert_eq!(next_word_boundary_char_index(text, CharIndex(0)).0, 2);
539        assert_eq!(next_word_boundary_char_index(text, CharIndex(2)).0, 3); // this does not skip the space between thumbs-up and 'skvΔ›lΓ‘'
540        assert_eq!(next_word_boundary_char_index(text, CharIndex(6)).0, 10);
541        assert_eq!(next_word_boundary_char_index(text, CharIndex(9)).0, 10);
542        assert_eq!(next_word_boundary_char_index(text, CharIndex(12)).0, 19);
543        assert_eq!(next_word_boundary_char_index(text, CharIndex(15)).0, 19);
544        assert_eq!(next_word_boundary_char_index(text, CharIndex(19)).0, 20);
545        assert_eq!(next_word_boundary_char_index(text, CharIndex(20)).0, 21);
546    }
547
548    #[test]
549    fn test_previous_word() {
550        let text = "abc def ghi";
551        assert_eq!(ccursor_previous_word(text, CCursor::new(7)).index.0, 4);
552        assert_eq!(ccursor_previous_word(text, CCursor::new(5)).index.0, 4);
553        assert_eq!(ccursor_previous_word(text, CCursor::new(4)).index.0, 0);
554        assert_eq!(ccursor_previous_word(text, CCursor::new(0)).index.0, 0);
555    }
556
557    #[test]
558    fn test_next_word() {
559        let text = "abc def ghi";
560        assert_eq!(ccursor_next_word(text, CCursor::new(0)).index.0, 3);
561        assert_eq!(ccursor_next_word(text, CCursor::new(3)).index.0, 7);
562        assert_eq!(ccursor_next_word(text, CCursor::new(7)).index.0, 11);
563        assert_eq!(ccursor_next_word(text, CCursor::new(11)).index.0, 11);
564    }
565
566    #[test]
567    fn test_index_conversion_roundtrip() {
568        // "Γ©" is 2 bytes, "πŸ‘" is 4 bytes.
569        let text = "aΓ©πŸ‘b";
570        let char_count = text.chars().count(); // 4
571        assert_eq!(char_count, 4);
572
573        // char -> byte, including the end index
574        assert_eq!(byte_index_from_char_index(text, CharIndex(0)).0, 0);
575        assert_eq!(byte_index_from_char_index(text, CharIndex(1)).0, 1);
576        assert_eq!(byte_index_from_char_index(text, CharIndex(2)).0, 3);
577        assert_eq!(byte_index_from_char_index(text, CharIndex(3)).0, 7);
578        assert_eq!(byte_index_from_char_index(text, CharIndex(4)).0, 8);
579        // Past the end clamps to the byte length:
580        assert_eq!(
581            byte_index_from_char_index(text, CharIndex(99)).0,
582            text.len()
583        );
584
585        // byte -> char, including the end index
586        assert_eq!(char_index_from_byte_index(text, ByteIndex(0)).0, 0);
587        assert_eq!(char_index_from_byte_index(text, ByteIndex(1)).0, 1);
588        assert_eq!(char_index_from_byte_index(text, ByteIndex(3)).0, 2);
589        assert_eq!(char_index_from_byte_index(text, ByteIndex(7)).0, 3);
590        // The end byte index must map to the character count, not to some byte offset:
591        assert_eq!(char_index_from_byte_index(text, ByteIndex(text.len())).0, 4);
592        // Past the end clamps to the character count:
593        assert_eq!(char_index_from_byte_index(text, ByteIndex(99)).0, 4);
594
595        // Empty string:
596        assert_eq!(byte_index_from_char_index("", CharIndex(0)).0, 0);
597        assert_eq!(char_index_from_byte_index("", ByteIndex(0)).0, 0);
598    }
599
600    #[test]
601    fn test_select_word_at() {
602        // CCursorRange::two(min, max) sets primary=max, secondary=min
603        let text = "hello world";
604        let range = select_word_at(text, CCursor::new(2));
605        let (lo, hi) = (
606            range.primary.index.min(range.secondary.index),
607            range.primary.index.max(range.secondary.index),
608        );
609        assert_eq!(lo.0, 0);
610        assert_eq!(hi.0, 5);
611
612        let range = select_word_at(text, CCursor::new(8));
613        let (lo, hi) = (
614            range.primary.index.min(range.secondary.index),
615            range.primary.index.max(range.secondary.index),
616        );
617        assert_eq!(lo.0, 6);
618        assert_eq!(hi.0, 11);
619    }
620
621    #[test]
622    fn test_extend_granular_select_words() {
623        let text = "alpha beta gamma";
624        let anchor = select_word_at(text, CCursor::new(8)); // "beta"
625        assert_eq!(anchor.slice_str(text), "beta");
626
627        // Dragging forward into "gamma" extends the selection to the end of that word:
628        let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(13));
629        assert_eq!(range.slice_str(text), "beta gamma");
630        assert_eq!(
631            range.primary.index.0, 16,
632            "primary should be at the pointer end"
633        );
634
635        // Dragging backward into "alpha" extends the selection to the start of that word:
636        let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(2));
637        assert_eq!(range.slice_str(text), "alpha beta");
638        assert_eq!(
639            range.primary.index.0, 0,
640            "primary should be at the pointer end"
641        );
642
643        // With the pointer still inside the anchor word, the selection stays the anchor word:
644        let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(7));
645        assert_eq!(range.slice_str(text), "beta");
646    }
647
648    #[test]
649    fn test_extend_granular_select_lines() {
650        let text = "first\nsecond\nthird";
651        let anchor = select_line_at(text, CCursor::new(8)); // "second"
652        assert_eq!(anchor.slice_str(text), "second");
653
654        let range = extend_granular_select(SelectGranularity::Line, anchor, text, CCursor::new(15));
655        assert_eq!(range.slice_str(text), "second\nthird");
656
657        let range = extend_granular_select(SelectGranularity::Line, anchor, text, CCursor::new(2));
658        assert_eq!(range.slice_str(text), "first\nsecond");
659    }
660
661    #[test]
662    fn test_word_boundary_large_text_performance() {
663        // Before the O(nΒ²) β†’ O(n) fix, this would take minutes on large text.
664        let large_text = "word ".repeat(200_000); // ~1MB
665        let len = large_text.chars().count();
666
667        let start = std::time::Instant::now();
668
669        let next = ccursor_next_word(&large_text, CCursor::new(len - 10));
670        assert!(next.index.0 <= len);
671
672        let prev = ccursor_previous_word(&large_text, CCursor::new(len - 10));
673        assert!(prev.index.0 < len);
674
675        let range = select_word_at(&large_text, CCursor::new(len - 3));
676        let lo = range.primary.index.min(range.secondary.index);
677        let hi = range.primary.index.max(range.secondary.index);
678        assert!(lo < hi, "Expected a non-empty word selection");
679
680        let elapsed = start.elapsed();
681        assert!(
682            elapsed.as_secs() < 5,
683            "Word boundary operations on 1MB text took {elapsed:?}, expected < 5s"
684        );
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691
692    #[test]
693    fn test_previous_word_graphemes() {
694        let cases = [
695            ("", 0, 0),
696            ("hello", 0, 0),
697            ("hello", "hello".chars().count(), 0),
698            ("hello world", 6, 0),
699            ("hello world", 8, 6),
700            ("hello world", "hello world".chars().count(), 6),
701            ("hello world   ", "hello world   ".chars().count(), 6),
702            ("hello   world", "hello   world".chars().count(), 8),
703            ("   ", "   ".chars().count(), 0),
704            ("hello, world", "hello, world".chars().count(), 7),
705            ("www.example.com", "www.example.com".chars().count(), 12),
706            ("μ•ˆλ…•! 😊 세상", 8, 6),
707            ("β€οΈπŸ‘ skvΔ›lΓ‘ knihovna πŸ‘β€οΈ", 18, 11),
708            (
709                "a e\u{301} b",
710                "a e\u{301} b".chars().count(),
711                "a e\u{301} ".chars().count(),
712            ),
713            (
714                "hi πŸ™‚ world",
715                "hi πŸ™‚ world".chars().count(),
716                "hi πŸ™‚ ".chars().count(),
717            ),
718            (
719                "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ world",
720                "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ world".chars().count(),
721                "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ ".chars().count(),
722            ),
723        ];
724
725        for (text, cursor, expected) in cases {
726            let result = ccursor_previous_word(text, CCursor::new(cursor));
727            assert_eq!(
728                result.index.0, expected,
729                "text={text:?}, cursor={cursor}, got={}, expected={expected}",
730                result.index.0
731            );
732        }
733    }
734}