ochrepad-core 0.2.0

Text model and editing engine of the ochrepad text editor (internal; no stable API)
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
//! `Editor`: owns buffers and views. [`Editor::apply`] is the only path that
//! mutates a document (PLAN 3.5).

use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use crate::action::{Action, ActionError};
use crate::buffer::{Buffer, BufferId, FileMeta, LineEdit};
use crate::changeset::{Bias, ChangeSet};
use crate::display::DisplayMap;
use crate::fold::{self, FoldSet};
use crate::history::Transaction;
use crate::position::{ByteOffset, byte_to_line_col, line_col_to_byte};
use crate::resolve::{Resolved, resolve, resolve_search};
use crate::selection::{Selection, SelectionSet};
use crate::view::{View, ViewId};

/// Monotonic time source for undo coalescing; replaceable in tests.
pub trait Clock: Send {
    fn now(&self) -> Duration;
}

pub struct SystemClock {
    origin: Instant,
}

impl Default for SystemClock {
    fn default() -> Self {
        Self {
            origin: Instant::now(),
        }
    }
}

impl Clock for SystemClock {
    fn now(&self) -> Duration {
        self.origin.elapsed()
    }
}

/// A clock that only moves when told to. Clones share the same time.
#[derive(Clone, Default)]
pub struct ManualClock(Arc<AtomicU64>);

impl ManualClock {
    pub fn advance(&self, d: Duration) {
        self.0.fetch_add(d.as_millis() as u64, Ordering::Relaxed);
    }
}

impl Clock for ManualClock {
    fn now(&self) -> Duration {
        Duration::from_millis(self.0.load(Ordering::Relaxed))
    }
}

#[derive(Clone, Debug)]
pub struct Settings {
    pub tab_width: usize,
    /// The Tab key inserts spaces instead of a tab character.
    pub use_spaces: bool,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            tab_width: 4,
            use_spaces: false,
        }
    }
}

pub struct Editor {
    buffers: BTreeMap<BufferId, Buffer>,
    views: BTreeMap<ViewId, View>,
    next_id: u64,
    pub settings: Settings,
    clock: Box<dyn Clock>,
    recording: Option<Vec<Action>>,
}

impl Default for Editor {
    fn default() -> Self {
        Self::with_clock(Box::new(SystemClock::default()))
    }
}

impl Editor {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_clock(clock: Box<dyn Clock>) -> Self {
        Self {
            buffers: BTreeMap::new(),
            views: BTreeMap::new(),
            next_id: 1,
            settings: Settings::default(),
            clock,
            recording: None,
        }
    }

    fn fresh_id(&mut self) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    pub fn add_buffer(&mut self, text: &str, meta: FileMeta) -> BufferId {
        let id = BufferId(self.fresh_id());
        self.buffers.insert(id, Buffer::new(id, text, meta));
        id
    }

    pub fn add_view(&mut self, buffer: BufferId) -> Result<ViewId, ActionError> {
        if !self.buffers.contains_key(&buffer) {
            return Err(ActionError::UnknownBuffer(buffer));
        }
        let id = ViewId(self.fresh_id());
        self.views.insert(id, View::new(id, buffer));
        Ok(id)
    }

    pub fn remove_view(&mut self, view: ViewId) -> Option<View> {
        self.views.remove(&view)
    }

    /// Removes the buffer and every view of it.
    pub fn remove_buffer(&mut self, buffer: BufferId) -> Option<Buffer> {
        self.views.retain(|_, v| v.buffer() != buffer);
        self.buffers.remove(&buffer)
    }

    pub fn buffer(&self, id: BufferId) -> Option<&Buffer> {
        self.buffers.get(&id)
    }

    pub fn buffer_mut(&mut self, id: BufferId) -> Option<&mut Buffer> {
        self.buffers.get_mut(&id)
    }

    pub fn view(&self, id: ViewId) -> Option<&View> {
        self.views.get(&id)
    }

    pub fn view_mut(&mut self, id: ViewId) -> Option<&mut View> {
        self.views.get_mut(&id)
    }

    pub fn buffers(&self) -> impl Iterator<Item = &Buffer> {
        self.buffers.values()
    }

    pub fn buffers_mut(&mut self) -> impl Iterator<Item = &mut Buffer> {
        self.buffers.values_mut()
    }

    pub fn views(&self) -> impl Iterator<Item = &View> {
        self.views.values()
    }

    /// The views of `buffer` that are tabs (not auxiliary ones).
    pub fn views_of(&self, buffer: BufferId) -> impl Iterator<Item = &View> {
        self.views
            .values()
            .filter(move |v| v.buffer() == buffer && !v.is_aux())
    }

    /// A view that is not a tab of its own (one side of a compare view). It
    /// follows edits like any view, is left out of
    /// [`views_of`](Self::views_of), and goes when its buffer is removed.
    pub fn add_aux_view(&mut self, buffer: BufferId) -> Result<ViewId, ActionError> {
        let id = self.add_view(buffer)?;
        if let Some(v) = self.views.get_mut(&id) {
            v.set_aux();
        }
        Ok(id)
    }

    pub fn start_recording(&mut self) {
        self.recording = Some(Vec::new());
    }

    pub fn is_recording(&self) -> bool {
        self.recording.is_some()
    }

    pub fn stop_recording(&mut self) -> Vec<Action> {
        self.recording.take().unwrap_or_default()
    }

    /// The actions recorded so far, while recording.
    pub fn recorded(&self) -> Option<&[Action]> {
        self.recording.as_deref()
    }

    pub(crate) fn take_recording(&mut self) -> Option<Vec<Action>> {
        self.recording.take()
    }

    pub(crate) fn restore_recording(&mut self, recording: Option<Vec<Action>>) {
        self.recording = recording;
    }

    /// Everything applied to `view`'s buffer until the matching
    /// [`Self::end_undo_group`] undoes as one step.
    pub fn begin_undo_group(&mut self, view: ViewId) -> Result<(), ActionError> {
        let (buffer, _) = self.lookup(view)?;
        self.buffers
            .get_mut(&buffer)
            .ok_or(ActionError::UnknownBuffer(buffer))?
            .history
            .begin_group();
        Ok(())
    }

    pub fn end_undo_group(&mut self, view: ViewId) -> Result<(), ActionError> {
        let (buffer, _) = self.lookup(view)?;
        self.buffers
            .get_mut(&buffer)
            .ok_or(ActionError::UnknownBuffer(buffer))?
            .history
            .end_group();
        Ok(())
    }

    fn lookup(&self, view: ViewId) -> Result<(BufferId, &View), ActionError> {
        let v = self
            .views
            .get(&view)
            .ok_or(ActionError::UnknownView(view))?;
        if !self.buffers.contains_key(&v.buffer()) {
            return Err(ActionError::UnknownBuffer(v.buffer()));
        }
        Ok((v.buffer(), v))
    }

    /// Resolves `action` against `view` and applies it: edits the rope, pushes
    /// undo, maps other views' selections, marks dirty lines for the
    /// highlighter, bumps the revision and records the action if recording.
    pub fn apply(&mut self, view: ViewId, action: Action) -> Result<(), ActionError> {
        let (buffer_id, _) = self.lookup(view)?;
        let read_only = self.buffers.get(&buffer_id).is_some_and(|b| b.read_only);
        match &action {
            Action::Undo | Action::Redo if read_only => return Err(ActionError::ReadOnly),
            Action::Undo => self.undo(view, buffer_id),
            Action::Redo => self.redo(view, buffer_id),
            Action::Fold
            | Action::Unfold
            | Action::ToggleFold
            | Action::FoldAll
            | Action::UnfoldAll
            | Action::FoldLevel(_)
            | Action::UnfoldLevel(_) => self.fold_action(view, buffer_id, &action),
            _ => {
                let resolved = self.resolve_in(view, buffer_id, &action)??;
                self.commit(view, buffer_id, resolved)?;
            }
        }
        self.sync_folds(buffer_id);
        if let Some(rec) = &mut self.recording
            && action.is_recordable()
        {
            rec.push(action);
        }
        Ok(())
    }

    /// Like [`apply`](Self::apply), but never recorded in a macro being
    /// recorded: for commands that act outside the view the macro plays in
    /// (Replace All in all open documents).
    pub fn apply_unrecorded(&mut self, view: ViewId, action: Action) -> Result<(), ActionError> {
        let recording = self.recording.take();
        let result = self.apply(view, action);
        self.recording = recording;
        result
    }

    /// Resolves `action` against the view's current state. The outer error
    /// is a missing view/buffer; the inner one the action's own failure.
    fn resolve_in(
        &self,
        view: ViewId,
        buffer_id: BufferId,
        action: &Action,
    ) -> Result<Result<Resolved, ActionError>, ActionError> {
        let buffer = self
            .buffers
            .get(&buffer_id)
            .ok_or(ActionError::UnknownBuffer(buffer_id))?;
        let v = self
            .views
            .get(&view)
            .ok_or(ActionError::UnknownView(view))?;
        let sels = &v.selections;
        Ok(match action {
            Action::Find { .. }
            | Action::Replace { .. }
            | Action::ReplaceAll { .. }
            | Action::SelectAllMatches(_) => resolve_search(action, &buffer.doc, sels),
            _ => {
                let rows = DisplayMap::new(buffer, v, self.settings.tab_width);
                Ok(resolve(action, &buffer.doc, sels, &self.settings, &rows))
            }
        })
    }

    /// Applies a resolved action: edits the rope, pushes undo, maps other
    /// views' selections, bumps the revision.
    fn commit(
        &mut self,
        view: ViewId,
        buffer_id: BufferId,
        resolved: Resolved,
    ) -> Result<(), ActionError> {
        match resolved {
            Resolved::Selections(sels) => {
                if let Some(b) = self.buffers.get_mut(&buffer_id) {
                    b.history.break_coalescing();
                }
                self.set_selections(view, sels);
            }
            Resolved::Edit { .. } if self.buffers.get(&buffer_id).is_some_and(|b| b.read_only) => {
                return Err(ActionError::ReadOnly);
            }
            Resolved::Edit {
                changes,
                after,
                kind,
            } => {
                let now = self.clock.now();
                let before = self.views[&view].selections.clone();
                let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
                    return Err(ActionError::UnknownBuffer(buffer_id));
                };
                let inverse = changes.invert(&buffer.doc);
                apply_changes(buffer, &changes);
                let rev_before = buffer.revision;
                let rev_after = buffer.next_revision;
                buffer.next_revision += 1;
                buffer.revision = rev_after;
                buffer.history.push(
                    Transaction {
                        changes: changes.clone(),
                        inverse,
                        before,
                        after: after.clone(),
                    },
                    kind,
                    rev_before,
                    rev_after,
                    now,
                );
                self.set_selections(view, after);
                self.map_other_views(buffer_id, view, &changes);
                self.map_folds(buffer_id, &changes);
            }
        }
        Ok(())
    }

    /// Replaces a buffer's text with `text` read from disk (an external
    /// change), as one undoable step; carets keep their line and column.
    /// The buffer takes `meta` and is marked saved.
    pub fn reload_buffer(
        &mut self,
        buffer: BufferId,
        text: &str,
        meta: FileMeta,
    ) -> Result<(), ActionError> {
        let view = self
            .views_of(buffer)
            .next()
            .map(View::id)
            .ok_or(ActionError::UnknownBuffer(buffer))?;
        let b = self
            .buffers
            .get(&buffer)
            .ok_or(ActionError::UnknownBuffer(buffer))?;
        if b.doc.to_string() != text {
            let new_doc = crate::text::Document::new(text);
            let remap = |p: ByteOffset| {
                let lc = byte_to_line_col(&b.doc, p);
                let mut q = line_col_to_byte(&new_doc, lc);
                while !new_doc.is_char_boundary(q) {
                    q.0 -= 1;
                }
                q
            };
            let after = self.views[&view]
                .selections
                .map(|s| Selection::new(remap(s.anchor), remap(s.head)));
            let changes = ChangeSet::new(
                b.doc.len(),
                vec![crate::changeset::Edit::new(
                    ByteOffset(0),
                    b.doc.len(),
                    text,
                )],
            );
            self.commit(
                view,
                buffer,
                Resolved::Edit {
                    changes,
                    after,
                    kind: crate::history::EditKind::Other,
                },
            )?;
        }
        if let Some(b) = self.buffers.get_mut(&buffer) {
            b.meta = meta;
            b.mark_saved();
        }
        self.sync_folds(buffer);
        Ok(())
    }

    fn undo(&mut self, view: ViewId, buffer_id: BufferId) {
        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
            return;
        };
        let Some(step) = buffer.history.pop_undo() else {
            return;
        };
        let inverses: Vec<ChangeSet> = step.txns.iter().rev().map(|t| t.inverse.clone()).collect();
        for inv in &inverses {
            apply_changes(buffer, inv);
        }
        buffer.revision = step.rev_before;
        let sels = step.txns[0].before.clone();
        buffer.history.push_redo(step);
        self.set_selections(view, sels);
        for inv in &inverses {
            self.map_other_views(buffer_id, view, inv);
            self.map_folds(buffer_id, inv);
        }
    }

    fn redo(&mut self, view: ViewId, buffer_id: BufferId) {
        let Some(buffer) = self.buffers.get_mut(&buffer_id) else {
            return;
        };
        let Some(step) = buffer.history.pop_redo() else {
            return;
        };
        let changes: Vec<ChangeSet> = step.txns.iter().map(|t| t.changes.clone()).collect();
        for cs in &changes {
            apply_changes(buffer, cs);
        }
        buffer.revision = step.rev_after;
        let sels = step.txns[step.txns.len() - 1].after.clone();
        buffer.history.push_undo(step);
        self.set_selections(view, sels);
        for cs in &changes {
            self.map_other_views(buffer_id, view, cs);
            self.map_folds(buffer_id, cs);
        }
    }

    fn set_selections(&mut self, view: ViewId, sels: SelectionSet) {
        if let Some(v) = self.views.get_mut(&view) {
            v.selections = sels;
        }
    }

    /// Maps every view's folds through `changes`, dropping the folds it
    /// touches (PLAN_v0.2.0 3.6). [`sync_folds`](Self::sync_folds) then
    /// recomputes their lines.
    fn map_folds(&mut self, buffer: BufferId, changes: &ChangeSet) {
        for v in self.views.values_mut() {
            if v.buffer() == buffer && !v.folds.is_empty() {
                v.folds.map(changes);
            }
        }
    }

    /// After any action: brings the folds' line numbers up to date and
    /// unfolds every fold hiding a caret, in every view of `buffer`.
    fn sync_folds(&mut self, buffer: BufferId) {
        let Some(doc) = self.buffers.get(&buffer).map(|b| &b.doc) else {
            return;
        };
        for v in self.views.values_mut() {
            if v.buffer() != buffer {
                continue;
            }
            // Also when an edit dropped the last fold: the hidden lines need
            // rebuilding. Cheap when nothing was mapped.
            v.folds.relines(doc);
            if v.folds.is_empty() {
                continue;
            }
            let hidden: Vec<usize> = v
                .selections
                .ranges()
                .iter()
                .map(|s| doc.line_of(s.head))
                .filter(|&l| v.folds.is_hidden(l))
                .collect();
            if !hidden.is_empty() {
                v.folds
                    .retain(|header, last| !hidden.iter().any(|&l| header < l && l <= last));
            }
        }
    }

    /// Folds the region `line` heads in `view`; returns whether it did.
    /// Carets inside move to the end of the header line.
    pub fn fold_at(&mut self, view: ViewId, line: usize) -> bool {
        let tab_width = self.settings.tab_width;
        let Some(v) = self.views.get_mut(&view) else {
            return false;
        };
        let Some(b) = self.buffers.get(&v.buffer()) else {
            return false;
        };
        let Some(last) = fold::region(&b.doc, line, b.fold_strategy, tab_width) else {
            return false;
        };
        v.folds.insert(&b.doc, [(line, last)]);
        reveal_carets(&b.doc, v);
        true
    }

    /// Unfolds the fold at `line` in `view`; returns whether there was one.
    pub fn unfold_at(&mut self, view: ViewId, line: usize) -> bool {
        self.views
            .get_mut(&view)
            .is_some_and(|v| v.folds.remove(line))
    }

    /// Unfolds `line` if it is folded, else folds the region it heads.
    pub fn toggle_fold_at(&mut self, view: ViewId, line: usize) -> bool {
        self.unfold_at(view, line) || self.fold_at(view, line)
    }

    fn fold_action(&mut self, view: ViewId, buffer: BufferId, action: &Action) {
        let tab_width = self.settings.tab_width;
        let (Some(v), Some(b)) = (self.views.get_mut(&view), self.buffers.get(&buffer)) else {
            return;
        };
        let (doc, strategy) = (&b.doc, b.fold_strategy);
        let caret = doc.line_of(v.selections.primary().head);
        let around = || fold::enclosing(doc, caret, strategy, tab_width);
        match action {
            Action::Fold => {
                if let Some(r) = around() {
                    v.folds.insert(doc, [r]);
                }
            }
            Action::ToggleFold => {
                if !v.folds.remove(caret)
                    && let Some(r) = around()
                {
                    v.folds.insert(doc, [r]);
                }
            }
            Action::Unfold => {
                if !v.folds.remove(caret)
                    && let Some((header, last)) = around()
                {
                    v.folds.retain(|h, _| h < header || h > last);
                }
            }
            Action::FoldAll => {
                let all = fold::regions(doc, strategy, tab_width);
                v.folds.insert(doc, all.iter().map(|r| (r.header, r.last)));
            }
            Action::UnfoldAll => v.folds = FoldSet::default(),
            Action::FoldLevel(n) => {
                let all = fold::regions(doc, strategy, tab_width);
                let level = all.iter().filter(|r| r.level == *n);
                v.folds.insert(doc, level.map(|r| (r.header, r.last)));
            }
            Action::UnfoldLevel(n) => {
                let level: std::collections::HashSet<usize> =
                    fold::regions(doc, strategy, tab_width)
                        .into_iter()
                        .filter(|r| r.level == *n)
                        .map(|r| r.header)
                        .collect();
                v.folds.retain(|h, _| !level.contains(&h));
            }
            _ => {}
        }
        reveal_carets(doc, v);
    }

    /// Shifts the selections of every other view of `buffer` through `changes`
    /// so their carets stay put relative to the text.
    fn map_other_views(&mut self, buffer: BufferId, except: ViewId, changes: &ChangeSet) {
        for v in self.views.values_mut() {
            if v.buffer() == buffer && v.id() != except {
                v.selections = v.selections.map(|s| Selection {
                    anchor: changes.map_position(s.anchor, Bias::Before),
                    head: changes.map_position(s.head, Bias::Before),
                    goal: s.goal,
                });
            }
        }
    }
}

/// Moves every selection head that a fold hides to the end of the fold's
/// header line, so folding does not immediately unfold again.
fn reveal_carets(doc: &crate::text::Document, v: &mut View) {
    let folds = &v.folds;
    if folds.is_empty() {
        return;
    }
    let moved = v.selections.map(|s| {
        let Some((start, _)) = folds.hidden_range(doc.line_of(s.head)) else {
            return s.clone();
        };
        let head = doc.line_end(start - 1);
        if s.is_empty() {
            Selection::caret(head)
        } else {
            Selection::new(s.anchor, head)
        }
    });
    v.selections = moved;
}

fn apply_changes(buffer: &mut Buffer, changes: &ChangeSet) {
    // `ChangeSet::apply` goes back to front, so each line edit is recorded in
    // the coordinates of the document at the moment it is applied.
    for e in changes.edits().iter().rev() {
        let start = buffer.doc.line_of(e.start);
        let edit = LineEdit {
            start,
            old_end: buffer.doc.line_of(e.end),
            new_end: start + e.text.bytes().filter(|&b| b == b'\n').count(),
        };
        buffer.record_line_edit(edit);
    }
    changes.apply(&mut buffer.doc);
}