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 {
40 } 40 }
41 } 41 }
42 } 42 }
43 /// Each editor keeps its own undo history, not the window's. 43 /// The editor's undo history, shared by its views, not the window's.
44 private let ownUndoManager = UndoManager() 44 var sharedUndoManager = UndoManager()
45 override var undoManager: UndoManager? { ownUndoManager } 45 override var undoManager: UndoManager? { sharedUndoManager }
46 var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular) 46 var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular)
47 var lineNumberColor = NSColor.tertiaryLabelColor 47 var lineNumberColor = NSColor.tertiaryLabelColor
48 var currentLineNumberColor = NSColor.labelColor 48 var currentLineNumberColor = NSColor.labelColor
Sources/OrgEditorAppKit/Modal.swift +1 −1
@@ -388,7 +388,7 @@ extension OrgEditor {
388 /// A block cursor in normal and visual states, a bar in insert state. 388 /// A block cursor in normal and visual states, a bar in insert state.
389 func updateCursor() { 389 func updateCursor() {
390 let block = modal && vim.mode != .insert 390 let block = modal && vim.mode != .insert
391 (textView as? OrgTextView)?.blockCursor = block 391 for view in orgTextViews { view.blockCursor = block }
392 dispatcher.mode = modal ? vim.mode.keymapMode : nil 392 dispatcher.mode = modal ? vim.mode.keymapMode : nil
393 let state = modal ? vim.mode.rawValue : nil 393 let state = modal ? vim.mode.rawValue : nil
394 if state != reportedMode { 394 if state != reportedMode {
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +11 −10
@@ -28,10 +28,12 @@ extension OrgEditor {
28 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } 28 wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a }
29 view.wrapperFolds = Set(wrapperHidden.keys) 29 view.wrapperFolds = Set(wrapperHidden.keys)
30 updateHiddenAndLayout() 30 updateHiddenAndLayout()
31 orgTextView?.redrawLineNumbers() 31 redrawViews()
32 textView.needsDisplay = true 32 for view in textViews {
33 let caret = textView.selectedRange().location 33 let caret = view.selectedRange().location
34 if let range = hidden.containing(caret) { setCaret(range.lowerBound - 1) } 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 }
35 } 37 }
36 38
37 39
@@ -70,7 +72,8 @@ extension OrgEditor {
70 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the 72 /// Lays out `ranges` again, each widened to whole lines and to the line before it: the
71 /// heading or opening line of a fold, whose fragment draws the fold mark. 73 /// heading or opening line of a fold, whose fragment draws the fold mark.
72 func invalidateLayout(lines ranges: [Range<Int>]) { 74 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
74 let text = textView.string as NSString 77 let text = textView.string as NSString
75 for range in ranges { 78 for range in ranges {
76 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location 79 let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location
@@ -78,7 +81,7 @@ extension OrgEditor {
78 guard let start = content.location(content.documentRange.location, offsetBy: lower), 81 guard let start = content.location(content.documentRange.location, offsetBy: lower),
79 let end = content.location(start, offsetBy: upper - lower), 82 let end = content.location(start, offsetBy: upper - lower),
80 let textRange = NSTextRange(location: start, end: end) else { continue } 83 let textRange = NSTextRange(location: start, end: end) else { continue }
81 textLayoutManager.invalidateLayout(for: textRange) 84 for layout in layoutManagers { layout.invalidateLayout(for: textRange) }
82 } 85 }
83 } 86 }
84 87
@@ -127,8 +130,7 @@ extension OrgEditor {
127 updateHiddenAndLayout() 130 updateHiddenAndLayout()
128 restyleOutsideEditing(0..<utf16Length) 131 restyleOutsideEditing(0..<utf16Length)
129 } 132 }
130 orgTextView?.redrawLineNumbers() 133 redrawViews()
131 textView.needsDisplay = true
132 let caret = textView.selectedRange().location 134 let caret = textView.selectedRange().location
133 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) } 135 if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) }
134 } 136 }
@@ -189,8 +191,7 @@ extension OrgEditor {
189 return 191 return
190 } 192 }
191 updateHiddenAndLayout() 193 updateHiddenAndLayout()
192 orgTextView?.redrawLineNumbers() 194 redrawViews()
193 textView.needsDisplay = true
194 if let narrowed { 195 if let narrowed {
195 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound))) 196 setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound)))
196 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0)) 197 textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0))
Sources/OrgEditorAppKit/OrgEditor+Images.swift +2 −2
@@ -28,9 +28,9 @@ extension OrgEditor {
28 func refreshImages() { 28 func refreshImages() {
29 keepingTopLine { 29 keepingTopLine {
30 restyleOutsideEditing(0..<utf16Length) 30 restyleOutsideEditing(0..<utf16Length)
31 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 31 invalidateAllLayout()
32 } 32 }
33 textView.needsDisplay = true 33 redrawViews()
34 } 34 }
35 35
36 private func loadImage(_ path: String) -> NSImage? { 36 private func loadImage(_ path: String) -> NSImage? {
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift +1 −1
@@ -13,7 +13,7 @@ extension OrgEditor {
13 shrunk.set(columns, in: table, text: textView.string) 13 shrunk.set(columns, in: table, text: textView.string)
14 restyleOutsideEditing(table) 14 restyleOutsideEditing(table)
15 invalidateLayout(lines: [table]) 15 invalidateLayout(lines: [table])
16 textView.needsDisplay = true 16 redrawViews()
17 } 17 }
18 18
19 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, 19 /// 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
6 6
7/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every 7/// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every
8/// character edit goes through `DocumentState.apply`, and only the affected region is restyled. 8/// 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.
9@MainActor 13@MainActor
10public final class OrgEditor: NSObject { 14public 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()
12 public private(set) var document: DocumentState 24 public private(set) var document: DocumentState
13 public internal(set) var view = ViewState() 25 public internal(set) var view = ViewState()
14 /// Called with the time from a character edit to restyled text. 26 /// Called with the time from a character edit to restyled text.
@@ -29,7 +41,7 @@ public final class OrgEditor: NSObject {
29 keepingTopLine { 41 keepingTopLine {
30 applyThemeToView() 42 applyThemeToView()
31 restyleEverything() 43 restyleEverything()
32 textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) 44 invalidateAllLayout()
33 } 45 }
34 } 46 }
35 } 47 }
@@ -86,73 +98,133 @@ public final class OrgEditor: NSObject {
86 self.highlighter = highlighter 98 self.highlighter = highlighter
87 self.mode = mode 99 self.mode = mode
88 let orgTextView = OrgTextView(usingTextLayoutManager: true) 100 let orgTextView = OrgTextView(usingTextLayoutManager: true)
89 textView = orgTextView 101 active = orgTextView
102 textViews = [orgTextView]
90 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap) 103 dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap)
91 super.init() 104 super.init()
92 orgTextView.keyHandler = { [weak self] event in self?.handleKey(event) ?? false } 105 configure(orgTextView, frame: frame, editable: editable)
93 orgTextView.onFocusChange = { [weak self] in 106 applyThemeToView()
94 guard let self else { return } 107 textView.textStorage?.delegate = self
95 let id = ObjectIdentifier(self.textLayoutManager) 108 textContentStorage.delegate = self
96 if let window = self.textView.window, window.isKeyWindow, window.firstResponder === self.textView { 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 {
97 Theme.focusedLayouts.insert(id) 140 Theme.focusedLayouts.insert(id)
98 } else { 141 } else {
99 Theme.focusedLayouts.remove(id) 142 Theme.focusedLayouts.remove(id)
100 } 143 }
101 self.redrawShaded([self.textView.selectedRange()]) 144 self.redrawShaded([view.selectedRange()])
102 } 145 }
103 orgTextView.onCommandClick = { [weak self] offset in 146 view.onCommandClick = { [weak self, unowned view] offset in
104 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil 147 guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil
105 || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false } 148 || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false }
149 self.active = view
106 self.setCaret(offset) 150 self.setCaret(offset)
107 self.run("org.link.open") 151 self.run("org.link.open")
108 return true 152 return true
109 } 153 }
110 orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false } 154 view.onClick = { [weak self, unowned view] offset in
111 orgTextView.accessibleText = { [weak self] in 155 self?.active = view
156 return self?.click(at: offset) ?? false
157 }
158 view.accessibleText = { [weak self] in
112 guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) } 159 guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) }
113 if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text } 160 if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text }
114 let text = AccessibleText(storage) 161 let text = AccessibleText(storage)
115 self.accessibleCache = (self.storageGeneration, text) 162 self.accessibleCache = (self.storageGeneration, text)
116 return text 163 return text
117 } 164 }
118 orgTextView.onMouseDown = { [weak self] in 165 view.onMouseDown = { [weak self, unowned view] in
166 self?.active = view
119 self?.markActive = false 167 self?.markActive = false
120 self?.modalMouseDown() 168 self?.modalMouseDown()
121 } 169 }
122 textView.usesFindBar = true 170 view.sharedUndoManager = undoManager
123 textView.frame = frame 171 view.usesFindBar = true
124 textView.isRichText = false 172 view.frame = frame
125 textView.isEditable = editable 173 view.isRichText = false
126 textView.allowsUndo = true 174 view.isEditable = editable
127 textView.isAutomaticQuoteSubstitutionEnabled = false 175 view.allowsUndo = true
128 textView.isAutomaticDashSubstitutionEnabled = false 176 view.isAutomaticQuoteSubstitutionEnabled = false
129 textView.isAutomaticTextReplacementEnabled = false 177 view.isAutomaticDashSubstitutionEnabled = false
130 textView.isAutomaticSpellingCorrectionEnabled = 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
131 applyThemeToView() 202 applyThemeToView()
132 textView.isVerticallyResizable = true 203 return view
133 textView.autoresizingMask = [.width] 204 }
134 textView.textContainer?.widthTracksTextView = true
135 textView.delegate = self
136 textView.textStorage?.delegate = self
137 textLayoutManager.delegate = self
138 textContentStorage.delegate = self
139 205
140 if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) } 206 /// Takes a view made by `addView` off the storage. The first view stays.
141 load(document.text) 207 public func removeView(_ view: NSTextView) {
142 // Files open at their start, as in Emacs; replacing the storage leaves it at the end. 208 guard let index = textViews.firstIndex(where: { $0 === view }), index > 0 else { return }
143 textView.setSelectedRange(NSRange(location: 0, length: 0)) 209 textViews.remove(at: index)
144 if isOrg { 210 if active === view { active = orgTextViews[0] }
145 let startup = Presentation.startupDisplay(document.tree, options: options) 211 if let layout = view.textLayoutManager {
146 indented = startup.indented 212 Theme.focusedLayouts.remove(ObjectIdentifier(layout))
147 hideStars = startup.hideStars 213 textContentStorage.removeTextLayoutManager(layout)
148 if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) } 214 }
149 shrunk = ShrunkColumns.startup(document.tree) 215 }
150 if startup.inlineImages { showsImages = true } 216
151 if startup.alignTables { _ = perform(AlignAllTables()) } 217 /// Lays every view out again.
152 if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) } 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
153 } 227 }
154 spellChecking = options.spellCheck
155 truncatesLines = options.startupTruncated
156 } 228 }
157 229
158 /// Replaces the storage's text. Setting the attributed string directly is about 100x 230 /// Replaces the storage's text. Setting the attributed string directly is about 100x
@@ -162,8 +234,10 @@ public final class OrgEditor: NSObject {
162 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) 234 textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
163 isLoading = false 235 isLoading = false
164 lines.reset(text as NSString) 236 lines.reset(text as NSString)
165 orgTextView?.lineIndex = lines 237 for view in orgTextViews {
166 orgTextView?.updateGutter() 238 view.lineIndex = lines
239 view.updateGutter()
240 }
167 styledUpTo = 0 241 styledUpTo = 0
168 styleNextChunk(Self.firstStyleChunk) 242 styleNextChunk(Self.firstStyleChunk)
169 scheduleStyling() 243 scheduleStyling()
@@ -181,16 +255,16 @@ public final class OrgEditor: NSObject {
181 styledUpTo = end 255 styledUpTo = end
182 } 256 }
183 257
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'.
185 private func applyThemeToView() { 259 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
191 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor 260 Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor
192 textView.selectedTextAttributes = [.backgroundColor: Theme.selection] 261 for view in orgTextViews {
193 if let view = orgTextView { 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]
194 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular) 268 view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular)
195 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor 269 view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor
196 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor 270 view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor
@@ -232,12 +306,13 @@ public final class OrgEditor: NSObject {
232 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage } 306 var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage }
233 var utf16Length: Int { (textView.string as NSString).length } 307 var utf16Length: Int { (textView.string as NSString).length }
234 308
235 /// A scroll view holding the text view, ready for a window. 309 /// A scroll view holding `view` (the active text view by default), ready for a window.
236 public func makeScrollView() -> NSScrollView { 310 public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView {
311 let textView = view ?? self.textView
237 let scroll = NSScrollView(frame: textView.frame) 312 let scroll = NSScrollView(frame: textView.frame)
238 scroll.hasVerticalScroller = true 313 scroll.hasVerticalScroller = true
239 scroll.documentView = textView 314 scroll.documentView = textView
240 orgTextView?.showsLineNumbers = showLineNumbers 315 (textView as? OrgTextView)?.showsLineNumbers = showLineNumbers
241 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height) 316 textView.minSize = NSSize(width: 0, height: scroll.contentSize.height)
242 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) 317 textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
243 return scroll 318 return scroll
@@ -300,7 +375,7 @@ public final class OrgEditor: NSObject {
300 } 375 }
301 /// Line numbers in a ruler beside the text. 376 /// Line numbers in a ruler beside the text.
302 public var showLineNumbers = true { 377 public var showLineNumbers = true {
303 didSet { orgTextView?.showsLineNumbers = showLineNumbers } 378 didSet { for view in orgTextViews { view.showsLineNumbers = showLineNumbers } }
304 } 379 }
305 var orgTextView: OrgTextView? { textView as? OrgTextView } 380 var orgTextView: OrgTextView? { textView as? OrgTextView }
306 381
@@ -672,8 +747,10 @@ public final class OrgEditor: NSObject {
672 onEditTiming?(clock.now - start) 747 onEditTiming?(clock.now - start)
673 let lineCount = lines.lineCount 748 let lineCount = lines.lineCount
674 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText) 749 lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText)
675 if lines.lineCount != lineCount { orgTextView?.updateGutter() } 750 for view in orgTextViews {
676 orgTextView?.redrawLineNumbers() 751 if lines.lineCount != lineCount { view.updateGutter() }
752 view.redrawLineNumbers()
753 }
677 onChange?() 754 onChange?()
678 } 755 }
679 756
@@ -703,7 +780,7 @@ public final class OrgEditor: NSObject {
703 } 780 }
704 781
705 private func redrawShaded(_ ranges: [NSRange]) { 782 private func redrawShaded(_ ranges: [NSRange]) {
706 guard let manager = textLayoutManager.textContentManager else { return } 783 let manager = textContentStorage
707 for old in ranges where old.length > 0 { 784 for old in ranges where old.length > 0 {
708 for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) { 785 for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) {
709 let lower = max(block.lowerBound, old.location) 786 let lower = max(block.lowerBound, old.location)
@@ -711,7 +788,7 @@ public final class OrgEditor: NSObject {
711 guard let start = manager.location(manager.documentRange.location, offsetBy: lower), 788 guard let start = manager.location(manager.documentRange.location, offsetBy: lower),
712 let end = manager.location(start, offsetBy: upper - lower), 789 let end = manager.location(start, offsetBy: upper - lower),
713 let range = NSTextRange(location: start, end: end) else { continue } 790 let range = NSTextRange(location: start, end: end) else { continue }
714 textLayoutManager.invalidateLayout(for: range) 791 for layout in layoutManagers { layout.invalidateLayout(for: range) }
715 } 792 }
716 } 793 }
717 } 794 }
@@ -756,27 +833,27 @@ extension OrgEditor: DocumentBuffer {
756 return [selected.location..<NSMaxRange(selected)] 833 return [selected.location..<NSMaxRange(selected)]
757 } 834 }
758 835
759 /// Runs `change`; if it changed the text, reloads the view with folds and the selection 836 /// Runs `change`; if it changed the text, reloads the views with folds and each view's
760 /// mapped through the change. Text-view undo refers to the old text, so it is cleared. 837 /// selection mapped through the change. Undo refers to the old text, so it is cleared.
761 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T { 838 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
762 let before = document.text 839 let before = document.text
763 let defaultsBefore = document.defaults 840 let defaultsBefore = document.defaults
764 let selected = textView.selectedRange() 841 let selections = textViews.map(\.selectedRange)
765 let result = try change(&document) 842 let result = try change(&document)
766 if document.text != before { 843 if document.text != before {
767 let edits = lineEdits(from: before, to: document.text) 844 let edits = lineEdits(from: before, to: document.text)
768 var state = view 845 var state = view
769 state.selection = [selected.location..<NSMaxRange(selected)] 846 state.selection = selections.map { $0.location..<NSMaxRange($0) }
770 let mapped = state.mapped(through: edits) 847 let mapped = state.mapped(through: edits)
771 // Shrunk columns were measured on the old text. 848 // Shrunk columns were measured on the old text.
772 shrunk = ShrunkColumns() 849 shrunk = ShrunkColumns()
773 load(document.text) 850 load(document.text)
774 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds)) 851 setFolds(FoldState(folds: mapped.folds, bodyFolds: mapped.bodyFolds, wrapperFolds: mapped.wrapperFolds))
775 let selection = mapped.selection[0] 852 for (view, selection) in zip(textViews, mapped.selection) {
776 setCaret(selection.lowerBound) 853 if view === active { setCaret(selection.lowerBound) } else { view.setSelectedRange(NSRange(location: selection.lowerBound, length: 0)) }
777 if !selection.isEmpty { textView.setSelectedRange(NSRange(selection)) } 854 if !selection.isEmpty { view.setSelectedRange(NSRange(selection)) }
778 textView.undoManager?.removeAllActions(withTarget: textView.textStorage!) 855 }
779 textView.undoManager?.removeAllActions(withTarget: textView) 856 undoManager.removeAllActions()
780 } else if document.defaults != defaultsBefore { 857 } else if document.defaults != defaultsBefore {
781 // New settings for the same text: TODO keywords may color differently. 858 // New settings for the same text: TODO keywords may color differently.
782 restyleEverything() 859 restyleEverything()
Sources/OrgEditorAppKit/ViewToggles.swift +3 −1
@@ -10,7 +10,7 @@ extension OrgEditor {
10 public var spellChecking: Bool { 10 public var spellChecking: Bool {
11 get { textView.isContinuousSpellCheckingEnabled } 11 get { textView.isContinuousSpellCheckingEnabled }
12 set { 12 set {
13 textView.isContinuousSpellCheckingEnabled = newValue 13 for view in textViews { view.isContinuousSpellCheckingEnabled = newValue }
14 if !newValue, let storage = textView.textStorage { 14 if !newValue, let storage = textView.textStorage {
15 storage.removeAttribute(.spellingState, range: NSRange(location: 0, length: storage.length)) 15 storage.removeAttribute(.spellingState, range: NSRange(location: 0, length: storage.length))
16 } 16 }
@@ -90,6 +90,8 @@ extension OrgEditor {
90 90
91extension OrgEditor: NSTextViewDelegate { 91extension OrgEditor: NSTextViewDelegate {
92 public func textViewDidChangeSelection(_ notification: Notification) { 92 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 }
93 selectionChanged() 95 selectionChanged()
94 if completionPopup != nil, let popup = completionPopup, textView.selectedRange().location != popup.completion.range.upperBound { 96 if completionPopup != nil, let popup = completionPopup, textView.selectedRange().location != popup.completion.range.upperBound {
95 refreshCompletion() 97 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
166 166
167**Document session** 167**Document session**
168 168
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.
170 170
171**Keymap format** 171**Keymap format**
172 172
docs/plans/2026-10-10-windows-and-panes.md +22 −29
@@ -4,7 +4,7 @@
4 4
5**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. 5**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.
6 6
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.
8 8
9**Tech Stack:** TextKit 2 (several `NSTextLayoutManager`s on one `NSTextContentStorage`), SwiftUI `WindowGroup`, Swift Testing. 9**Tech Stack:** TextKit 2 (several `NSTextLayoutManager`s on one `NSTextContentStorage`), SwiftUI `WindowGroup`, Swift Testing.
10 10
@@ -24,8 +24,9 @@
24| 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 | 24| 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 |
25| 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 | 25| 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 |
26| Killing a buffer | Removed from every pane; a pane showing it falls back to its previous buffer, else empty | Emacs behaviour | 26| 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 | 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 | Per buffer | They are buffer-local in Org | 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 |
29| Undo | One `UndoManager` per buffer, returned from every view's `undoManager(for:)` | `C-/` in either view undoes the last edit to the file | 30| Undo | One `UndoManager` per buffer, returned from every view's `undoManager(for:)` | `C-/` in either view undoes the last edit to the file |
30| Quick Open, search field, palette, conflict sheet | Per window (moved from `AppCommands` to `WindowModel`) | Global booleans would present them in every window at once | 31| Quick Open, search field, palette, conflict sheet | Per window (moved from `AppCommands` to `WindowModel`) | Global booleans would present them in every window at once |
31| 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 | 32| 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 @@
33 34
34## Review focus 35## Review focus
35 36
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.
37- 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. 38- 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.
38- 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. 39- 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.
39- Killing a buffer shown in two panes of two windows: both panes fall back, neither crashes on a stale editor. 40- Killing a buffer shown in two panes of two windows: both panes fall back, neither crashes on a stale editor.
@@ -51,37 +52,29 @@
51- [ ] 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. 52- [ ] 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.
52- [ ] Commit "Spike: two text views on one content storage". 53- [ ] Commit "Spike: two text views on one content storage".
53 54
54### Task 1: `EditorBuffer` 55### Task 1: Several text views on one editor (done)
55 56
56**Files:** 57**Files:**
57- Create: `Sources/OrgEditorAppKit/EditorBuffer.swift` 58- Modify: `Sources/OrgEditorAppKit/OrgEditor.swift`, `Keys.swift`, `OrgEditor+Folding.swift`, `OrgEditor+Images.swift`, `OrgEditor+Shrink.swift`, `Modal.swift`, `ViewToggles.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/MultiViewTests.swift`, `TwoViewsSpikeTests.swift` (Task 0)
59- Test: `Tests/OrgEditorAppKitTests/EditorBufferTests.swift`
60 60
61**Interfaces:** 61**Interfaces:**
62- Produces: 62- Produces:
63 63
64```swift 64```swift
65@MainActor public final class EditorBuffer: NSObject, DocumentBuffer { 65extension OrgEditor {
66 public let contentStorage: NSTextContentStorage 66 public var textView: NSTextView { get } // the view with focus, or the last to have had it
67 public let undoManager: UndoManager 67 public private(set) var textViews: [NSTextView] // the first made with the editor
68 public private(set) var document: DocumentState // DocumentBuffer 68 public let undoManager: UndoManager // shared by every view
69 public var selection: [Range<Int>] // the focused view's, set by views 69 public func addView(frame: NSRect = ...) -> NSTextView
70 public func perform(_ command: any OrgCommand, now: Date, answers: [String: String]) -> CommandStep 70 public func removeView(_ view: NSTextView) // never the first
71 public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T 71 public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView
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
76} 72}
77``` 73```
78 74
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). 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.
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`. 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.
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. 77- [x] Commit "One editor, several text views".
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".
85 78
86### Task 2: `EditorPane` and the session 79### Task 2: `EditorPane` and the session
87 80
@@ -123,7 +116,7 @@ public indirect enum PaneLayout: Equatable, Sendable {
123- [ ] 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. 116- [ ] 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.
124- [ ] Implement `PaneLayout`; run the tests. 117- [ ] Implement `PaneLayout`; run the tests.
125- [ ] 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. 118- [ ] 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).
127- [ ] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders. 120- [ ] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders.
128- [ ] Commit "Editor panes and pane layout in the session". 121- [ ] Commit "Editor panes and pane layout in the session".
129 122
@@ -131,7 +124,7 @@ public indirect enum PaneLayout: Equatable, Sendable {
131 124
132**Files:** 125**Files:**
133- 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` 126- 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`
135 128
136**Interfaces:** 129**Interfaces:**
137 130
@@ -146,8 +139,8 @@ public indirect enum PaneLayout: Equatable, Sendable {
146 139
147`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`. 140`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`.
148 141
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. 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.
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`). 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`).
151- [ ] Outline column and sidebar selection follow `session.focused`. 144- [ ] Outline column and sidebar selection follow `session.focused`.
152- [ ] 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`. 145- [ ] 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`.
153- [ ] 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, ⌃⌘`. 146- [ ] 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, ⌃⌘`.