Debian Codegraph @

helix-core/src/history.rs

raw symbols SCIP
1 use crate::{Assoc, ChangeSet, Range, Rope, Selection, Transaction};
2 use once_cell::sync::Lazy;
3 use regex::Regex;
4 use std::num::NonZeroUsize;
5 use std::time::{Duration, Instant};
6
7 #[derive(Debug, Clone)]
8 pub struct State {
9 pub doc: Rope,
10 pub selection: Selection,
11 }
12
13 /// Stores the history of changes to a buffer.
14 ///
15 /// Currently the history is represented as a vector of revisions. The vector
16 /// always has at least one element: the empty root revision. Each revision
17 /// with the exception of the root has a parent revision, a [Transaction]
18 /// that can be applied to its parent to transition from the parent to itself,
19 /// and an inversion of that transaction to transition from the parent to its
20 /// latest child.
21 ///
22 /// When using `u` to undo a change, an inverse of the stored transaction will
23 /// be applied which will transition the buffer to the parent state.
24 ///
25 /// Each revision with the exception of the last in the vector also has a
26 /// last child revision. When using `U` to redo a change, the last child transaction
27 /// will be applied to the current state of the buffer.
28 ///
29 /// The current revision is the one currently displayed in the buffer.
30 ///
31 /// Committing a new revision to the history will update the last child of the
32 /// current revision, and push a new revision to the end of the vector.
33 ///
34 /// Revisions are committed with a timestamp. :earlier and :later can be used
35 /// to jump to the closest revision to a moment in time relative to the timestamp
36 /// of the current revision plus (:later) or minus (:earlier) the duration
37 /// given to the command. If a single integer is given, the editor will instead
38 /// jump the given number of revisions in the vector.
39 ///
40 /// Limitations:
41 /// * Changes in selections currently don't commit history changes. The selection
42 /// will only be updated to the state after a committed buffer change.
43 /// * The vector of history revisions is currently unbounded. This might
44 /// cause the memory consumption to grow significantly large during long
45 /// editing sessions.
46 /// * Because delete transactions currently don't store the text that they
47 /// delete, we also store an inversion of the transaction.
48 ///
49 /// Using time to navigate the history: <https://github.com/helix-editor/helix/pull/194>
50 #[derive(Debug)]
51 pub struct History {
52 revisions: Vec<Revision>,
53 current: usize,
54 }
55
56 /// A single point in history. See [History] for more information.
57 #[derive(Debug, Clone)]
58 struct Revision {
59 parent: usize,
60 last_child: Option<NonZeroUsize>,
61 transaction: Transaction,
62 // We need an inversion for undos because delete transactions don't store
63 // the deleted text.
64 inversion: Transaction,
65 timestamp: Instant,
66 }
67
68 impl Default for History {
69 fn default() -> Self {
70 // Add a dummy root revision with empty transaction
71 Self {
72 revisions: vec![Revision {
73 parent: 0,
74 last_child: None,
75 transaction: Transaction::from(ChangeSet::new("".into())),
76 inversion: Transaction::from(ChangeSet::new("".into())),
77 timestamp: Instant::now(),
78 }],
79 current: 0,
80 }
81 }
82 }
83
84 impl History {
85 pub fn commit_revision(&mut self, transaction: &Transaction, original: &State) {
86 self.commit_revision_at_timestamp(transaction, original, Instant::now());
87 }
88
89 pub fn commit_revision_at_timestamp(
90 &mut self,
91 transaction: &Transaction,
92 original: &State,
93 timestamp: Instant,
94 ) {
95 let inversion = transaction
96 .invert(&original.doc)
97 // Store the current cursor position
98 .with_selection(original.selection.clone());
99
100 let new_current = self.revisions.len();
101 self.revisions[self.current].last_child = NonZeroUsize::new(new_current);
102 self.revisions.push(Revision {
103 parent: self.current,
104 last_child: None,
105 transaction: transaction.clone(),
106 inversion,
107 timestamp,
108 });
109 self.current = new_current;
110 }
111
112 #[inline]
113 pub fn current_revision(&self) -> usize {
114 self.current
115 }
116
117 #[inline]
118 pub const fn at_root(&self) -> bool {
119 self.current == 0
120 }
121
122 /// Returns the changes since the given revision composed into a transaction.
123 /// Returns None if there are no changes between the current and given revisions.
124 pub fn changes_since(&self, revision: usize) -> Option<Transaction> {
125 let lca = self.lowest_common_ancestor(revision, self.current);
126 let up = self.path_up(revision, lca);
127 let down = self.path_up(self.current, lca);
128 let up_txns = up
129 .iter()
130 .rev()
131 .map(|&n| self.revisions[n].inversion.clone());
132 let down_txns = down.iter().map(|&n| self.revisions[n].transaction.clone());
133
134 down_txns.chain(up_txns).reduce(|acc, tx| tx.compose(acc))
135 }
136
137 /// Undo the last edit.
138 pub fn undo(&mut self) -> Option<&Transaction> {
139 if self.at_root() {
140 return None;
141 }
142
143 let current_revision = &self.revisions[self.current];
144 self.current = current_revision.parent;
145 Some(&current_revision.inversion)
146 }
147
148 /// Redo the last edit.
149 pub fn redo(&mut self) -> Option<&Transaction> {
150 let current_revision = &self.revisions[self.current];
151 let last_child = current_revision.last_child?;
152 self.current = last_child.get();
153
154 Some(&self.revisions[last_child.get()].transaction)
155 }
156
157 // Get the position of last change
158 pub fn last_edit_pos(&self) -> Option<usize> {
159 if self.current == 0 {
160 return None;
161 }
162 let current_revision = &self.revisions[self.current];
163 let primary_selection = current_revision
164 .inversion
165 .selection()
166 .expect("inversion always contains a selection")
167 .primary();
168 let (_from, to, _fragment) = current_revision
169 .transaction
170 .changes_iter()
171 // find a change that matches the primary selection
172 .find(|(from, to, _fragment)| Range::new(*from, *to).overlaps(&primary_selection))
173 // or use the first change
174 .or_else(|| current_revision.transaction.changes_iter().next())
175 .unwrap();
176 let pos = current_revision
177 .transaction
178 .changes()
179 .map_pos(to, Assoc::After);
180 Some(pos)
181 }
182
183 fn lowest_common_ancestor(&self, mut a: usize, mut b: usize) -> usize {
184 use std::collections::HashSet;
185 let mut a_path_set = HashSet::new();
186 let mut b_path_set = HashSet::new();
187 loop {
188 a_path_set.insert(a);
189 b_path_set.insert(b);
190 if a_path_set.contains(&b) {
191 return b;
192 }
193 if b_path_set.contains(&a) {
194 return a;
195 }
196 a = self.revisions[a].parent; // Relies on the parent of 0 being 0.
197 b = self.revisions[b].parent; // Same as above.
198 }
199 }
200
201 /// List of nodes on the way from `n` to 'a`. Doesn't include `a`.
202 /// Includes `n` unless `a == n`. `a` must be an ancestor of `n`.
203 fn path_up(&self, mut n: usize, a: usize) -> Vec<usize> {
204 let mut path = Vec::new();
205 while n != a {
206 path.push(n);
207 n = self.revisions[n].parent;
208 }
209 path
210 }
211
212 /// Create a [`Transaction`] that will jump to a specific revision in the history.
213 fn jump_to(&mut self, to: usize) -> Vec<Transaction> {
214 let lca = self.lowest_common_ancestor(self.current, to);
215 let up = self.path_up(self.current, lca);
216 let down = self.path_up(to, lca);
217 self.current = to;
218 let up_txns = up.iter().map(|&n| self.revisions[n].inversion.clone());
219 let down_txns = down
220 .iter()
221 .rev()
222 .map(|&n| self.revisions[n].transaction.clone());
223 up_txns.chain(down_txns).collect()
224 }
225
226 /// Creates a [`Transaction`] that will undo `delta` revisions.
227 fn jump_backward(&mut self, delta: usize) -> Vec<Transaction> {
228 self.jump_to(self.current.saturating_sub(delta))
229 }
230
231 /// Creates a [`Transaction`] that will redo `delta` revisions.
232 fn jump_forward(&mut self, delta: usize) -> Vec<Transaction> {
233 self.jump_to(
234 self.current
235 .saturating_add(delta)
236 .min(self.revisions.len() - 1),
237 )
238 }
239
240 /// Helper for a binary search case below.
241 fn revision_closer_to_instant(&self, i: usize, instant: Instant) -> usize {
242 let dur_im1 = instant.duration_since(self.revisions[i - 1].timestamp);
243 let dur_i = self.revisions[i].timestamp.duration_since(instant);
244 use std::cmp::Ordering::*;
245 match dur_im1.cmp(&dur_i) {
246 Less => i - 1,
247 Equal | Greater => i,
248 }
249 }
250
251 /// Creates a [`Transaction`] that will match a revision created at around
252 /// `instant`.
253 fn jump_instant(&mut self, instant: Instant) -> Vec<Transaction> {
254 let search_result = self
255 .revisions
256 .binary_search_by(|rev| rev.timestamp.cmp(&instant));
257 let revision = match search_result {
258 Ok(revision) => revision,
259 Err(insert_point) => match insert_point {
260 0 => 0,
261 n if n == self.revisions.len() => n - 1,
262 i => self.revision_closer_to_instant(i, instant),
263 },
264 };
265 self.jump_to(revision)
266 }
267
268 /// Creates a [`Transaction`] that will match a revision created `duration` ago
269 /// from the timestamp of current revision.
270 fn jump_duration_backward(&mut self, duration: Duration) -> Vec<Transaction> {
271 match self.revisions[self.current].timestamp.checked_sub(duration) {
272 Some(instant) => self.jump_instant(instant),
273 None => self.jump_to(0),
274 }
275 }
276
277 /// Creates a [`Transaction`] that will match a revision created `duration` in
278 /// the future from the timestamp of the current revision.
279 fn jump_duration_forward(&mut self, duration: Duration) -> Vec<Transaction> {
280 match self.revisions[self.current].timestamp.checked_add(duration) {
281 Some(instant) => self.jump_instant(instant),
282 None => self.jump_to(self.revisions.len() - 1),
283 }
284 }
285
286 /// Creates an undo [`Transaction`].
287 pub fn earlier(&mut self, uk: UndoKind) -> Vec<Transaction> {
288 use UndoKind::*;
289 match uk {
290 Steps(n) => self.jump_backward(n),
291 TimePeriod(d) => self.jump_duration_backward(d),
292 }
293 }
294
295 /// Creates a redo [`Transaction`].
296 pub fn later(&mut self, uk: UndoKind) -> Vec<Transaction> {
297 use UndoKind::*;
298 match uk {
299 Steps(n) => self.jump_forward(n),
300 TimePeriod(d) => self.jump_duration_forward(d),
301 }
302 }
303 }
304
305 /// Whether to undo by a number of edits or a duration of time.
306 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
307 pub enum UndoKind {
308 Steps(usize),
309 TimePeriod(std::time::Duration),
310 }
311
312 /// A subset of systemd.time time span syntax units.
313 const TIME_UNITS: &[(&[&str], &str, u64)] = &[
314 (&["seconds", "second", "sec", "s"], "seconds", 1),
315 (&["minutes", "minute", "min", "m"], "minutes", 60),
316 (&["hours", "hour", "hr", "h"], "hours", 60 * 60),
317 (&["days", "day", "d"], "days", 24 * 60 * 60),
318 ];
319
320 /// Checks if the duration input can be turned into a valid duration. It must be a
321 /// positive integer and denote the [unit of time.](`TIME_UNITS`)
322 /// Examples of valid durations:
323 /// * `5 sec`
324 /// * `5 min`
325 /// * `5 hr`
326 /// * `5 days`
327 static DURATION_VALIDATION_REGEX: Lazy<Regex> =
328 Lazy::new(|| Regex::new(r"^(?:\d+\s*[a-z]+\s*)+$").unwrap());
329
330 /// Captures both the number and unit as separate capture groups.
331 static NUMBER_UNIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"(\d+)\s*([a-z]+)").unwrap());
332
333 /// Parse a string (e.g. "5 sec") and try to convert it into a [`Duration`].
334 fn parse_human_duration(s: &str) -> Result<Duration, String> {
335 if !DURATION_VALIDATION_REGEX.is_match(s) {
336 return Err("duration should be composed \
337 of positive integers followed by time units"
338 .to_string());
339 }
340
341 let mut specified = [false; TIME_UNITS.len()];
342 let mut seconds = 0u64;
343 for cap in NUMBER_UNIT_REGEX.captures_iter(s) {
344 let (n, unit_str) = (&cap[1], &cap[2]);
345
346 let n: u64 = n.parse().map_err(|_| format!("integer too large: {}", n))?;
347
348 let time_unit = TIME_UNITS
349 .iter()
350 .enumerate()
351 .find(|(_, (forms, _, _))| forms.iter().any(|f| f == &unit_str));
352
353 if let Some((i, (_, unit, mul))) = time_unit {
354 if specified[i] {
355 return Err(format!("{} specified more than once", unit));
356 }
357 specified[i] = true;
358
359 let new_seconds = n.checked_mul(*mul).and_then(|s| seconds.checked_add(s));
360 match new_seconds {
361 Some(ns) => seconds = ns,
362 None => return Err("duration too large".to_string()),
363 }
364 } else {
365 return Err(format!("incorrect time unit: {}", unit_str));
366 }
367 }
368
369 Ok(Duration::from_secs(seconds))
370 }
371
372 impl std::str::FromStr for UndoKind {
373 type Err = String;
374
375 fn from_str(s: &str) -> Result<Self, Self::Err> {
376 let s = s.trim();
377 if s.is_empty() {
378 Ok(Self::Steps(1usize))
379 } else if let Ok(n) = s.parse::<usize>() {
380 Ok(UndoKind::Steps(n))
381 } else {
382 Ok(Self::TimePeriod(parse_human_duration(s)?))
383 }
384 }
385 }
386
387 #[cfg(test)]
388 mod test {
389 use super::*;
390 use crate::Selection;
391
392 #[test]
393 fn test_undo_redo() {
394 let mut history = History::default();
395 let doc = Rope::from("hello");
396 let mut state = State {
397 doc,
398 selection: Selection::point(0),
399 };
400
401 let transaction1 =
402 Transaction::change(&state.doc, vec![(5, 5, Some(" world!".into()))].into_iter());
403
404 // Need to commit before applying!
405 history.commit_revision(&transaction1, &state);
406 transaction1.apply(&mut state.doc);
407 assert_eq!("hello world!", state.doc);
408
409 // ---
410
411 let transaction2 =
412 Transaction::change(&state.doc, vec![(6, 11, Some("世界".into()))].into_iter());
413
414 // Need to commit before applying!
415 history.commit_revision(&transaction2, &state);
416 transaction2.apply(&mut state.doc);
417 assert_eq!("hello 世界!", state.doc);
418
419 // ---
420 fn undo(history: &mut History, state: &mut State) {
421 if let Some(transaction) = history.undo() {
422 transaction.apply(&mut state.doc);
423 }
424 }
425 fn redo(history: &mut History, state: &mut State) {
426 if let Some(transaction) = history.redo() {
427 transaction.apply(&mut state.doc);
428 }
429 }
430
431 undo(&mut history, &mut state);
432 assert_eq!("hello world!", state.doc);
433 redo(&mut history, &mut state);
434 assert_eq!("hello 世界!", state.doc);
435 undo(&mut history, &mut state);
436 undo(&mut history, &mut state);
437 assert_eq!("hello", state.doc);
438
439 // undo at root is a no-op
440 undo(&mut history, &mut state);
441 assert_eq!("hello", state.doc);
442 }
443
444 #[test]
445 fn test_earlier_later() {
446 let mut history = History::default();
447 let doc = Rope::from("a\n");
448 let mut state = State {
449 doc,
450 selection: Selection::point(0),
451 };
452
453 fn undo(history: &mut History, state: &mut State) {
454 if let Some(transaction) = history.undo() {
455 transaction.apply(&mut state.doc);
456 }
457 }
458
459 fn earlier(history: &mut History, state: &mut State, uk: UndoKind) {
460 let txns = history.earlier(uk);
461 for txn in txns {
462 txn.apply(&mut state.doc);
463 }
464 }
465
466 fn later(history: &mut History, state: &mut State, uk: UndoKind) {
467 let txns = history.later(uk);
468 for txn in txns {
469 txn.apply(&mut state.doc);
470 }
471 }
472
473 fn commit_change(
474 history: &mut History,
475 state: &mut State,
476 change: crate::transaction::Change,
477 instant: Instant,
478 ) {
479 let txn = Transaction::change(&state.doc, vec![change].into_iter());
480 history.commit_revision_at_timestamp(&txn, state, instant);
481 txn.apply(&mut state.doc);
482 }
483
484 let t0 = Instant::now();
485 let t = |n| t0.checked_add(Duration::from_secs(n)).unwrap();
486
487 commit_change(&mut history, &mut state, (1, 1, Some(" b".into())), t(0));
488 assert_eq!("a b\n", state.doc);
489
490 commit_change(&mut history, &mut state, (3, 3, Some(" c".into())), t(10));
491 assert_eq!("a b c\n", state.doc);
492
493 commit_change(&mut history, &mut state, (5, 5, Some(" d".into())), t(20));
494 assert_eq!("a b c d\n", state.doc);
495
496 undo(&mut history, &mut state);
497 assert_eq!("a b c\n", state.doc);
498
499 commit_change(&mut history, &mut state, (5, 5, Some(" e".into())), t(30));
500 assert_eq!("a b c e\n", state.doc);
501
502 undo(&mut history, &mut state);
503 undo(&mut history, &mut state);
504 assert_eq!("a b\n", state.doc);
505
506 commit_change(&mut history, &mut state, (1, 3, None), t(40));
507 assert_eq!("a\n", state.doc);
508
509 commit_change(&mut history, &mut state, (1, 1, Some(" f".into())), t(50));
510 assert_eq!("a f\n", state.doc);
511
512 use UndoKind::*;
513
514 earlier(&mut history, &mut state, Steps(3));
515 assert_eq!("a b c d\n", state.doc);
516
517 later(&mut history, &mut state, TimePeriod(Duration::new(20, 0)));
518 assert_eq!("a\n", state.doc);
519
520 earlier(&mut history, &mut state, TimePeriod(Duration::new(19, 0)));
521 assert_eq!("a b c d\n", state.doc);
522
523 earlier(
524 &mut history,
525 &mut state,
526 TimePeriod(Duration::new(10000, 0)),
527 );
528 assert_eq!("a\n", state.doc);
529
530 later(&mut history, &mut state, Steps(50));
531 assert_eq!("a f\n", state.doc);
532
533 earlier(&mut history, &mut state, Steps(4));
534 assert_eq!("a b c\n", state.doc);
535
536 later(&mut history, &mut state, TimePeriod(Duration::new(1, 0)));
537 assert_eq!("a b c\n", state.doc);
538
539 later(&mut history, &mut state, TimePeriod(Duration::new(5, 0)));
540 assert_eq!("a b c d\n", state.doc);
541
542 later(&mut history, &mut state, TimePeriod(Duration::new(6, 0)));
543 assert_eq!("a b c e\n", state.doc);
544
545 later(&mut history, &mut state, Steps(1));
546 assert_eq!("a\n", state.doc);
547 }
548
549 #[test]
550 fn test_parse_undo_kind() {
551 use UndoKind::*;
552
553 // Default is one step.
554 assert_eq!("".parse(), Ok(Steps(1)));
555
556 // An integer means the number of steps.
557 assert_eq!("1".parse(), Ok(Steps(1)));
558 assert_eq!(" 16 ".parse(), Ok(Steps(16)));
559
560 // Duration has a strict format.
561 let validation_err = Err("duration should be composed \
562 of positive integers followed by time units"
563 .to_string());
564 assert_eq!(" 16 33".parse::<UndoKind>(), validation_err);
565 assert_eq!(" seconds 22 ".parse::<UndoKind>(), validation_err);
566 assert_eq!(" -4 m".parse::<UndoKind>(), validation_err);
567 assert_eq!("5s 3".parse::<UndoKind>(), validation_err);
568
569 // Units are u64.
570 assert_eq!(
571 "18446744073709551616minutes".parse::<UndoKind>(),
572 Err("integer too large: 18446744073709551616".to_string())
573 );
574
575 // Units are validated.
576 assert_eq!(
577 "1 millennium".parse::<UndoKind>(),
578 Err("incorrect time unit: millennium".to_string())
579 );
580
581 // Units can't be specified twice.
582 assert_eq!(
583 "2 seconds 6s".parse::<UndoKind>(),
584 Err("seconds specified more than once".to_string())
585 );
586
587 // Various formats are correctly handled.
588 assert_eq!(
589 "4s".parse::<UndoKind>(),
590 Ok(TimePeriod(Duration::from_secs(4)))
591 );
592 assert_eq!(
593 "2m".parse::<UndoKind>(),
594 Ok(TimePeriod(Duration::from_secs(120)))
595 );
596 assert_eq!(
597 "5h".parse::<UndoKind>(),
598 Ok(TimePeriod(Duration::from_secs(5 * 60 * 60)))
599 );
600 assert_eq!(
601 "3d".parse::<UndoKind>(),
602 Ok(TimePeriod(Duration::from_secs(3 * 24 * 60 * 60)))
603 );
604 assert_eq!(
605 "1m30s".parse::<UndoKind>(),
606 Ok(TimePeriod(Duration::from_secs(90)))
607 );
608 assert_eq!(
609 "1m 20 seconds".parse::<UndoKind>(),
610 Ok(TimePeriod(Duration::from_secs(80)))
611 );
612 assert_eq!(
613 " 2 minute 1day".parse::<UndoKind>(),
614 Ok(TimePeriod(Duration::from_secs(24 * 60 * 60 + 2 * 60)))
615 );
616 assert_eq!(
617 "3 d 2hour 5 minutes 30sec".parse::<UndoKind>(),
618 Ok(TimePeriod(Duration::from_secs(
619 3 * 24 * 60 * 60 + 2 * 60 * 60 + 5 * 60 + 30
620 )))
621 );
622
623 // Sum overflow is handled.
624 assert_eq!(
625 "18446744073709551615minutes".parse::<UndoKind>(),
626 Err("duration too large".to_string())
627 );
628 assert_eq!(
629 "1 minute 18446744073709551615 seconds".parse::<UndoKind>(),
630 Err("duration too large".to_string())
631 );
632 }
633 }