twrite-core 0.9.2

Headless buffer, movement, syntax, and hook primitives for twrite
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
use std::ops::Range;
use std::path::Path;

use ropey::Rope;

use crate::{
    coordinates::Point,
    error::{EditorError, Result},
    history::{Edit, History, Transaction},
};

/// A text buffer that manages document contents, cursor position,
/// and undo/redo history.
///
/// `EditorBuffer` stores its text in a [`Rope`], making insertion,
/// deletion, and line-based operations efficient for an editor.
///
/// Cursor positions are represented internally as byte offsets.
///
/// # Examples
///
/// ```
/// use twrite_core::EditorBuffer;
///
/// let buffer = EditorBuffer::new("Hello, world!");
///
/// assert_eq!(buffer.len_bytes(), 13);
/// assert_eq!(buffer.len_lines(), 1);
/// assert_eq!(buffer.cursor_offset(), 0);
/// ```
#[derive(Debug)]
pub struct EditorBuffer {
    text: Rope,
    cursor: usize,
    history: History,
    version: usize,
}

impl EditorBuffer {
    /// Creates a new editor buffer containing `initial_text`.
    ///
    /// The cursor is initially positioned at byte offset `0`, and the
    /// undo/redo history starts empty.
    pub fn new(initial_text: &str) -> Self {
        Self {
            text: Rope::from_str(initial_text),
            cursor: 0,
            history: History::default(),
            version: 0,
        }
    }

    /// Returns the monotonic document version, incremented on every text modification.
    pub fn version(&self) -> usize {
        self.version
    }

    /// Returns a reference to the underlying text.
    ///
    /// The returned [`Rope`] can be used to inspect the document without
    /// copying its contents.
    pub fn text(&self) -> &Rope {
        &self.text
    }

    /// Returns the current cursor position as a byte offset.
    ///
    /// The cursor is always maintained at a valid UTF-8 character boundary.
    pub fn cursor_offset(&self) -> usize {
        self.cursor
    }

    /// Returns the total number of bytes in the document.
    pub fn len_bytes(&self) -> usize {
        self.text.len_bytes()
    }

    /// Returns the number of lines in the document.
    pub fn len_lines(&self) -> usize {
        self.text.len_lines()
    }

    /// Returns the contents of a line as a [`String`].
    ///
    /// Returns an empty string if `line_idx` is outside the document.
    pub fn line_to_string(&self, line_idx: usize) -> String {
        if line_idx >= self.text.len_lines() {
            return String::new();
        }

        self.text.line(line_idx).to_string()
    }

    /// Converts a byte offset into a [`Point`].
    ///
    /// The returned point contains a zero-based row and a byte-based
    /// column. If `offset` is beyond the end of the document, it is
    /// clamped to the document's end.
    pub fn offset_to_point(&self, offset: usize) -> Point {
        let clamped = offset.min(self.text.len_bytes());
        let row = self.text.byte_to_line(clamped);
        let line_start_byte = self.text.line_to_byte(row);
        let column = clamped - line_start_byte;

        Point::new(row, column)
    }

    /// Converts a [`Point`] into a byte offset.
    ///
    /// If the row is outside the document, the returned offset points to
    /// the end of the document. If the column exceeds the length of the
    /// line, it is clamped to the end of that line.
    pub fn point_to_offset(&self, point: Point) -> usize {
        if point.row >= self.text.len_lines() {
            return self.text.len_bytes();
        }
        let line_start_byte = self.text.line_to_byte(point.row);
        let line_len = self.text.line(point.row).len_bytes();
        let col = point.column.min(line_len);
        line_start_byte + col
    }

    /// Returns the current cursor position as a [`Point`].
    pub fn cursor_point(&self) -> Point {
        self.offset_to_point(self.cursor)
    }

    /// Sets the cursor to the given byte offset.
    ///
    /// The offset is clamped to the document's bounds.
    ///
    /// The resulting cursor position is kept on a valid UTF-8 character
    /// boundary.
    pub fn set_cursor_offset(&mut self, offset: usize) {
        let offset = offset.min(self.text.len_bytes());
        self.cursor = self.text.char_to_byte(self.text.byte_to_char(offset));
    }

    /// Sets the cursor to the given document position.
    ///
    /// The row and column are clamped to the document's bounds.
    pub fn set_cursor_point(&mut self, point: Point) {
        self.cursor = self.point_to_offset(point);
    }

    /// Moves the cursor one character to the right.
    ///
    /// Does nothing if the cursor is already at the end of the document.
    pub fn move_cursor_right(&mut self) {
        if self.cursor < self.text.len_bytes() {
            let char_idx = self.text.byte_to_char(self.cursor);
            let next_char = (char_idx + 1).min(self.text.len_chars());
            self.cursor = self.text.char_to_byte(next_char);
        }
    }

    /// Moves the cursor one line upward.
    ///
    /// The column is preserved when possible. If the target line is shorter,
    /// the cursor is placed at the end of that line.
    pub fn move_cursor_up(&mut self) {
        let point = self.cursor_point();
        if point.row > 0 {
            self.set_cursor_point(Point::new(point.row - 1, point.column));
        }
    }

    /// Moves the cursor one line downward.
    ///
    /// The column is preserved when possible. If the target line is shorter,
    /// the cursor is placed at the end of that line.
    pub fn move_cursor_down(&mut self) {
        let point = self.cursor_point();
        if point.row + 1 < self.text.len_lines() {
            self.set_cursor_point(Point::new(point.row + 1, point.column));
        }
    }

    /// Moves the cursor one character to the left.
    ///
    /// Does nothing if the cursor is already at the beginning of the
    /// document.
    pub fn move_cursor_left(&mut self) {
        if self.cursor > 0 {
            let char_idx = self.text.byte_to_char(self.cursor);
            self.cursor = self.text.char_to_byte(char_idx - 1);
        }
    }

    /// Returns the byte offset of the previous word start relative to current cursor.
    pub fn prev_word_offset(&self) -> usize {
        crate::movement::find_prev_word_start(&self.text, self.cursor)
    }

    /// Returns the byte offset of the next word end relative to current cursor.
    pub fn next_word_offset(&self) -> usize {
        crate::movement::find_next_word_end(&self.text, self.cursor)
    }

    /// Returns the byte offset of the start of the current line.
    pub fn line_start_offset(&self) -> usize {
        crate::movement::find_line_start(&self.text, self.cursor)
    }

    /// Returns the byte offset of the end of the current line (excluding trailing newline).
    pub fn line_end_offset(&self) -> usize {
        crate::movement::find_line_end(&self.text, self.cursor)
    }

    /// Returns the byte range of the word, punctuation token, or whitespace run containing `offset`.
    pub fn word_range_at(&self, offset: usize) -> Range<usize> {
        crate::movement::find_word_range_at(&self.text, offset)
    }

    /// Returns the byte range of the full line containing `offset`, including
    /// any trailing line terminator.
    pub fn line_range_at(&self, offset: usize) -> Range<usize> {
        crate::movement::find_line_range_at(&self.text, offset)
    }

    /// Moves the cursor to the start of the previous word.
    pub fn move_cursor_prev_word(&mut self) {
        self.cursor = self.prev_word_offset();
    }

    /// Moves the cursor to the end of the next word.
    pub fn move_cursor_next_word(&mut self) {
        self.cursor = self.next_word_offset();
    }

    /// Moves the cursor to the beginning of the current line.
    pub fn move_cursor_line_start(&mut self) {
        self.cursor = self.line_start_offset();
    }

    /// Moves the cursor to the end of the current line.
    pub fn move_cursor_line_end(&mut self) {
        self.cursor = self.line_end_offset();
    }

    /// Deletes the text from the previous word boundary up to the cursor.
    ///
    /// Returns `true` if text was deleted, or `false` if the cursor was already at the beginning.
    pub fn delete_prev_word(&mut self) -> bool {
        let target = self.prev_word_offset();
        if target < self.cursor {
            self.delete_range(target..self.cursor);
            true
        } else {
            false
        }
    }

    /// Deletes the text from the cursor up to the next word boundary.
    ///
    /// Returns `true` if text was deleted, or `false` if the cursor was already at the end.
    pub fn delete_next_word(&mut self) -> bool {
        let target = self.next_word_offset();
        if self.cursor < target {
            self.delete_range(self.cursor..target);
            true
        } else {
            false
        }
    }

    /// Inserts `text` at the current cursor position.
    ///
    /// The inserted text becomes a single undoable transaction, and the
    /// cursor is moved to the end of the inserted text.
    ///
    /// Inserting new text after undoing clears the redo history.
    pub fn insert(&mut self, text: &str) {
        let previous_cursor = self.cursor;
        let char_idx = self.text.byte_to_char(self.cursor);
        self.text.insert(char_idx, text);
        self.cursor += text.len();

        let tx = Transaction {
            edits: vec![Edit {
                bytes_range: previous_cursor..previous_cursor,
                inserted_text: text.to_string(),
                deleted_text: String::new(),
            }],
            previous_cursor,
            resulting_cursor: self.cursor,
        };

        self.history.undo_stack.push(tx);
        self.history.redo_stack.clear();
        self.version += 1;
    }

    /// Deletes the character immediately before the cursor.
    ///
    /// If the cursor is at the beginning of the document, this method does
    /// nothing.
    ///
    /// The deleted character is recorded as an undoable transaction and
    /// the cursor moves to the beginning of the deleted character.
    ///
    /// Inserting new text after undoing clears the redo history.
    pub fn backspace(&mut self) {
        if self.cursor == 0 {
            return;
        }

        let char_idx = self.text.byte_to_char(self.cursor);
        let previous_char_byte = self.text.char_to_byte(char_idx - 1);
        let range_to_delete = previous_char_byte..self.cursor;
        let deleted_text = self.text.byte_slice(range_to_delete.clone()).to_string();

        let previous_cursor = self.cursor;
        self.text.remove((char_idx - 1)..char_idx);
        self.cursor = previous_char_byte;

        let tx = Transaction {
            edits: vec![Edit {
                bytes_range: range_to_delete,
                inserted_text: String::new(),
                deleted_text,
            }],
            previous_cursor,
            resulting_cursor: self.cursor,
        };

        self.history.undo_stack.push(tx);
        self.history.redo_stack.clear();
        self.version += 1;
    }

    /// Deletes the character at the current cursor position.
    ///
    /// If the cursor is at the end of the document, this method does nothing.
    /// The cursor remains at the same byte offset after the deletion.
    ///
    /// The deleted text is recorded as a transaction so the operation can be
    /// undone and redone.
    pub fn delete(&mut self) {
        if self.cursor >= self.text.len_bytes() {
            return;
        }

        let char_idx = self.text.byte_to_char(self.cursor);
        let next_char = char_idx + 1;

        let end = self.text.char_to_byte(next_char);
        let byte_range = self.cursor..end;
        let deleted_text = self.text.byte_slice(byte_range.clone()).to_string();

        self.text.remove(char_idx..next_char);

        let tx = Transaction {
            edits: vec![Edit {
                bytes_range: byte_range,
                inserted_text: String::new(),
                deleted_text,
            }],
            previous_cursor: self.cursor,
            resulting_cursor: self.cursor,
        };

        self.history.undo_stack.push(tx);
        self.history.redo_stack.clear();
        self.version += 1;
    }

    /// Deletes the text within `range`.
    ///
    /// The deletion is recorded as an undoable transaction and the cursor
    /// is set to the start of `range`.
    pub fn delete_range(&mut self, range: Range<usize>) {
        let start = range.start.min(self.text.len_bytes());
        let end = range.end.min(self.text.len_bytes());
        if start >= end {
            return;
        }

        let start_char = self.text.byte_to_char(start);
        let end_char = self.text.byte_to_char(end);
        let deleted_text = self.text.byte_slice(start..end).to_string();
        let previous_cursor = self.cursor;

        self.text.remove(start_char..end_char);
        self.cursor = start;

        let tx = Transaction {
            edits: vec![Edit {
                bytes_range: start..end,
                inserted_text: String::new(),
                deleted_text,
            }],
            previous_cursor,
            resulting_cursor: self.cursor,
        };

        self.history.undo_stack.push(tx);
        self.history.redo_stack.clear();
        self.version += 1;
    }

    /// Replaces the text within `range` with `text`.
    ///
    /// If `range` is empty, this is equivalent to [`Self::insert`].
    pub fn replace_range(&mut self, range: Range<usize>, text: &str) {
        let start = range.start.min(self.text.len_bytes());
        let end = range.end.min(self.text.len_bytes());
        if start == end {
            self.cursor = start;
            self.insert(text);
            return;
        }

        let start_char = self.text.byte_to_char(start);
        let end_char = self.text.byte_to_char(end);
        let deleted_text = self.text.byte_slice(start..end).to_string();
        let previous_cursor = self.cursor;

        self.text.remove(start_char..end_char);
        self.text.insert(start_char, text);
        self.cursor = start + text.len();

        let tx = Transaction {
            edits: vec![Edit {
                bytes_range: start..end,
                inserted_text: text.to_string(),
                deleted_text,
            }],
            previous_cursor,
            resulting_cursor: self.cursor,
        };

        self.history.undo_stack.push(tx);
        self.history.redo_stack.clear();
        self.version += 1;
    }

    /// Applies multiple non-overlapping replacements as a single undoable transaction.
    ///
    /// `replacements` holds `(range, replacement_text)` pairs. They are applied
    /// back-to-front so earlier byte offsets stay valid, recorded as one
    /// [`Transaction`](crate::history::Transaction), and undone/redone together.
    /// Returns the number of replacements applied. Overlapping, empty, or
    /// out-of-bounds ranges are skipped. A no-op leaves the version untouched.
    pub fn replace_many(&mut self, replacements: Vec<(Range<usize>, String)>) -> usize {
        let len = self.text.len_bytes();
        let mut valid: Vec<(usize, usize, String)> = Vec::with_capacity(replacements.len());
        for (range, text) in replacements {
            if range.start >= range.end || range.end > len {
                continue;
            }
            if !self.is_char_boundary(range.start) || !self.is_char_boundary(range.end) {
                continue;
            }
            valid.push((range.start, range.end, text));
        }
        if valid.is_empty() {
            return 0;
        }
        valid.sort_by_key(|(start, _, _)| *start);
        // Matches from a single scan never overlap, but callers may pass
        // arbitrary ranges: keep the first of any overlapping pair.
        let mut dedup: Vec<(usize, usize, String)> = Vec::with_capacity(valid.len());
        for (start, end, text) in valid {
            if let Some((_, last_end, _)) = dedup.last()
                && start < *last_end
            {
                continue;
            }
            dedup.push((start, end, text));
        }
        if dedup.is_empty() {
            return 0;
        }

        let previous_cursor = self.cursor;
        // Apply back-to-front so earlier byte offsets stay valid, then store
        // the edits ascending; undo/redo both walk descending (see below).
        let mut edits: Vec<Edit> = Vec::with_capacity(dedup.len());
        for (start, end, text) in dedup.iter().rev() {
            let deleted_text = self.text.byte_slice(*start..*end).to_string();
            let start_char = self.text.byte_to_char(*start);
            let end_char = self.text.byte_to_char(*end);
            self.text.remove(start_char..end_char);
            self.text.insert(start_char, text);
            edits.push(Edit {
                bytes_range: *start..*end,
                inserted_text: text.clone(),
                deleted_text,
            });
        }
        edits.reverse();

        // Cursor tracks the end of the last replacement: earlier edits shift
        // it by the sum of their length deltas.
        let mut shift: i64 = 0;
        for edit in &edits[..edits.len() - 1] {
            shift += edit.inserted_text.len() as i64
                - (edit.bytes_range.end - edit.bytes_range.start) as i64;
        }
        let last = &edits[edits.len() - 1];
        let new_cursor = (last.bytes_range.start as i64 + shift + last.inserted_text.len() as i64)
            .max(0) as usize;
        self.cursor = new_cursor.min(self.text.len_bytes());

        let tx = Transaction {
            edits,
            previous_cursor,
            resulting_cursor: self.cursor,
        };
        let applied = tx.edits.len();

        self.history.undo_stack.push(tx);
        self.history.redo_stack.clear();
        self.version += 1;
        applied
    }

    /// Undoes the most recent transaction.
    ///
    /// If there is no transaction to undo, this method does nothing.
    /// The undone transaction is moved to the redo stack.
    pub fn undo(&mut self) {
        if let Some(tx) = self.history.undo_stack.pop() {
            // Stored ranges are original-document coordinates. Undone
            // descending, each edit's inserted text sits at its stored start
            // plus the length deltas of all still-applied earlier edits.
            let mut prefix = Vec::with_capacity(tx.edits.len() + 1);
            prefix.push(0i64);
            for edit in &tx.edits {
                let delta = edit.inserted_text.len() as i64
                    - (edit.bytes_range.end - edit.bytes_range.start) as i64;
                prefix.push(prefix.last().copied().unwrap_or(0) + delta);
            }
            for (index, edit) in tx.edits.iter().enumerate().rev() {
                let start = (edit.bytes_range.start as i64 + prefix[index]).max(0) as usize;
                let end = start + edit.inserted_text.len();

                if end > start {
                    let start_char = self.text.byte_to_char(start);
                    let end_char = self.text.byte_to_char(end);
                    self.text.remove(start_char..end_char);
                }
                if !edit.deleted_text.is_empty() {
                    let start_char = self.text.byte_to_char(start);
                    self.text.insert(start_char, &edit.deleted_text);
                }
            }
            self.cursor = tx.previous_cursor;
            self.history.redo_stack.push(tx);
            self.version += 1;
        }
    }

    /// Returns whether an undo transaction is available.
    pub fn can_undo(&self) -> bool {
        !self.history.undo_stack.is_empty()
    }

    /// Returns whether a redo transaction is available.
    pub fn can_redo(&self) -> bool {
        !self.history.redo_stack.is_empty()
    }

    /// Redoes the most recently undone transaction.
    ///
    /// If there is no transaction to redo, this method does nothing.
    /// The redone transaction is moved back to the undo stack.
    pub fn redo(&mut self) {
        if let Some(tx) = self.history.redo_stack.pop() {
            // Descending (like `undo`): higher offsets are re-applied first so
            // earlier stored ranges stay valid for multi-edit transactions.
            for edit in tx.edits.iter().rev() {
                let start = edit.bytes_range.start;
                let end = start + edit.deleted_text.len();

                if end > start {
                    let start_char = self.text.byte_to_char(start);
                    let end_char = self.text.byte_to_char(end);
                    self.text.remove(start_char..end_char);
                }
                if !edit.inserted_text.is_empty() {
                    let start_char = self.text.byte_to_char(start);
                    self.text.insert(start_char, &edit.inserted_text);
                }
            }
            self.cursor = tx.resulting_cursor;
            self.history.undo_stack.push(tx);
            self.version += 1;
        }
    }

    /// Checks whether `offset` falls on a valid UTF-8 character boundary.
    pub fn is_char_boundary(&self, offset: usize) -> bool {
        if offset > self.text.len_bytes() {
            return false;
        }
        let char_idx = self.text.byte_to_char(offset);
        self.text.char_to_byte(char_idx) == offset
    }

    /// Validates that `offset` is within bounds and lies on a UTF-8 character boundary.
    pub fn validate_offset(&self, offset: usize) -> Result<()> {
        let len = self.text.len_bytes();
        if offset > len {
            return Err(EditorError::OutOfBounds { offset, len });
        }
        if !self.is_char_boundary(offset) {
            return Err(EditorError::InvalidCharBoundary { offset });
        }
        Ok(())
    }

    /// Validates that `range` is well-formed, within bounds, and on UTF-8 character boundaries.
    pub fn validate_range(&self, range: &Range<usize>) -> Result<()> {
        let len = self.text.len_bytes();
        if range.start > range.end || range.end > len {
            return Err(EditorError::InvalidRange {
                range: range.clone(),
                len,
            });
        }
        if !self.is_char_boundary(range.start) {
            return Err(EditorError::InvalidCharBoundary {
                offset: range.start,
            });
        }
        if !self.is_char_boundary(range.end) {
            return Err(EditorError::InvalidCharBoundary { offset: range.end });
        }
        Ok(())
    }

    /// Attempts to read the text of the given `row`, returning an error if out of bounds.
    pub fn try_line_to_string(&self, row: usize) -> Result<String> {
        let total_lines = self.text.len_lines();
        if row >= total_lines {
            return Err(EditorError::InvalidRow { row, total_lines });
        }
        Ok(self.text.line(row).to_string())
    }

    /// Attempts to replace the text within `range`, validating bounds and UTF-8 boundaries.
    pub fn try_replace_range(&mut self, range: Range<usize>, text: &str) -> Result<()> {
        self.validate_range(&range)?;
        self.replace_range(range, text);
        Ok(())
    }

    /// Attempts to delete the text within `range`, validating bounds and UTF-8 boundaries.
    pub fn try_delete_range(&mut self, range: Range<usize>) -> Result<()> {
        self.validate_range(&range)?;
        self.delete_range(range);
        Ok(())
    }

    /// Loads document text directly from a file path.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        Ok(Self::new(&content))
    }

    /// Saves the current buffer contents to a file path.
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        std::fs::write(path, self.text.to_string())?;
        Ok(())
    }
}