This commit is contained in:
@@ -194,6 +194,38 @@ public record Edit(UUID author, long seq, List<Edit.Component> components) {
|
||||
return written;
|
||||
}
|
||||
|
||||
// ── Undoing ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The walk that takes this one back: run it over the text this edit
|
||||
* produced and the earlier text comes out again. Removals become writes
|
||||
* of exactly what was removed — which is why the text the edit ran over
|
||||
* has to be at hand — and writes become removals of the same length.
|
||||
* {@code base} is the text this edit was applied to, and counts that do
|
||||
* not fit it are clamped the same way {@link #apply} clamps them.
|
||||
*/
|
||||
public Edit invert(String base) {
|
||||
List<Component> inverse = new ArrayList<>(components.size());
|
||||
int index = 0;
|
||||
|
||||
for (Component component : components) {
|
||||
if (component instanceof Retain retain) {
|
||||
int count = Math.min(retain.count(), base.length() - index);
|
||||
if (count <= 0) break;
|
||||
add(inverse, new Retain(count));
|
||||
index += count;
|
||||
} else if (component instanceof Delete delete) {
|
||||
int count = Math.min(delete.count(), base.length() - index);
|
||||
if (count <= 0) break;
|
||||
add(inverse, new Insert(base.substring(index, index + count)));
|
||||
index += count;
|
||||
} else if (component instanceof Insert insert) {
|
||||
add(inverse, new Delete(insert.text().length()));
|
||||
}
|
||||
}
|
||||
return new Edit(author, seq, inverse);
|
||||
}
|
||||
|
||||
// ── Transforming ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user