Commit 79b6abf507

79b6abf50780b1c1a19da122f679edc90be62c8e

parent: 564370e071

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 04:25 UTC

One editor, several text views

Layout: unified · split

Sources/OrgEditorAppKit/Keys.swift +3 −3
@@ -40,9 +40,9 @@ final class OrgTextView: NSTextView {
4040 }
4141 }
4242 }
43 /// Each editor keeps its own undo history, not the window's.
44 private let ownUndoManager = UndoManager()
45 override var undoManager: UndoManager? { ownUndoManager }
43 /// The editor's undo history, shared by its views, not the window's.
44 var sharedUndoManager = UndoManager()
45 override var undoManager: UndoManager? { sharedUndoManager }
4646 var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
4747 var lineNumberColor = NSColor.tertiaryLabelColor
4848 var currentLineNumberColor = NSColor.labelColor
Sources/OrgEditorAppKit/Modal.swift +1 −1
@@ -388,7 +388,7 @@ extension OrgEditor {
388388 /// A block cursor in normal and visual states, a bar in insert state.
389389 func updateCursor() {
390390 let block = modal && vim.mode != .insert
391 (textView as? OrgTextView)?.blockCursor = block
391 for view in orgTextViews { view.blockCursor = block }
392392 dispatcher.mode = modal ? vim.mode.keymapMode : nil
393393 let state = modal ? vim.mode.rawValue : nil
394394 if state != reportedMode {
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +11 −10
@@ -28,10 +28,12 @@ extension OrgEditor {
2828 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
2929 view.wrapperFolds = Set(wrapperHidden.keys)
3030 updateHiddenAndLayout()
31 orgTextView?.redrawLineNumbers()
32 textView.needsDisplay = true
33 let caret = textView.selectedRange().location
34 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) }
31 redrawViews()
32 for view in textViews {
33 let caret = view.selectedRange().location
34 guard let range = hidden.containing(caret) else { continue }
35 if view === active { setCaret(range.lowerBound - 1) } else { view.setSelectedRange(NSRange(location: max(0, range.lowerBound - 1), length: 0)) }
36 }
3537 }
3638
3739
@@ -70,7 +72,8 @@ extension OrgEditor {
7072 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
7173 /// heading or opening line of a fold, whose fragment draws the fold mark.
7274 func invalidateLayout(lines ranges: [Range<Int>]) {
73 guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return }
75 guard !ranges.isEmpty else { return }
76 let content = textContentStorage
7477 let text = textView.string as NSString
7578 for range in ranges {
7679 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
@@ -78,7 +81,7 @@ extension OrgEditor {
7881 guard let start = content.location(content.documentRange.location, offsetBy: lower),
7982 let end = content.location(start, offsetBy: upper - lower),
8083 let textRange = NSTextRange(location: start, end: end) else { continue }
81 textLayoutManager.invalidateLayout(for: textRange)
84 for layout in layoutManagers { layout.invalidateLayout(for: textRange) }
8285 }
8386 }
8487
@@ -127,8 +130,7 @@ extension OrgEditor {
127130 updateHiddenAndLayout()
128131 restyleOutsideEditing(0..<utf16Length)
129132 }
130 orgTextView?.redrawLineNumbers()
131 textView.needsDisplay = true
133 redrawViews()
132134 let caret = textView.selectedRange().location
133135 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
134136 }
@@ -189,8 +191,7 @@ extension OrgEditor {
189191 return
190192 }
191193 updateHiddenAndLayout()
192 orgTextView?.redrawLineNumbers()
193 textView.needsDisplay = true
194 redrawViews()
194195 if let narrowed {
195196 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
196197 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
Sources/OrgEditorAppKit/OrgEditor+Images.swift +2 −2
@@ -28,9 +28,9 @@ extension OrgEditor {
2828 func refreshImages() {
2929 keepingTopLine {
3030 restyleOutsideEditing(0..<utf16Length)
31 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
31 invalidateAllLayout()
3232 }
33 textView.needsDisplay = true
33 redrawViews()
3434 }
3535
3636 private func loadImage(_ path: String) -> NSImage? {
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift +1 −1
@@ -13,7 +13,7 @@ extension OrgEditor {
1313 shrunk.set(columns, in: table, text: textView.string)
1414 restyleOutsideEditing(table)
1515 invalidateLayout(lines: [table])
16 textView.needsDisplay = true
16 redrawViews()
1717 }
1818
1919 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
Sources/OrgEditorAppKit/OrgEditor.swift +148 −71
@@ -6,9 +6,21 @@ import OrgPresentation
66
77/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
88/// character edit goes through `DocumentState.apply`, and only the affected region is restyled.
9///
10/// The editor is the buffer: text, undo, folds, narrowing, sparse trees and evil state are its,
11/// as they are a buffer's in Emacs. It can show in several text views at once (`addView`),
12/// each with its own caret, scroll position and focus, as windows show a buffer.
913@MainActor
1014public final class OrgEditor: NSObject {
11 public let textView: NSTextView
15 /// The text view commands act on: the one with focus, or the last to have had it.
16 public var textView: NSTextView { active }
17 private(set) var active: OrgTextView
18 /// Every text view on the storage; the first was made with the editor.
19 public private(set) var textViews: [NSTextView] = []
20 var orgTextViews: [OrgTextView] { textViews.compactMap { $0 as? OrgTextView } }
21 var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
22 /// One undo history for the buffer, whichever view edits it.
23 public let undoManager = UndoManager()
1224 public private(set) var document: DocumentState
1325 public internal(set) var view = ViewState()
1426 /// Called with the time from a character edit to restyled text.
@@ -29,7 +41,7 @@ public final class OrgEditor: NSObject {
2941 keepingTopLine {
3042 applyThemeToView()
3143 restyleEverything()
32 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
44 invalidateAllLayout()
3345 }
3446 }
3547 }
@@ -86,73 +98,133 @@ public final class OrgEditor: NSObject {
8698 self.highlighter = highlighter
8799 self.mode = mode
88100 let orgTextView = OrgTextView(usingTextLayoutManager: true)
89 textView = orgTextView
101 active = orgTextView
102 textViews = [orgTextView]
90103 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
91104 super.init()
92 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false }
93 orgTextView.onFocusChange = { [weak self] in
94 guard let self else { return }
95 let id = ObjectIdentifier(self.textLayoutManager)
96 if let window = self.textView.window, window.isKeyWindow, window.firstResponder === self.textView {
105 configure(orgTextView, frame: frame, editable: editable)
106 applyThemeToView()
107 textView.textStorage?.delegate = self
108 textContentStorage.delegate = self
109
110 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
111 load(document.text)
112 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
113 textView.setSelectedRange(NSRange(location: 0, length: 0))
114 if isOrg {
115 let startup = Presentation.startupDisplay(document.tree, options: options)
116 indented = startup.indented
117 hideStars = startup.hideStars
118 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) }
119 shrunk = ShrunkColumns.startup(document.tree)
120 if startup.inlineImages { showsImages = true }
121 if startup.alignTables { _ = perform(AlignAllTables()) }
122 if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) }
123 }
124 spellChecking = options.spellCheck
125 truncatesLines = options.startupTruncated
126 }
127
128 /// A text view's settings and callbacks; the same for every view of the editor.
129 private func configure(_ view: OrgTextView, frame: NSRect, editable: Bool) {
130 view.keyHandler = { [weak self, unowned view] event in
131 guard let self else { return false }
132 self.active = view
133 return self.handleKey(event)
134 }
135 view.onFocusChange = { [weak self, unowned view] in
136 guard let self, let layout = view.textLayoutManager else { return }
137 let id = ObjectIdentifier(layout)
138 if view.window?.firstResponder === view { self.active = view }
139 if let window = view.window, window.isKeyWindow, window.firstResponder === view {
97140 Theme.focusedLayouts.insert(id)
98141 } else {
99142 Theme.focusedLayouts.remove(id)
100143 }
101 self.redrawShaded([self.textView.selectedRange()])
144 self.redrawShaded([view.selectedRange()])
102145 }
103 orgTextView.onCommandClick = { [weak self] offset in
146 view.onCommandClick = { [weak self, unowned view] offset in
104147 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil
105148 || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false }
149 self.active = view
106150 self.setCaret(offset)
107151 self.run("org.link.open")
108152 return true
109153 }
110 orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false }
111 orgTextView.accessibleText = { [weak self] in
154 view.onClick = { [weak self, unowned view] offset in
155 self?.active = view
156 return self?.click(at: offset) ?? false
157 }
158 view.accessibleText = { [weak self] in
112159 guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) }
113160 if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text }
114161 let text = AccessibleText(storage)
115162 self.accessibleCache = (self.storageGeneration, text)
116163 return text
117164 }
118 orgTextView.onMouseDown = { [weak self] in
165 view.onMouseDown = { [weak self, unowned view] in
166 self?.active = view
119167 self?.markActive = false
120168 self?.modalMouseDown()
121169 }
122 textView.usesFindBar = true
123 textView.frame = frame
124 textView.isRichText = false
125 textView.isEditable = editable
126 textView.allowsUndo = true
127 textView.isAutomaticQuoteSubstitutionEnabled = false
128 textView.isAutomaticDashSubstitutionEnabled = false
129 textView.isAutomaticTextReplacementEnabled = false
130 textView.isAutomaticSpellingCorrectionEnabled = false
170 view.sharedUndoManager = undoManager
171 view.usesFindBar = true
172 view.frame = frame
173 view.isRichText = false
174 view.isEditable = editable
175 view.allowsUndo = true
176 view.isAutomaticQuoteSubstitutionEnabled = false
177 view.isAutomaticDashSubstitutionEnabled = false
178 view.isAutomaticTextReplacementEnabled = false
179 view.isAutomaticSpellingCorrectionEnabled = false
180 view.isVerticallyResizable = true
181 view.autoresizingMask = [.width]
182 view.textContainer?.widthTracksTextView = true
183 view.delegate = self
184 view.textLayoutManager?.delegate = self
185 }
186
187 /// Another text view on the same text, with its own layout, caret and scroll position.
188 /// Its layout manager's delegate is set before its first layout, which TextKit needs.
189 public func addView(frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800)) -> NSTextView {
190 let layout = NSTextLayoutManager()
191 layout.delegate = self
192 textContentStorage.addTextLayoutManager(layout)
193 let container = NSTextContainer(size: NSSize(width: frame.width, height: CGFloat.greatestFiniteMagnitude))
194 layout.textContainer = container
195 let view = OrgTextView(frame: frame, textContainer: container)
196 textViews.append(view)
197 configure(view, frame: frame, editable: active.isEditable)
198 view.lineIndex = lines
199 view.showsLineNumbers = showLineNumbers
200 view.isContinuousSpellCheckingEnabled = active.isContinuousSpellCheckingEnabled
201 view.blockCursor = active.blockCursor
131202 applyThemeToView()
132 textView.isVerticallyResizable = true
133 textView.autoresizingMask = [.width]
134 textView.textContainer?.widthTracksTextView = true
135 textView.delegate = self
136 textView.textStorage?.delegate = self
137 textLayoutManager.delegate = self
138 textContentStorage.delegate = self
203 return view
204 }
139205
140 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) }
141 load(document.text)
142 // Files open at their start, as in Emacs; replacing the storage leaves it at the end.
143 textView.setSelectedRange(NSRange(location: 0, length: 0))
144 if isOrg {
145 let startup = Presentation.startupDisplay(document.tree, options: options)
146 indented = startup.indented
147 hideStars = startup.hideStars
148 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) }
149 shrunk = ShrunkColumns.startup(document.tree)
150 if startup.inlineImages { showsImages = true }
151 if startup.alignTables { _ = perform(AlignAllTables()) }
152 if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) }
206 /// Takes a view made by `addView` off the storage. The first view stays.
207 public func removeView(_ view: NSTextView) {
208 guard let index = textViews.firstIndex(where: { $0 === view }), index > 0 else { return }
209 textViews.remove(at: index)
210 if active === view { active = orgTextViews[0] }
211 if let layout = view.textLayoutManager {
212 Theme.focusedLayouts.remove(ObjectIdentifier(layout))
213 textContentStorage.removeTextLayoutManager(layout)
214 }
215 }
216
217 /// Lays every view out again.
218 func invalidateAllLayout() {
219 for layout in layoutManagers { layout.invalidateLayout(for: layout.documentRange) }
220 }
221
222 /// Redraws every view, line numbers included.
223 func redrawViews() {
224 for view in orgTextViews {
225 view.redrawLineNumbers()
226 view.needsDisplay = true
153227 }
154 spellChecking = options.spellCheck
155 truncatesLines = options.startupTruncated
156228 }
157229
158230 /// Replaces the storage's text. Setting the attributed string directly is about 100x
@@ -162,8 +234,10 @@ public final class OrgEditor: NSObject {
162234 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
163235 isLoading = false
164236 lines.reset(text as NSString)
165 orgTextView?.lineIndex = lines
166 orgTextView?.updateGutter()
237 for view in orgTextViews {
238 view.lineIndex = lines
239 view.updateGutter()
240 }
167241 styledUpTo = 0
168242 styleNextChunk(Self.firstStyleChunk)
169243 scheduleStyling()
@@ -181,16 +255,16 @@ public final class OrgEditor: NSObject {
181255 styledUpTo = end
182256 }
183257
184 /// The text view's own colors and font, and the line numbers'.
258 /// Every text view's own colors and font, and the line numbers'.
185259 private func applyThemeToView() {
186 textView.font = theme.font
187 textView.typingAttributes = theme.base
188 textView.drawsBackground = true
189 textView.backgroundColor = theme.color("background") ?? .textBackgroundColor
190 textView.insertionPointColor = theme.color("cursor") ?? .textColor
191260 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
192 textView.selectedTextAttributes = [.backgroundColor: Theme.selection]
193 if let view = orgTextView {
261 for view in orgTextViews {
262 view.font = theme.font
263 view.typingAttributes = theme.base
264 view.drawsBackground = true
265 view.backgroundColor = theme.color("background") ?? .textBackgroundColor
266 view.insertionPointColor = theme.color("cursor") ?? .textColor
267 view.selectedTextAttributes = [.backgroundColor: Theme.selection]
194268 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
195269 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
196270 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
@@ -232,12 +306,13 @@ public final class OrgEditor: NSObject {
232306 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
233307 var utf16Length: Int { (textView.string as NSString).length }
234308
235 /// A scroll view holding the text view, ready for a window.
236 public func makeScrollView() -> NSScrollView {
309 /// A scroll view holding `view` (the active text view by default), ready for a window.
310 public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView {
311 let textView = view ?? self.textView
237312 let scroll = NSScrollView(frame: textView.frame)
238313 scroll.hasVerticalScroller = true
239314 scroll.documentView = textView
240 orgTextView?.showsLineNumbers = showLineNumbers
315 (textView as? OrgTextView)?.showsLineNumbers = showLineNumbers
241316 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
242317 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
243318 return scroll
@@ -300,7 +375,7 @@ public final class OrgEditor: NSObject {
300375 }
301376 /// Line numbers in a ruler beside the text.
302377 public var showLineNumbers = true {
303 didSet { orgTextView?.showsLineNumbers = showLineNumbers }
378 didSet { for view in orgTextViews { view.showsLineNumbers = showLineNumbers } }
304379 }
305380 var orgTextView: OrgTextView? { textView as? OrgTextView }
306381
@@ -672,8 +747,10 @@ public final class OrgEditor: NSObject {
672747 onEditTiming?(clock.now - start)
673748 let lineCount = lines.lineCount
674749 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
675 if lines.lineCount != lineCount { orgTextView?.updateGutter() }
676 orgTextView?.redrawLineNumbers()
750 for view in orgTextViews {
751 if lines.lineCount != lineCount { view.updateGutter() }
752 view.redrawLineNumbers()
753 }
677754 onChange?()
678755 }
679756
@@ -703,7 +780,7 @@ public final class OrgEditor: NSObject {
703780 }
704781
705782 private func redrawShaded(_ ranges: [NSRange]) {
706 guard let manager = textLayoutManager.textContentManager else { return }
783 let manager = textContentStorage
707784 for old in ranges where old.length > 0 {
708785 for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
709786 let lower = max(block.lowerBound, old.location)
@@ -711,7 +788,7 @@ public final class OrgEditor: NSObject {
711788 guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
712789 let end = manager.location(start, offsetBy: upper - lower),
713790 let range = NSTextRange(location: start, end: end) else { continue }
714 textLayoutManager.invalidateLayout(for: range)
791 for layout in layoutManagers { layout.invalidateLayout(for: range) }
715792 }
716793 }
717794 }
@@ -756,27 +833,27 @@ extension OrgEditor: DocumentBuffer {
756833 return [selected.location..<NSMaxRange(selected)]
757834 }
758835
759 /// Runs `change`; if it changed the text, reloads the view with folds and the selection
760 /// mapped through the change. Text-view undo refers to the old text, so it is cleared.
836 /// Runs `change`; if it changed the text, reloads the views with folds and each view's
837 /// selection mapped through the change. Undo refers to the old text, so it is cleared.
761838 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
762839 let before = document.text
763840 let defaultsBefore = document.defaults
764 let selected = textView.selectedRange()
841 let selections = textViews.map(\.selectedRange)
765842 let result = try change(&document)
766843 if document.text != before {
767844 let edits = lineEdits(from: before, to: document.text)
768845 var state = view
769 state.selection = [selected.location..<NSMaxRange(selected)]
846 state.selection = selections.map { $0.location..<NSMaxRange($0) }
770847 let mapped = state.mapped(through: edits)
771848 // Shrunk columns were measured on the old text.
772849 shrunk = ShrunkColumns()
773850 load(document.text)
774851 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
775 let selection = mapped.selection[0]
776 setCaret(selection.lowerBound)
777 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) }
778 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!)
779 textView.undoManager?.removeAllActions(withTarget: textView)
852 for (view, selection) in zip(textViews, mapped.selection) {
853 if view === active { setCaret(selection.lowerBound) } else { view.setSelectedRange(NSRange(location: selection.lowerBound, length: 0)) }
854 if !selection.isEmpty { view.setSelectedRange(NSRange(selection)) }
855 }
856 undoManager.removeAllActions()
780857 } else if document.defaults != defaultsBefore {
781858 // New settings for the same text: TODO keywords may color differently.
782859 restyleEverything()
Sources/OrgEditorAppKit/ViewToggles.swift +3 −1
@@ -10,7 +10,7 @@ extension OrgEditor {
1010 public var spellChecking: Bool {
1111 get { textView.isContinuousSpellCheckingEnabled }
1212 set {
13 textView.isContinuousSpellCheckingEnabled = newValue
13 for view in textViews { view.isContinuousSpellCheckingEnabled = newValue }
1414 if !newValue, let storage = textView.textStorage {
1515 storage.removeAttribute(.spellingState, range: NSRange(location: 0, length: storage.length))
1616 }
@@ -90,6 +90,8 @@ extension OrgEditor {
9090
9191extension OrgEditor: NSTextViewDelegate {
9292 public func textViewDidChangeSelection(_ notification: Notification) {
93 // Another view's caret moving (a mapped selection, say) is its own business.
94 guard (notification.object as AnyObject?) === textView else { return }
9395 selectionChanged()
9496 if completionPopup != nil, let popup = completionPopup, textView.selectedRange().location != popup.completion.range.upperBound {
9597 refreshCompletion()
Tests/OrgEditorAppKitTests/MultiViewTests.swift added +92
@@ -0,0 +1,92 @@
1import AppKit
2import OrgCore
3import OrgDocument
4import OrgPresentation
5import Testing
6@testable import OrgEditorAppKit
7
8/// One editor, several text views on its storage: text, undo, folds and narrowing are the
9/// editor's; the caret and the focus are each view's.
10@MainActor
11struct MultiViewTests {
12 @MainActor struct Two {
13 let editor: OrgEditor
14 let second: NSTextView
15 let windows: [NSWindow]
16
17 init(_ text: String) {
18 _ = NSApplication.shared
19 let editor = OrgEditor(document: DocumentState(bytes: Array(text.utf8)))
20 let second = editor.addView()
21 let windows = [editor.textView, second].map { view in
22 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 800), styleMask: [.titled], backing: .buffered, defer: false)
23 window.contentView = editor.makeScrollView(for: view)
24 return window
25 }
26 windows[0].makeFirstResponder(editor.textView)
27 editor.finishStyling()
28 for view in editor.textViews { view.textLayoutManager!.ensureLayout(for: view.textLayoutManager!.documentRange) }
29 self.editor = editor
30 self.second = second
31 self.windows = windows
32 }
33
34 func lines(_ view: NSTextView) -> Int {
35 let layout = view.textLayoutManager!
36 layout.ensureLayout(for: layout.documentRange)
37 var count = 0
38 layout.enumerateTextLayoutFragments(from: layout.documentRange.location, options: [.ensuresLayout]) { _ in count += 1; return true }
39 return count
40 }
41 }
42
43 @Test func typingInOneViewShowsInTheOtherAndInTheDocument() {
44 let two = Two("* a\nbody\n")
45 two.editor.textView.insertText("X", replacementRange: NSRange(location: 0, length: 0))
46 #expect(two.second.string == "X* a\nbody\n")
47 #expect(two.editor.document.text == "X* a\nbody\n")
48 }
49
50 @Test func undoIsShared() {
51 let two = Two("* a\nbody\n")
52 two.editor.textView.insertText("X", replacementRange: NSRange(location: 0, length: 0))
53 two.second.undoManager?.undo()
54 #expect(two.second.string == "* a\nbody\n")
55 #expect(two.editor.document.text == "* a\nbody\n")
56 }
57
58 @Test func foldsAreTheEditors() {
59 let two = Two("* a\nbody\n* b\n")
60 let before = two.lines(two.second)
61 two.editor.setCaret(0)
62 _ = two.editor.cycleAtCaret()
63 #expect(two.lines(two.second) < before)
64 #expect(two.lines(two.editor.textView) == two.lines(two.second))
65 }
66
67 @Test func commandsActOnTheFocusedView() {
68 let two = Two("* a\nbody\n* b\nmore\n")
69 two.windows[1].makeFirstResponder(two.second)
70 #expect(two.editor.textView === two.second)
71 two.second.setSelectedRange(NSRange(location: 9, length: 0))
72 _ = two.editor.cycleAtCaret()
73 #expect(two.editor.foldState.folds == [9])
74 }
75
76 @Test func aDiskChangeMapsEveryViewsCaret() {
77 let two = Two("* a\nbody\n")
78 two.second.setSelectedRange(NSRange(location: 5, length: 0))
79 _ = two.editor.diskChanged(to: Array("XY* a\nbody\n".utf8))
80 #expect(two.second.selectedRange() == NSRange(location: 7, length: 0))
81 #expect(two.second.string == "XY* a\nbody\n")
82 }
83
84 @Test func removingAViewDetachesItsLayoutManager() {
85 let two = Two("* a\n")
86 let storage = two.editor.textView.textLayoutManager!.textContentManager!
87 #expect(storage.textLayoutManagers.count == 2)
88 two.editor.removeView(two.second)
89 #expect(storage.textLayoutManagers.count == 1)
90 #expect(two.editor.textViews.count == 1)
91 }
92}
docs/design.md +1 −1
@@ -166,7 +166,7 @@ struct TextEdit { let range: Range<Int>; let replacement: String } // UTF-16
166166
167167**Document session**
168168
169One session per open file owns the text, original bytes, tree, revision counter, merge base and undo history. Each window or split has its own selection, fold state and narrowing, mapped through every edit. On an external reload or merge, view state is mapped through the diff; folds on headings that no longer exist are dropped.
169One session per open file owns the text, original bytes, tree, revision counter, merge base and undo history. Each window or split has its own selection and scroll position; folds, narrowing and sparse trees are the buffer's and show the same in every view, as Emacs keeps them buffer-local. Selections are mapped through every edit. On an external reload or merge, view state is mapped through the diff; folds on headings that no longer exist are dropped.
170170
171171**Keymap format**
172172
docs/plans/2026-10-10-windows-and-panes.md +22 −29
@@ -4,7 +4,7 @@
44
55**Goal:** More than one editor window, and a window split into panes, each pane showing any open buffer with its own caret, folds, narrowing and scroll position, so two files (or two places in one file) sit side by side as `C-x 2` / `C-x 3` give in Emacs.
66
7**Architecture:** The editor is split into a buffer and views. `EditorBuffer` (new, `OrgEditorAppKit`) owns the `NSTextContentStorage`, the `DocumentState`, the revision, the undo manager and the `DocumentBuffer` conformance; `OrgEditor` becomes a view over it: an `NSTextView` with its own `NSTextLayoutManager` on the shared storage, holding selection, folds, narrowing and the layout-fragment delegate that draws them. `DocumentSession` keeps one `Entry` per open file but no longer has a single "current" buffer: each `EditorPane` (new, `OrgApp`) shows one path, and a `WindowModel` per main window holds a `PaneLayout` tree of panes and the focused one. The session forwards its old `path`, `outline`, `isDirty`, `conflict`, `revealRequest` and `editVersion` to the focused pane so the agenda, capture, menus and palette keep working unchanged.
7**Architecture:** `OrgEditor` stays the buffer, as it already is (`DocumentBuffer`, the text storage, undo), and gains views: `addView()` makes another `NSTextView` with its own `NSTextLayoutManager` on the editor's `NSTextContentStorage`, and `textView` is the view with focus, the one commands act on. Folds, narrowing, sparse trees, shrunk columns, inline images and evil state stay the editor's: TextKit hides folded text through the content storage's delegate, which every layout manager shares, and in Emacs these are buffer-local too. `DocumentSession` keeps one `Entry` per open file but no longer has a single "current" buffer: each `EditorPane` (new, `OrgApp`) shows one path, and a `WindowModel` per main window holds a `PaneLayout` tree of panes and the focused one. The session forwards its old `path`, `outline`, `isDirty`, `conflict`, `revealRequest` and `editVersion` to the focused pane so the agenda, capture, menus and palette keep working unchanged.
88
99**Tech Stack:** TextKit 2 (several `NSTextLayoutManager`s on one `NSTextContentStorage`), SwiftUI `WindowGroup`, Swift Testing.
1010
@@ -24,8 +24,9 @@
2424| Pane layout | A binary tree: `.pane(id)` or `.split(axis, first, second, fraction)` | `C-x 2` after `C-x 3` must work; one direction per window would refuse it |
2525| Buffers per pane | Each pane keeps its own ordered list of buffers it has shown, as its tab bar | Matches editor groups users know; `C-x b` switches in the focused pane as in Emacs |
2626| Killing a buffer | Removed from every pane; a pane showing it falls back to its previous buffer, else empty | Emacs behaviour |
27| Narrowing | Per view, as the design doc says | Two views of one buffer at different places is the point |
28| Shrunk table columns, inline-image toggle, markup toggle | Per buffer | They are buffer-local in Org |
27| Folds, narrowing, sparse trees | Per buffer | Folded text is hidden through the content storage's delegate, shared by every layout manager; Emacs keeps visibility and narrowing buffer-local as well |
28| Shrunk table columns, inline-image toggle, markup toggle, evil state, mark | Per buffer | They are buffer-local in Org and evil |
29| Caret, selection, scroll position, focus | Per view | What a window owns in Emacs |
2930| Undo | One `UndoManager` per buffer, returned from every view's `undoManager(for:)` | `C-/` in either view undoes the last edit to the file |
3031| Quick Open, search field, palette, conflict sheet | Per window (moved from `AppCommands` to `WindowModel`) | Global booleans would present them in every window at once |
3132| Jump requests (agenda, capture, backlinks) | Go to the key main window's focused pane; open a main window if none | Where the user is looking |
@@ -33,7 +34,7 @@
3334
3435## Review focus
3536
36- Typing in one view while the other view has a fold over the edited range: the fold must be mapped or dropped, never left covering the wrong text.
37- A fold set from one view must hide the same text in the other view, and each view's caret must leave text that a fold from the other view hid.
3738- Undo from view B of an edit typed in view A: the storage reverts, both views restyle, A's caret lands where the edit was.
3839- Closing the last main window with dirty buffers: the buffers stay open in the session, and a new window shows them again; the dock-quit path still asks to save.
3940- Killing a buffer shown in two panes of two windows: both panes fall back, neither crashes on a stale editor.
@@ -51,37 +52,29 @@
5152- [ ] If any check fails, stop and amend this plan before Task 1: the fallback is per-view `NSTextStorage`s kept in step by replaying edits, which is a different Task 1.
5253- [ ] Commit "Spike: two text views on one content storage".
5354
54### Task 1: `EditorBuffer`
55### Task 1: Several text views on one editor (done)
5556
5657**Files:**
57- Create: `Sources/OrgEditorAppKit/EditorBuffer.swift`
58- Modify: `Sources/OrgEditorAppKit/OrgEditor.swift` (the parts moved out), `OrgEditor+Styling.swift`, `OrgEditor+Folding.swift` (see `2026-10-10-file-splits.md`, which lands first)
59- Test: `Tests/OrgEditorAppKitTests/EditorBufferTests.swift`
58- Modify: `Sources/OrgEditorAppKit/OrgEditor.swift`, `Keys.swift`, `OrgEditor+Folding.swift`, `OrgEditor+Images.swift`, `OrgEditor+Shrink.swift`, `Modal.swift`, `ViewToggles.swift`
59- Test: `Tests/OrgEditorAppKitTests/MultiViewTests.swift`, `TwoViewsSpikeTests.swift` (Task 0)
6060
6161**Interfaces:**
6262- Produces:
6363
6464```swift
65@MainActor public final class EditorBuffer: NSObject, DocumentBuffer {
66 public let contentStorage: NSTextContentStorage
67 public let undoManager: UndoManager
68 public private(set) var document: DocumentState // DocumentBuffer
69 public var selection: [Range<Int>] // the focused view's, set by views
70 public func perform(_ command: any OrgCommand, now: Date, answers: [String: String]) -> CommandStep
71 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T
72 public func addView(_ view: OrgEditor) // weak; receives storageEdited and restyle
73 public func removeView(_ view: OrgEditor)
74 public var shrunkColumns: ShrunkColumns
75 public var showMarkup: Bool, showInlineImages: Bool
65extension OrgEditor {
66 public var textView: NSTextView { get } // the view with focus, or the last to have had it
67 public private(set) var textViews: [NSTextView] // the first made with the editor
68 public let undoManager: UndoManager // shared by every view
69 public func addView(frame: NSRect = ...) -> NSTextView
70 public func removeView(_ view: NSTextView) // never the first
71 public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView
7672}
7773```
7874
79- [ ] Write the failing tests: `two views see one edit` (make a buffer with text, two `OrgEditor`s on it, insert in one through its text view, the other's `textView.string` matches); `undo is shared`; `folds map independently` (fold a heading in A, insert a line above it in B, A's hidden range moved by the delta, B has none).
80- [ ] Move from `OrgEditor` to `EditorBuffer`: the storage and its delegate (`textStorage(_:didProcessEditing:…)`, the incremental reparse and revision bump), `DocumentState`, the `DocumentBuffer` extension, the attribute styling of the storage (theme base, highlighting, markup hiding attributes that live on the storage), `isLoading`, `load(text:)`. `OrgEditor.init` takes an `EditorBuffer` and creates its own layout manager and text view on `buffer.contentStorage`.
81- [ ] `EditorBuffer` tells each view after a storage edit: `view.storageEdited(range, delta)` (today's `OrgEditor.storageEdited`, now per view, mapping `HiddenRanges`, `FoldedHeadings`, the narrowing and shrunk-column boxes), and `view.restyle(range)` for fragment invalidation.
82- [ ] `OrgEditor.undoManager(for:)` returns `buffer.undoManager`.
83- [ ] Run the tests; run the whole suite (`swift test`): the existing `OrgEditorAppKitTests` construct `OrgEditor` directly and need the buffer argument.
84- [ ] Commit "Split the editor into EditorBuffer and views".
75- [x] Tests: typing in one view shows in the other and in the document; undo is shared; folds are the editor's; commands act on the focused view; a disk change maps every view's caret; removing a view detaches its layout manager.
76- [x] `active` follows first responder, key presses and clicks; layout invalidation, theme, line numbers, spell checking and the block cursor apply to every view; a disk change maps every view's selection; `textViewDidChangeSelection` ignores other views' carets.
77- [x] Commit "One editor, several text views".
8578
8679### Task 2: `EditorPane` and the session
8780
@@ -123,7 +116,7 @@ public indirect enum PaneLayout: Equatable, Sendable {
123116- [ ] Write the failing `PaneLayout` tests: split right then split below the second pane gives three panes in reading order; removing the middle one leaves a two-pane split with the remaining fraction; `only` collapses; `next` wraps; removing the only pane returns nil.
124117- [ ] Implement `PaneLayout`; run the tests.
125118- [ ] Write the failing `EditorPane` tests with a `DocumentSession` over an in-memory `FileSystem` (as `DocumentSessionTests` do): opening a path in pane A then showing it in pane B leaves one `Entry`; killing it empties both panes' `path` and `shown`; a pane's `shown` keeps order and drops killed paths; `reveal(_:in:)` bumps only that pane's request; `dirtyPaths` counts a buffer once however many panes show it.
126- [ ] Implement `EditorPane` and the session changes: `Entry` keeps `buffer: EditorBuffer` (attached by the first view; `attach` becomes `attach(_ buffer:, for path:)`), `current` is replaced by `focused`, `history` moves into each pane. `bufferChanged(path)` refreshes every pane showing that path (outline per pane, since a pane's outline is the buffer's; compute once and assign to each).
119- [ ] Implement `EditorPane` and the session changes: `Entry` keeps its `buffer` (the `OrgEditor`, attached once per path; `attach` becomes `attach(_ buffer:, for path:)`), `current` is replaced by `focused`, `history` moves into each pane. `bufferChanged(path)` refreshes every pane showing that path (outline per pane, since a pane's outline is the buffer's; compute once and assign to each).
127120- [ ] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders.
128121- [ ] Commit "Editor panes and pane layout in the session".
129122
@@ -131,7 +124,7 @@ public indirect enum PaneLayout: Equatable, Sendable {
131124
132125**Files:**
133126- Create: `Sources/Orgstar/PaneView.swift` (one pane: `BufferTabs` + `EditorView` for that pane), `Sources/Orgstar/PaneLayoutView.swift` (recursive `HSplitView`/`VSplitView` over `PaneLayout`, using `PaneDivider` for the fraction), `Sources/Orgstar/WindowModel.swift`
134- Modify: `Sources/Orgstar/EditorView.swift` (takes an `EditorPane`; one `OrgEditor` per (pane, path), created on `EditorBuffer` from the session's entry), `Sources/Orgstar/ContentView.swift`, `Sources/Orgstar/BufferTabs.swift`, `Sources/Orgstar/OrgstarApp.swift`
127- Modify: `Sources/Orgstar/EditorView.swift` (takes an `EditorPane`; one `OrgEditor` per path, shared by panes, and one text view per (pane, path) from `addView`), `Sources/Orgstar/ContentView.swift`, `Sources/Orgstar/BufferTabs.swift`, `Sources/Orgstar/OrgstarApp.swift`
135128
136129**Interfaces:**
137130
@@ -146,8 +139,8 @@ public indirect enum PaneLayout: Equatable, Sendable {
146139
147140`AppCommands` keeps `editor` (the focused view) and gains `keyWindow: WindowModel?`, set from `NSWindow.didBecomeKeyNotification` by the window's root view; its four presentation booleans move to `WindowModel` and every menu action that set them goes through `keyWindow`.
148141
149- [ ] `WindowGroup("orgstar", id: "main")` replaces `Window("orgstar", id: "main")`; the root view creates its `WindowModel` and one pane (`session.makePane()`) in `onAppear`, registers the model with `commands`, and on disappear closes its panes (`session.closePane`) so killed views release their layout managers (`buffer.removeView`). Buffers stay in the session.
150- [ ] `EditorView` creates editors per `(pane.id, path)`; the shown editor's text view becoming first responder sets `commands.editor` and `session.focused = pane` (an `onFocus` callback on `OrgEditor`, from `becomeFirstResponder` on `OrgTextView` in `Sources/OrgEditorAppKit/Keys.swift`).
142- [ ] `WindowGroup("orgstar", id: "main")` replaces `Window("orgstar", id: "main")`; the root view creates its `WindowModel` and one pane (`session.makePane()`) in `onAppear`, registers the model with `commands`, and on disappear closes its panes (`session.closePane`) so their text views are removed (`editor.removeView`). Buffers stay in the session.
143- [ ] `EditorView` keeps one `OrgEditor` per path and one text view per `(pane.id, path)` from `addView`, removed with `removeView` when the pane closes; a text view becoming first responder sets `commands.editor` and `session.focused = pane` (an `onFocus` callback on `OrgEditor`, from `becomeFirstResponder` on `OrgTextView` in `Sources/OrgEditorAppKit/Keys.swift`).
151144- [ ] Outline column and sidebar selection follow `session.focused`.
152145- [ ] Jump requests (`AppCommands.jumpRequest`) are handled by the key window's root view only: `commands.keyWindow === model`. With no main window open, `openWindow(id: "main")` first, then the request is delivered on the new window's first `onAppear`.
153146- [ ] Commands, as `app.*` ids dispatched where `app.quick-open` is today: `app.split-below`, `app.split-right`, `app.pane-close`, `app.pane-only`, `app.pane-next`, `app.window-new`. Menu: File ▸ New Window; View ▸ Split Below, Split Right, Close Pane, Close Other Panes, Next Pane. Emacs preset: `C-x 2`, `C-x 3`, `C-x 0`, `C-x 1`, `C-x o`, `C-x 5 2`. Doom: `SPC w s`, `SPC w v`, `SPC w d`, `SPC w o`, `SPC w w`, and `C-w s/v/c/o/w` in normal state. Mac: shortcuts chosen after checking `macBindings`; proposal ⌥⌘N, ⌥⌘-, ⌥⌘\, ⌃⌘W, ⌃⌘1, ⌃⌘`.