Undo/redo support in ViEditor

This commit is contained in:
Jeremy Soller 2023-11-13 13:31:06 -07:00
parent 7830f4107c
commit 5352fdee94
No known key found for this signature in database
GPG key ID: DCFCA852D3906975
5 changed files with 198 additions and 68 deletions

View file

@ -21,6 +21,7 @@ self_cell = "1.0.1"
swash = { version = "0.1.8", optional = true } swash = { version = "0.1.8", optional = true }
syntect = { version = "5.1.0", optional = true } syntect = { version = "5.1.0", optional = true }
sys-locale = { version = "0.3.1", optional = true } sys-locale = { version = "0.3.1", optional = true }
undo_2 = { version = "0.2.0", optional = true }
unicode-linebreak = "0.1.5" unicode-linebreak = "0.1.5"
unicode-script = "0.5.5" unicode-script = "0.5.5"
unicode-segmentation = "1.10.1" unicode-segmentation = "1.10.1"
@ -46,7 +47,7 @@ std = [
"sys-locale", "sys-locale",
"unicode-bidi/std", "unicode-bidi/std",
] ]
vi = ["modit", "syntect"] vi = ["modit", "syntect", "undo_2"]
wasm-web = ["sys-locale?/js"] wasm-web = ["sys-locale?/js"]
warn_on_missing_glyphs = [] warn_on_missing_glyphs = []
fontconfig = ["fontdb/fontconfig", "std"] fontconfig = ["fontdb/fontconfig", "std"]

View file

@ -124,7 +124,12 @@ impl Editor {
} }
if let Some(ref mut change) = self.change { if let Some(ref mut change) = self.change {
let item = ChangeItem::Delete(start, change_text); let item = ChangeItem {
start,
end,
text: change_text,
insert: false,
};
change.items.push(item); change.items.push(item);
} }
} }
@ -140,10 +145,8 @@ impl Editor {
return cursor; return cursor;
} }
if let Some(ref mut change) = self.change { // Save cursor for change tracking
let item = ChangeItem::Insert(cursor, data.to_string()); let start = cursor;
change.items.push(item);
}
let line: &mut BufferLine = &mut self.buffer.lines[cursor.line]; let line: &mut BufferLine = &mut self.buffer.lines[cursor.line];
let insert_line = cursor.line + 1; let insert_line = cursor.line + 1;
@ -208,6 +211,16 @@ impl Editor {
// Append the text after insertion // Append the text after insertion
cursor.index = self.buffer.lines[cursor.line].text().len() - after_len; cursor.index = self.buffer.lines[cursor.line].text().len() - after_len;
if let Some(ref mut change) = self.change {
let item = ChangeItem {
start,
end: cursor,
text: data.to_string(),
insert: true,
};
change.items.push(item);
}
cursor cursor
} }
} }
@ -348,9 +361,36 @@ impl Edit for Editor {
self.set_cursor(new_cursor); self.set_cursor(new_cursor);
} }
fn apply_change(&mut self, change: &Change) -> bool {
// Cannot apply changes if there is a pending change
match self.change.take() {
Some(pending) => {
if !pending.items.is_empty() {
//TODO: is this a good idea?
log::warn!("pending change caused apply_change to be ignored!");
self.change = Some(pending);
return false;
}
}
None => {}
}
for item in change.items.iter() {
//TODO: edit cursor if needed?
if item.insert {
self.cursor = self.insert_at(item.start, &item.text, None);
} else {
self.cursor = item.start;
self.delete_range(item.start, item.end);
}
}
true
}
fn start_change(&mut self) { fn start_change(&mut self) {
//TODO: what to do if overwriting change? if self.change.is_none() {
self.change = Some(Change::default()); self.change = Some(Change::default());
}
} }
fn finish_change(&mut self) -> Option<Change> { fn finish_change(&mut self) -> Option<Change> {

View file

@ -93,15 +93,41 @@ pub enum Action {
GotoLine(usize), GotoLine(usize),
} }
/// A unique change to an editor
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum ChangeItem { pub struct ChangeItem {
Delete(Cursor, String), /// Cursor indicating start of change
Insert(Cursor, String), pub start: Cursor,
/// Cursor indicating end of change
pub end: Cursor,
/// Text to be inserted or deleted
pub text: String,
/// Insert if true, delete if false
pub insert: bool,
} }
impl ChangeItem {
// Reverse change item (in place)
pub fn reverse(&mut self) {
self.insert = !self.insert;
}
}
/// A set of change items grouped into one logical change
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct Change { pub struct Change {
items: Vec<ChangeItem>, /// Change items grouped into one change
pub items: Vec<ChangeItem>,
}
impl Change {
// Reverse change (in place)
pub fn reverse(&mut self) {
self.items.reverse();
for item in self.items.iter_mut() {
item.reverse();
}
}
} }
/// A trait to allow easy replacements of [`Editor`], like `SyntaxEditor` /// A trait to allow easy replacements of [`Editor`], like `SyntaxEditor`
@ -158,6 +184,9 @@ pub trait Edit {
/// attributes, or with the previous character's attributes if None is given. /// attributes, or with the previous character's attributes if None is given.
fn insert_string(&mut self, data: &str, attrs_list: Option<AttrsList>); fn insert_string(&mut self, data: &str, attrs_list: Option<AttrsList>);
/// Apply a change
fn apply_change(&mut self, change: &Change) -> bool;
/// Start collecting change /// Start collecting change
fn start_change(&mut self); fn start_change(&mut self);

View file

@ -304,6 +304,10 @@ impl<'a> Edit for SyntaxEditor<'a> {
self.editor.insert_string(data, attrs_list); self.editor.insert_string(data, attrs_list);
} }
fn apply_change(&mut self, change: &Change) -> bool {
self.editor.apply_change(change)
}
fn start_change(&mut self) { fn start_change(&mut self) {
self.editor.start_change(); self.editor.start_change();
} }

View file

@ -1,6 +1,7 @@
use alloc::string::String; use alloc::string::String;
use core::cmp; use core::cmp;
use modit::{Event, Key, Motion, Parser, TextObject, WordIter}; use modit::{Event, Key, Motion, Parser, TextObject, WordIter};
use undo_2::Commands;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use crate::{ use crate::{
@ -10,6 +11,20 @@ use crate::{
pub use modit::{ViMode, ViParser}; pub use modit::{ViMode, ViParser};
fn undo_2_action<E: Edit>(editor: &mut E, action: undo_2::Action<&Change>) {
match action {
undo_2::Action::Do(change) => {
editor.apply_change(change);
}
undo_2::Action::Undo(change) => {
//TODO: make this more efficient
let mut reversed = change.clone();
reversed.reverse();
editor.apply_change(&reversed);
}
}
}
fn search<E: Edit>(editor: &mut E, search: &str, forwards: bool) { fn search<E: Edit>(editor: &mut E, search: &str, forwards: bool) {
let mut cursor = editor.cursor(); let mut cursor = editor.cursor();
let start_line = cursor.line; let start_line = cursor.line;
@ -124,6 +139,7 @@ pub struct ViEditor<'a> {
parser: ViParser, parser: ViParser,
passthrough: bool, passthrough: bool,
search_opt: Option<(String, bool)>, search_opt: Option<(String, bool)>,
commands: Commands<Change>,
} }
impl<'a> ViEditor<'a> { impl<'a> ViEditor<'a> {
@ -133,6 +149,7 @@ impl<'a> ViEditor<'a> {
parser: ViParser::new(), parser: ViParser::new(),
passthrough: false, passthrough: false,
search_opt: None, search_opt: None,
commands: Commands::new(),
} }
} }
@ -179,66 +196,24 @@ impl<'a> ViEditor<'a> {
pub fn parser(&self) -> &ViParser { pub fn parser(&self) -> &ViParser {
&self.parser &self.parser
} }
}
impl<'a> Edit for ViEditor<'a> { /// Redo a change
fn buffer(&self) -> &Buffer { pub fn redo(&mut self) {
self.editor.buffer() log::info!("Redo");
for action in self.commands.redo() {
undo_2_action(&mut self.editor, action);
}
} }
fn buffer_mut(&mut self) -> &mut Buffer { /// Undo a change
self.editor.buffer_mut() pub fn undo(&mut self) {
log::info!("Undo");
for action in self.commands.undo() {
undo_2_action(&mut self.editor, action);
}
} }
fn cursor(&self) -> Cursor { fn action_inner(&mut self, font_system: &mut FontSystem, action: Action) {
self.editor.cursor()
}
fn set_cursor(&mut self, cursor: Cursor) {
self.editor.set_cursor(cursor);
}
fn select_opt(&self) -> Option<Cursor> {
self.editor.select_opt()
}
fn set_select_opt(&mut self, select_opt: Option<Cursor>) {
self.editor.set_select_opt(select_opt);
}
fn tab_width(&self) -> usize {
self.editor.tab_width()
}
fn set_tab_width(&mut self, tab_width: usize) {
self.editor.set_tab_width(tab_width);
}
fn shape_as_needed(&mut self, font_system: &mut FontSystem) {
self.editor.shape_as_needed(font_system);
}
fn copy_selection(&self) -> Option<String> {
self.editor.copy_selection()
}
fn delete_selection(&mut self) -> bool {
self.editor.delete_selection()
}
fn insert_string(&mut self, data: &str, attrs_list: Option<AttrsList>) {
self.editor.insert_string(data, attrs_list);
}
fn start_change(&mut self) {
self.editor.start_change();
}
fn finish_change(&mut self) -> Option<Change> {
self.editor.finish_change()
}
fn action(&mut self, font_system: &mut FontSystem, action: Action) {
let editor = &mut self.editor; let editor = &mut self.editor;
log::info!("Action {:?}", action); log::info!("Action {:?}", action);
@ -268,6 +243,7 @@ impl<'a> Edit for ViEditor<'a> {
return editor.action(font_system, action); return editor.action(font_system, action);
} }
}; };
self.parser.parse(key, false, |event| { self.parser.parse(key, false, |event| {
log::info!(" Event {:?}", event); log::info!(" Event {:?}", event);
let action = match event { let action = match event {
@ -347,7 +323,9 @@ impl<'a> Edit for ViEditor<'a> {
return; return;
} }
Event::Undo => { Event::Undo => {
log::info!("TODO"); for action in self.commands.undo() {
undo_2_action(editor, action);
}
return; return;
} }
Event::Motion(motion) => { Event::Motion(motion) => {
@ -636,6 +614,84 @@ impl<'a> Edit for ViEditor<'a> {
editor.action(font_system, action); editor.action(font_system, action);
}); });
} }
}
impl<'a> Edit for ViEditor<'a> {
fn buffer(&self) -> &Buffer {
self.editor.buffer()
}
fn buffer_mut(&mut self) -> &mut Buffer {
self.editor.buffer_mut()
}
fn cursor(&self) -> Cursor {
self.editor.cursor()
}
fn set_cursor(&mut self, cursor: Cursor) {
self.editor.set_cursor(cursor);
}
fn select_opt(&self) -> Option<Cursor> {
self.editor.select_opt()
}
fn set_select_opt(&mut self, select_opt: Option<Cursor>) {
self.editor.set_select_opt(select_opt);
}
fn tab_width(&self) -> usize {
self.editor.tab_width()
}
fn set_tab_width(&mut self, tab_width: usize) {
self.editor.set_tab_width(tab_width);
}
fn shape_as_needed(&mut self, font_system: &mut FontSystem) {
self.editor.shape_as_needed(font_system);
}
fn copy_selection(&self) -> Option<String> {
self.editor.copy_selection()
}
fn delete_selection(&mut self) -> bool {
self.editor.delete_selection()
}
fn insert_string(&mut self, data: &str, attrs_list: Option<AttrsList>) {
self.editor.insert_string(data, attrs_list);
}
fn apply_change(&mut self, change: &Change) -> bool {
self.editor.apply_change(change)
}
fn start_change(&mut self) {
self.editor.start_change();
}
fn finish_change(&mut self) -> Option<Change> {
self.editor.finish_change()
}
fn action(&mut self, font_system: &mut FontSystem, action: Action) {
self.start_change();
self.action_inner(font_system, action);
match self.finish_change() {
Some(change) => {
if !change.items.is_empty() {
log::info!("{:?}", change);
self.commands.push(change);
}
}
None => {}
}
}
#[cfg(feature = "swash")] #[cfg(feature = "swash")]
fn draw<F>( fn draw<F>(