Skip to main content

continuity_buffer/
inverse_op.rs

1//! Inverse-op derivation for undo recording.
2//!
3//! Given an `EditOp`, the substring it removed (empty for `Insert`),
4//! and the post-edit rope, return the op that would undo it. Pure
5//! logic; the recovery path uses it on replayed edits to reconstruct
6//! undo records without having the pre-edit rope on hand.
7
8use continuity_text::{EditOp, Position, Range};
9use ropey::Rope;
10
11use crate::Error;
12
13/// Compute the inverse of `op` given the original removed text and the
14/// post-edit rope. Pure logic; reusable by recovery (which has only
15/// `(rope_after, op, removed_text)`) as well as by the core thread.
16///
17/// # Errors
18///
19/// Returns [`Error::Text`] when positions fall outside `rope_after`.
20pub fn compute_inverse_op(
21    op: &EditOp,
22    removed_text: &str,
23    rope_after: &Rope,
24) -> Result<EditOp, Error> {
25    match op {
26        EditOp::Insert { at, text } => {
27            let start_byte = at.to_byte_offset(rope_after)?;
28            let end_byte = start_byte
29                .saturating_add(text.len())
30                .min(rope_after.len_bytes());
31            let end = Position::from_byte_offset(rope_after, end_byte)?;
32            Ok(EditOp::delete(Range::new(*at, end)))
33        }
34        EditOp::Delete { range } => Ok(EditOp::insert(range.start, removed_text.to_string())),
35        EditOp::Replace { range, text } => {
36            let start_byte = range.start.to_byte_offset(rope_after)?;
37            let end_byte = start_byte
38                .saturating_add(text.len())
39                .min(rope_after.len_bytes());
40            let end = Position::from_byte_offset(rope_after, end_byte)?;
41            Ok(EditOp::replace(
42                Range::new(range.start, end),
43                removed_text.to_string(),
44            ))
45        }
46    }
47}