textloom 0.1.0

A reusable native rich-text editing core with optional egui, winit, and AccessKit adapters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
use std::{collections::VecDeque, ops::Range};

use crate::document::Delta;
use crate::{
    Document, Error, Fragment, InlineStyle, Movement, ParagraphKind, Position, SearchOptions,
    Selection, StylePatch,
};

/// Native IME preedit. It is rendered over `replacement` and never stored in the document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composition {
    pub text: String,
    /// UTF-8 byte offsets supplied by the input method; `None` means a hidden cursor.
    pub selection: Option<Range<usize>>,
    pub replacement: Selection,
}

/// Limits apply to retained undo and redo entries together.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HistoryLimits {
    pub max_entries: usize,
    pub max_bytes: usize,
}

impl Default for HistoryLimits {
    fn default() -> Self {
        Self {
            max_entries: 256,
            max_bytes: 8 * 1024 * 1024,
        }
    }
}

#[derive(Clone, Copy)]
struct EditState {
    selection: Selection,
    style: InlineStyle,
}

struct HistoryEntry {
    deltas: Vec<Delta>,
    before: EditState,
    after: EditState,
    typing: bool,
    bytes: usize,
}

/// A document, directional selection, bounded history, and transient IME state.
///
/// Adjacent single-paragraph insertions with the same style form one undo step.
/// Call [`Self::break_history_group`] between independently undoable operations.
pub struct Editor {
    document: Document,
    selection: Selection,
    typing_style: InlineStyle,
    undo: VecDeque<HistoryEntry>,
    redo: Vec<HistoryEntry>,
    history_bytes: usize,
    limits: HistoryLimits,
    coalesce_typing: bool,
    preferred_column: Option<usize>,
    composition: Option<Composition>,
}

impl Default for Editor {
    fn default() -> Self {
        Self::new(Document::new())
    }
}

impl Editor {
    pub fn new(document: Document) -> Self {
        Self {
            typing_style: document.style_at(Position::default()),
            document,
            selection: Selection::default(),
            undo: VecDeque::new(),
            redo: Vec::new(),
            history_bytes: 0,
            limits: HistoryLimits::default(),
            coalesce_typing: false,
            preferred_column: None,
            composition: None,
        }
    }

    pub fn from_text(text: &str) -> Self {
        Self::new(Document::from_text(text))
    }
    pub fn document(&self) -> &Document {
        &self.document
    }
    pub fn selection(&self) -> Selection {
        self.selection
    }
    pub fn typing_style(&self) -> InlineStyle {
        self.typing_style
    }
    pub fn composition(&self) -> Option<&Composition> {
        self.composition.as_ref()
    }
    pub fn can_undo(&self) -> bool {
        !self.undo.is_empty()
    }
    pub fn can_redo(&self) -> bool {
        !self.redo.is_empty()
    }
    pub fn history_limits(&self) -> HistoryLimits {
        self.limits
    }
    /// Conservative estimate of text and formatting retained by undo and redo.
    /// Shared navigation indexes and allocator overhead are excluded.
    pub fn history_bytes(&self) -> usize {
        self.history_bytes
    }
    pub fn undo_len(&self) -> usize {
        self.undo.len()
    }
    pub fn redo_len(&self) -> usize {
        self.redo.len()
    }

    pub fn set_history_limits(&mut self, limits: HistoryLimits) {
        self.limits = limits;
        self.break_history_group();
        self.enforce_limits();
    }

    pub fn clear_history(&mut self) {
        self.undo.clear();
        self.redo.clear();
        self.history_bytes = 0;
        self.break_history_group();
    }

    pub fn break_history_group(&mut self) {
        self.coalesce_typing = false;
    }

    /// Validate both endpoints before changing selection. Explicit selection cancels preedit.
    pub fn set_selection(&mut self, selection: Selection) -> Result<(), Error> {
        self.document.validate_position(selection.anchor)?;
        self.document.validate_position(selection.focus)?;
        self.composition = None;
        self.selection = selection;
        self.typing_style = self.document.style_at(selection.focus);
        self.preferred_column = None;
        self.break_history_group();
        Ok(())
    }

    pub fn select_all(&mut self) {
        // Both endpoints are always valid for this document.
        let _ = self.set_selection(Selection::new(Position::default(), self.document.end()));
    }

    pub fn selected_text(&self) -> String {
        self.document
            .text(self.selection.range())
            .expect("editor maintains a valid selection")
    }

    /// Capture selected text, inline styles, and paragraph metadata for a rich clipboard.
    pub fn selected_fragment(&self) -> Fragment {
        self.document
            .fragment(self.selection.range())
            .expect("editor maintains a valid selection")
    }

    /// Paste rich text as one undo step. Source paragraph kinds are preserved
    /// at paragraph starts; insertion into existing text retains its first kind.
    pub fn insert_fragment(&mut self, fragment: &Fragment) -> Result<(), Error> {
        self.ensure_no_composition()?;
        let before = self.state();
        let (delta, caret) = self
            .document
            .replace_fragment(self.selection.range(), fragment)?;
        self.selection = Selection::caret(caret);
        self.typing_style = self.document.style_at(caret);
        self.preferred_column = None;
        self.break_history_group();
        if !delta.is_empty() {
            self.record(vec![delta], before, false);
        }
        Ok(())
    }

    /// Select the next match after the current selection, optionally wrapping.
    /// Returns false without changing selection when no match is available.
    pub fn find_next(
        &mut self,
        query: &str,
        options: SearchOptions,
        wrap: bool,
    ) -> Result<bool, Error> {
        self.find_match(query, options, wrap, false)
    }

    /// Select the preceding match, optionally wrapping to the last match.
    pub fn find_previous(
        &mut self,
        query: &str,
        options: SearchOptions,
        wrap: bool,
    ) -> Result<bool, Error> {
        self.find_match(query, options, wrap, true)
    }

    fn find_match(
        &mut self,
        query: &str,
        options: SearchOptions,
        wrap: bool,
        backward: bool,
    ) -> Result<bool, Error> {
        self.ensure_no_composition()?;
        let matches = self.document.find(query, options);
        let selection = self.selection.range();
        let found = if backward {
            matches
                .iter()
                .rev()
                .find(|range| range.end <= selection.start)
                .or_else(|| if wrap { matches.last() } else { None })
        } else {
            matches
                .iter()
                .find(|range| range.start >= selection.end)
                .or_else(|| if wrap { matches.first() } else { None })
        };
        if let Some(range) = found {
            self.set_selection(Selection::new(range.start, range.end))?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Replace every nonoverlapping match as one undo step, preserving each
    /// match's initial style. Ranges refer to the original document, so joined
    /// combining marks and inserted paragraph breaks cannot invalidate later matches.
    pub fn replace_all(
        &mut self,
        query: &str,
        replacement: &str,
        options: SearchOptions,
    ) -> Result<usize, Error> {
        self.ensure_no_composition()?;
        let matches = self.document.find(query, options);
        if matches.is_empty() {
            return Ok(0);
        }
        let before = self.state();
        let (delta, caret) = self.document.replace_matches(&matches, replacement)?;
        self.selection = Selection::caret(caret);
        self.typing_style = self.document.style_at(caret);
        self.preferred_column = None;
        self.break_history_group();
        if !delta.is_empty() {
            self.record(vec![delta], before, false);
        }
        Ok(matches.len())
    }

    pub fn insert_text(&mut self, text: &str) -> Result<(), Error> {
        self.ensure_no_composition()?;
        let typing = self.selection.is_caret() && !text.is_empty() && !text.contains(['\n', '\r']);
        self.replace_selection(text, typing)
    }

    /// Replace a forward document range and move the caret after inserted text.
    /// Undo restores the selection that existed before this programmatic edit.
    pub fn replace_range(&mut self, range: Range<Position>, text: &str) -> Result<(), Error> {
        self.ensure_no_composition()?;
        if range.start > range.end {
            return Err(Error::InvalidRange);
        }
        self.document.validate_position(range.start)?;
        self.document.validate_position(range.end)?;
        let before = self.state();
        self.selection = Selection::new(range.start, range.end);
        self.replace_selection_with_before(text, false, before)
    }

    /// Enter continues lists and returns to body text after a heading.
    /// Enter on an empty list item exits the list without inserting a blank paragraph.
    pub fn insert_paragraph(&mut self) -> Result<(), Error> {
        self.ensure_no_composition()?;
        if self.selection.is_caret() {
            let paragraph = self
                .document
                .paragraph(self.selection.focus.paragraph)
                .expect("valid selection");
            if paragraph.text().is_empty()
                && matches!(
                    paragraph.kind(),
                    ParagraphKind::Bullet { .. } | ParagraphKind::Ordered { .. }
                )
            {
                return self.set_paragraph_kind(ParagraphKind::Body);
            }
        }
        self.replace_selection("\n", false)
    }

    pub fn delete_backward(&mut self) -> Result<(), Error> {
        self.ensure_no_composition()?;
        if self.selection.is_caret() {
            let focus = self.selection.focus;
            let previous = self.previous_grapheme(focus);
            if previous == focus {
                return Ok(());
            }
            let before = self.state();
            self.selection = Selection::new(previous, focus);
            return self.replace_selection_with_before("", false, before);
        }
        self.replace_selection("", false)
    }

    pub fn delete_forward(&mut self) -> Result<(), Error> {
        self.ensure_no_composition()?;
        if self.selection.is_caret() {
            let focus = self.selection.focus;
            let next = self.next_grapheme(focus);
            if next == focus {
                return Ok(());
            }
            let before = self.state();
            self.selection = Selection::new(focus, next);
            return self.replace_selection_with_before("", false, before);
        }
        self.replace_selection("", false)
    }

    /// Delete the selection or the preceding Unicode word, including intervening whitespace.
    pub fn delete_word_backward(&mut self) -> Result<(), Error> {
        self.delete_word(false)
    }

    /// Delete the selection or the following Unicode word, including intervening whitespace.
    pub fn delete_word_forward(&mut self) -> Result<(), Error> {
        self.delete_word(true)
    }

    fn delete_word(&mut self, forward: bool) -> Result<(), Error> {
        self.ensure_no_composition()?;
        if !self.selection.is_caret() {
            return self.replace_selection("", false);
        }
        let focus = self.selection.focus;
        let target = if forward {
            self.next_word(focus)
        } else {
            self.previous_word(focus)
        };
        if target == focus {
            return Ok(());
        }
        let before = self.state();
        self.selection = Selection::new(focus, target);
        self.replace_selection_with_before("", false, before)
    }

    pub fn apply_style(&mut self, patch: StylePatch) -> Result<(), Error> {
        self.ensure_no_composition()?;
        self.break_history_group();
        let before = self.state();
        let delta = self.document.apply_style(self.selection.range(), patch)?;
        patch.apply(&mut self.typing_style);
        if let Some(delta) = delta {
            self.record(vec![delta], before, false);
        }
        Ok(())
    }

    /// Applies paragraph formatting to every selected paragraph. An endpoint at
    /// the start of the next paragraph excludes that paragraph.
    /// Ordered numbering starts at `start` in the first selected item and
    /// continues through following consecutive items with the same indent.
    pub fn set_paragraph_kind(&mut self, kind: ParagraphKind) -> Result<(), Error> {
        self.ensure_no_composition()?;
        let range = self.selection.range();
        let end = if range.end.paragraph > range.start.paragraph && range.end.byte == 0 {
            range.end.paragraph
        } else {
            range.end.paragraph + 1
        };
        let before = self.state();
        let delta = self.document.set_kind(range.start.paragraph..end, kind)?;
        self.break_history_group();
        if let Some(delta) = delta {
            self.record(vec![delta], before, false);
        }
        Ok(())
    }

    /// Increase selected list item indentation, clamped at 255; body text is unchanged.
    pub fn indent_list(&mut self) -> Result<(), Error> {
        self.change_list_indent(true)
    }

    /// Decrease selected list item indentation. Level-zero items become body text.
    pub fn outdent_list(&mut self) -> Result<(), Error> {
        self.change_list_indent(false)
    }

    fn change_list_indent(&mut self, increase: bool) -> Result<(), Error> {
        self.ensure_no_composition()?;
        let range = self.selection.range();
        let end = if range.end.paragraph > range.start.paragraph && range.end.byte == 0 {
            range.end.paragraph
        } else {
            range.end.paragraph + 1
        };
        let before = self.state();
        let delta = self
            .document
            .change_list_indent(range.start.paragraph..end, increase);
        self.break_history_group();
        if !delta.is_empty() {
            self.record(vec![delta], before, false);
        }
        Ok(())
    }

    /// Moves by logical graphemes/words/paragraphs; visual wrapped-line movement
    /// is supplied by a GUI adapter's layout engine through `set_selection`.
    pub fn move_cursor(&mut self, movement: Movement, extend: bool) -> Result<(), Error> {
        self.ensure_no_composition()?;
        self.break_history_group();
        let vertical = matches!(movement, Movement::ParagraphUp | Movement::ParagraphDown);
        if !extend
            && !self.selection.is_caret()
            && matches!(
                movement,
                Movement::GraphemeBackward
                    | Movement::WordBackward
                    | Movement::GraphemeForward
                    | Movement::WordForward
            )
        {
            let range = self.selection.range();
            let position = if matches!(
                movement,
                Movement::GraphemeBackward | Movement::WordBackward
            ) {
                range.start
            } else {
                range.end
            };
            return self.set_selection(Selection::caret(position));
        }
        let focus = self.selection.focus;
        let position = match movement {
            Movement::GraphemeBackward => self.previous_grapheme(focus),
            Movement::GraphemeForward => self.next_grapheme(focus),
            Movement::WordBackward => self.previous_word(focus),
            Movement::WordForward => self.next_word(focus),
            Movement::ParagraphStart => Position::new(focus.paragraph, 0),
            Movement::ParagraphEnd => {
                Position::new(focus.paragraph, self.paragraph_text(focus.paragraph).len())
            }
            Movement::DocumentStart => Position::default(),
            Movement::DocumentEnd => self.document.end(),
            Movement::ParagraphUp | Movement::ParagraphDown => {
                let column = self.preferred_column.unwrap_or_else(|| {
                    self.document
                        .paragraph(focus.paragraph)
                        .expect("valid selection")
                        .grapheme_index(focus.byte)
                        .expect("valid caret")
                });
                self.preferred_column = Some(column);
                let paragraph = if movement == Movement::ParagraphUp {
                    focus.paragraph.saturating_sub(1)
                } else {
                    (focus.paragraph + 1).min(self.document.paragraphs().len() - 1)
                };
                let text = self.document.paragraph(paragraph).expect("valid paragraph");
                Position::new(
                    paragraph,
                    text.byte_from_grapheme(column).unwrap_or(text.text().len()),
                )
            }
        };
        if !vertical {
            self.preferred_column = None;
        }
        if extend {
            self.selection.focus = position;
        } else {
            self.selection = Selection::caret(position);
        }
        self.typing_style = self.document.style_at(position);
        Ok(())
    }

    pub fn begin_composition(&mut self) {
        if self.composition.is_none() {
            self.break_history_group();
            self.composition = Some(Composition {
                text: String::new(),
                selection: None,
                replacement: self.selection,
            });
        }
    }

    /// Preedit offsets follow native IME UTF-8 byte coordinates, which may be
    /// Unicode scalar boundaries within an unfinished grapheme.
    pub fn update_composition(
        &mut self,
        text: &str,
        selection: Option<Range<usize>>,
    ) -> Result<(), Error> {
        if let Some(range) = &selection
            && (range.start > range.end
                || range.end > text.len()
                || !text.is_char_boundary(range.start)
                || !text.is_char_boundary(range.end))
        {
            return Err(Error::InvalidCompositionSelection);
        }
        self.begin_composition();
        let composition = self
            .composition
            .as_mut()
            .expect("composition just initialized");
        composition.text.clear();
        composition.text.push_str(text);
        composition.selection = selection;
        Ok(())
    }

    /// A complete composition is a single undo step, including replacement of a selection.
    pub fn commit_composition(&mut self, text: &str) -> Result<(), Error> {
        self.break_history_group();
        if let Some(composition) = self.composition.take() {
            self.selection = composition.replacement;
        }
        self.replace_selection(text, false)
    }

    pub fn cancel_composition(&mut self) -> bool {
        if let Some(composition) = self.composition.take() {
            self.selection = composition.replacement;
            self.break_history_group();
            true
        } else {
            false
        }
    }

    pub fn undo(&mut self) -> bool {
        self.cancel_composition();
        self.break_history_group();
        let Some(entry) = self.undo.pop_back() else {
            return false;
        };
        for delta in entry.deltas.iter().rev() {
            self.document.replay(delta, false);
        }
        self.restore(entry.before);
        self.redo.push(entry);
        true
    }

    pub fn redo(&mut self) -> bool {
        self.cancel_composition();
        self.break_history_group();
        let Some(entry) = self.redo.pop() else {
            return false;
        };
        for delta in &entry.deltas {
            self.document.replay(delta, true);
        }
        self.restore(entry.after);
        self.undo.push_back(entry);
        true
    }

    fn ensure_no_composition(&self) -> Result<(), Error> {
        if self.composition.is_some() {
            Err(Error::CompositionActive)
        } else {
            Ok(())
        }
    }

    fn state(&self) -> EditState {
        EditState {
            selection: self.selection,
            style: self.typing_style,
        }
    }
    fn restore(&mut self, state: EditState) {
        self.selection = state.selection;
        self.typing_style = state.style;
        self.preferred_column = None;
    }

    fn replace_selection(&mut self, text: &str, typing: bool) -> Result<(), Error> {
        self.replace_selection_with_before(text, typing, self.state())
    }

    fn replace_selection_with_before(
        &mut self,
        text: &str,
        typing: bool,
        before: EditState,
    ) -> Result<(), Error> {
        let result = self
            .document
            .replace(self.selection.range(), text, self.typing_style);
        let (delta, caret) = match result {
            Ok(result) => result,
            Err(error) => {
                self.restore(before);
                return Err(error);
            }
        };
        self.selection = Selection::caret(caret);
        self.preferred_column = None;
        if !delta.is_empty() {
            self.record(vec![delta], before, typing);
        }
        Ok(())
    }

    fn record(&mut self, deltas: Vec<Delta>, before: EditState, typing: bool) {
        for entry in self.redo.drain(..) {
            self.history_bytes = self.history_bytes.saturating_sub(entry.bytes);
        }
        let after = self.state();
        let mut entry = HistoryEntry {
            bytes: deltas.iter().map(Delta::retained_bytes).sum(),
            deltas,
            before,
            after,
            typing,
        };
        let merge = self.coalesce_typing
            && typing
            && self.undo.back().is_some_and(|previous| {
                previous.typing
                    && previous.after.selection == before.selection
                    && previous.after.style == before.style
                    && previous.deltas.len() == 1
                    && entry.deltas.len() == 1
                    && previous.deltas[0].start == entry.deltas[0].start
                    && previous.deltas[0].before.len() == 1
                    && previous.deltas[0].after.len() == 1
                    && entry.deltas[0].before.len() == 1
                    && entry.deltas[0].after.len() == 1
            });
        if merge {
            let previous = self.undo.back_mut().expect("checked entry");
            self.history_bytes = self.history_bytes.saturating_sub(previous.bytes);
            previous.deltas[0].after = std::mem::take(&mut entry.deltas[0].after);
            previous.after = after;
            previous.bytes = previous.deltas[0].retained_bytes();
            self.history_bytes = self.history_bytes.saturating_add(previous.bytes);
        } else {
            self.history_bytes = self.history_bytes.saturating_add(entry.bytes);
            self.undo.push_back(entry);
        }
        self.coalesce_typing = typing;
        self.enforce_limits();
    }

    fn enforce_limits(&mut self) {
        while self.undo.len() + self.redo.len() > self.limits.max_entries
            || self.history_bytes > self.limits.max_bytes
        {
            // Dropping oldest undo or farthest redo preserves the applicable chain.
            let entry = self.undo.pop_front().or_else(|| {
                if self.redo.is_empty() {
                    None
                } else {
                    Some(self.redo.remove(0))
                }
            });
            let Some(entry) = entry else {
                break;
            };
            self.history_bytes = self.history_bytes.saturating_sub(entry.bytes);
        }
    }

    fn paragraph_text(&self, paragraph: usize) -> &str {
        self.document
            .paragraph(paragraph)
            .expect("valid paragraph")
            .text()
    }

    fn previous_grapheme(&self, position: Position) -> Position {
        if position.byte == 0 {
            if position.paragraph == 0 {
                return position;
            }
            return Position::new(
                position.paragraph - 1,
                self.paragraph_text(position.paragraph - 1).len(),
            );
        }
        Position::new(
            position.paragraph,
            self.document
                .paragraph(position.paragraph)
                .expect("valid paragraph")
                .previous_grapheme(position.byte),
        )
    }

    fn next_grapheme(&self, position: Position) -> Position {
        let text = self.paragraph_text(position.paragraph);
        if position.byte == text.len() {
            if position.paragraph + 1 == self.document.paragraphs().len() {
                return position;
            }
            return Position::new(position.paragraph + 1, 0);
        }
        Position::new(
            position.paragraph,
            self.document
                .paragraph(position.paragraph)
                .expect("valid paragraph")
                .next_grapheme(position.byte),
        )
    }

    fn previous_word(&self, position: Position) -> Position {
        if position.byte == 0 {
            return self.previous_grapheme(position);
        }
        Position::new(
            position.paragraph,
            self.document
                .paragraph(position.paragraph)
                .expect("valid paragraph")
                .previous_word(position.byte),
        )
    }

    fn next_word(&self, position: Position) -> Position {
        let text = self.paragraph_text(position.paragraph);
        if position.byte == text.len() {
            return self.next_grapheme(position);
        }
        Position::new(
            position.paragraph,
            self.document
                .paragraph(position.paragraph)
                .expect("valid paragraph")
                .next_word(position.byte),
        )
    }
}