#include "TextEditing.hpp" #include using namespace tp; using namespace tp::text; namespace { bool isBlank(char byte) { return byte == ' ' || byte == '\t'; } // Where an offset of the text before a batch of edits lands after it. The changes are ascending and do // not overlap, all in the coordinates of the text before the batch. size_t mapThrough(size_t offset, const std::vector& changes, Bias bias) { long long delta = 0; for (const TextChange& change : changes) { if (offset < change.offset) break; const size_t end = change.offset + change.removed; const bool past = offset > end || (offset == end && change.removed > 0); const bool pushedByInsert = change.removed == 0 && offset == change.offset && bias == Bias::After; if (past || pushedByInsert) { delta += (long long) change.inserted - (long long) change.removed; continue; } if (offset == change.offset) return size_t((long long) offset + delta); return size_t((long long) change.offset + delta) + (bias == Bias::After ? change.inserted : 0); } return size_t((long long) offset + delta); } // Sorts edits and joins those that overlap, so a batch built from several cursors is always applicable. std::vector merged(std::vector edits) { std::stable_sort(edits.begin(), edits.end(), [](const Edit& a, const Edit& b) { return a.range.start != b.range.start ? a.range.start < b.range.start : a.range.end < b.range.end; }); std::vector out; for (Edit& edit : edits) { if (!out.empty() && edit.range.start < out.back().range.end) { out.back().range.end = std::max(out.back().range.end, edit.range.end); out.back().text += edit.text; continue; } out.push_back(std::move(edit)); } return out; } std::vector changesOf(const std::vector& edits) { std::vector changes; changes.reserve(edits.size()); for (const Edit& edit : edits) changes.push_back({ edit.range.start, edit.range.length(), edit.text.size() }); return changes; } std::vector splitLines(std::string_view text) { std::vector lines; size_t start = 0; while (true) { const size_t end = text.find('\n', start); if (end == std::string_view::npos) break; lines.push_back(text.substr(start, end - start)); start = end + 1; } // A final line break ends the last line rather than opening an empty one. if (start < text.size() || lines.empty()) lines.push_back(text.substr(start)); return lines; } char closerOf(char opener) { switch (opener) { case '(': return ')'; case '[': return ']'; case '{': return '}'; default: return 0; } } char openerOf(char closer) { switch (closer) { case ')': return '('; case ']': return '['; case '}': return '{'; default: return 0; } } } IndentStyle text::detectIndentation(const Document& document, IndentStyle fallback) { size_t tabLines = 0; size_t spaceLines = 0; size_t steps[9] = {}; size_t previousSpaces = 0; const size_t lines = std::min(document.lineCount(), 2000); for (size_t line = 0; line < lines; line++) { const size_t start = document.lineStart(line); const size_t end = document.lineEnd(line); if (start == end) continue; if (document.at(start) == '\t') { tabLines++; continue; } size_t spaces = 0; while (start + spaces < end && document.at(start + spaces) == ' ') spaces++; // A line of only spaces says nothing about how code is indented. if (start + spaces == end) continue; if (spaces) spaceLines++; const size_t step = spaces > previousSpaces ? spaces - previousSpaces : previousSpaces - spaces; if (step >= 1 && step <= 8) steps[step]++; previousSpaces = spaces; } if (!tabLines && !spaceLines) return fallback; IndentStyle style = fallback; style.insertSpaces = spaceLines >= tabLines; if (style.insertSpaces) { size_t best = 0; for (size_t step = 2; step <= 8; step++) { if (steps[step] > steps[best]) best = step; } if (best) style.tabSize = best; } return style; } // ---------------------- Construction ---------------------- // Editor::Editor(Document& document, EditorOptions options) : mDocument(document), mOptions(std::move(options)) { mCursors.push_back({ Selection(0) }); mListener = mDocument.addListener([this](const DocumentChange& change) { documentChanged(change); }); } Editor::~Editor() { mDocument.removeListener(mListener); } // ---------------------- Cursors ---------------------- // size_t Editor::clamped(size_t offset) const { return utf8::alignToBoundary(mDocument.buffer(), std::min(offset, mDocument.size())); } Selection Editor::clamped(Selection selection) const { return { clamped(selection.anchor), clamped(selection.caret) }; } std::vector Editor::selections() const { std::vector out; out.reserve(mCursors.size()); for (const Cursor& cursor : mCursors) out.push_back(cursor.selection); return out; } bool Editor::hasSelection() const { return std::any_of(mCursors.begin(), mCursors.end(), [](const Cursor& cursor) { return !cursor.selection.empty(); }); } void Editor::normalize() { if (mCursors.empty()) mCursors.push_back({ Selection(0) }); if (mCursors.size() == 1) { mPrimary = 0; return; } struct Tagged { Cursor cursor; bool primary = false; }; std::vector tagged; tagged.reserve(mCursors.size()); for (size_t index = 0; index < mCursors.size(); index++) tagged.push_back({ mCursors[index], index == mPrimary }); std::stable_sort(tagged.begin(), tagged.end(), [](const Tagged& a, const Tagged& b) { const Selection& left = a.cursor.selection; const Selection& right = b.cursor.selection; return left.start() != right.start() ? left.start() < right.start() : left.end() < right.end(); }); std::vector out; for (Tagged& next : tagged) { if (!out.empty()) { Selection& kept = out.back().cursor.selection; const Selection& added = next.cursor.selection; // Cursors that overlap, or touch with one of them empty, are one cursor. const bool touches = added.start() == kept.end() && (added.empty() || kept.empty()); if (added.start() < kept.end() || touches) { const size_t start = kept.start(); const size_t end = std::max(kept.end(), added.end()); const bool reversed = next.primary ? added.reversed() : kept.reversed(); kept = reversed ? Selection(end, start) : Selection(start, end); if (next.primary) { out.back().primary = true; out.back().cursor.preferredColumn = next.cursor.preferredColumn; } continue; } } out.push_back(std::move(next)); } mCursors.clear(); mPrimary = 0; for (size_t index = 0; index < out.size(); index++) { if (out[index].primary) mPrimary = index; mCursors.push_back(out[index].cursor); } } void Editor::setCursors(const std::vector& selections, size_t primary) { mCursors.clear(); for (const Selection& selection : selections) mCursors.push_back({ clamped(selection) }); mPrimary = mCursors.empty() ? 0 : std::min(primary, mCursors.size() - 1); normalize(); } void Editor::forgetTypingState() { mLastKind = EditKind::Other; mAutoClosed.clear(); mOccurrenceWholeWord = false; } void Editor::setSelection(Selection selection) { setCursors({ selection }, 0); forgetTypingState(); } void Editor::setSelections(const std::vector& selections, size_t primary) { setCursors(selections, primary); forgetTypingState(); } void Editor::setCaret(size_t offset, bool extend) { setSelection(extend ? Selection(selection().anchor, offset) : Selection(offset)); } void Editor::addCursor(Selection selection) { mCursors.push_back({ clamped(selection) }); mPrimary = mCursors.size() - 1; normalize(); forgetTypingState(); } void Editor::collapseToPrimary() { const Cursor primary = mCursors[mPrimary]; mCursors.assign(1, primary); mPrimary = 0; forgetTypingState(); } void Editor::setColumnSelection(Position from, Position to) { const size_t tabSize = mOptions.tabSize; const size_t lastLine = mDocument.lineCount() - 1; from.line = std::min(from.line, lastLine); to.line = std::min(to.line, lastLine); const size_t fromVisible = utf8::visibleColumn(mDocument.line(from.line), from.column, tabSize); const size_t toVisible = utf8::visibleColumn(mDocument.line(to.line), to.column, tabSize); std::vector selections; size_t primary = 0; for (size_t line = std::min(from.line, to.line); line <= std::max(from.line, to.line); line++) { const std::string text = mDocument.line(line); const size_t start = mDocument.lineStart(line); if (line == to.line) primary = selections.size(); selections.emplace_back( start + utf8::columnAtVisible(text, fromVisible, tabSize), start + utf8::columnAtVisible(text, toVisible, tabSize) ); } setCursors(selections, primary); forgetTypingState(); } // ---------------------- Motion ---------------------- // size_t Editor::firstNonBlank(size_t line) const { const size_t end = mDocument.lineEnd(line); size_t offset = mDocument.lineStart(line); while (offset < end && isBlank(mDocument.at(offset))) offset++; return offset; } size_t Editor::wordLeft(size_t from) const { const PieceTree& text = mDocument.buffer(); if (from == 0) return 0; const size_t lineStart = text.lineStart(text.lineOf(from)); // At the start of a line the previous word is the end of the line above. if (from == lineStart) return from - 1; const auto classBefore = [&](size_t offset) { return utf8::classify(utf8::codePointAt(text, utf8::previousCodePoint(text, offset)), mOptions.wordSeparators); }; size_t offset = from; while (offset > lineStart && classBefore(offset) == utf8::CharClass::Whitespace) offset = utf8::previousCodePoint(text, offset); if (offset == lineStart) return lineStart; const utf8::CharClass run = classBefore(offset); while (offset > lineStart && classBefore(offset) == run) offset = utf8::previousCodePoint(text, offset); return offset; } size_t Editor::wordRight(size_t from) const { const PieceTree& text = mDocument.buffer(); if (from >= text.size()) return text.size(); const size_t lineEnd = text.lineEnd(text.lineOf(from)); if (from == lineEnd) return from + 1; const auto classAt = [&](size_t offset) { return utf8::classify(utf8::codePointAt(text, offset), mOptions.wordSeparators); }; size_t offset = from; while (offset < lineEnd && classAt(offset) == utf8::CharClass::Whitespace) offset = utf8::nextCodePoint(text, offset); if (offset == lineEnd) return lineEnd; const utf8::CharClass run = classAt(offset); while (offset < lineEnd && classAt(offset) == run) offset = utf8::nextCodePoint(text, offset); return offset; } size_t Editor::verticalTarget(Cursor& cursor, long lines) const { const Position position = mDocument.positionAt(cursor.selection.caret); if (cursor.preferredColumn == kNoPosition) { cursor.preferredColumn = utf8::visibleColumn(mDocument.line(position.line), position.column, mOptions.tabSize); } const long wanted = long(position.line) + lines; if (wanted < 0) return 0; if (wanted >= long(mDocument.lineCount())) return mDocument.size(); const std::string text = mDocument.line(size_t(wanted)); return mDocument.lineStart(size_t(wanted)) + utf8::columnAtVisible(text, cursor.preferredColumn, mOptions.tabSize); } size_t Editor::moved(Cursor& cursor, Motion motion) const { const PieceTree& text = mDocument.buffer(); const size_t from = cursor.selection.caret; if (motion == Motion::Up) return verticalTarget(cursor, -1); if (motion == Motion::Down) return verticalTarget(cursor, 1); cursor.preferredColumn = kNoPosition; switch (motion) { case Motion::Left: return utf8::previousBoundary(text, from); case Motion::Right: return utf8::nextBoundary(text, from); case Motion::WordLeft: return wordLeft(from); case Motion::WordRight: return wordRight(from); case Motion::LineStart: return text.lineStart(text.lineOf(from)); case Motion::SmartLineStart: { const size_t line = text.lineOf(from); const size_t indented = firstNonBlank(line); return from == indented ? text.lineStart(line) : indented; } case Motion::LineEnd: return text.lineEnd(text.lineOf(from)); case Motion::DocumentStart: return 0; case Motion::DocumentEnd: return text.size(); default: return from; } } size_t Editor::target(Motion motion, size_t from) const { Cursor cursor{ Selection(clamped(from)) }; return moved(cursor, motion); } void Editor::move(Motion motion, bool extend, size_t count) { for (Cursor& cursor : mCursors) { for (size_t step = 0; step < count; step++) { Selection& selection = cursor.selection; // Left and Right over a selection only collapse it to that side. if (step == 0 && !extend && !selection.empty() && (motion == Motion::Left || motion == Motion::Right)) { selection = Selection(motion == Motion::Left ? selection.start() : selection.end()); cursor.preferredColumn = kNoPosition; continue; } const size_t caret = moved(cursor, motion); selection = extend ? Selection(selection.anchor, caret) : Selection(caret); } } normalize(); forgetTypingState(); } void Editor::selectAll() { setSelection({ 0, mDocument.size() }); } Range Editor::wordAt(size_t offset) const { const PieceTree& text = mDocument.buffer(); offset = clamped(offset); const size_t line = text.lineOf(offset); const size_t lineStart = text.lineStart(line); const size_t lineEnd = text.lineEnd(line); if (lineStart == lineEnd) return { offset, offset }; const auto classAt = [&](size_t at) { return utf8::classify(utf8::codePointAt(text, at), mOptions.wordSeparators); }; // The run under the offset; a word that ends right at the offset wins over the punctuation or space after it. size_t probe = offset; if (offset == lineEnd) { probe = utf8::previousCodePoint(text, offset); } else if (offset > lineStart && classAt(offset) != utf8::CharClass::Word) { const utf8::CharClass before = classAt(utf8::previousCodePoint(text, offset)); const bool wordBefore = before == utf8::CharClass::Word; const bool textBeforeSpace = classAt(offset) == utf8::CharClass::Whitespace && before != utf8::CharClass::Whitespace; if (wordBefore || textBeforeSpace) probe = utf8::previousCodePoint(text, offset); } const utf8::CharClass run = classAt(probe); size_t start = probe; while (start > lineStart && classAt(utf8::previousCodePoint(text, start)) == run) start = utf8::previousCodePoint(text, start); size_t end = utf8::nextCodePoint(text, probe); while (end < lineEnd && classAt(end) == run) end = utf8::nextCodePoint(text, end); return { start, end }; } void Editor::selectWordAt(size_t offset) { const Range word = wordAt(offset); setSelection({ word.start, word.end }); } void Editor::selectLineAt(size_t offset) { const size_t line = mDocument.lineOf(clamped(offset)); setSelection({ mDocument.lineStart(line), mDocument.lineEnd(line) }); } void Editor::expandToLines() { for (Cursor& cursor : mCursors) { const size_t first = mDocument.lineOf(cursor.selection.start()); const size_t last = mDocument.lineOf(cursor.selection.end()); cursor.selection = Selection(mDocument.lineStart(first), mDocument.lineStart(last + 1)); cursor.preferredColumn = kNoPosition; } normalize(); forgetTypingState(); } void Editor::addCursorAbove() { std::vector added; for (const Cursor& cursor : mCursors) { if (mDocument.lineOf(cursor.selection.caret) == 0) continue; Cursor above{ Selection(cursor.selection.caret), cursor.preferredColumn }; above.selection = Selection(verticalTarget(above, -1)); added.push_back(above); } mCursors.insert(mCursors.end(), added.begin(), added.end()); normalize(); forgetTypingState(); } void Editor::addCursorBelow() { std::vector added; for (const Cursor& cursor : mCursors) { if (mDocument.lineOf(cursor.selection.caret) + 1 >= mDocument.lineCount()) continue; Cursor below{ Selection(cursor.selection.caret), cursor.preferredColumn }; below.selection = Selection(verticalTarget(below, 1)); added.push_back(below); } mCursors.insert(mCursors.end(), added.begin(), added.end()); normalize(); forgetTypingState(); } bool Editor::addNextOccurrence() { // The first press only turns carets into word selections; the following ones add matches. const bool anyEmpty = std::any_of(mCursors.begin(), mCursors.end(), [](const Cursor& cursor) { return cursor.selection.empty(); }); if (anyEmpty) { bool changed = false; for (Cursor& cursor : mCursors) { if (!cursor.selection.empty()) continue; const Range word = wordAt(cursor.selection.caret); if (word.empty()) continue; cursor.selection = Selection(word.start, word.end); changed = true; } normalize(); mLastKind = EditKind::Other; mAutoClosed.clear(); mOccurrenceWholeWord = changed; return changed; } const Selection current = selection(); SearchOptions options; options.caseSensitive = true; options.wholeWord = mOccurrenceWholeWord; options.wordSeparators = mOptions.wordSeparators; const TextSearch search(mDocument.substr(current.range()), options); size_t from = current.end(); for (size_t attempt = 0; attempt <= mCursors.size(); attempt++) { const std::optional match = search.next(mDocument.buffer(), from, true); if (!match) return false; const bool taken = std::any_of(mCursors.begin(), mCursors.end(), [&](const Cursor& cursor) { return cursor.selection.range() == *match; }); if (!taken) { mCursors.push_back({ Selection(match->start, match->end) }); mPrimary = mCursors.size() - 1; normalize(); return true; } from = match->end; } return false; } bool Editor::selectAllOccurrences() { Selection current = selection(); bool wholeWord = mOccurrenceWholeWord; if (current.empty()) { const Range word = wordAt(current.caret); if (word.empty()) return false; current = Selection(word.start, word.end); wholeWord = true; } SearchOptions options; options.caseSensitive = true; options.wholeWord = wholeWord; options.wordSeparators = mOptions.wordSeparators; const std::vector matches = TextSearch(mDocument.substr(current.range()), options).all(mDocument.buffer()); if (matches.empty()) return false; std::vector selections; size_t primary = 0; for (const Range& match : matches) { if (match == current.range()) primary = selections.size(); selections.emplace_back(match.start, match.end); } setCursors(selections, primary); mLastKind = EditKind::Other; mAutoClosed.clear(); mOccurrenceWholeWord = wholeWord; return true; } std::optional Editor::matchingBracket(size_t offset) const { const PieceTree& text = mDocument.buffer(); offset = std::min(offset, text.size()); // The bracket under the offset wins over the one before it. size_t at = kNoPosition; if (offset < text.size() && (closerOf(text.at(offset)) || openerOf(text.at(offset)))) at = offset; else if (offset > 0 && (closerOf(text.at(offset - 1)) || openerOf(text.at(offset - 1)))) at = offset - 1; if (at == kNoPosition) return std::nullopt; const char bracket = text.at(at); size_t depth = 0; if (const char closer = closerOf(bracket)) { for (size_t scan = at; scan < text.size(); scan++) { const char byte = text.at(scan); if (byte == bracket) depth++; else if (byte == closer && --depth == 0) return scan; } return std::nullopt; } const char opener = openerOf(bracket); for (size_t scan = at + 1; scan-- > 0;) { const char byte = text.at(scan); if (byte == bracket) depth++; else if (byte == opener && --depth == 0) return scan; } return std::nullopt; } bool Editor::jumpToMatchingBracket(bool extend) { bool moved = false; for (Cursor& cursor : mCursors) { const std::optional partner = matchingBracket(cursor.selection.caret); if (!partner) continue; cursor.selection = extend ? Selection(cursor.selection.anchor, *partner) : Selection(*partner); cursor.preferredColumn = kNoPosition; moved = true; } normalize(); forgetTypingState(); return moved; } // ---------------------- Committing edits ---------------------- // UndoMode Editor::undoModeFor(EditKind kind) const { const auto typing = [](EditKind value) { return value == EditKind::Typing || value == EditKind::TypingFirstSpace || value == EditKind::TypingMoreSpaces; }; const auto spaces = [](EditKind value) { return value == EditKind::TypingFirstSpace || value == EditKind::TypingMoreSpaces; }; if (typing(kind)) { if (!typing(mLastKind)) return UndoMode::NewStep; if (!mOptions.typingUndoByWord) return UndoMode::MergeWithLast; // A word and the space after it part ways; the space and the next word stay together, so undo walks // back word by word. if (mLastKind == EditKind::TypingFirstSpace) return UndoMode::MergeWithLast; return spaces(mLastKind) == spaces(kind) ? UndoMode::MergeWithLast : UndoMode::NewStep; } if (kind == EditKind::EraseLeft || kind == EditKind::EraseRight) { return mLastKind == kind ? UndoMode::MergeWithLast : UndoMode::NewStep; } return UndoMode::NewStep; } bool Editor::commit(std::vector edits, EditKind kind, const Placement& place) { const std::vector before = selections(); const size_t version = mDocument.version(); const size_t primary = mPrimary; mApplying = true; const std::vector results = mDocument.apply(std::move(edits), undoModeFor(kind)); mApplying = false; const bool changed = mDocument.version() != version; setCursors(place(results), primary); if (changed) { mDocument.annotateStep(before, selections()); mLastKind = kind; } const bool typing = kind != EditKind::Other; if (!typing) mAutoClosed.clear(); mOccurrenceWholeWord = false; return changed; } bool Editor::commitFollowing(std::vector edits, EditKind kind, Bias caretBias) { edits = merged(std::move(edits)); const std::vector changes = changesOf(edits); const std::vector before = selections(); return commit(std::move(edits), kind, [&](const std::vector&) { std::vector after; after.reserve(before.size()); for (const Selection& selection : before) { if (selection.empty()) { after.emplace_back(mapThrough(selection.caret, changes, caretBias)); continue; } // Text inserted at the edges of a selection stays inside it, as indenting selected lines shows. const size_t start = mapThrough(selection.start(), changes, Bias::Before); const size_t end = std::max(start, mapThrough(selection.end(), changes, Bias::After)); after.push_back(selection.reversed() ? Selection(end, start) : Selection(start, end)); } return after; }); } void Editor::documentChanged(const DocumentChange& change) { if (change.reason == DocumentChange::Reason::Reset) { for (Cursor& cursor : mCursors) { cursor.selection = clamped(cursor.selection); cursor.preferredColumn = kNoPosition; } normalize(); forgetTypingState(); return; } for (const TextChange& one : change.changes) { for (size_t& closer : mAutoClosed) closer = transformOffset(closer, one, Bias::After); if (mApplying) continue; // Somebody else edited the document (another editor of it, undo, a program): the cursors keep their // place in the text. for (Cursor& cursor : mCursors) { Selection& selection = cursor.selection; if (selection.empty()) { selection = Selection(transformOffset(selection.caret, one, Bias::After)); } else { const size_t start = transformOffset(selection.start(), one, Bias::After); const size_t end = std::max(start, transformOffset(selection.end(), one, Bias::Before)); selection = selection.reversed() ? Selection(end, start) : Selection(start, end); } cursor.preferredColumn = kNoPosition; } } if (mApplying) return; normalize(); mLastKind = EditKind::Other; } bool Editor::undo() { std::vector restored; if (!mDocument.undo(&restored)) return false; if (!restored.empty()) setCursors(restored, mPrimary); forgetTypingState(); return true; } bool Editor::redo() { std::vector restored; if (!mDocument.redo(&restored)) return false; if (!restored.empty()) setCursors(restored, mPrimary); forgetTypingState(); return true; } void Editor::pushUndoStop() { mDocument.pushUndoStop(); mLastKind = EditKind::Other; } // ---------------------- Typing ---------------------- // std::string Editor::accepted(std::string_view text, size_t replacedBytes, size_t cursorCount) const { std::string input = mOptions.inputFilter ? mOptions.inputFilter(text) : std::string(text); normalizeLineBreaks(input); if (!mOptions.multiLine) std::erase(input, '\n'); if (mOptions.maximumLength) { const size_t kept = mDocument.size() - std::min(replacedBytes, mDocument.size()); const size_t room = mOptions.maximumLength > kept ? mOptions.maximumLength - kept : 0; const size_t share = room / std::max(1, cursorCount); if (input.size() > share) input.resize(utf8::alignDown(std::string_view(input), share)); } return input; } const std::pair* Editor::pairOpenedBy(std::string_view text) const { for (const auto& pair : mOptions.pairs) { if (pair.first == text) return &pair; } return nullptr; } bool Editor::isCloser(std::string_view text) const { return std::any_of(mOptions.pairs.begin(), mOptions.pairs.end(), [&](const auto& pair) { return pair.second == text; }); } bool Editor::type(std::string_view text) { size_t selected = 0; for (const Cursor& cursor : mCursors) selected += cursor.selection.range().length(); const std::string input = accepted(text, selected, mCursors.size()); if (input.empty()) return false; const PieceTree& buffer = mDocument.buffer(); const bool allEmpty = !hasSelection(); if (mOptions.autoClosePairs) { // Typing the closer this editor added a moment ago steps over it instead of doubling it. const bool overtypes = allEmpty && isCloser(input) && std::all_of(mCursors.begin(), mCursors.end(), [&](const Cursor& cursor) { const size_t caret = cursor.selection.caret; return std::find(mAutoClosed.begin(), mAutoClosed.end(), caret) != mAutoClosed.end() && buffer.substr(caret, input.size()) == input; }); if (overtypes) { for (Cursor& cursor : mCursors) { std::erase(mAutoClosed, cursor.selection.caret); cursor.selection = Selection(cursor.selection.caret + input.size()); } normalize(); return false; } if (const auto* pair = pairOpenedBy(input)) { if (!allEmpty) { // With text selected the pair wraps it and the text stays selected. std::vector edits; for (const Cursor& cursor : mCursors) { const Range range = cursor.selection.range(); edits.push_back({ range, pair->first + (range.empty() ? std::string() : mDocument.substr(range)) + pair->second }); } const std::vector before = selections(); return commit(std::move(edits), EditKind::Other, [&](const std::vector& results) { std::vector after; for (size_t index = 0; index < results.size(); index++) { const size_t start = results[index].start + pair->first.size(); const size_t end = results[index].end - pair->second.size(); after.push_back(before[index].reversed() ? Selection(end, start) : Selection(start, end)); } return after; }); } const bool closes = std::all_of(mCursors.begin(), mCursors.end(), [&](const Cursor& cursor) { const size_t caret = cursor.selection.caret; // Only where a closer would not glue onto following text. if (caret < buffer.size()) { const char next = buffer.at(caret); const bool roomAfter = next == ' ' || next == '\t' || next == '\n' || next == ',' || next == ';' || next == '.' || next == ':' || isCloser(std::string_view(&next, 1)); if (!roomAfter) return false; } if (pair->first != pair->second || caret == 0) return true; // A quote right after a word is an apostrophe or the end of a string, not the start of one. const size_t before = utf8::previousCodePoint(buffer, caret); return utf8::classify(utf8::codePointAt(buffer, before), mOptions.wordSeparators) != utf8::CharClass::Word && buffer.substr(before, caret - before) != pair->first; }); if (closes) { std::vector edits; for (const Cursor& cursor : mCursors) edits.push_back({ cursor.selection.range(), pair->first + pair->second }); const bool changed = commit(std::move(edits), EditKind::Typing, [&](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.start + pair->first.size()); return after; }); for (const Cursor& cursor : mCursors) mAutoClosed.push_back(cursor.selection.caret); return changed; } } } EditKind kind = EditKind::Typing; if (input == " ") { const bool afterSpace = mLastKind == EditKind::TypingFirstSpace || mLastKind == EditKind::TypingMoreSpaces; kind = afterSpace ? EditKind::TypingMoreSpaces : EditKind::TypingFirstSpace; } // Typing over a selection replaces it, and that replacement is a step of its own. if (!allEmpty) pushUndoStop(); std::vector edits; for (const Cursor& cursor : mCursors) edits.push_back({ cursor.selection.range(), input }); return commit(std::move(edits), kind, [](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.end); return after; }); } bool Editor::insert(std::string_view text) { size_t selected = 0; for (const Cursor& cursor : mCursors) selected += cursor.selection.range().length(); // Text copied from several cursors goes back one line per cursor. const std::string whole = accepted(text, selected, 1); std::vector lines; if (mCursors.size() > 1) lines = splitLines(whole); const bool distributes = lines.size() == mCursors.size() && mCursors.size() > 1; std::vector edits; if (distributes) { for (size_t index = 0; index < mCursors.size(); index++) edits.push_back({ mCursors[index].selection.range(), std::string(lines[index]) }); } else { const std::string each = mCursors.size() > 1 ? accepted(text, selected, mCursors.size()) : whole; for (const Cursor& cursor : mCursors) edits.push_back({ cursor.selection.range(), each }); } return commit(std::move(edits), EditKind::Other, [](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.end); return after; }); } std::string Editor::indentUnit() const { return mOptions.insertSpaces ? std::string(std::max(1, mOptions.tabSize), ' ') : std::string("\t"); } std::string Editor::leadingWhitespace(size_t line, size_t upTo) const { const size_t start = mDocument.lineStart(line); const size_t end = std::min(firstNonBlank(line), upTo); return end > start ? mDocument.substr(start, end - start) : std::string(); } bool Editor::newLine() { if (!mOptions.multiLine) return false; const PieceTree& buffer = mDocument.buffer(); std::vector edits; // How far before the end of each inserted text its caret goes. std::vector tails; for (const Cursor& cursor : mCursors) { const Range range = cursor.selection.range(); const std::string indentation = mOptions.autoIndent ? leadingWhitespace(buffer.lineOf(range.start), range.start) : std::string(); std::string text = "\n" + indentation; size_t tail = 0; // Enter between a bracket pair opens an indented line between them. const bool betweenPair = mOptions.autoIndent && range.start > 0 && range.end < buffer.size() && closerOf(buffer.at(range.start - 1)) && closerOf(buffer.at(range.start - 1)) == buffer.at(range.end); if (betweenPair) { text += indentUnit(); tail = 1 + indentation.size(); text += "\n" + indentation; } edits.push_back({ range, std::move(text) }); tails.push_back(tail); } return commit(std::move(edits), EditKind::Other, [&](const std::vector& results) { std::vector after; for (size_t index = 0; index < results.size(); index++) after.emplace_back(results[index].end - tails[index]); return after; }); } // ---------------------- Erasing ---------------------- // bool Editor::erase(Motion towards) { const PieceTree& buffer = mDocument.buffer(); const bool allEmpty = !hasSelection(); std::vector edits; for (const Cursor& cursor : mCursors) { const Selection& selection = cursor.selection; if (!selection.empty()) { edits.push_back({ selection.range(), {} }); continue; } const size_t caret = selection.caret; Range range{ caret, caret }; Cursor probe = cursor; const size_t other = moved(probe, towards); range = { std::min(caret, other), std::max(caret, other) }; if (towards == Motion::Left && caret > 0) { const size_t lineStart = buffer.lineStart(buffer.lineOf(caret)); // A pair this editor just closed goes away as one. const bool pairHere = mOptions.autoClosePairs && caret < buffer.size() && std::find(mAutoClosed.begin(), mAutoClosed.end(), caret) != mAutoClosed.end(); if (pairHere) { const auto* pair = pairOpenedBy(buffer.substr(range.start, range.length())); if (pair && buffer.substr(caret, pair->second.size()) == pair->second) range.end = caret + pair->second.size(); } // Inside the indentation, spaces go back to the previous tab stop. const bool inIndentation = mOptions.useTabStops && mOptions.insertSpaces && mOptions.tabSize > 1 && caret > lineStart && firstNonBlank(buffer.lineOf(caret)) >= caret; if (inIndentation) { const size_t column = caret - lineStart; size_t spaces = column % mOptions.tabSize ? column % mOptions.tabSize : mOptions.tabSize; size_t start = caret; while (spaces > 0 && start > lineStart && buffer.at(start - 1) == ' ') { start--; spaces--; } if (start < caret) range = { start, std::max(range.end, caret) }; } } if (!range.empty()) edits.push_back({ range, {} }); } if (edits.empty()) return false; EditKind kind = EditKind::Other; if (allEmpty && towards == Motion::Left) kind = EditKind::EraseLeft; if (allEmpty && towards == Motion::Right) kind = EditKind::EraseRight; return commitFollowing(std::move(edits), kind); } bool Editor::eraseSelections() { std::vector edits; for (const Cursor& cursor : mCursors) { if (!cursor.selection.empty()) edits.push_back({ cursor.selection.range(), {} }); } return !edits.empty() && commitFollowing(std::move(edits)); } // ---------------------- Lines ---------------------- // auto Editor::lineBlocks() const -> std::vector { std::vector blocks; for (const Cursor& cursor : mCursors) { const Selection& selection = cursor.selection; const size_t first = mDocument.lineOf(selection.start()); size_t last = mDocument.lineOf(selection.end()); // A selection that ends at the very start of a line does not take that line. if (last > first && selection.end() == mDocument.lineStart(last)) last--; if (!blocks.empty() && first <= blocks.back().last + 1) blocks.back().last = std::max(blocks.back().last, last); else blocks.push_back({ first, last }); } return blocks; } size_t Editor::blockOf(const std::vector& blocks, size_t line) const { for (size_t index = 0; index < blocks.size(); index++) { if (line >= blocks[index].first && line <= blocks[index].last) return index; } return 0; } bool Editor::deleteLines() { const std::vector blocks = lineBlocks(); const size_t lineCount = mDocument.lineCount(); std::vector edits; for (const LineBlock& block : blocks) { Range range; if (block.last + 1 < lineCount) range = { mDocument.lineStart(block.first), mDocument.lineStart(block.last + 1) }; else if (block.first > 0) range = { mDocument.lineEnd(block.first - 1), mDocument.size() }; else range = { 0, mDocument.size() }; edits.push_back({ range, {} }); } // Each caret keeps its column on the line that moves up into its place. struct Landing { size_t line = 0; size_t column = 0; }; std::vector landings; for (const Cursor& cursor : mCursors) { const Position position = mDocument.positionAt(cursor.selection.caret); const size_t block = blockOf(blocks, mDocument.lineOf(cursor.selection.start())); size_t removedBefore = 0; for (size_t index = 0; index < block; index++) removedBefore += blocks[index].last - blocks[index].first + 1; landings.push_back({ blocks[block].first - removedBefore, position.column }); } return commit(std::move(edits), EditKind::Other, [&](const std::vector&) { std::vector after; for (const Landing& landing : landings) { const size_t line = std::min(landing.line, mDocument.lineCount() - 1); after.emplace_back(mDocument.offsetAt({ line, landing.column })); } return after; }); } bool Editor::tab() { const bool spansLines = std::any_of(mCursors.begin(), mCursors.end(), [&](const Cursor& cursor) { return mDocument.lineOf(cursor.selection.start()) != mDocument.lineOf(cursor.selection.end()); }); if (spansLines) return indent(); std::vector edits; for (const Cursor& cursor : mCursors) { const Range range = cursor.selection.range(); std::string text = "\t"; if (mOptions.insertSpaces) { const Position position = mDocument.positionAt(range.start); const size_t tabSize = std::max(1, mOptions.tabSize); const size_t column = utf8::visibleColumn(mDocument.line(position.line), position.column, tabSize); text.assign(tabSize - column % tabSize, ' '); } edits.push_back({ range, std::move(text) }); } return commit(std::move(edits), EditKind::Other, [](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.end); return after; }); } bool Editor::indent() { const std::string unit = indentUnit(); std::vector edits; for (const LineBlock& block : lineBlocks()) { for (size_t line = block.first; line <= block.last; line++) { const size_t start = mDocument.lineStart(line); // Blank lines stay blank, unless the caret sits alone on one. if (start == mDocument.lineEnd(line) && block.first != block.last) continue; edits.push_back({ { start, start }, unit }); } } return !edits.empty() && commitFollowing(std::move(edits)); } bool Editor::outdent() { const size_t tabSize = std::max(1, mOptions.tabSize); std::vector edits; for (const LineBlock& block : lineBlocks()) { for (size_t line = block.first; line <= block.last; line++) { const size_t start = mDocument.lineStart(line); const size_t end = mDocument.lineEnd(line); if (start == end) continue; size_t remove = 0; if (mDocument.at(start) == '\t') { remove = 1; } else { size_t spaces = 0; while (start + spaces < end && mDocument.at(start + spaces) == ' ') spaces++; // Back to the previous tab stop, which is a full step only from a tab stop. if (spaces) remove = spaces % tabSize ? spaces % tabSize : tabSize; } if (remove) edits.push_back({ { start, start + remove }, {} }); } } return !edits.empty() && commitFollowing(std::move(edits)); } bool Editor::moveLines(int direction) { if (!direction) return false; const std::vector blocks = lineBlocks(); const size_t lineCount = mDocument.lineCount(); std::vector edits; std::vector shifts(blocks.size(), 0); for (size_t index = 0; index < blocks.size(); index++) { const LineBlock& block = blocks[index]; const size_t start = mDocument.lineStart(block.first); const size_t end = mDocument.lineEnd(block.last); const std::string lines = mDocument.substr(start, end - start); if (direction < 0) { if (block.first == 0) continue; const std::string above = mDocument.line(block.first - 1); edits.push_back({ { mDocument.lineStart(block.first - 1), end }, lines + "\n" + above }); shifts[index] = -(long long) (above.size() + 1); } else { if (block.last + 1 >= lineCount) continue; const std::string below = mDocument.line(block.last + 1); edits.push_back({ { start, mDocument.lineEnd(block.last + 1) }, below + "\n" + lines }); shifts[index] = (long long) (below.size() + 1); } } if (edits.empty()) return false; // The moved lines carry their selections along. std::vector after; for (const Cursor& cursor : mCursors) { const long long shift = shifts[blockOf(blocks, mDocument.lineOf(cursor.selection.start()))]; after.emplace_back(size_t((long long) cursor.selection.anchor + shift), size_t((long long) cursor.selection.caret + shift)); } return commit(std::move(edits), EditKind::Other, [&](const std::vector&) { return after; }); } bool Editor::copyLines(int direction) { if (!direction) return false; const std::vector blocks = lineBlocks(); std::vector edits; std::vector lengths; for (const LineBlock& block : blocks) { const size_t start = mDocument.lineStart(block.first); const size_t end = mDocument.lineEnd(block.last); edits.push_back({ { end, end }, "\n" + mDocument.substr(start, end - start) }); lengths.push_back(end - start + 1); } // Copying down leaves the cursors on the lower copy, copying up on the upper one. std::vector after; for (const Cursor& cursor : mCursors) { const size_t block = blockOf(blocks, mDocument.lineOf(cursor.selection.start())); size_t shift = direction > 0 ? lengths[block] : 0; for (size_t index = 0; index < block; index++) shift += lengths[index]; after.emplace_back(cursor.selection.anchor + shift, cursor.selection.caret + shift); } return commit(std::move(edits), EditKind::Other, [&](const std::vector&) { return after; }); } bool Editor::insertLineBelow() { if (!mOptions.multiLine) return false; std::vector edits; for (const Cursor& cursor : mCursors) { const size_t line = mDocument.lineOf(cursor.selection.caret); const size_t end = mDocument.lineEnd(line); edits.push_back({ { end, end }, "\n" + (mOptions.autoIndent ? leadingWhitespace(line, end) : std::string()) }); } return commit(std::move(edits), EditKind::Other, [](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.end); return after; }); } bool Editor::insertLineAbove() { if (!mOptions.multiLine) return false; std::vector edits; for (const Cursor& cursor : mCursors) { const size_t line = mDocument.lineOf(cursor.selection.caret); const size_t start = mDocument.lineStart(line); const std::string indentation = mOptions.autoIndent ? leadingWhitespace(line, mDocument.lineEnd(line)) : std::string(); edits.push_back({ { start, start }, indentation + "\n" }); } return commit(std::move(edits), EditKind::Other, [](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.end - 1); return after; }); } bool Editor::joinLines() { const size_t lineCount = mDocument.lineCount(); std::vector edits; for (const LineBlock& block : lineBlocks()) { // A caret joins its line with the next; a selection over several lines joins those. const size_t last = block.first == block.last ? block.last + 1 : block.last; if (last >= lineCount) continue; const auto trimmedEnd = [&](size_t line) { const size_t start = mDocument.lineStart(line); size_t end = mDocument.lineEnd(line); while (end > start && isBlank(mDocument.at(end - 1))) end--; return end; }; const size_t from = trimmedEnd(block.first); bool hasText = from > mDocument.lineStart(block.first); std::string joined; for (size_t line = block.first + 1; line <= last; line++) { const size_t start = firstNonBlank(line); const size_t end = trimmedEnd(line); if (end <= start) continue; if (hasText) joined += ' '; joined += mDocument.substr(start, end - start); hasText = true; } edits.push_back({ { from, mDocument.lineEnd(last) }, std::move(joined) }); } // A caret in the joined stretch ends up at the seam. return !edits.empty() && commitFollowing(std::move(edits), EditKind::Other, Bias::Before); } bool Editor::toggleLineComment(std::string_view prefix) { if (prefix.empty()) return false; std::vector edits; for (const LineBlock& block : lineBlocks()) { bool allCommented = true; bool anyText = false; size_t indentation = kNoPosition; for (size_t line = block.first; line <= block.last; line++) { const size_t start = firstNonBlank(line); if (start == mDocument.lineEnd(line)) continue; anyText = true; indentation = std::min(indentation, start - mDocument.lineStart(line)); if (mDocument.substr(start, prefix.size()) != prefix) allCommented = false; } for (size_t line = block.first; line <= block.last; line++) { const size_t lineStart = mDocument.lineStart(line); const size_t start = firstNonBlank(line); const bool blank = start == mDocument.lineEnd(line); if (blank && anyText) continue; if (anyText && allCommented) { size_t length = prefix.size(); if (mDocument.at(start + length) == ' ') length++; edits.push_back({ { start, start + length }, {} }); } else { const size_t at = anyText ? lineStart + indentation : start; edits.push_back({ { at, at }, std::string(prefix) + " " }); } } } return !edits.empty() && commitFollowing(std::move(edits)); } bool Editor::transformCase(LetterCase letterCase) { std::vector edits; for (const Cursor& cursor : mCursors) { const Range range = cursor.selection.empty() ? wordAt(cursor.selection.caret) : cursor.selection.range(); if (range.empty()) continue; const std::string original = mDocument.substr(range); std::string changed = letterCase == LetterCase::Upper ? utf8::toUpper(original) : utf8::toLower(original); if (changed != original) edits.push_back({ range, std::move(changed) }); } if (edits.empty()) return false; // The mapping keeps byte lengths, so the selections stay where they are. const std::vector before = selections(); return commit(merged(std::move(edits)), EditKind::Other, [&](const std::vector&) { return before; }); } bool Editor::sortLines(bool descending) { std::vector blocks = lineBlocks(); if (!hasSelection()) blocks = { { 0, mDocument.lineCount() - 1 } }; std::vector edits; for (const LineBlock& block : blocks) { if (block.first == block.last) continue; std::vector lines; for (size_t line = block.first; line <= block.last; line++) lines.push_back(mDocument.line(line)); std::vector sorted = lines; std::stable_sort(sorted.begin(), sorted.end()); if (descending) std::reverse(sorted.begin(), sorted.end()); if (sorted == lines) continue; std::string text; for (size_t index = 0; index < sorted.size(); index++) text += (index ? "\n" : "") + sorted[index]; edits.push_back({ { mDocument.lineStart(block.first), mDocument.lineEnd(block.last) }, std::move(text) }); } return !edits.empty() && commitFollowing(std::move(edits)); } bool Editor::trimTrailingWhitespace() { std::vector blocks = lineBlocks(); if (!hasSelection()) blocks = { { 0, mDocument.lineCount() - 1 } }; std::vector edits; for (const LineBlock& block : blocks) { for (size_t line = block.first; line <= block.last; line++) { const size_t start = mDocument.lineStart(line); const size_t end = mDocument.lineEnd(line); size_t kept = end; while (kept > start && isBlank(mDocument.at(kept - 1))) kept--; if (kept < end) edits.push_back({ { kept, end }, {} }); } } return !edits.empty() && commitFollowing(std::move(edits)); } bool Editor::transposeCharacters() { const PieceTree& buffer = mDocument.buffer(); std::vector edits; for (const Cursor& cursor : mCursors) { if (!cursor.selection.empty()) continue; // At the end of a line the two characters before the caret trade places. size_t middle = cursor.selection.caret; const size_t line = buffer.lineOf(middle); if (middle == buffer.lineEnd(line)) middle = utf8::previousBoundary(buffer, middle); const size_t start = utf8::previousBoundary(buffer, middle); const size_t end = utf8::nextBoundary(buffer, middle); if (start < buffer.lineStart(line) || start == middle || middle == end || end > buffer.lineEnd(line)) continue; edits.push_back({ { start, end }, buffer.substr(middle, end - middle) + buffer.substr(start, middle - start) }); } if (edits.empty()) return false; return commit(merged(std::move(edits)), EditKind::Other, [](const std::vector& results) { std::vector after; for (const Range& result : results) after.emplace_back(result.end); return after; }); } bool Editor::replaceRange(Range range, std::string_view text) { std::vector edits; edits.push_back({ range, std::string(text) }); return commitFollowing(std::move(edits)); } size_t Editor::replaceAll(const TextSearch& search, std::string_view with, std::optional within) { const PieceTree& buffer = mDocument.buffer(); const std::vector matches = within ? search.all(buffer, *within) : search.all(buffer); if (matches.empty()) return 0; std::vector edits; edits.reserve(matches.size()); for (const Range& match : matches) edits.push_back({ match, search.replacement(buffer, match, with) }); commitFollowing(std::move(edits)); return matches.size(); } // ---------------------- Clipboard ---------------------- // std::string Editor::copyText() const { std::string out; bool first = true; for (const Cursor& cursor : mCursors) { const Selection& selection = cursor.selection; if (selection.empty() && !mOptions.emptySelectionTakesLine) continue; if (!first) out += '\n'; first = false; if (selection.empty()) { out += mDocument.line(mDocument.lineOf(selection.caret)); // The line break marks the text as a whole line; with several cursors the separator already does. if (mCursors.size() == 1) out += '\n'; } else { out += mDocument.substr(selection.range()); } } return out; } bool Editor::cut(std::string& out) { out = copyText(); if (out.empty()) return false; std::vector edits; const size_t lineCount = mDocument.lineCount(); for (const Cursor& cursor : mCursors) { const Selection& selection = cursor.selection; if (!selection.empty()) { edits.push_back({ selection.range(), {} }); continue; } if (!mOptions.emptySelectionTakesLine) continue; const size_t line = mDocument.lineOf(selection.caret); if (line + 1 < lineCount) edits.push_back({ { mDocument.lineStart(line), mDocument.lineStart(line + 1) }, {} }); else if (line > 0) edits.push_back({ { mDocument.lineEnd(line - 1), mDocument.size() }, {} }); else edits.push_back({ { 0, mDocument.size() }, {} }); } return !edits.empty() && commitFollowing(std::move(edits)); }