From 3aa4806515bcf5040cbfe6b34e704ac6959e7b6e Mon Sep 17 00:00:00 2001 From: Krzosa Karol Date: Sat, 10 Aug 2024 07:25:44 +0200 Subject: [PATCH] Fix non-edit doing caret adjustment --- src/text_editor/buffer_history.cpp | 57 ++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 18 deletions(-) diff --git a/src/text_editor/buffer_history.cpp b/src/text_editor/buffer_history.cpp index fe32d7d..fd450df 100644 --- a/src/text_editor/buffer_history.cpp +++ b/src/text_editor/buffer_history.cpp @@ -119,7 +119,7 @@ void AssertRanges(Array carets) { } } -void AdjustCarets(Array edits, Array *carets, bool kill_selection = false) { +void AdjustCarets(Array edits, Array *carets) { Scratch scratch; Array new_carets = TightCopy(scratch, *carets); ForItem(edit, edits) { @@ -131,28 +131,14 @@ void AdjustCarets(Array edits, Array *carets, bool kill_selection = Caret &old_cursor = carets->data[i]; Caret &new_cursor = new_carets.data[i]; - if (old_cursor.range.min == edit.range.min) { - new_cursor.range.min += insert_size; - } else if (old_cursor.range.min > edit.range.min) { + if (old_cursor.range.min > edit.range.min) { new_cursor.range.min += offset; - } - - if (old_cursor.range.max == edit.range.max) { - new_cursor.range.max += insert_size; - } else if (old_cursor.range.max > edit.range.max) { new_cursor.range.max += offset; } } } - for (Int i = 0; i < carets->len; i += 1) { - carets->data[i] = new_carets[i]; - if (kill_selection) { - carets->data[i].range.max = carets->data[i].range.min; - } - } - - IF_DEBUG(AssertRanges(*carets)); + for (Int i = 0; i < carets->len; i += 1) carets->data[i] = new_carets[i]; } bool KILL_SELECTION = true; @@ -174,5 +160,40 @@ void EndEdit(Buffer *buffer, Array *edits, Array *carets, bool kill } #endif - AdjustCarets(*edits, carets, kill_selection); + // Adjust carets + // this one also moves the carets forward if they are aligned with edit + // + Scratch scratch; + Array new_carets = TightCopy(scratch, *carets); + ForItem(edit, *edits) { + Int remove_size = GetSize(edit.range); + Int insert_size = edit.string.len; + Int offset = insert_size - remove_size; + + for (Int i = 0; i < carets->len; i += 1) { + Caret &old_cursor = carets->data[i]; + Caret &new_cursor = new_carets.data[i]; + + if (old_cursor.range.min == edit.range.min) { + new_cursor.range.min += insert_size; + } else if (old_cursor.range.min > edit.range.min) { + new_cursor.range.min += offset; + } + + if (old_cursor.range.max == edit.range.max) { + new_cursor.range.max += insert_size; + } else if (old_cursor.range.max > edit.range.max) { + new_cursor.range.max += offset; + } + + Assert(new_cursor.range.max >= new_cursor.range.min); + } + } + + for (Int i = 0; i < carets->len; i += 1) { + carets->data[i] = new_carets[i]; + if (kill_selection) { + carets->data[i].range.max = carets->data[i].range.min; + } + } }