Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//
// TextViewController+UndoHistory.swift
// TableProEditorKit
//

import AppKit
import TableProTextEngine

// Every step's ranges point into `text`, so the history is only good for that exact text.
public struct EditorUndoHistory {
let history: CEUndoManager.History
public let text: String
}

public extension TextViewController {
func takeUndoHistory() -> EditorUndoHistory? {
guard let textView, let undoManager = textView.editorUndoManager else { return nil }
let history = undoManager.history
guard !history.isEmpty else { return nil }
undoManager.clearStack()
return EditorUndoHistory(history: history, text: textView.string)
}

@discardableResult
func restoreUndoHistory(_ history: EditorUndoHistory) -> Bool {
// Literal equality: the text can be megabytes, and canonical `==` normalizes all of it.
guard let textView, let undoManager = textView.editorUndoManager,
(history.text as NSString).isEqual(to: textView.string) else { return false }
undoManager.restore(history.history)
return true
}

// A whole-document change made by code, as one step Undo takes back. Like Replace All it skips the typing filters
// and the suggestion triggers. The selection stays where it was, clamped, as `setText` leaves it.
func replaceDocumentText(_ text: String) {
guard let textView else { return }
guard textView.isEditable else {
setText(text)
return
}
endSnippetSession()
let selection = textView.selectionManager.textSelections.map(\.range)
textView.undoManager?.beginUndoGrouping()
isApplyingUnfilteredEdits = true
textView.replaceCharacters(
in: NSRange(location: 0, length: textView.textStorage.length),
with: text,
skipUpdateSelection: true
)
isApplyingUnfilteredEdits = false
textView.undoManager?.endUndoGrouping()
textView.selectionManager.setSelectedRanges(selection)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@ public extension SourceEditor {

init(
text: TextAPI,
documentID: AnyHashable? = nil,
editorState: Binding<SourceEditorState>,
highlightProviders: [any HighlightProviding]?,
textCoordinators: [any TextViewCoordinator]
) {
self.textSync = TextBindingSync(text: text, phase: phase)
self.textSync = TextBindingSync(text: text, documentID: documentID, phase: phase)
self._editorState = editorState
self.highlightProviders = highlightProviders ?? [TreeSitterClient()]
self.textCoordinators = textCoordinators
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public struct SourceEditor: NSViewControllerRepresentable {
foldProvider: LineFoldProvider? = nil,
undoManager: CEUndoManager? = nil,
coordinators: [any TextViewCoordinator] = [],
completionDelegate: CodeSuggestionDelegate? = nil
completionDelegate: CodeSuggestionDelegate? = nil,
documentID: AnyHashable? = nil
) {
self.text = .binding(text)
self.language = language
Expand All @@ -50,6 +51,7 @@ public struct SourceEditor: NSViewControllerRepresentable {
self.undoManager = undoManager
self.coordinators = coordinators
self.completionDelegate = completionDelegate
self.documentID = documentID
}

/// Initializes a new source editor
Expand Down Expand Up @@ -96,6 +98,8 @@ public struct SourceEditor: NSViewControllerRepresentable {
var undoManager: CEUndoManager?
var coordinators: [any TextViewCoordinator]
var completionDelegate: CodeSuggestionDelegate?
// While it stays the same, a new binding value is an edit Undo can take back; a new one starts a new history.
var documentID: AnyHashable?

public typealias NSViewControllerType = TextViewController

Expand Down Expand Up @@ -135,6 +139,7 @@ public struct SourceEditor: NSViewControllerRepresentable {
public func makeCoordinator() -> Coordinator {
Coordinator(
text: text,
documentID: documentID,
editorState: $state,
highlightProviders: highlightProviders,
textCoordinators: coordinators
Expand Down Expand Up @@ -166,7 +171,11 @@ public struct SourceEditor: NSViewControllerRepresentable {

coordinator.textSync.text = text
if case .binding(let binding) = text {
coordinator.textSync.applyRepresentableText(binding.wrappedValue, controller: controller)
coordinator.textSync.applyRepresentableText(
binding.wrappedValue,
documentID: documentID,
controller: controller
)
}

if !coordinator.phase.consumePendingEditorChange() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ final class TextBindingSync {

var text: SourceEditor.TextAPI
private(set) var lastSyncedText: String?
private(set) var documentID: AnyHashable?

private let phase: RepresentableSyncPhase
private(set) var writebackTask: Task<Void, Never>?

init(text: SourceEditor.TextAPI, phase: RepresentableSyncPhase) {
init(text: SourceEditor.TextAPI, documentID: AnyHashable? = nil, phase: RepresentableSyncPhase) {
self.text = text
self.documentID = documentID
self.phase = phase
if case .binding(let binding) = text {
lastSyncedText = binding.wrappedValue
Expand Down Expand Up @@ -90,27 +92,29 @@ final class TextBindingSync {
return newText
}

/// Pushes an external binding change down into the text view. The editor's
/// content wins while one of its own edits is still in flight, so user
/// typing is never clobbered by a stale binding snapshot.
///
/// Routes through `TextViewController.setText` on purpose. The text-view
/// level `replaceCharacters` is the user-edit path: it is gated on
/// `isEditable`, runs mutation filters, and fires suggestion triggers,
/// none of which should happen for a programmatic whole-document
/// replacement. The controller-level call also rebuilds the highlighter
/// for the replacement storage; calling the text view directly leaves
/// tree-sitter state for the old document and highlighting never recovers.
func applyRepresentableText(_ newValue: String, controller: TextViewController) {
// The editor's content wins while one of its own edits is in flight. In the same named document a new value is one
// undoable edit; another document, or an owner that names none, gets `setText`: a new history and a highlighter
// rebuilt for the new storage, even when the text is the same.
func applyRepresentableText(
_ newValue: String,
documentID: AnyHashable? = nil,
controller: TextViewController
) {
guard !phase.isEditorChangePending else { return }
let isSameDocument = documentID == self.documentID
self.documentID = documentID
// Compare with NSString literal equality. The text can be multiple megabytes and bridged from NSTextStorage,
// so Swift's canonical `!=` walks the whole string through Unicode normalization on every representable update.
if let lastSyncedText, (newValue as NSString).isEqual(to: lastSyncedText) { return }
if isSameDocument, let lastSyncedText, (newValue as NSString).isEqual(to: lastSyncedText) { return }

writebackTask?.cancel()
writebackTask = nil
phase.applyRepresentableValue {
controller.setText(newValue)
if isSameDocument, documentID != nil {
controller.replaceDocumentText(newValue)
} else {
controller.setText(newValue)
}
}
lastSyncedText = newValue
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,23 @@ import TextStory
/// If needed, the automatic undo grouping can be overridden using the `beginGrouping()` and `endGrouping()` methods.
public class CEUndoManager: UndoManager {
/// Represents a group of mutations that should be treated as one mutation when undoing/redoing.
private struct UndoGroup {
struct UndoGroup {
var mutations: [Mutation]
}

/// A single undo mutation.
private struct Mutation {
struct Mutation {
var mutation: TextMutation
var inverse: TextMutation
}

public struct History {
var undoStack: [UndoGroup]
var redoStack: [UndoGroup]

public var isEmpty: Bool { undoStack.isEmpty && redoStack.isEmpty }
}

private var _isUndoing: Bool = false
private var _isRedoing: Bool = false

Expand Down Expand Up @@ -195,6 +202,18 @@ public class CEUndoManager: UndoManager {
redoStack.removeAll()
}

public var history: History {
History(undoStack: undoStack, redoStack: redoStack)
}

// The next edit starts its own step instead of joining the restored history's last one.
public func restore(_ history: History) {
undoStack = history.undoStack
redoStack = history.redoStack
isGrouping = false
shouldBreakNextGroup = true
}

// MARK: - Mutations

override public func registerUndo(withTarget target: Any, selector: Selector, object anObject: Any?) {
Expand Down
Loading
Loading