ycpp::UndoManager gives a document undo and redo. It is a port of Yjs's Y.UndoManager.
It records what you change in part of a document, its scope. On undo(), it reverts the
latest step. Only the changes it recorded are reverted. In a shared document, that means a
user undoes their own edits, never a peer's.
An undo is an ordinary edit. It runs in a transaction of the document, emits an update, and peers receive it like any other change.
The undo manager is built when -Dundo=enabled (the default). Include <ycpp/undo_manager.hpp>.
#include <cstdio>
#include <ycpp/doc.hpp>
#include <ycpp/text.hpp>
#include <ycpp/undo_manager.hpp>
int main() {
ycpp::Doc doc(1);
ycpp::TextRef text = doc.text("body");
ycpp::UndoManager undo(doc);
undo.add_to_scope(text.scope_parent(), text.scope_name());
(void)text.insert(0, "Hello");
undo.stop_capturing(); // the next edit starts a new step
(void)text.insert(5, " world");
undo.undo(); // "Hello"
undo.undo(); // ""
undo.redo(); // "Hello"
std::printf("%s\n", text.to_string().c_str()); // Hello
}In Yjs this is new Y.UndoManager(text). In ycpp the manager is built on the document, and
the scope is added after.
The scope says which types the manager watches. A manager with an empty scope records nothing.
undo.add_to_scope(text.scope_parent(), text.scope_name()); // one type
undo.add_to_scope(list.scope_parent(), list.scope_name()); // and another
undo.add_to_scope(doc); // or the whole document- Every handle has
scope_parent()andscope_name(). Together they name the type: a root type by its name, a nested type by the item that holds it. - A type in the scope covers everything nested inside it. Undoing the insert of a nested map removes the map and its content.
add_to_scope(doc)makes the whole document the scope.expand_scope(parent, name)is the same asadd_to_scope, under Yjs's other name.- Two managers with different scopes on one document are independent. Each undoes only its own types.
A manager records a transaction only if its origin is tracked.
At the start, two origins are tracked:
- null: the origin of a plain local write, or of
transact()without an argument. undo.origin(): the manager's own origin, which its undo and redo transactions carry. That is how an undo lands on the redo stack.
undo.add_tracked_origin(ycpp::Any{"toolbar"}); // also record these
undo.remove_tracked_origin(ycpp::Any{nullptr}); // stop recording null-origin writesOrigins are compared by value. Yjs can also track a class, matching any origin object of that
class; an Any has no class, so ycpp has no equivalent.
A remote update applied with plain apply_update has a null origin. The manager tracks
null, so it would record the peer's change as if it were local, and a later undo would revert
it. Yjs behaves the same way, which is why Yjs providers pass themselves as the origin.
Apply peers' updates under an origin the manager does not track:
{
ycpp::Doc::TransactionGuard guard = doc.transact(ycpp::Any{"remote"});
(void)doc.apply_update(bytes);
}
// or, for a v2 update:
(void)doc.apply_update_v2(bytes_v2, ycpp::Any{"remote"});The other way works too: give your local edits an origin, track that, and stop tracking null.
Here two replicas edit one text. The local manager only undoes the local edits.
#include <ycpp/doc.hpp>
#include <ycpp/text.hpp>
#include <ycpp/undo_manager.hpp>
ycpp::Doc local(1);
ycpp::Doc peer(2);
ycpp::UndoOptions options;
options.capture_timeout = 10000; // the two local edits share one step
ycpp::UndoManager undo(local, options);
ycpp::TextRef text = local.text("t");
undo.add_to_scope(text.scope_parent(), text.scope_name());
(void)text.insert(0, "abc");
(void)peer.apply_update(local.encode_state_as_update());
(void)peer.text("t").insert(3, "def");
{
ycpp::Doc::TransactionGuard guard = local.transact(ycpp::Any{"remote"});
(void)local.apply_update(peer.encode_state_as_update(local.state_vector()));
}
(void)text.insert(6, "ghi"); // "abcdefghi"
undo.undo(); // "def": the peer's text staysWhy the peer's text survives:
- Every item has an id: the client id of the replica that wrote it, and a clock.
- A step of the manager lists the ids it inserted and the ids it deleted.
- The peer's transaction had an untracked origin, so no step lists the peer's items.
- Undo deletes exactly the items the step inserted, by id. The peer's items have the peer's client id. Nothing in the step names them.
The same holds for deletions. Undoing a delete puts back the deleted content as new items. It does not undo what a peer did to the neighbourhood in the meantime.
Undoing a map write that replaced an older value puts the older value back. If a peer has
written the same key since, that restore overwrites the peer's value, as in Yjs. Set
ignore_remote_map_changes to leave a key alone when its current value comes from a peer:
ycpp::UndoOptions options;
options.ignore_remote_map_changes = true;Edits that come close together are folded into one step, so that undo removes a typed word, not one letter.
UndoOptions::capture_timeoutis the window, in milliseconds. The default is 500, as in Yjs.- A recorded edit less than
capture_timeoutafter the previous one joins the previous step. stop_capturing()closes the current step. The next edit starts a new one, whatever the time.- One transaction is always one step, or part of one. Group writes with
transact()to undo them together.
Rules the picture shows:
- An undo takes the newest step from the undo stack, reverts it, and pushes the inverse onto the redo stack.
- A redo does the reverse.
- A new recorded edit clears the redo stack, as in any editor.
UndoOptions::now lets you supply the clock: a function and a context pointer that return the
time in milliseconds. Tests use it to drive the timeout without sleeping. When it is null, the
manager reads a monotonic clock.
A step is reverted as a whole. If it inserted something and deleted that same thing, reverting it changes nothing.
For example, insert(0, "abc") then erase(0, 3) in one transaction is one step. undo()
finds nothing to delete (the text is already gone) and nothing to restore (the step inserted
it). It returns false and drops the step from the stack, as Yjs does.
The same happens across a folded step: an insert and a delete of the same element within the capture window are one step. Undoing it does not bring the element back.
bool can_undo() const;
bool can_redo() const;
std::span<const StackItem> undo_stack() const; // oldest first
std::span<const StackItem> redo_stack() const;
bool undo();
bool redo();
void clear(bool clear_undo = true, bool clear_redo = true);undo()andredo()returnfalsewhen the stack is empty, or when no step changed anything.clear()empties one or both stacks.
A StackItem is one step, Yjs's StackItem:
insertions: the ids the step inserted. Undo deletes them.deletions: the ids the step deleted. Undo restores their content.meta: anAnyMapfor your own data. The manager leaves it empty.uid: a stable identity for the step, kept across the copies the manager makes.
push_undo(item) and push_redo(item) put steps back onto the stacks, for an application that
saved them and restores them (Yjs's initUndoStack and initRedoStack).
Two callbacks refine what is recorded and undone. Both are a function pointer and a context.
// Whether a transaction may be recorded at all: Yjs's captureTransaction.
undo.set_capture_transaction(
[](void*, const ycpp::Doc&, const ycpp::Any& origin) {
return !(origin == ycpp::Any{"autosave"});
});
// Whether an item that an undo would delete may be deleted: Yjs's deleteFilter.
bool locked = false; // your own state, read through the context pointer
undo.set_delete_filter(
[](void* context, const ycpp::ID&) { return !*static_cast<bool*>(context); }, &locked);If the delete filter refuses every item of a step, the undo changes nothing and returns
false.
An undo or a redo runs in a transaction whose origin is undo.origin(). Each manager has its
own value. An observer or an on_update handler can check it:
if (doc.origin() == undo.origin()) {
// this change is an undo or a redo of that manager
}set_origin(value) replaces that value with one you choose, and updates the tracked entry that
names it.
The manager reports changes to its stacks, as Yjs's stack-item-* events:
const std::uint64_t id = undo.observe(
[](void*, const ycpp::StackEvent& event) {
// event.kind: added, updated, popped or cleared
// event.type: undo or redo (which stack)
// event.stack_item: the step; event.origin: the transaction's origin
});
// ...
undo.remove_observer(id);added: a new step was pushed.updated: an edit was folded into the newest step.popped: a step was taken off a stack byundo()orredo().cleared: the stacks were cleared.
During an undo(), you see two events. First added of type redo: the inverse lands on the
redo stack. Then popped of type undo.
Unlike document observers, these return a number, not a Connection. They belong to the
manager, so they end with it.
- An
UndoManagercannot be copied or moved. - It may outlive its
Doc. It then does nothing. - The
Docmay be moved. The manager follows it. - Destroying a manager, even from inside a callback during a transaction, is safe. The other managers keep working.