| 1 | use std::fmt::Debug; |
| 2 | |
| 3 | use crate::input::Selection; |
| 4 | |
| 5 | /// One text replacement, in the coordinates of the document as it stood |
| 6 | /// immediately before the replacement was applied. |
| 7 | #[derive(Debug, PartialEq, Clone)] |
| 8 | pub(super) struct Change { |
| 9 | pub(super) token_delta: Option<Box<super::inline_tokens::TokenDelta>>, |
| 10 | pub(crate) old_range: Selection, |
| 11 | pub(crate) old_text: String, |
| 12 | pub(crate) new_range: Selection, |
| 13 | pub(crate) new_text: String, |
| 14 | } |
| 15 | |
| 16 | impl Change { |
| 17 | pub(super) fn new( |
| 18 | old_range: impl Into<Selection>, |
| 19 | old_text: &str, |
| 20 | new_range: impl Into<Selection>, |
| 21 | new_text: &str, |
| 22 | ) -> Self { |
| 23 | Self { |
| 24 | token_delta: None, |
| 25 | old_range: old_range.into(), |
| 26 | old_text: old_text.to_string(), |
| 27 | new_range: new_range.into(), |
| 28 | new_text: new_text.to_string(), |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | /// The same change as it would read after `delta` bytes were inserted |
| 33 | /// (positive) or removed (negative) ahead of it. |
| 34 | pub(super) fn shifted(&self, delta: isize) -> Self { |
| 35 | let shift = |offset: usize| (offset as isize + delta).max(0) as usize; |
| 36 | Self { |
| 37 | token_delta: self.token_delta.clone(), |
| 38 | old_range: (shift(self.old_range.start)..shift(self.old_range.end)).into(), |
| 39 | old_text: self.old_text.clone(), |
| 40 | new_range: (shift(self.new_range.start)..shift(self.new_range.end)).into(), |
| 41 | new_text: self.new_text.clone(), |
| 42 | } |
| 43 | } |
| 44 | } |