TextEditBuffer now owns a text::Document (piece tree with undo history) and a text::Editor (cursors and commands) instead of a std::string with a caret. TextField, TextArea, the Markdown editor and everything built from them keep their API. ui::TextEditor is reduced to binding events to engine commands: the key map, clipboard, input method, caret blink. Its own undo stack is gone; history, selections restored by undo, and grapheme-aware stepping come from the engine. New in multiple-line editors: several cursors (Alt+click, Ctrl+Alt+Up/Down, Ctrl+D, Ctrl+Shift+L, Escape back to one), move/copy/delete lines (Alt+Up/Down, Alt+Shift+Up/Down, Ctrl+Shift+K), select lines (Ctrl+L), indent/outdent (Ctrl+]/[), jump to bracket, Enter keeps the indentation. Consecutive Backspace/Delete presses undo together. Document changes now report the lines they touched. Adds widgetsTextEditingBench. Co-Authored-By: Claude <noreply@anthropic.com>
335 lines
10 KiB
C++
335 lines
10 KiB
C++
#include "TextDocument.hpp"
|
|
|
|
#include <algorithm>
|
|
|
|
using namespace tp;
|
|
using namespace tp::text;
|
|
|
|
size_t text::transformOffset(size_t offset, const TextChange& change, Bias bias) {
|
|
if (offset < change.offset) return offset;
|
|
|
|
const size_t end = change.offset + change.removed;
|
|
if (offset > end || (offset == end && change.removed > 0)) return offset - change.removed + change.inserted;
|
|
// At the start of the change, or inside the removed range.
|
|
if (offset == change.offset && change.removed > 0) return offset;
|
|
return bias == Bias::After ? change.offset + change.inserted : change.offset;
|
|
}
|
|
|
|
Eol text::normalizeLineBreaks(std::string& text) {
|
|
const size_t firstReturn = text.find('\r');
|
|
if (firstReturn == std::string::npos) return Eol::LF;
|
|
|
|
size_t lf = 0;
|
|
size_t crlf = 0;
|
|
size_t cr = 0;
|
|
for (size_t index = 0; index < firstReturn; index++)
|
|
lf += text[index] == '\n';
|
|
|
|
size_t write = firstReturn;
|
|
for (size_t read = firstReturn; read < text.size(); read++) {
|
|
const char byte = text[read];
|
|
if (byte == '\r') {
|
|
if (read + 1 < text.size() && text[read + 1] == '\n') {
|
|
crlf++;
|
|
read++;
|
|
} else {
|
|
cr++;
|
|
}
|
|
text[write++] = '\n';
|
|
continue;
|
|
}
|
|
lf += byte == '\n';
|
|
text[write++] = byte;
|
|
}
|
|
text.resize(write);
|
|
|
|
if (crlf >= lf && crlf >= cr) return Eol::CRLF;
|
|
return cr > lf ? Eol::CR : Eol::LF;
|
|
}
|
|
|
|
std::string text::withLineBreaks(std::string_view text, Eol eol) {
|
|
if (eol == Eol::LF) return std::string(text);
|
|
|
|
const std::string_view sequence = eolSequence(eol);
|
|
std::string out;
|
|
out.reserve(text.size() + text.size() / 16);
|
|
for (const char byte : text) {
|
|
if (byte == '\n') out.append(sequence);
|
|
else out += byte;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
namespace {
|
|
size_t lineBreaksIn(std::string_view text) { return size_t(std::count(text.begin(), text.end(), '\n')); }
|
|
}
|
|
|
|
Document::Document(std::string text) {
|
|
mEol = normalizeLineBreaks(text);
|
|
mBuffer.assign(std::move(text));
|
|
}
|
|
|
|
void Document::setText(std::string text) {
|
|
mEol = normalizeLineBreaks(text);
|
|
mBuffer.assign(std::move(text));
|
|
clearHistory();
|
|
mGroupHasStep = false;
|
|
|
|
for (Anchor& anchor : mAnchors)
|
|
anchor.offset = std::min(anchor.offset, mBuffer.size());
|
|
|
|
mContentId = ++mNextContentId;
|
|
changed({ DocumentChange::Reason::Reset, {} });
|
|
}
|
|
|
|
std::string Document::text(Eol eol) const {
|
|
if (eol == Eol::LF) return mBuffer.text();
|
|
|
|
const std::string_view sequence = eolSequence(eol);
|
|
std::string out;
|
|
out.reserve(mBuffer.size() + (mBuffer.lineCount() - 1) * (sequence.size() - 1));
|
|
mBuffer.read(0, mBuffer.size(), [&](std::string_view run) {
|
|
for (const char byte : run) {
|
|
if (byte == '\n') out.append(sequence);
|
|
else out += byte;
|
|
}
|
|
});
|
|
return out;
|
|
}
|
|
|
|
// ---------------------- Editing ---------------------- //
|
|
|
|
Document::Step& Document::stepFor(UndoMode mode) {
|
|
mRedo.clear();
|
|
|
|
const bool joinsGroup = mGroupDepth > 0 && mGroupHasStep;
|
|
const bool merges = mGroupDepth == 0 && mode == UndoMode::MergeWithLast && !mStopPending;
|
|
mStopPending = false;
|
|
if (!mUndo.empty() && (joinsGroup || merges)) return mUndo.back();
|
|
|
|
if (mHistoryLimit && mUndo.size() >= mHistoryLimit) mUndo.erase(mUndo.begin());
|
|
mUndo.emplace_back();
|
|
mUndo.back().contentBefore = mContentId;
|
|
if (mGroupDepth > 0) mGroupHasStep = true;
|
|
return mUndo.back();
|
|
}
|
|
|
|
void Document::applyRecord(Record record, Step& step, std::vector<TextChange>& changes) {
|
|
const TextChange change{ record.offset, record.removed.size(), record.inserted.size(),
|
|
mBuffer.lineOf(record.offset), lineBreaksIn(record.removed), lineBreaksIn(record.inserted) };
|
|
mBuffer.replace(record.offset, record.removed.size(), record.inserted);
|
|
changes.push_back(change);
|
|
|
|
for (Anchor& anchor : mAnchors) {
|
|
if (anchor.used) anchor.offset = transformOffset(anchor.offset, change, anchor.bias);
|
|
}
|
|
|
|
// Keystrokes that continue one another are stored as one record, so a typed paragraph is one string in
|
|
// the history rather than a record per character.
|
|
if (!step.records.empty()) {
|
|
Record& last = step.records.back();
|
|
if (last.removed.empty() && record.removed.empty() && record.offset == last.offset + last.inserted.size()) {
|
|
last.inserted += record.inserted;
|
|
return;
|
|
}
|
|
if (last.inserted.empty() && record.inserted.empty()) {
|
|
if (record.offset + record.removed.size() == last.offset) {
|
|
last.removed.insert(0, record.removed);
|
|
last.offset = record.offset;
|
|
return;
|
|
}
|
|
if (record.offset == last.offset) {
|
|
last.removed += record.removed;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
step.records.push_back(std::move(record));
|
|
}
|
|
|
|
Range Document::replace(Range range, std::string_view text, UndoMode mode) {
|
|
std::vector<Edit> edits;
|
|
edits.push_back({ range, std::string(text) });
|
|
return apply(std::move(edits), mode)[0];
|
|
}
|
|
|
|
std::vector<Range> Document::apply(std::vector<Edit> edits, UndoMode mode) {
|
|
const size_t total = mBuffer.size();
|
|
std::vector<Range> results(edits.size());
|
|
if (edits.empty()) return results;
|
|
|
|
for (Edit& edit : edits) {
|
|
edit.range.start = std::min(edit.range.start, total);
|
|
edit.range.end = std::clamp(edit.range.end, edit.range.start, total);
|
|
normalizeLineBreaks(edit.text);
|
|
}
|
|
|
|
std::vector<size_t> order(edits.size());
|
|
for (size_t index = 0; index < order.size(); index++)
|
|
order[index] = index;
|
|
std::stable_sort(order.begin(), order.end(), [&edits](size_t a, size_t b) {
|
|
const Range& left = edits[a].range;
|
|
const Range& right = edits[b].range;
|
|
return left.start != right.start ? left.start < right.start : left.end < right.end;
|
|
});
|
|
|
|
// Ascending pass: drop what overlaps or does nothing, and work out where each text ends up.
|
|
std::vector<size_t> kept;
|
|
size_t previousEnd = 0;
|
|
long long delta = 0;
|
|
for (const size_t index : order) {
|
|
const Edit& edit = edits[index];
|
|
const bool overlaps = edit.range.start < previousEnd;
|
|
const bool nothing = edit.range.empty() && edit.text.empty();
|
|
const size_t start = size_t((long long) (overlaps ? previousEnd : edit.range.start) + delta);
|
|
if (overlaps || nothing) {
|
|
results[index] = { start, start };
|
|
continue;
|
|
}
|
|
|
|
results[index] = { start, start + edit.text.size() };
|
|
delta += (long long) edit.text.size() - (long long) edit.range.length();
|
|
previousEnd = edit.range.end;
|
|
kept.push_back(index);
|
|
}
|
|
if (kept.empty()) return results;
|
|
|
|
// Descending pass: applying from the end keeps the offsets of the edits still to come valid.
|
|
Step& step = stepFor(mode);
|
|
DocumentChange change;
|
|
for (auto index = kept.rbegin(); index != kept.rend(); ++index) {
|
|
Edit& edit = edits[*index];
|
|
Record record{ edit.range.start, mBuffer.substr(edit.range.start, edit.range.length()), std::move(edit.text) };
|
|
applyRecord(std::move(record), step, change.changes);
|
|
}
|
|
|
|
mContentId = ++mNextContentId;
|
|
step.contentAfter = mContentId;
|
|
changed(std::move(change));
|
|
return results;
|
|
}
|
|
|
|
void Document::beginGroup() {
|
|
if (mGroupDepth++ == 0) mGroupHasStep = false;
|
|
}
|
|
|
|
void Document::endGroup() {
|
|
if (mGroupDepth == 0) return;
|
|
if (--mGroupDepth == 0) {
|
|
mGroupHasStep = false;
|
|
// What follows a group never merges into it.
|
|
mStopPending = true;
|
|
}
|
|
}
|
|
|
|
bool Document::undo(std::vector<Selection>* selections) {
|
|
if (mUndo.empty() || mGroupDepth > 0) return false;
|
|
|
|
Step step = std::move(mUndo.back());
|
|
mUndo.pop_back();
|
|
|
|
DocumentChange change;
|
|
change.reason = DocumentChange::Reason::Undo;
|
|
for (auto record = step.records.rbegin(); record != step.records.rend(); ++record) {
|
|
const TextChange reverted{ record->offset, record->inserted.size(), record->removed.size(),
|
|
mBuffer.lineOf(record->offset), lineBreaksIn(record->inserted), lineBreaksIn(record->removed) };
|
|
mBuffer.replace(record->offset, record->inserted.size(), record->removed);
|
|
change.changes.push_back(reverted);
|
|
for (Anchor& anchor : mAnchors) {
|
|
if (anchor.used) anchor.offset = transformOffset(anchor.offset, reverted, anchor.bias);
|
|
}
|
|
}
|
|
|
|
if (selections && step.annotated) *selections = step.before;
|
|
mContentId = step.contentBefore;
|
|
mRedo.push_back(std::move(step));
|
|
mStopPending = true;
|
|
changed(std::move(change));
|
|
return true;
|
|
}
|
|
|
|
bool Document::redo(std::vector<Selection>* selections) {
|
|
if (mRedo.empty() || mGroupDepth > 0) return false;
|
|
|
|
Step step = std::move(mRedo.back());
|
|
mRedo.pop_back();
|
|
|
|
DocumentChange change;
|
|
change.reason = DocumentChange::Reason::Redo;
|
|
for (const Record& record : step.records) {
|
|
const TextChange reapplied{ record.offset, record.removed.size(), record.inserted.size(),
|
|
mBuffer.lineOf(record.offset), lineBreaksIn(record.removed), lineBreaksIn(record.inserted) };
|
|
mBuffer.replace(record.offset, record.removed.size(), record.inserted);
|
|
change.changes.push_back(reapplied);
|
|
for (Anchor& anchor : mAnchors) {
|
|
if (anchor.used) anchor.offset = transformOffset(anchor.offset, reapplied, anchor.bias);
|
|
}
|
|
}
|
|
|
|
if (selections && step.annotated) *selections = step.after;
|
|
mContentId = step.contentAfter;
|
|
mUndo.push_back(std::move(step));
|
|
mStopPending = true;
|
|
changed(std::move(change));
|
|
return true;
|
|
}
|
|
|
|
void Document::clearHistory() {
|
|
mUndo.clear();
|
|
mRedo.clear();
|
|
mStopPending = false;
|
|
}
|
|
|
|
void Document::setHistoryLimit(size_t steps) {
|
|
mHistoryLimit = steps;
|
|
if (mHistoryLimit && mUndo.size() > mHistoryLimit) mUndo.erase(mUndo.begin(), mUndo.end() - long(mHistoryLimit));
|
|
}
|
|
|
|
void Document::annotateStep(const std::vector<Selection>& before, const std::vector<Selection>& after) {
|
|
if (mUndo.empty()) return;
|
|
|
|
Step& step = mUndo.back();
|
|
if (!step.annotated) step.before = before;
|
|
step.after = after;
|
|
step.annotated = true;
|
|
}
|
|
|
|
// ---------------------- Listeners and anchors ---------------------- //
|
|
|
|
void Document::changed(DocumentChange change) {
|
|
mVersion++;
|
|
// A listener may add or remove listeners while it runs.
|
|
for (size_t index = 0; index < mListeners.size(); index++) {
|
|
const Listener listener = mListeners[index].second;
|
|
if (listener) listener(change);
|
|
}
|
|
}
|
|
|
|
size_t Document::addListener(Listener listener) {
|
|
mListeners.emplace_back(mNextListenerId, std::move(listener));
|
|
return mNextListenerId++;
|
|
}
|
|
|
|
void Document::removeListener(size_t id) {
|
|
std::erase_if(mListeners, [id](const auto& entry) { return entry.first == id; });
|
|
}
|
|
|
|
size_t Document::createAnchor(size_t offset, Bias bias) {
|
|
const Anchor anchor{ std::min(offset, mBuffer.size()), bias, true };
|
|
for (size_t id = 0; id < mAnchors.size(); id++) {
|
|
if (!mAnchors[id].used) {
|
|
mAnchors[id] = anchor;
|
|
return id;
|
|
}
|
|
}
|
|
mAnchors.push_back(anchor);
|
|
return mAnchors.size() - 1;
|
|
}
|
|
|
|
size_t Document::anchorOffset(size_t id) const {
|
|
return id < mAnchors.size() && mAnchors[id].used ? mAnchors[id].offset : kNoPosition;
|
|
}
|
|
|
|
void Document::removeAnchor(size_t id) {
|
|
if (id < mAnchors.size()) mAnchors[id].used = false;
|
|
}
|