Windows and panes !235
34 files changed, +1587 −380
Layout: unified · split
Sources/OrgApp/DocumentSession.swift +160 −90
| @@ -42,30 +42,36 @@ public enum SaveMode: String, Sendable, CaseIterable { | ||
| 42 | 42 | case explicit |
| 43 | 43 | } |
| 44 | 44 | |
| 45 | /// The files open in a window, as Emacs's buffers: each keeps its text, caret, undo and | |
| 46 | /// unsaved edits while another is shown. The current buffer's outline, saving and requests | |
| 47 | /// for the editor to show a location are what most views use. The view layer attaches an | |
| 48 | /// editor to each buffer and follows `path` and `revealRequest`. | |
| 45 | /// The files open in the app, as Emacs's buffers: each keeps its text, caret, undo and | |
| 46 | /// unsaved edits while another is shown. Buffers show in panes (`EditorPane`), one or more | |
| 47 | /// per window; `focused` is the pane commands and menus act on, and the properties below | |
| 48 | /// that describe one buffer (`path`, `outline`, `isDirty`, `conflict`, `revealRequest`) are | |
| 49 | /// its. The view layer attaches an editor to each buffer and, per pane, follows the pane's | |
| 50 | /// `path` and `revealRequest`. | |
| 49 | 51 | @MainActor |
| 50 | 52 | @Observable |
| 51 | 53 | public final class DocumentSession { |
| 52 | /// The current buffer's file. | |
| 53 | public private(set) var path: String? | |
| 54 | /// A copy of the current buffer's state as of its last change. Not observed: it changes | |
| 55 | /// on every keystroke; views follow `path`, `isDirty` and `outline`. | |
| 56 | @ObservationIgnored public private(set) var document: DocumentState? | |
| 57 | public private(set) var outline: [OutlineEntry] = [] | |
| 58 | /// Bumped when the buffer settles after edits, and when a file opens: views that read | |
| 59 | /// `document` follow this. | |
| 60 | public private(set) var editVersion = 0 | |
| 61 | public private(set) var isDirty = false | |
| 54 | /// Where buffers show. There is always at least one. | |
| 55 | public private(set) var panes: [EditorPane] | |
| 56 | /// The pane with focus: what `open`, `reveal`, saving and the forwarders below act on. | |
| 57 | public var focused: EditorPane | |
| 58 | /// The focused pane's file. | |
| 59 | public var path: String? { focused.path } | |
| 60 | /// The focused pane's buffer state. Not observed: it changes on every keystroke; views | |
| 61 | /// follow `path`, `isDirty` and `outline`. | |
| 62 | public var document: DocumentState? { current?.buffer.document } | |
| 63 | public var outline: [OutlineEntry] { focused.outline } | |
| 64 | /// Bumped when the focused buffer settles after edits, and when a file opens: views that | |
| 65 | /// read `document` follow this. | |
| 66 | public var editVersion: Int { focused.editVersion } | |
| 67 | public var isDirty: Bool { focused.isDirty } | |
| 62 | 68 | /// The file isn't UTF-8, so it can't be edited or saved. |
| 63 | public private(set) var isReadOnly = false | |
| 64 | /// Set while the buffer and the file on disk conflict; says how to resolve it. | |
| 65 | public private(set) var conflict: String? | |
| 66 | /// Bumped to ask the editor to reveal an offset. | |
| 67 | public private(set) var revealRequest: (offset: Int, id: Int)? | |
| 68 | /// Open files, in the order buffers were opened (each after the one current then). | |
| 69 | public var isReadOnly: Bool { focused.isReadOnly } | |
| 70 | /// Set while the focused buffer and the file on disk conflict; says how to resolve it. | |
| 71 | public var conflict: String? { focused.conflict } | |
| 72 | /// Bumped to ask the focused pane's editor to reveal an offset. | |
| 73 | public var revealRequest: (offset: Int, id: Int)? { focused.revealRequest } | |
| 74 | /// Open files, in the order buffers were opened (each after the one focused then). | |
| 69 | 75 | public private(set) var openPaths: [String] = [] |
| 70 | 76 | /// Open files with unsaved edits. |
| 71 | 77 | public private(set) var dirtyPaths: Set<String> = [] |
| @@ -91,8 +97,10 @@ public final class DocumentSession { | ||
| 91 | 97 | public func refreshSetup() { |
| 92 | 98 | guard let entry = current else { return } |
| 93 | 99 | resolveSetup(entry) |
| 94 | refresh() | |
| 95 | editVersion += 1 | |
| 100 | for pane in panes(showing: entry.path) { | |
| 101 | refresh(pane) | |
| 102 | pane.editVersion += 1 | |
| 103 | } | |
| 96 | 104 | } |
| 97 | 105 | |
| 98 | 106 | /// The entry's setup files read again, as its text names them now. |
| @@ -118,10 +126,11 @@ public final class DocumentSession { | ||
| 118 | 126 | private let fileSystem: FileSystem |
| 119 | 127 | private let recovery: RecoveryStore |
| 120 | 128 | @ObservationIgnored private var entries: [Entry] = [] |
| 121 | @ObservationIgnored private var current: Entry? | |
| 122 | /// Paths, most recently shown first. | |
| 129 | /// The focused pane's buffer. | |
| 130 | private var current: Entry? { focused.path.flatMap(entry) } | |
| 131 | /// Paths, most recently shown first, across every pane. | |
| 123 | 132 | @ObservationIgnored private var history: [String] = [] |
| 124 | @ObservationIgnored private var outlineUpdate: Task<Void, Never>? | |
| 133 | @ObservationIgnored private var outlineUpdates: [String: Task<Void, Never>] = [:] | |
| 125 | 134 | private var requestID = 0 |
| 126 | 135 | |
| 127 | 136 | public init( |
| @@ -130,10 +139,34 @@ public final class DocumentSession { | ||
| 130 | 139 | ) { |
| 131 | 140 | self.fileSystem = fileSystem |
| 132 | 141 | self.recovery = recovery |
| 142 | let pane = EditorPane() | |
| 143 | panes = [pane] | |
| 144 | focused = pane | |
| 145 | } | |
| 146 | ||
| 147 | // MARK: - Panes | |
| 148 | ||
| 149 | /// A new, empty pane. | |
| 150 | public func makePane() -> EditorPane { | |
| 151 | let pane = EditorPane() | |
| 152 | panes.append(pane) | |
| 153 | return pane | |
| 154 | } | |
| 155 | ||
| 156 | /// Removes `pane`; its buffers stay open. The last pane stays. | |
| 157 | public func closePane(_ pane: EditorPane) { | |
| 158 | guard panes.count > 1, let index = panes.firstIndex(where: { $0 === pane }) else { return } | |
| 159 | panes.remove(at: index) | |
| 160 | if focused === pane { focused = panes[0] } | |
| 161 | } | |
| 162 | ||
| 163 | /// The panes showing `path`. | |
| 164 | private func panes(showing path: String) -> [EditorPane] { | |
| 165 | panes.filter { $0.path == path } | |
| 133 | 166 | } |
| 134 | 167 | |
| 135 | 168 | private var buffer: DocumentBuffer? { current?.buffer } |
| 136 | /// The current buffer's pending autosave, for tests to wait on. | |
| 169 | /// The focused buffer's pending autosave, for tests to wait on. | |
| 137 | 170 | var autosave: Task<Void, Never>? { current?.autosave } |
| 138 | 171 | private var url: URL? { path.map { URL(fileURLWithPath: $0) } } |
| 139 | 172 | /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text. |
| @@ -186,12 +219,17 @@ public final class DocumentSession { | ||
| 186 | 219 | /// Open buffers, most recently shown first. |
| 187 | 220 | public var recentPaths: [String] { history.filter(isOpen) } |
| 188 | 221 | |
| 189 | /// Shows the buffer of `path`, opening the file if it isn't open. | |
| 222 | /// Shows the buffer of `path` in the focused pane, opening the file if it isn't open. | |
| 190 | 223 | public func open(_ path: String) { |
| 224 | open(path, in: focused) | |
| 225 | } | |
| 226 | ||
| 227 | /// Shows the buffer of `path` in `pane`, opening the file if it isn't open. | |
| 228 | public func open(_ path: String, in pane: EditorPane) { | |
| 191 | 229 | let interval = Perf.begin("session.open") |
| 192 | 230 | defer { interval.end((path as NSString).lastPathComponent) } |
| 193 | 231 | if let existing = entry(path) { |
| 194 | activate(existing) | |
| 232 | show(existing, in: pane) | |
| 195 | 233 | return |
| 196 | 234 | } |
| 197 | 235 | do { |
| @@ -200,108 +238,141 @@ public final class DocumentSession { | ||
| 200 | 238 | return |
| 201 | 239 | } |
| 202 | 240 | let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path))) |
| 203 | let index = current.flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count | |
| 241 | let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count | |
| 204 | 242 | entries.insert(entry, at: index) |
| 205 | activate(entry) | |
| 243 | show(entry, in: pane) | |
| 206 | 244 | } catch { |
| 207 | 245 | lastError = "Can't open \(path): \(error.localizedDescription)" |
| 208 | 246 | } |
| 209 | 247 | } |
| 210 | 248 | |
| 211 | private func activate(_ entry: Entry) { | |
| 212 | current = entry | |
| 213 | path = entry.path | |
| 214 | conflict = entry.conflict | |
| 215 | revealRequest = nil | |
| 249 | private func show(_ entry: Entry, in pane: EditorPane) { | |
| 250 | pane.path = entry.path | |
| 251 | if !pane.shown.contains(entry.path) { pane.shown.append(entry.path) } | |
| 252 | pane.history.removeAll { $0 == entry.path } | |
| 253 | pane.history.insert(entry.path, at: 0) | |
| 254 | pane.revealRequest = nil | |
| 216 | 255 | history.removeAll { $0 == entry.path } |
| 217 | 256 | history.insert(entry.path, at: 0) |
| 218 | refresh() | |
| 257 | refresh(pane) | |
| 219 | 258 | } |
| 220 | 259 | |
| 221 | /// The buffer before or after the current one, wrapping. | |
| 260 | /// The buffer before or after the focused one, wrapping, in the focused pane. | |
| 222 | 261 | public func cycle(_ step: Int) { |
| 223 | 262 | guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return } |
| 224 | activate(entries[((index + step) % entries.count + entries.count) % entries.count]) | |
| 263 | show(entries[((index + step) % entries.count + entries.count) % entries.count], in: focused) | |
| 225 | 264 | } |
| 226 | 265 | |
| 227 | /// The buffer shown before the current one. | |
| 266 | /// The buffer shown before the focused one. | |
| 228 | 267 | public func showPrevious() { |
| 229 | 268 | guard let previous = recentPaths.dropFirst().first else { return } |
| 230 | 269 | open(previous) |
| 231 | 270 | } |
| 232 | 271 | |
| 233 | /// Closes the buffer of `path` without saving it; the most recent other buffer shows. | |
| 272 | /// Closes the buffer of `path` without saving it. A pane showing it shows the buffer it | |
| 273 | /// showed before, else the most recent other buffer, else nothing. | |
| 234 | 274 | public func kill(_ path: String) { |
| 235 | 275 | guard let entry = entry(path) else { return } |
| 236 | 276 | entry.autosave?.cancel() |
| 237 | 277 | entries.removeAll { $0 === entry } |
| 238 | 278 | history.removeAll { $0 == path } |
| 239 | if entry === current { | |
| 240 | current = nil | |
| 241 | if let next = recentPaths.first.flatMap(self.entry) ?? entries.last { | |
| 242 | activate(next) | |
| 279 | outlineUpdates[path]?.cancel() | |
| 280 | outlineUpdates[path] = nil | |
| 281 | for pane in panes { | |
| 282 | pane.shown.removeAll { $0 == path } | |
| 283 | pane.history.removeAll { $0 == path } | |
| 284 | guard pane.path == path else { continue } | |
| 285 | if let next = pane.history.first.flatMap(self.entry) ?? recentPaths.first.flatMap(self.entry) ?? entries.last { | |
| 286 | show(next, in: pane) | |
| 243 | 287 | } else { |
| 244 | outlineUpdate?.cancel() | |
| 245 | self.path = nil | |
| 246 | document = nil | |
| 247 | outline = [] | |
| 248 | isDirty = false | |
| 249 | conflict = nil | |
| 250 | revealRequest = nil | |
| 251 | refreshLists() | |
| 288 | pane.path = nil | |
| 289 | pane.outline = [] | |
| 290 | pane.isDirty = false | |
| 291 | pane.isReadOnly = false | |
| 292 | pane.conflict = nil | |
| 293 | pane.revealRequest = nil | |
| 252 | 294 | } |
| 253 | } else { | |
| 254 | refreshLists() | |
| 255 | 295 | } |
| 296 | refreshLists() | |
| 256 | 297 | } |
| 257 | 298 | |
| 258 | /// Closes the current buffer without saving, as when its file was deleted. | |
| 299 | /// Closes the focused buffer without saving, as when its file was deleted. | |
| 259 | 300 | public func close() { |
| 260 | 301 | if let path { kill(path) } |
| 261 | 302 | } |
| 262 | 303 | |
| 263 | /// Makes `buffer`, built from `document`, the live state of the current file. | |
| 304 | /// Makes `buffer`, built from `document`, the live state of the focused file. | |
| 264 | 305 | public func attach(_ buffer: DocumentBuffer) { |
| 265 | current?.buffer = buffer | |
| 266 | refresh() | |
| 306 | if let path { attach(buffer, for: path) } | |
| 307 | } | |
| 308 | ||
| 309 | /// Makes `buffer`, built from the file's `document`, the live state of `path`. | |
| 310 | public func attach(_ buffer: DocumentBuffer, for path: String) { | |
| 311 | guard let entry = entry(path) else { return } | |
| 312 | entry.buffer = buffer | |
| 313 | for pane in panes(showing: path) { refresh(pane) } | |
| 267 | 314 | } |
| 268 | 315 | |
| 269 | /// The buffer of `path` changed in its editor: the current one updates its views, another | |
| 270 | /// saves on its own. | |
| 316 | /// The buffer of `path` changed in its editor: the panes showing it update their views | |
| 317 | /// once typing pauses, and it saves on its own. | |
| 271 | 318 | public func bufferChanged(_ path: String) { |
| 272 | 319 | guard let entry = entry(path) else { return } |
| 273 | if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() } | |
| 320 | changed(entry) | |
| 274 | 321 | } |
| 275 | 322 | |
| 276 | /// The buffer changed through typing. The outline follows once typing pauses. | |
| 323 | /// The focused buffer changed through typing. | |
| 277 | 324 | public func bufferChanged() { |
| 278 | refresh(outline: false) | |
| 279 | outlineUpdate?.cancel() | |
| 280 | outlineUpdate = Task { [weak self] in | |
| 281 | try? await Task.sleep(for: .milliseconds(300)) | |
| 282 | guard !Task.isCancelled, let self, let document = self.document else { return } | |
| 283 | self.outline = self.isOrg ? Presentation.outline(document.tree) : [] | |
| 284 | self.editVersion += 1 | |
| 325 | if let current { changed(current) } | |
| 326 | } | |
| 327 | ||
| 328 | /// A buffer changed, typed or not: the panes showing it update their views, the outline | |
| 329 | /// once typing pauses, and it saves on its own. | |
| 330 | private func changed(_ entry: Entry) { | |
| 331 | let showing = panes(showing: entry.path) | |
| 332 | for pane in showing { refresh(pane, outline: false) } | |
| 333 | outlineUpdates[entry.path]?.cancel() | |
| 334 | if !showing.isEmpty { | |
| 335 | let path = entry.path | |
| 336 | outlineUpdates[path] = Task { [weak self, weak entry] in | |
| 337 | try? await Task.sleep(for: .milliseconds(300)) | |
| 338 | guard !Task.isCancelled, let self, let entry else { return } | |
| 339 | let outline = Self.isOrgPath(path) ? Presentation.outline(entry.buffer.document.tree) : [] | |
| 340 | for pane in self.panes(showing: path) { | |
| 341 | pane.outline = outline | |
| 342 | pane.editVersion += 1 | |
| 343 | } | |
| 344 | } | |
| 285 | 345 | } |
| 286 | if let current { scheduleAutosave(current) } | |
| 346 | scheduleAutosave(entry) | |
| 347 | refreshLists() | |
| 287 | 348 | } |
| 288 | 349 | |
| 289 | private func refresh(outline updateOutline: Bool = true) { | |
| 350 | /// `pane`'s view of its buffer, from the buffer's state. | |
| 351 | private func refresh(_ pane: EditorPane, outline updateOutline: Bool = true) { | |
| 290 | 352 | let interval = Perf.begin("session.refresh") |
| 291 | 353 | defer { interval.end() } |
| 292 | 354 | refreshLists() |
| 293 | guard let buffer else { return } | |
| 294 | let state = buffer.document | |
| 295 | document = state | |
| 296 | if isDirty != state.isDirty { isDirty = state.isDirty } | |
| 297 | if isReadOnly == state.isEditable { isReadOnly = !state.isEditable } | |
| 298 | if conflict != current?.conflict { conflict = current?.conflict } | |
| 355 | guard let entry = pane.path.flatMap(entry) else { return } | |
| 356 | let state = entry.buffer.document | |
| 357 | if pane.isDirty != state.isDirty { pane.isDirty = state.isDirty } | |
| 358 | if pane.isReadOnly == state.isEditable { pane.isReadOnly = !state.isEditable } | |
| 359 | if pane.conflict != entry.conflict { pane.conflict = entry.conflict } | |
| 299 | 360 | if updateOutline { |
| 300 | outline = isOrg ? Presentation.outline(state.tree) : [] | |
| 301 | editVersion += 1 | |
| 361 | pane.outline = Self.isOrgPath(entry.path) ? Presentation.outline(state.tree) : [] | |
| 362 | pane.editVersion += 1 | |
| 302 | 363 | } |
| 303 | 364 | } |
| 304 | 365 | |
| 366 | /// Every pane showing `entry`, from the buffer's state. | |
| 367 | private func refresh(_ entry: Entry) { | |
| 368 | for pane in panes(showing: entry.path) { refresh(pane) } | |
| 369 | } | |
| 370 | ||
| 371 | /// The focused pane, from its buffer's state. | |
| 372 | private func refresh() { | |
| 373 | refresh(focused) | |
| 374 | } | |
| 375 | ||
| 305 | 376 | private func refreshLists() { |
| 306 | 377 | let paths = entries.map(\.path) |
| 307 | 378 | if paths != openPaths { openPaths = paths } |
| @@ -366,7 +437,7 @@ public final class DocumentSession { | ||
| 366 | 437 | } catch { |
| 367 | 438 | lastError = "Can't save \(name): \(error.localizedDescription)" |
| 368 | 439 | } |
| 369 | if entry === current { refresh() } else { refreshLists() } | |
| 440 | refresh(entry) | |
| 370 | 441 | return !entry.buffer.document.isDirty |
| 371 | 442 | } |
| 372 | 443 | |
| @@ -669,9 +740,7 @@ public final class DocumentSession { | ||
| 669 | 740 | do { |
| 670 | 741 | let options = self.options |
| 671 | 742 | let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) } |
| 672 | if case .commit = step { | |
| 673 | if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() } | |
| 674 | } | |
| 743 | if case .commit = step { changed(entry) } | |
| 675 | 744 | return step |
| 676 | 745 | } catch { |
| 677 | 746 | return .failed("\(error)") |
| @@ -830,11 +899,6 @@ public final class DocumentSession { | ||
| 830 | 899 | babelTask?.cancel() |
| 831 | 900 | } |
| 832 | 901 | |
| 833 | /// A buffer changed outside typing: the current one updates its views, another saves. | |
| 834 | private func changed(_ entry: Entry) { | |
| 835 | if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() } | |
| 836 | } | |
| 837 | ||
| 838 | 902 | // MARK: - Locations |
| 839 | 903 | |
| 840 | 904 | /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets |
| @@ -859,9 +923,15 @@ public final class DocumentSession { | ||
| 859 | 923 | reveal(offset) |
| 860 | 924 | } |
| 861 | 925 | |
| 926 | /// Asks the focused pane's editor to show `offset`. | |
| 862 | 927 | public func reveal(_ offset: Int) { |
| 928 | reveal(offset, in: focused) | |
| 929 | } | |
| 930 | ||
| 931 | /// Asks `pane`'s editor to show `offset`. | |
| 932 | public func reveal(_ offset: Int, in pane: EditorPane) { | |
| 863 | 933 | requestID += 1 |
| 864 | revealRequest = (offset, requestID) | |
| 934 | pane.revealRequest = (offset, requestID) | |
| 865 | 935 | } |
| 866 | 936 | |
| 867 | 937 | /// Called when the workspace sees a file change on disk: an open buffer of it takes the |
| @@ -885,6 +955,6 @@ public final class DocumentSession { | ||
| 885 | 955 | case .unchanged: |
| 886 | 956 | break |
| 887 | 957 | } |
| 888 | if entry === current { refresh() } else { refreshLists() } | |
| 958 | refresh(entry) | |
| 889 | 959 | } |
| 890 | 960 | } |
Sources/OrgApp/EditorPane.swift added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import OrgPresentation | |
| 4 | ||
| 5 | /// One place a buffer shows, as a window shows a buffer in Emacs: which file, the buffers it | |
| 6 | /// has shown (its tabs), and what the editor view in it follows. The session keeps these in | |
| 7 | /// step with the buffers. | |
| 8 | @MainActor | |
| 9 | @Observable | |
| 10 | public final class EditorPane: Identifiable { | |
| 11 | public let id = PaneID() | |
| 12 | /// The file shown, nil for an empty pane. | |
| 13 | public internal(set) var path: String? | |
| 14 | /// Open files this pane has shown, in the order it first showed them: its tabs. | |
| 15 | public internal(set) var shown: [String] = [] | |
| 16 | /// Files this pane has shown, most recent first. | |
| 17 | public internal(set) var history: [String] = [] | |
| 18 | public internal(set) var outline: [OutlineEntry] = [] | |
| 19 | /// Bumped when the shown buffer settles after edits, and when a file opens here. | |
| 20 | public internal(set) var editVersion = 0 | |
| 21 | public internal(set) var isDirty = false | |
| 22 | /// The file isn't UTF-8, so it can't be edited or saved. | |
| 23 | public internal(set) var isReadOnly = false | |
| 24 | /// Set while the shown buffer and the file on disk conflict; says how to resolve it. | |
| 25 | public internal(set) var conflict: String? | |
| 26 | /// Bumped to ask the editor in this pane to reveal an offset. | |
| 27 | public internal(set) var revealRequest: (offset: Int, id: Int)? | |
| 28 | ||
| 29 | public init() {} | |
| 30 | } | |
Sources/OrgApp/PaneLayout.swift added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// Identifies a pane for as long as it exists. | |
| 4 | public struct PaneID: Hashable, Sendable { | |
| 5 | private let raw = UUID() | |
| 6 | public init() {} | |
| 7 | } | |
| 8 | ||
| 9 | /// How a window divides its editor area: one pane, or two layouts side by side (`horizontal`) | |
| 10 | /// or one above the other (`vertical`), with the first's share of the space. | |
| 11 | public indirect enum PaneLayout: Equatable, Sendable { | |
| 12 | public enum Axis: Equatable, Sendable { case horizontal, vertical } | |
| 13 | ||
| 14 | case pane(PaneID) | |
| 15 | case split(axis: Axis, first: PaneLayout, second: PaneLayout, fraction: Double) | |
| 16 | ||
| 17 | /// Panes in reading order: left before right, top before bottom. | |
| 18 | public var panes: [PaneID] { | |
| 19 | switch self { | |
| 20 | case .pane(let id): [id] | |
| 21 | case .split(_, let first, let second, _): first.panes + second.panes | |
| 22 | } | |
| 23 | } | |
| 24 | ||
| 25 | /// `id` halved along `axis`, with `new` after it. | |
| 26 | public func splitting(_ id: PaneID, axis: Axis, new: PaneID) -> PaneLayout { | |
| 27 | switch self { | |
| 28 | case .pane(id): .split(axis: axis, first: .pane(id), second: .pane(new), fraction: 0.5) | |
| 29 | case .pane: self | |
| 30 | case .split(let a, let first, let second, let fraction): | |
| 31 | .split(axis: a, first: first.splitting(id, axis: axis, new: new), second: second.splitting(id, axis: axis, new: new), fraction: fraction) | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | /// The layout without `id`; its sibling takes the space. Nil when `id` was the only pane. | |
| 36 | public func removing(_ id: PaneID) -> PaneLayout? { | |
| 37 | switch self { | |
| 38 | case .pane(id): nil | |
| 39 | case .pane: self | |
| 40 | case .split(let axis, let first, let second, let fraction): | |
| 41 | switch (first.removing(id), second.removing(id)) { | |
| 42 | case (nil, let rest?), (let rest?, nil): rest | |
| 43 | case (let a?, let b?): .split(axis: axis, first: a, second: b, fraction: fraction) | |
| 44 | case (nil, nil): nil | |
| 45 | } | |
| 46 | } | |
| 47 | } | |
| 48 | ||
| 49 | /// The split whose divider lies between `before` (the last pane of its first side) and | |
| 50 | /// `after` (the first pane of its second side), with `fraction` for its first side. Each | |
| 51 | /// split is one such adjacency in reading order, so the pair names it. | |
| 52 | public func settingFraction(_ fraction: Double, ofSplitBetween before: PaneID, and after: PaneID) -> PaneLayout { | |
| 53 | switch self { | |
| 54 | case .pane: self | |
| 55 | case .split(let axis, let first, let second, let old): | |
| 56 | if first.panes.last == before, second.panes.first == after { | |
| 57 | .split(axis: axis, first: first, second: second, fraction: min(max(fraction, 0.1), 0.9)) | |
| 58 | } else { | |
| 59 | .split(axis: axis, first: first.settingFraction(fraction, ofSplitBetween: before, and: after), second: second.settingFraction(fraction, ofSplitBetween: before, and: after), fraction: old) | |
| 60 | } | |
| 61 | } | |
| 62 | } | |
| 63 | ||
| 64 | /// Only `id`, filling the window. | |
| 65 | public func only(_ id: PaneID) -> PaneLayout { .pane(id) } | |
| 66 | ||
| 67 | /// The pane after `id` in reading order, wrapping; the first when `id` isn't here. | |
| 68 | public func next(after id: PaneID) -> PaneID { | |
| 69 | let all = panes | |
| 70 | guard let index = all.firstIndex(of: id) else { return all[0] } | |
| 71 | return all[(index + 1) % all.count] | |
| 72 | } | |
| 73 | } | |
Sources/OrgCore/Keymap/PresetDoom.swift +49
| @@ -59,6 +59,55 @@ extension KeymapPreset { | ||
| 59 | 59 | keys = "SPC f s" |
| 60 | 60 | command = "app.save" |
| 61 | 61 | mode = "normal" |
| 62 | # Windows | |
| 63 | [[bind]] | |
| 64 | keys = "SPC w s" | |
| 65 | command = "app.split-below" | |
| 66 | mode = "normal" | |
| 67 | [[bind]] | |
| 68 | keys = "SPC w v" | |
| 69 | command = "app.split-right" | |
| 70 | mode = "normal" | |
| 71 | [[bind]] | |
| 72 | keys = "SPC w d" | |
| 73 | command = "app.pane-close" | |
| 74 | mode = "normal" | |
| 75 | [[bind]] | |
| 76 | keys = "SPC w c" | |
| 77 | command = "app.pane-close" | |
| 78 | mode = "normal" | |
| 79 | [[bind]] | |
| 80 | keys = "SPC w o" | |
| 81 | command = "app.pane-only" | |
| 82 | mode = "normal" | |
| 83 | [[bind]] | |
| 84 | keys = "SPC w w" | |
| 85 | command = "app.pane-next" | |
| 86 | mode = "normal" | |
| 87 | [[bind]] | |
| 88 | keys = "SPC w n" | |
| 89 | command = "app.window-new" | |
| 90 | mode = "normal" | |
| 91 | [[bind]] | |
| 92 | keys = "C-w s" | |
| 93 | command = "app.split-below" | |
| 94 | mode = "normal" | |
| 95 | [[bind]] | |
| 96 | keys = "C-w v" | |
| 97 | command = "app.split-right" | |
| 98 | mode = "normal" | |
| 99 | [[bind]] | |
| 100 | keys = "C-w c" | |
| 101 | command = "app.pane-close" | |
| 102 | mode = "normal" | |
| 103 | [[bind]] | |
| 104 | keys = "C-w o" | |
| 105 | command = "app.pane-only" | |
| 106 | mode = "normal" | |
| 107 | [[bind]] | |
| 108 | keys = "C-w w" | |
| 109 | command = "app.pane-next" | |
| 110 | mode = "normal" | |
| 62 | 111 | # Buffers |
| 63 | 112 | [[bind]] |
| 64 | 113 | keys = "SPC b b" |
Sources/OrgCore/Keymap/PresetEmacs.swift +18
| @@ -240,6 +240,24 @@ extension KeymapPreset { | ||
| 240 | 240 | keys = "C-x k" |
| 241 | 241 | command = "app.buffer.kill" |
| 242 | 242 | [[bind]] |
| 243 | keys = "C-x 2" | |
| 244 | command = "app.split-below" | |
| 245 | [[bind]] | |
| 246 | keys = "C-x 3" | |
| 247 | command = "app.split-right" | |
| 248 | [[bind]] | |
| 249 | keys = "C-x 0" | |
| 250 | command = "app.pane-close" | |
| 251 | [[bind]] | |
| 252 | keys = "C-x 1" | |
| 253 | command = "app.pane-only" | |
| 254 | [[bind]] | |
| 255 | keys = "C-x o" | |
| 256 | command = "app.pane-next" | |
| 257 | [[bind]] | |
| 258 | keys = "C-x 5 2" | |
| 259 | command = "app.window-new" | |
| 260 | [[bind]] | |
| 243 | 261 | keys = "C-x <right>" |
| 244 | 262 | command = "app.buffer.next" |
| 245 | 263 | [[bind]] |
Sources/OrgCore/Keymap/PresetMac.swift +18
| @@ -7,6 +7,24 @@ extension KeymapPreset { | ||
| 7 | 7 | keys = "C-S-TAB" |
| 8 | 8 | command = "app.buffer.previous" |
| 9 | 9 | [[bind]] |
| 10 | keys = "C-s-2" | |
| 11 | command = "app.split-below" | |
| 12 | [[bind]] | |
| 13 | keys = "C-s-3" | |
| 14 | command = "app.split-right" | |
| 15 | [[bind]] | |
| 16 | keys = "C-s-0" | |
| 17 | command = "app.pane-close" | |
| 18 | [[bind]] | |
| 19 | keys = "C-s-1" | |
| 20 | command = "app.pane-only" | |
| 21 | [[bind]] | |
| 22 | keys = "M-s-`" | |
| 23 | command = "app.pane-next" | |
| 24 | [[bind]] | |
| 25 | keys = "M-s-n" | |
| 26 | command = "app.window-new" | |
| 27 | [[bind]] | |
| 10 | 28 | keys = "C-s-t" |
| 11 | 29 | command = "org.todo.cycle" |
| 12 | 30 | [[bind]] |
Sources/OrgEditorAppKit/EditorCommands.swift +6
| @@ -68,6 +68,12 @@ public enum EditorCommands { | ||
| 68 | 68 | EditorCommand(id: "app.buffer.next", title: "Next Buffer", action: .app), |
| 69 | 69 | EditorCommand(id: "app.buffer.previous", title: "Previous Buffer", action: .app), |
| 70 | 70 | EditorCommand(id: "app.buffer.last", title: "Last Buffer", action: .app), |
| 71 | EditorCommand(id: "app.split-below", title: "Split Pane Below", action: .app), | |
| 72 | EditorCommand(id: "app.split-right", title: "Split Pane Right", action: .app), | |
| 73 | EditorCommand(id: "app.pane-close", title: "Close Pane", action: .app), | |
| 74 | EditorCommand(id: "app.pane-only", title: "Close Other Panes", action: .app), | |
| 75 | EditorCommand(id: "app.pane-next", title: "Next Pane", action: .app), | |
| 76 | EditorCommand(id: "app.window-new", title: "New Window", action: .app), | |
| 71 | 77 | EditorCommand(id: "app.babel.cancel", title: "Cancel Running Task", action: .app), |
| 72 | 78 | EditorCommand(id: "app.toggle-tab-bar", title: "Show or Hide Tab Bar", action: .app), |
| 73 | 79 | EditorCommand(id: "app.toggle-outline", title: "Show or Hide Outline", action: .app), |
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. | |
| 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 } | |
| 46 | 46 | var lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: 11, weight: .regular) |
| 47 | 47 | var lineNumberColor = NSColor.tertiaryLabelColor |
| 48 | 48 | var currentLineNumberColor = NSColor.labelColor |
Sources/OrgEditorAppKit/Modal.swift +1 −1
| @@ -388,7 +388,7 @@ extension OrgEditor { | ||
| 388 | 388 | /// A block cursor in normal and visual states, a bar in insert state. |
| 389 | 389 | func updateCursor() { |
| 390 | 390 | let block = modal && vim.mode != .insert |
| 391 | (textView as? OrgTextView)?.blockCursor = block | |
| 391 | for view in orgTextViews { view.blockCursor = block } | |
| 392 | 392 | dispatcher.mode = modal ? vim.mode.keymapMode : nil |
| 393 | 393 | let state = modal ? vim.mode.rawValue : nil |
| 394 | 394 | if state != reportedMode { |
Sources/OrgEditorAppKit/OrgEditor+Folding.swift +23 −12
| @@ -28,10 +28,17 @@ extension OrgEditor { | ||
| 28 | 28 | wrapperHidden = Dictionary(found.map { ($0.start, $0.hidden) }) { a, _ in a } |
| 29 | 29 | view.wrapperFolds = Set(wrapperHidden.keys) |
| 30 | 30 | 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 | caretsOutOfHiddenText() | |
| 33 | } | |
| 34 | ||
| 35 | /// Every view's caret moved to just before the hidden text it sits in, if any. | |
| 36 | func caretsOutOfHiddenText() { | |
| 37 | for view in textViews { | |
| 38 | let caret = view.selectedRange().location | |
| 39 | guard let range = hidden.containing(caret) else { continue } | |
| 40 | if view === active { setCaret(max(0, range.lowerBound - 1)) } else { view.setSelectedRange(NSRange(location: max(0, range.lowerBound - 1), length: 0)) } | |
| 41 | } | |
| 35 | 42 | } |
| 36 | 43 | |
| 37 | 44 | |
| @@ -70,7 +77,8 @@ extension OrgEditor { | ||
| 70 | 77 | /// Lays out `ranges` again, each widened to whole lines and to the line before it: the |
| 71 | 78 | /// heading or opening line of a fold, whose fragment draws the fold mark. |
| 72 | 79 | func invalidateLayout(lines ranges: [Range<Int>]) { |
| 73 | guard !ranges.isEmpty, let content = textLayoutManager.textContentManager else { return } | |
| 80 | guard !ranges.isEmpty else { return } | |
| 81 | let content = textContentStorage | |
| 74 | 82 | let text = textView.string as NSString |
| 75 | 83 | for range in ranges { |
| 76 | 84 | let lower = text.lineRange(for: NSRange(location: max(0, min(range.lowerBound, text.length) - 1), length: 0)).location |
| @@ -78,7 +86,7 @@ extension OrgEditor { | ||
| 78 | 86 | guard let start = content.location(content.documentRange.location, offsetBy: lower), |
| 79 | 87 | let end = content.location(start, offsetBy: upper - lower), |
| 80 | 88 | let textRange = NSTextRange(location: start, end: end) else { continue } |
| 81 | textLayoutManager.invalidateLayout(for: textRange) | |
| 89 | for layout in layoutManagers { layout.invalidateLayout(for: textRange) } | |
| 82 | 90 | } |
| 83 | 91 | } |
| 84 | 92 | |
| @@ -127,10 +135,8 @@ extension OrgEditor { | ||
| 127 | 135 | updateHiddenAndLayout() |
| 128 | 136 | restyleOutsideEditing(0..<utf16Length) |
| 129 | 137 | } |
| 130 | orgTextView?.redrawLineNumbers() | |
| 131 | textView.needsDisplay = true | |
| 132 | let caret = textView.selectedRange().location | |
| 133 | if let range = hidden.containing(caret) { setCaret(max(0, range.lowerBound - 1)) } | |
| 138 | redrawViews() | |
| 139 | caretsOutOfHiddenText() | |
| 134 | 140 | } |
| 135 | 141 | |
| 136 | 142 | /// Leaves a sparse tree for ordinary folds: headings with something shown below them |
| @@ -189,10 +195,15 @@ extension OrgEditor { | ||
| 189 | 195 | return |
| 190 | 196 | } |
| 191 | 197 | updateHiddenAndLayout() |
| 192 | orgTextView?.redrawLineNumbers() | |
| 193 | textView.needsDisplay = true | |
| 198 | redrawViews() | |
| 194 | 199 | if let narrowed { |
| 195 | 200 | setCaret(max(narrowed.lowerBound, min(caret, narrowed.upperBound))) |
| 201 | for view in textViews where view !== active { | |
| 202 | let other = view.selectedRange().location | |
| 203 | if !(narrowed.lowerBound...narrowed.upperBound).contains(other) { | |
| 204 | view.setSelectedRange(NSRange(location: max(narrowed.lowerBound, min(other, narrowed.upperBound)), length: 0)) | |
| 205 | } | |
| 206 | } | |
| 196 | 207 | textView.scrollRangeToVisible(NSRange(location: narrowed.lowerBound, length: 0)) |
| 197 | 208 | } else { |
| 198 | 209 | textView.scrollRangeToVisible(NSRange(location: caret, length: 0)) |
Sources/OrgEditorAppKit/OrgEditor+Images.swift +2 −2
| @@ -28,9 +28,9 @@ extension OrgEditor { | ||
| 28 | 28 | func refreshImages() { |
| 29 | 29 | keepingTopLine { |
| 30 | 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 | 36 | private func loadImage(_ path: String) -> NSImage? { |
Sources/OrgEditorAppKit/OrgEditor+Shrink.swift +1 −1
| @@ -13,7 +13,7 @@ extension OrgEditor { | ||
| 13 | 13 | shrunk.set(columns, in: table, text: textView.string) |
| 14 | 14 | restyleOutsideEditing(table) |
| 15 | 15 | invalidateLayout(lines: [table]) |
| 16 | textView.needsDisplay = true | |
| 16 | redrawViews() | |
| 17 | 17 | } |
| 18 | 18 | |
| 19 | 19 | /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`, |
Sources/OrgEditorAppKit/OrgEditor.swift +157 −71
| @@ -6,9 +6,23 @@ import OrgPresentation | ||
| 6 | 6 | |
| 7 | 7 | /// A TextKit 2 text view over a `DocumentState`. The text storage mirrors the document; every |
| 8 | 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 | 13 | @MainActor |
| 10 | 14 | public 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() | |
| 24 | /// A text view of this editor took keyboard focus. | |
| 25 | public var onFocus: ((NSTextView) -> Void)? | |
| 12 | 26 | public private(set) var document: DocumentState |
| 13 | 27 | public internal(set) var view = ViewState() |
| 14 | 28 | /// Called with the time from a character edit to restyled text. |
| @@ -29,7 +43,7 @@ public final class OrgEditor: NSObject { | ||
| 29 | 43 | keepingTopLine { |
| 30 | 44 | applyThemeToView() |
| 31 | 45 | restyleEverything() |
| 32 | textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange) | |
| 46 | invalidateAllLayout() | |
| 33 | 47 | } |
| 34 | 48 | } |
| 35 | 49 | } |
| @@ -86,73 +100,140 @@ public final class OrgEditor: NSObject { | ||
| 86 | 100 | self.highlighter = highlighter |
| 87 | 101 | self.mode = mode |
| 88 | 102 | let orgTextView = OrgTextView(usingTextLayoutManager: true) |
| 89 | textView = orgTextView | |
| 103 | active = orgTextView | |
| 104 | textViews = [orgTextView] | |
| 90 | 105 | dispatcher = KeyDispatcher(keymap: KeymapPreset.emacs.keymap) |
| 91 | 106 | 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 { | |
| 107 | configure(orgTextView, frame: frame, editable: editable) | |
| 108 | applyThemeToView() | |
| 109 | textView.textStorage?.delegate = self | |
| 110 | textContentStorage.delegate = self | |
| 111 | ||
| 112 | if isOrg { shaded.set(Presentation.shadedBlocks(document.tree)) } | |
| 113 | load(document.text) | |
| 114 | // Files open at their start, as in Emacs; replacing the storage leaves it at the end. | |
| 115 | textView.setSelectedRange(NSRange(location: 0, length: 0)) | |
| 116 | if isOrg { | |
| 117 | let startup = Presentation.startupDisplay(document.tree, options: options) | |
| 118 | indented = startup.indented | |
| 119 | hideStars = startup.hideStars | |
| 120 | if startup.folds != FoldState() { setFolds(startup.folds, wrappers: startup.wrappers) } | |
| 121 | shrunk = ShrunkColumns.startup(document.tree) | |
| 122 | if startup.inlineImages { showsImages = true } | |
| 123 | if startup.alignTables { _ = perform(AlignAllTables()) } | |
| 124 | if !indented || !hideStars { restyleOutsideEditing(0..<utf16Length) } | |
| 125 | } | |
| 126 | spellChecking = options.spellCheck | |
| 127 | truncatesLines = options.startupTruncated | |
| 128 | } | |
| 129 | ||
| 130 | /// A text view's settings and callbacks; the same for every view of the editor. | |
| 131 | private func configure(_ view: OrgTextView, frame: NSRect, editable: Bool) { | |
| 132 | view.keyHandler = { [weak self, unowned view] event in | |
| 133 | guard let self else { return false } | |
| 134 | self.active = view | |
| 135 | return self.handleKey(event) | |
| 136 | } | |
| 137 | view.onFocusChange = { [weak self, unowned view] in | |
| 138 | guard let self, let layout = view.textLayoutManager else { return } | |
| 139 | let id = ObjectIdentifier(layout) | |
| 140 | if view.window?.firstResponder === view, self.active !== view { | |
| 141 | self.active = view | |
| 142 | // Its caret may sit in text another view folded or narrowed away since. | |
| 143 | self.selectionChanged() | |
| 144 | self.onFocus?(view) | |
| 145 | } else if view.window?.firstResponder === view { | |
| 146 | self.onFocus?(view) | |
| 147 | } | |
| 148 | if let window = view.window, window.isKeyWindow, window.firstResponder === view { | |
| 97 | 149 | Theme.focusedLayouts.insert(id) |
| 98 | 150 | } else { |
| 99 | 151 | Theme.focusedLayouts.remove(id) |
| 100 | 152 | } |
| 101 | self.redrawShaded([self.textView.selectedRange()]) | |
| 153 | self.redrawShaded([view.selectedRange()]) | |
| 102 | 154 | } |
| 103 | orgTextView.onCommandClick = { [weak self] offset in | |
| 155 | view.onCommandClick = { [weak self, unowned view] offset in | |
| 104 | 156 | guard let self, Links.link(at: offset, text: self.document.text, tree: self.document.tree) != nil |
| 105 | 157 | || Links.timestampDays(at: offset, text: self.document.text) != nil else { return false } |
| 158 | self.active = view | |
| 106 | 159 | self.setCaret(offset) |
| 107 | 160 | self.run("org.link.open") |
| 108 | 161 | return true |
| 109 | 162 | } |
| 110 | orgTextView.onClick = { [weak self] offset in self?.click(at: offset) ?? false } | |
| 111 | orgTextView.accessibleText = { [weak self] in | |
| 163 | view.onClick = { [weak self, unowned view] offset in | |
| 164 | self?.active = view | |
| 165 | return self?.click(at: offset) ?? false | |
| 166 | } | |
| 167 | view.accessibleText = { [weak self] in | |
| 112 | 168 | guard let self, let storage = self.textView.textStorage else { return AccessibleText(NSAttributedString()) } |
| 113 | 169 | if let cached = self.accessibleCache, cached.storage == self.storageGeneration { return cached.text } |
| 114 | 170 | let text = AccessibleText(storage) |
| 115 | 171 | self.accessibleCache = (self.storageGeneration, text) |
| 116 | 172 | return text |
| 117 | 173 | } |
| 118 | orgTextView.onMouseDown = { [weak self] in | |
| 174 | view.onMouseDown = { [weak self, unowned view] in | |
| 175 | self?.active = view | |
| 119 | 176 | self?.markActive = false |
| 120 | 177 | self?.modalMouseDown() |
| 121 | 178 | } |
| 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 | |
| 179 | view.sharedUndoManager = undoManager | |
| 180 | view.usesFindBar = true | |
| 181 | view.frame = frame | |
| 182 | view.isRichText = false | |
| 183 | view.isEditable = editable | |
| 184 | view.allowsUndo = true | |
| 185 | view.isAutomaticQuoteSubstitutionEnabled = false | |
| 186 | view.isAutomaticDashSubstitutionEnabled = false | |
| 187 | view.isAutomaticTextReplacementEnabled = false | |
| 188 | view.isAutomaticSpellingCorrectionEnabled = false | |
| 189 | view.isVerticallyResizable = true | |
| 190 | view.autoresizingMask = [.width] | |
| 191 | view.textContainer?.widthTracksTextView = true | |
| 192 | view.delegate = self | |
| 193 | view.textLayoutManager?.delegate = self | |
| 194 | } | |
| 195 | ||
| 196 | /// Another text view on the same text, with its own layout, caret and scroll position. | |
| 197 | /// Its layout manager's delegate is set before its first layout, which TextKit needs. | |
| 198 | public func addView(frame: NSRect = NSRect(x: 0, y: 0, width: 600, height: 800)) -> NSTextView { | |
| 199 | let layout = NSTextLayoutManager() | |
| 200 | layout.delegate = self | |
| 201 | textContentStorage.addTextLayoutManager(layout) | |
| 202 | let container = NSTextContainer(size: NSSize(width: frame.width, height: CGFloat.greatestFiniteMagnitude)) | |
| 203 | layout.textContainer = container | |
| 204 | let view = OrgTextView(frame: frame, textContainer: container) | |
| 205 | textViews.append(view) | |
| 206 | configure(view, frame: frame, editable: active.isEditable) | |
| 207 | view.lineIndex = lines | |
| 208 | view.showsLineNumbers = showLineNumbers | |
| 209 | view.isContinuousSpellCheckingEnabled = active.isContinuousSpellCheckingEnabled | |
| 210 | view.blockCursor = active.blockCursor | |
| 131 | 211 | 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 | |
| 212 | return view | |
| 213 | } | |
| 139 | 214 | |
| 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) } | |
| 215 | /// Takes a view made by `addView` off the storage. The first view stays. | |
| 216 | public func removeView(_ view: NSTextView) { | |
| 217 | guard let index = textViews.firstIndex(where: { $0 === view }), index > 0 else { return } | |
| 218 | textViews.remove(at: index) | |
| 219 | if active === view { active = orgTextViews[0] } | |
| 220 | if let layout = view.textLayoutManager { | |
| 221 | Theme.focusedLayouts.remove(ObjectIdentifier(layout)) | |
| 222 | textContentStorage.removeTextLayoutManager(layout) | |
| 223 | } | |
| 224 | } | |
| 225 | ||
| 226 | /// Lays every view out again. | |
| 227 | func invalidateAllLayout() { | |
| 228 | for layout in layoutManagers { layout.invalidateLayout(for: layout.documentRange) } | |
| 229 | } | |
| 230 | ||
| 231 | /// Redraws every view, line numbers included. | |
| 232 | func redrawViews() { | |
| 233 | for view in orgTextViews { | |
| 234 | view.redrawLineNumbers() | |
| 235 | view.needsDisplay = true | |
| 153 | 236 | } |
| 154 | spellChecking = options.spellCheck | |
| 155 | truncatesLines = options.startupTruncated | |
| 156 | 237 | } |
| 157 | 238 | |
| 158 | 239 | /// Replaces the storage's text. Setting the attributed string directly is about 100x |
| @@ -162,8 +243,10 @@ public final class OrgEditor: NSObject { | ||
| 162 | 243 | textView.textStorage?.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) |
| 163 | 244 | isLoading = false |
| 164 | 245 | lines.reset(text as NSString) |
| 165 | orgTextView?.lineIndex = lines | |
| 166 | orgTextView?.updateGutter() | |
| 246 | for view in orgTextViews { | |
| 247 | view.lineIndex = lines | |
| 248 | view.updateGutter() | |
| 249 | } | |
| 167 | 250 | styledUpTo = 0 |
| 168 | 251 | styleNextChunk(Self.firstStyleChunk) |
| 169 | 252 | scheduleStyling() |
| @@ -181,16 +264,16 @@ public final class OrgEditor: NSObject { | ||
| 181 | 264 | styledUpTo = end |
| 182 | 265 | } |
| 183 | 266 | |
| 184 | /// The text view's own colors and font, and the line numbers'. | |
| 267 | /// Every text view's own colors and font, and the line numbers'. | |
| 185 | 268 | 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 | 269 | Theme.selection = theme.color("selection") ?? .selectedTextBackgroundColor |
| 192 | textView.selectedTextAttributes = [.backgroundColor: Theme.selection] | |
| 193 | if let view = orgTextView { | |
| 270 | for view in orgTextViews { | |
| 271 | view.font = theme.font | |
| 272 | view.typingAttributes = theme.base | |
| 273 | view.drawsBackground = true | |
| 274 | view.backgroundColor = theme.color("background") ?? .textBackgroundColor | |
| 275 | view.insertionPointColor = theme.color("cursor") ?? .textColor | |
| 276 | view.selectedTextAttributes = [.backgroundColor: Theme.selection] | |
| 194 | 277 | view.lineNumberFont = NSFont.monospacedDigitSystemFont(ofSize: max(8, theme.font.pointSize - 2), weight: .regular) |
| 195 | 278 | view.lineNumberColor = theme.color("line-number") ?? .tertiaryLabelColor |
| 196 | 279 | view.currentLineNumberColor = theme.color("line-number-current") ?? .labelColor |
| @@ -232,12 +315,13 @@ public final class OrgEditor: NSObject { | ||
| 232 | 315 | var textContentStorage: NSTextContentStorage { textLayoutManager.textContentManager as! NSTextContentStorage } |
| 233 | 316 | var utf16Length: Int { (textView.string as NSString).length } |
| 234 | 317 | |
| 235 | /// A scroll view holding the text view, ready for a window. | |
| 236 | public func makeScrollView() -> NSScrollView { | |
| 318 | /// A scroll view holding `view` (the active text view by default), ready for a window. | |
| 319 | public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView { | |
| 320 | let textView = view ?? self.textView | |
| 237 | 321 | let scroll = NSScrollView(frame: textView.frame) |
| 238 | 322 | scroll.hasVerticalScroller = true |
| 239 | 323 | scroll.documentView = textView |
| 240 | orgTextView?.showsLineNumbers = showLineNumbers | |
| 324 | (textView as? OrgTextView)?.showsLineNumbers = showLineNumbers | |
| 241 | 325 | textView.minSize = NSSize(width: 0, height: scroll.contentSize.height) |
| 242 | 326 | textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) |
| 243 | 327 | return scroll |
| @@ -300,7 +384,7 @@ public final class OrgEditor: NSObject { | ||
| 300 | 384 | } |
| 301 | 385 | /// Line numbers in a ruler beside the text. |
| 302 | 386 | public var showLineNumbers = true { |
| 303 | didSet { orgTextView?.showsLineNumbers = showLineNumbers } | |
| 387 | didSet { for view in orgTextViews { view.showsLineNumbers = showLineNumbers } } | |
| 304 | 388 | } |
| 305 | 389 | var orgTextView: OrgTextView? { textView as? OrgTextView } |
| 306 | 390 | |
| @@ -672,8 +756,10 @@ public final class OrgEditor: NSObject { | ||
| 672 | 756 | onEditTiming?(clock.now - start) |
| 673 | 757 | let lineCount = lines.lineCount |
| 674 | 758 | lines.replace(edit.range, newLength: edit.replacement.utf16.count, in: newText) |
| 675 | if lines.lineCount != lineCount { orgTextView?.updateGutter() } | |
| 676 | orgTextView?.redrawLineNumbers() | |
| 759 | for view in orgTextViews { | |
| 760 | if lines.lineCount != lineCount { view.updateGutter() } | |
| 761 | view.redrawLineNumbers() | |
| 762 | } | |
| 677 | 763 | onChange?() |
| 678 | 764 | } |
| 679 | 765 | |
| @@ -703,7 +789,7 @@ public final class OrgEditor: NSObject { | ||
| 703 | 789 | } |
| 704 | 790 | |
| 705 | 791 | private func redrawShaded(_ ranges: [NSRange]) { |
| 706 | guard let manager = textLayoutManager.textContentManager else { return } | |
| 792 | let manager = textContentStorage | |
| 707 | 793 | for old in ranges where old.length > 0 { |
| 708 | 794 | for block in shaded.all where block.overlaps(old.location..<NSMaxRange(old)) { |
| 709 | 795 | let lower = max(block.lowerBound, old.location) |
| @@ -711,7 +797,7 @@ public final class OrgEditor: NSObject { | ||
| 711 | 797 | guard let start = manager.location(manager.documentRange.location, offsetBy: lower), |
| 712 | 798 | let end = manager.location(start, offsetBy: upper - lower), |
| 713 | 799 | let range = NSTextRange(location: start, end: end) else { continue } |
| 714 | textLayoutManager.invalidateLayout(for: range) | |
| 800 | for layout in layoutManagers { layout.invalidateLayout(for: range) } | |
| 715 | 801 | } |
| 716 | 802 | } |
| 717 | 803 | } |
| @@ -756,27 +842,27 @@ extension OrgEditor: DocumentBuffer { | ||
| 756 | 842 | return [selected.location..<NSMaxRange(selected)] |
| 757 | 843 | } |
| 758 | 844 | |
| 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. | |
| 845 | /// Runs `change`; if it changed the text, reloads the views with folds and each view's | |
| 846 | /// selection mapped through the change. Undo refers to the old text, so it is cleared. | |
| 761 | 847 | public func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T { |
| 762 | 848 | let before = document.text |
| 763 | 849 | let defaultsBefore = document.defaults |
| 764 | let selected = textView.selectedRange() | |
| 850 | let selections = textViews.map(\.selectedRange) | |
| 765 | 851 | let result = try change(&document) |
| 766 | 852 | if document.text != before { |
| 767 | 853 | let edits = lineEdits(from: before, to: document.text) |
| 768 | 854 | var state = view |
| 769 | state.selection = [selected.location..<NSMaxRange(selected)] | |
| 855 | state.selection = selections.map { $0.location..<NSMaxRange($0) } | |
| 770 | 856 | let mapped = state.mapped(through: edits) |
| 771 | 857 | // Shrunk columns were measured on the old text. |
| 772 | 858 | shrunk = ShrunkColumns() |
| 773 | 859 | load(document.text) |
| 774 | 860 | 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) | |
| 861 | for (view, selection) in zip(textViews, mapped.selection) { | |
| 862 | if view === active { setCaret(selection.lowerBound) } else { view.setSelectedRange(NSRange(location: selection.lowerBound, length: 0)) } | |
| 863 | if !selection.isEmpty { view.setSelectedRange(NSRange(selection)) } | |
| 864 | } | |
| 865 | undoManager.removeAllActions() | |
| 780 | 866 | } else if document.defaults != defaultsBefore { |
| 781 | 867 | // New settings for the same text: TODO keywords may color differently. |
| 782 | 868 | restyleEverything() |
Sources/OrgEditorAppKit/ViewToggles.swift +3 −1
| @@ -10,7 +10,7 @@ extension OrgEditor { | ||
| 10 | 10 | public var spellChecking: Bool { |
| 11 | 11 | get { textView.isContinuousSpellCheckingEnabled } |
| 12 | 12 | set { |
| 13 | textView.isContinuousSpellCheckingEnabled = newValue | |
| 13 | for view in textViews { view.isContinuousSpellCheckingEnabled = newValue } | |
| 14 | 14 | if !newValue, let storage = textView.textStorage { |
| 15 | 15 | storage.removeAttribute(.spellingState, range: NSRange(location: 0, length: storage.length)) |
| 16 | 16 | } |
| @@ -90,6 +90,8 @@ extension OrgEditor { | ||
| 90 | 90 | |
| 91 | 91 | extension OrgEditor: NSTextViewDelegate { |
| 92 | 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 | 95 | selectionChanged() |
| 94 | 96 | if completionPopup != nil, let popup = completionPopup, textView.selectedRange().location != popup.completion.range.upperBound { |
| 95 | 97 | refreshCompletion() |
Sources/Orgstar/BlockEditorView.swift +1 −1
| @@ -46,7 +46,7 @@ struct CodeEditor: NSViewRepresentable { | ||
| 46 | 46 | let done: (Bool) -> Void |
| 47 | 47 | |
| 48 | 48 | func makeNSView(context: Context) -> NSScrollView { |
| 49 | let editor = OrgEditor(document: DocumentState(bytes: [UInt8](text.utf8)), highlighter: EditorView.highlighter, mode: .plain(language: language)) | |
| 49 | let editor = OrgEditor(document: DocumentState(bytes: [UInt8](text.utf8)), highlighter: PaneView.highlighter, mode: .plain(language: language)) | |
| 50 | 50 | editor.keymap = Keymap([ |
| 51 | 51 | KeyBinding(keys: KeySequence.parse("C-c '")!, command: "app.block.save"), |
| 52 | 52 | KeyBinding(keys: KeySequence.parse("C-c C-k")!, command: "app.block.cancel"), |
Sources/Orgstar/BufferTabs.swift +8 −10
| @@ -26,15 +26,17 @@ struct PaneDivider: View { | ||
| 26 | 26 | } |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | /// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits. | |
| 29 | /// A tab for each buffer the pane has shown: click to show it, × to close it, a dot for | |
| 30 | /// unsaved edits. | |
| 30 | 31 | struct BufferTabs: View { |
| 31 | 32 | let session: DocumentSession |
| 33 | let pane: EditorPane | |
| 32 | 34 | @Environment(\.orgTheme) private var theme |
| 33 | 35 | |
| 34 | 36 | var body: some View { |
| 35 | 37 | ScrollView(.horizontal, showsIndicators: false) { |
| 36 | 38 | HStack(spacing: 0) { |
| 37 | ForEach(session.openPaths, id: \.self) { path in | |
| 39 | ForEach(pane.shown, id: \.self) { path in | |
| 38 | 40 | tab(path) |
| 39 | 41 | } |
| 40 | 42 | } |
| @@ -45,19 +47,15 @@ struct BufferTabs: View { | ||
| 45 | 47 | } |
| 46 | 48 | |
| 47 | 49 | private func tab(_ path: String) -> some View { |
| 48 | let current = path == session.path | |
| 50 | let current = path == pane.path | |
| 49 | 51 | return HStack(spacing: 6) { |
| 50 | 52 | Text(session.bufferName(path)) |
| 51 | 53 | .lineLimit(1) |
| 52 | 54 | .foregroundStyle(current ? .primary : .secondary) |
| 53 | 55 | .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton) |
| 54 | .accessibilityAction { session.open(path) } | |
| 56 | .accessibilityAction { session.open(path, in: pane) } | |
| 55 | 57 | Button { |
| 56 | if path == session.path { | |
| 57 | if UnsavedChanges.resolve(session) { session.kill(path) } | |
| 58 | } else if UnsavedChanges.resolve(session, paths: [path]) { | |
| 59 | session.kill(path) | |
| 60 | } | |
| 58 | if UnsavedChanges.resolve(session, paths: [path]) { session.kill(path) } | |
| 61 | 59 | } label: { |
| 62 | 60 | Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark") |
| 63 | 61 | .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold)) |
| @@ -74,7 +72,7 @@ struct BufferTabs: View { | ||
| 74 | 72 | .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) } |
| 75 | 73 | .overlay(alignment: .trailing) { Divider() } |
| 76 | 74 | .contentShape(Rectangle()) |
| 77 | .onTapGesture { session.open(path) } | |
| 75 | .onTapGesture { session.open(path, in: pane) } | |
| 78 | 76 | .help(path) |
| 79 | 77 | } |
| 80 | 78 | } |
Sources/Orgstar/ContentView.swift +107 −12
| @@ -97,6 +97,44 @@ struct ContentView: View { | ||
| 97 | 97 | @State private var plainOutlineShown = false |
| 98 | 98 | @State private var showingImport = false |
| 99 | 99 | @AppStorage("showTabBar") private var showTabBar = false |
| 100 | /// This window's panes. | |
| 101 | @State private var window: WindowModel? | |
| 102 | ||
| 103 | private var editorSettings: EditorSettings { | |
| 104 | EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme) | |
| 105 | } | |
| 106 | ||
| 107 | /// The pane that had the focus when a sheet opened, to act on when it closes. | |
| 108 | @State private var sheetTarget: EditorPane? | |
| 109 | ||
| 110 | /// Puts the focus back on the pane a sheet was opened from. | |
| 111 | private func restoreSheetTarget() { | |
| 112 | guard let target = sheetTarget, session.panes.contains(where: { $0 === target }) else { return } | |
| 113 | sheetTarget = nil | |
| 114 | session.focused = target | |
| 115 | if let window = commands.store.window(of: target.id) { window.focused = target.id } | |
| 116 | if let path = target.path, let textView = commands.store.textView(for: target.id, path: path) { | |
| 117 | textView.window?.makeFirstResponder(textView) | |
| 118 | commands.editor = commands.store.editor(for: path) | |
| 119 | } | |
| 120 | } | |
| 121 | ||
| 122 | /// The window holding the focused pane: this one, or an editor window. | |
| 123 | private var paneWindow: WindowModel? { | |
| 124 | commands.store.window(of: session.focused.id) ?? window | |
| 125 | } | |
| 126 | ||
| 127 | /// Gives the focused pane's text view the keyboard, after a pane command moved the focus. | |
| 128 | private func focusPane(_ window: WindowModel) { | |
| 129 | let pane = window.focusedPane | |
| 130 | session.focused = pane | |
| 131 | if let path = pane.path, let textView = commands.store.textView(for: pane.id, path: path) { | |
| 132 | textView.window?.makeFirstResponder(textView) | |
| 133 | commands.editor = commands.store.editor(for: path) | |
| 134 | } else { | |
| 135 | commands.editor = nil | |
| 136 | } | |
| 137 | } | |
| 100 | 138 | /// Carets of restored buffers, shown when each first shows. |
| 101 | 139 | @State private var pendingCarets: [String: Int] = [:] |
| 102 | 140 | @State private var query = "" |
| @@ -118,10 +156,9 @@ struct ContentView: View { | ||
| 118 | 156 | private var detail: some View { |
| 119 | 157 | if let previewPath { |
| 120 | 158 | FilePreview(path: previewPath) |
| 121 | } else if session.path != nil { | |
| 122 | VStack(spacing: 0) { | |
| 123 | if showTabBar { BufferTabs(session: session) } | |
| 124 | EditorView(session: session, commands: commands, keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme, onAppCommand: perform, onExternal: runExternal, knownTags: { [index = workspace.index] in (try? index.tags()) ?? [] }) | |
| 159 | } else if !session.openPaths.isEmpty, let window { | |
| 160 | PaneLayoutView(layout: window.layout, window: window) { pane in | |
| 161 | PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform) | |
| 125 | 162 | } |
| 126 | 163 | .safeAreaInset(edge: .bottom, spacing: 0) { |
| 127 | 164 | VStack(spacing: 0) { |
| @@ -240,7 +277,38 @@ struct ContentView: View { | ||
| 240 | 277 | let copies = session.syncConflictCopies().count |
| 241 | 278 | if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") } |
| 242 | 279 | } |
| 243 | .onChange(of: session.openPaths) { BufferRestore.save(session) } | |
| 280 | .onChange(of: session.openPaths) { _, paths in | |
| 281 | BufferRestore.save(session) | |
| 282 | for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) } | |
| 283 | } | |
| 284 | .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings } | |
| 285 | .onAppear { | |
| 286 | commands.externalHandler = runExternal | |
| 287 | commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] } | |
| 288 | commands.mainWindowOpen = true | |
| 289 | if let stale = window { commands.store.windows.removeAll { $0 === stale } } | |
| 290 | // The session's first pane the first time; a new one showing the focused buffer | |
| 291 | // when the window opens again. | |
| 292 | let pane: EditorPane | |
| 293 | if commands.store.window(of: session.panes[0].id) == nil, window == nil { | |
| 294 | pane = session.panes[0] | |
| 295 | } else { | |
| 296 | pane = session.makePane() | |
| 297 | if let path = session.focused.path { session.open(path, in: pane) } | |
| 298 | } | |
| 299 | let model = WindowModel(session: session, pane: pane) | |
| 300 | window = model | |
| 301 | commands.store.windows.insert(model, at: 0) | |
| 302 | model.focus(pane.id) | |
| 303 | } | |
| 304 | .onDisappear { | |
| 305 | commands.mainWindowOpen = false | |
| 306 | guard let model = window else { return } | |
| 307 | for id in model.layout.panes { commands.store.releasePane(id) } | |
| 308 | model.closeAll() | |
| 309 | commands.store.windows.removeAll { $0 === model } | |
| 310 | commands.editor = nil | |
| 311 | } | |
| 244 | 312 | .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode } |
| 245 | 313 | .onChange(of: options, initial: true) { _, options in session.options = options } |
| 246 | 314 | .onChange(of: preset, initial: true) { loadKeymap() } |
| @@ -271,10 +339,16 @@ struct ContentView: View { | ||
| 271 | 339 | .sheet(isPresented: $commands.showingPalette) { |
| 272 | 340 | PaletteView(commands: commands) { id in |
| 273 | 341 | commands.showingPalette = false |
| 274 | // After the sheet closes, so app commands can present their own. | |
| 275 | DispatchQueue.main.async { perform(id) } | |
| 342 | // After the sheet closes, so app commands can present their own, and in the | |
| 343 | // pane that had the focus when it opened: closing a sheet makes this window key. | |
| 344 | DispatchQueue.main.async { | |
| 345 | restoreSheetTarget() | |
| 346 | perform(id) | |
| 347 | } | |
| 276 | 348 | } |
| 277 | 349 | } |
| 350 | .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } } | |
| 351 | .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } } | |
| 278 | 352 | .onChange(of: session.conflict) { _, conflict in |
| 279 | 353 | if conflict != nil { commands.showingConflict = true } |
| 280 | 354 | } |
| @@ -298,7 +372,7 @@ struct ContentView: View { | ||
| 298 | 372 | hotKey?.unregister() |
| 299 | 373 | hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil |
| 300 | 374 | } |
| 301 | .onChange(of: commands.runRequest?.serial) { | |
| 375 | .onChange(of: commands.runRequest?.serial, initial: true) { | |
| 302 | 376 | if let id = commands.runRequest?.id { perform(id) } |
| 303 | 377 | } |
| 304 | 378 | .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in |
| @@ -331,8 +405,12 @@ struct ContentView: View { | ||
| 331 | 405 | } |
| 332 | 406 | .sheet(isPresented: $commands.showingQuickOpen) { |
| 333 | 407 | QuickOpenView(workspace: workspace) { entry in |
| 334 | selectedFile = entry.path | |
| 335 | 408 | commands.showingQuickOpen = false |
| 409 | DispatchQueue.main.async { | |
| 410 | restoreSheetTarget() | |
| 411 | selectedFile = entry.path | |
| 412 | if selectedFile == entry.path { session.open(entry.path) } | |
| 413 | } | |
| 336 | 414 | } |
| 337 | 415 | } |
| 338 | 416 | .alert("orgstar", isPresented: errorShown) { |
| @@ -405,7 +483,7 @@ struct ContentView: View { | ||
| 405 | 483 | let url = URL(fileURLWithPath: path) |
| 406 | 484 | let html = HTMLExport.page( |
| 407 | 485 | selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil, |
| 408 | codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme) | |
| 486 | codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme) | |
| 409 | 487 | ) |
| 410 | 488 | do { |
| 411 | 489 | try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent()) |
| @@ -456,7 +534,7 @@ struct ContentView: View { | ||
| 456 | 534 | ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly) |
| 457 | 535 | : HTMLExport.page( |
| 458 | 536 | text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly, |
| 459 | codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme) | |
| 537 | codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme) | |
| 460 | 538 | ) |
| 461 | 539 | do { |
| 462 | 540 | try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) |
| @@ -472,7 +550,7 @@ struct ContentView: View { | ||
| 472 | 550 | let target = destination ?? ExportScope.output(for: url, name: name, extension: ext) |
| 473 | 551 | let html = HTMLExport.page( |
| 474 | 552 | text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, |
| 475 | codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme) | |
| 553 | codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme) | |
| 476 | 554 | ) |
| 477 | 555 | let directory = url.deletingLastPathComponent() |
| 478 | 556 | if format == "print-pdf" { commands.show("Exporting to PDF…") } |
| @@ -651,6 +729,23 @@ struct ContentView: View { | ||
| 651 | 729 | let all = session.openPaths |
| 652 | 730 | if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) } |
| 653 | 731 | case "app.toggle-tab-bar": showTabBar.toggle() |
| 732 | case "app.split-below": paneWindow?.split(.vertical) | |
| 733 | case "app.split-right": paneWindow?.split(.horizontal) | |
| 734 | case "app.pane-close": | |
| 735 | guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") } | |
| 736 | commands.store.releasePane(window.focused) | |
| 737 | window.close(window.focused) | |
| 738 | focusPane(window) | |
| 739 | case "app.pane-only": | |
| 740 | guard let window = paneWindow else { return } | |
| 741 | for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) } | |
| 742 | window.closeOthers() | |
| 743 | focusPane(window) | |
| 744 | case "app.pane-next": | |
| 745 | guard let window = paneWindow else { return } | |
| 746 | window.focusNext() | |
| 747 | focusPane(window) | |
| 748 | case "app.window-new": openWindow(id: "editor") | |
| 654 | 749 | case "app.babel.cancel": |
| 655 | 750 | if session.isRunningBabel { |
| 656 | 751 | session.cancelBabel() |
Sources/Orgstar/EditorStore.swift added +80
| @@ -0,0 +1,80 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgEditorAppKit | |
| 4 | ||
| 5 | /// The editors of the open buffers and the text views the panes show them in, across every | |
| 6 | /// window: one `OrgEditor` per file, one text view per pane that shows it. | |
| 7 | @MainActor | |
| 8 | final class EditorStore { | |
| 9 | /// The editor of each open file. | |
| 10 | private(set) var editors: [String: OrgEditor] = [:] | |
| 11 | /// Each pane's text view per file, with its scroll view, kept while the pane shows | |
| 12 | /// another buffer so its caret and scroll position stay. | |
| 13 | private(set) var views: [PaneID: [String: (scroll: NSScrollView, textView: NSTextView)]] = [:] | |
| 14 | /// The pane each text view belongs to. | |
| 15 | private var paneOf: [ObjectIdentifier: EditorPane] = [:] | |
| 16 | /// The pane using an editor's first text view, which can't be removed from the editor. | |
| 17 | private var primaryOwner: [String: PaneID] = [:] | |
| 18 | /// The editor windows, for the pane commands. | |
| 19 | var windows: [WindowModel] = [] | |
| 20 | ||
| 21 | func editor(for path: String) -> OrgEditor? { editors[path] } | |
| 22 | ||
| 23 | func pane(of textView: NSTextView) -> EditorPane? { paneOf[ObjectIdentifier(textView)] } | |
| 24 | ||
| 25 | func window(of pane: PaneID) -> WindowModel? { windows.first { $0.pane(pane) != nil } } | |
| 26 | ||
| 27 | /// The text view `pane` shows `path` in, made with `make` the first time. | |
| 28 | func view(for pane: EditorPane, path: String, make: () -> OrgEditor?) -> (editor: OrgEditor, scroll: NSScrollView, textView: NSTextView)? { | |
| 29 | let editor: OrgEditor | |
| 30 | if let existing = editors[path] { | |
| 31 | editor = existing | |
| 32 | } else { | |
| 33 | guard let made = make() else { return nil } | |
| 34 | editors[path] = made | |
| 35 | editor = made | |
| 36 | } | |
| 37 | if let shown = views[pane.id]?[path] { return (editor, shown.scroll, shown.textView) } | |
| 38 | let textView: NSTextView | |
| 39 | if primaryOwner[path] == nil { | |
| 40 | primaryOwner[path] = pane.id | |
| 41 | textView = editor.textViews[0] | |
| 42 | } else { | |
| 43 | textView = editor.addView() | |
| 44 | } | |
| 45 | let scroll = editor.makeScrollView(for: textView) | |
| 46 | scroll.autoresizingMask = [.width, .height] | |
| 47 | views[pane.id, default: [:]][path] = (scroll, textView) | |
| 48 | paneOf[ObjectIdentifier(textView)] = pane | |
| 49 | return (editor, scroll, textView) | |
| 50 | } | |
| 51 | ||
| 52 | /// The text view `pane` shows `path` in, if it has one. | |
| 53 | func textView(for pane: PaneID, path: String) -> NSTextView? { views[pane]?[path]?.textView } | |
| 54 | ||
| 55 | /// Drops `pane`'s text views; its buffers stay. | |
| 56 | func releasePane(_ pane: PaneID) { | |
| 57 | for (path, shown) in views[pane] ?? [:] { drop(shown, path: path, pane: pane) } | |
| 58 | views[pane] = nil | |
| 59 | } | |
| 60 | ||
| 61 | /// Drops every text view of `path` and its editor, as the buffer closes. | |
| 62 | func releasePath(_ path: String) { | |
| 63 | for pane in views.keys { | |
| 64 | if let shown = views[pane]?[path] { drop(shown, path: path, pane: pane) } | |
| 65 | views[pane]?[path] = nil | |
| 66 | } | |
| 67 | editors[path] = nil | |
| 68 | primaryOwner[path] = nil | |
| 69 | } | |
| 70 | ||
| 71 | private func drop(_ shown: (scroll: NSScrollView, textView: NSTextView), path: String, pane: PaneID) { | |
| 72 | shown.scroll.removeFromSuperview() | |
| 73 | paneOf[ObjectIdentifier(shown.textView)] = nil | |
| 74 | if primaryOwner[path] == pane { | |
| 75 | primaryOwner[path] = nil | |
| 76 | } else { | |
| 77 | editors[path]?.removeView(shown.textView) | |
| 78 | } | |
| 79 | } | |
| 80 | } | |
Sources/Orgstar/EditorView.swift deleted −130
| @@ -1,130 +0,0 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgCore | |
| 4 | import OrgEditorAppKit | |
| 5 | import OrgPresentation | |
| 6 | import OrgHighlight | |
| 7 | import SwiftUI | |
| 8 | ||
| 9 | /// The TextKit 2 editors for the session's buffers: one per open file, kept while another | |
| 10 | /// shows so its caret, folds and undo stay. An editor becomes its buffer's live state; reveal | |
| 11 | /// requests go to the one showing. | |
| 12 | struct EditorView: NSViewRepresentable { | |
| 13 | /// One highlighter for every editor: it caches compiled grammars and results. | |
| 14 | static let highlighter = TreeSitterHighlighter() | |
| 15 | ||
| 16 | let session: DocumentSession | |
| 17 | let commands: AppCommands | |
| 18 | let keymap: Keymap | |
| 19 | let modal: Bool | |
| 20 | let optionAsMeta: OptionAsMeta | |
| 21 | let options: EditingOptions | |
| 22 | let showMarkup: Bool | |
| 23 | let showLineNumbers: Bool | |
| 24 | let theme: ThemeSpec | |
| 25 | let onAppCommand: (String) -> Void | |
| 26 | let onExternal: (ExternalRequest) -> Void | |
| 27 | let knownTags: @Sendable () -> [String] | |
| 28 | ||
| 29 | final class Coordinator { | |
| 30 | var editor: OrgEditor? | |
| 31 | var path: String? | |
| 32 | var revealID = 0 | |
| 33 | /// Editors of open buffers, with their scroll views. | |
| 34 | var editors: [String: (editor: OrgEditor, scroll: NSScrollView)] = [:] | |
| 35 | } | |
| 36 | ||
| 37 | func makeCoordinator() -> Coordinator { Coordinator() } | |
| 38 | ||
| 39 | func makeNSView(context: Context) -> NSView { | |
| 40 | NSView() | |
| 41 | } | |
| 42 | ||
| 43 | func updateNSView(_ container: NSView, context: Context) { | |
| 44 | let coordinator = context.coordinator | |
| 45 | // Buffers that were killed take their editors with them. | |
| 46 | for path in coordinator.editors.keys where !session.openPaths.contains(path) { | |
| 47 | coordinator.editors[path]?.scroll.removeFromSuperview() | |
| 48 | coordinator.editors[path] = nil | |
| 49 | } | |
| 50 | if coordinator.path != session.path { | |
| 51 | coordinator.path = session.path | |
| 52 | container.subviews.forEach { $0.removeFromSuperview() } | |
| 53 | coordinator.editor = nil | |
| 54 | if let path = session.path, let shown = coordinator.editors[path] ?? makeEditor(container, coordinator) { | |
| 55 | coordinator.editors[path] = shown | |
| 56 | shown.scroll.frame = container.bounds | |
| 57 | container.addSubview(shown.scroll) | |
| 58 | container.window?.makeFirstResponder(shown.editor.textView) | |
| 59 | coordinator.editor = shown.editor | |
| 60 | commands.editor = shown.editor | |
| 61 | session.attach(shown.editor) | |
| 62 | } else { | |
| 63 | commands.editor = nil | |
| 64 | } | |
| 65 | } | |
| 66 | if let editor = coordinator.editor { | |
| 67 | if editor.keymap != keymap { editor.keymap = keymap } | |
| 68 | editor.modal = modal | |
| 69 | editor.optionAsMeta = optionAsMeta | |
| 70 | editor.options = options | |
| 71 | editor.showMarkup = showMarkup | |
| 72 | editor.showLineNumbers = showLineNumbers | |
| 73 | editor.themeSpec = theme | |
| 74 | } | |
| 75 | container.window?.isDocumentEdited = !session.dirtyPaths.isEmpty | |
| 76 | if let request = session.revealRequest, request.id != coordinator.revealID { | |
| 77 | coordinator.revealID = request.id | |
| 78 | coordinator.editor?.reveal(request.offset) | |
| 79 | } | |
| 80 | } | |
| 81 | ||
| 82 | /// An editor for the current buffer, which becomes the buffer's live state. | |
| 83 | private func makeEditor(_ container: NSView, _ coordinator: Coordinator) -> (editor: OrgEditor, scroll: NSScrollView)? { | |
| 84 | guard let document = session.document else { return nil } | |
| 85 | let mode: OrgEditor.Mode = session.isOrg ? .org : .plain(language: session.path.flatMap(FileTypes.language)) | |
| 86 | let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable, highlighter: Self.highlighter, mode: mode, options: options) | |
| 87 | let path = session.path ?? "" | |
| 88 | editor.onChange = { [weak session] in session?.bufferChanged(path) } | |
| 89 | if !path.isEmpty { editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent() } | |
| 90 | editor.onMessage = { [weak commands] in commands?.show($0) } | |
| 91 | editor.onKeysPending = { [weak commands] keys, next in | |
| 92 | commands?.pendingKeys = keys | |
| 93 | commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) } | |
| 94 | } | |
| 95 | editor.onModeChange = { [weak commands] in commands?.editorState = $0 } | |
| 96 | editor.onSelectionChange = { [weak commands] in commands?.selection = $0 } | |
| 97 | editor.onAppCommand = onAppCommand | |
| 98 | editor.onOpenFile = { [weak session, weak commands] typed in | |
| 99 | let expanded = (typed as NSString).expandingTildeInPath | |
| 100 | let base = URL(fileURLWithPath: path).deletingLastPathComponent() | |
| 101 | let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path | |
| 102 | guard FileManager.default.fileExists(atPath: target) else { | |
| 103 | commands?.show("No file \(typed)") | |
| 104 | return | |
| 105 | } | |
| 106 | session?.open(target) | |
| 107 | } | |
| 108 | editor.onJumpToEditor = { [weak session, weak coordinator] other, offset in | |
| 109 | guard let session, let path = coordinator?.editors.first(where: { $0.value.editor === other })?.key else { return } | |
| 110 | session.open(path) | |
| 111 | session.reveal(offset) | |
| 112 | } | |
| 113 | editor.onExternal = onExternal | |
| 114 | editor.knownTags = knownTags | |
| 115 | editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) } | |
| 116 | editor.onEffect = { [weak commands] effect in | |
| 117 | switch effect { | |
| 118 | case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link } | |
| 119 | case .copy(let text): | |
| 120 | NSPasteboard.general.clearContents() | |
| 121 | NSPasteboard.general.setString(text, forType: .string) | |
| 122 | case .refreshSetup: session.refreshSetup() | |
| 123 | case .message, .sparseTree, .fold: break | |
| 124 | } | |
| 125 | } | |
| 126 | let scroll = editor.makeScrollView() | |
| 127 | scroll.autoresizingMask = [.width, .height] | |
| 128 | return (editor, scroll) | |
| 129 | } | |
| 130 | } | |
Sources/Orgstar/EditorWindowView.swift added +53
| @@ -0,0 +1,53 @@ | ||
| 1 | import OrgApp | |
| 2 | import SwiftUI | |
| 3 | ||
| 4 | /// A window of panes alone, as a second Emacs frame: no sidebar or search. It opens on the | |
| 5 | /// buffer the focused pane showed, and its panes leave the session when it closes. | |
| 6 | struct EditorWindowView: View { | |
| 7 | let session: DocumentSession | |
| 8 | let commands: AppCommands | |
| 9 | let clock: ClockModel | |
| 10 | @AppStorage("showTabBar") private var showTabBar = false | |
| 11 | @State private var window: WindowModel? | |
| 12 | @Environment(\.openWindow) private var openWindow | |
| 13 | ||
| 14 | /// App commands run in the main window; it comes back if it was closed. | |
| 15 | private func run(_ id: String) { | |
| 16 | if !commands.mainWindowOpen { openWindow(id: "main") } | |
| 17 | commands.run(id) | |
| 18 | } | |
| 19 | ||
| 20 | var body: some View { | |
| 21 | Group { | |
| 22 | if let window { | |
| 23 | PaneLayoutView(layout: window.layout, window: window) { pane in | |
| 24 | PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar) { run($0) } | |
| 25 | } | |
| 26 | .safeAreaInset(edge: .bottom, spacing: 0) { | |
| 27 | VStack(spacing: 0) { | |
| 28 | ModeLine(session: session, commands: commands, clock: clock) { run($0) } | |
| 29 | EchoArea(commands: commands) | |
| 30 | } | |
| 31 | } | |
| 32 | } | |
| 33 | } | |
| 34 | .navigationTitle(window?.focusedPane.path.map(session.bufferName) ?? "orgstar") | |
| 35 | .onAppear { | |
| 36 | guard window == nil else { return } | |
| 37 | let pane = session.makePane() | |
| 38 | if let path = session.focused.path { session.open(path, in: pane) } | |
| 39 | let model = WindowModel(session: session, pane: pane) | |
| 40 | window = model | |
| 41 | commands.store.windows.append(model) | |
| 42 | model.focus(pane.id) | |
| 43 | } | |
| 44 | .onDisappear { | |
| 45 | guard let model = window else { return } | |
| 46 | for id in model.layout.panes { commands.store.releasePane(id) } | |
| 47 | model.closeAll() | |
| 48 | commands.store.windows.removeAll { $0 === model } | |
| 49 | commands.editor = nil | |
| 50 | if let main = commands.store.windows.first { main.focus(main.focused) } | |
| 51 | } | |
| 52 | } | |
| 53 | } | |
Sources/Orgstar/OrgstarApp.swift +33 −1
| @@ -20,8 +20,19 @@ final class AppCommands { | ||
| 20 | 20 | private var jumpID = 0 |
| 21 | 21 | /// Days the agenda window should show, from a followed timestamp. |
| 22 | 22 | var agendaRequest: (start: Int, days: Int)? |
| 23 | /// The editor showing the open file, for menus and the palette. | |
| 23 | /// The editor with focus, for menus and the palette. | |
| 24 | 24 | var editor: OrgEditor? |
| 25 | /// The editors and text views of every pane in every window. | |
| 26 | let store = EditorStore() | |
| 27 | /// The main window is on screen. App commands run there, so an editor window reopens it | |
| 28 | /// before asking for one. | |
| 29 | var mainWindowOpen = false | |
| 30 | /// What every editor is set up with, from the settings; the main window keeps it current. | |
| 31 | var editorSettings = EditorSettings() | |
| 32 | /// Runs work outside the text (a table recalculation in Emacs); the main window sets it. | |
| 33 | var externalHandler: ((ExternalRequest) -> Void)? | |
| 34 | /// Tags used across the workspace, for tag completion; the main window sets it. | |
| 35 | var knownTags: () -> [String] = { [] } | |
| 25 | 36 | /// The pending key prefix, and what can follow it. |
| 26 | 37 | var pendingKeys: String? |
| 27 | 38 | /// The editor's evil state in the Doom preset. |
| @@ -317,6 +328,14 @@ struct OrgstarApp: App { | ||
| 317 | 328 | } |
| 318 | 329 | } |
| 319 | 330 | .defaultSize(width: 1280, height: 860) |
| 331 | WindowGroup("Editor", id: "editor") { | |
| 332 | if case .success = workspace { | |
| 333 | EditorWindowView(session: session, commands: commands, clock: clock) | |
| 334 | .environment(\.orgTheme, ConfigSync.shared.theme) | |
| 335 | } | |
| 336 | } | |
| 337 | .defaultSize(width: 900, height: 700) | |
| 338 | .commandsRemoved() | |
| 320 | 339 | Window("Agenda", id: "agenda") { |
| 321 | 340 | if case .success(let model) = workspace { |
| 322 | 341 | AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock) |
| @@ -384,6 +403,17 @@ struct OrgstarApp: App { | ||
| 384 | 403 | .disabled(session.dirtyPaths.isEmpty) |
| 385 | 404 | } |
| 386 | 405 | CommandGroup(after: .sidebar) { |
| 406 | Button("Split Pane Below") { commands.run("app.split-below") } | |
| 407 | .keyboardShortcut("2", modifiers: [.command, .control]) | |
| 408 | Button("Split Pane Right") { commands.run("app.split-right") } | |
| 409 | .keyboardShortcut("3", modifiers: [.command, .control]) | |
| 410 | Button("Close Pane") { commands.run("app.pane-close") } | |
| 411 | .keyboardShortcut("0", modifiers: [.command, .control]) | |
| 412 | Button("Close Other Panes") { commands.run("app.pane-only") } | |
| 413 | .keyboardShortcut("1", modifiers: [.command, .control]) | |
| 414 | Button("Next Pane") { commands.run("app.pane-next") } | |
| 415 | .keyboardShortcut("`", modifiers: [.command, .option]) | |
| 416 | Divider() | |
| 387 | 417 | Button("Show or Hide Outline") { commands.run("app.toggle-outline") } |
| 388 | 418 | .keyboardShortcut("o", modifiers: [.command, .option]) |
| 389 | 419 | Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") } |
| @@ -416,6 +446,8 @@ struct OrgstarApp: App { | ||
| 416 | 446 | CommandGroup(after: .newItem) { |
| 417 | 447 | Button("Capture…") { commands.run("app.capture") } |
| 418 | 448 | .keyboardShortcut("n", modifiers: [.command, .shift]) |
| 449 | Button("New Window") { commands.run("app.window-new") } | |
| 450 | .keyboardShortcut("n", modifiers: [.command, .option]) | |
| 419 | 451 | } |
| 420 | 452 | } |
| 421 | 453 | .commands { |
Sources/Orgstar/PaneLayoutView.swift added +95
| @@ -0,0 +1,95 @@ | ||
| 1 | import OrgApp | |
| 2 | import SwiftUI | |
| 3 | ||
| 4 | /// A window's panes as its layout divides them, with a draggable divider at each split. | |
| 5 | struct PaneLayoutView<Content: View>: View { | |
| 6 | let layout: PaneLayout | |
| 7 | let window: WindowModel | |
| 8 | @ViewBuilder let content: (EditorPane) -> Content | |
| 9 | ||
| 10 | var body: some View { | |
| 11 | switch layout { | |
| 12 | case .pane(let id): | |
| 13 | if let pane = window.pane(id) { content(pane) } else { Color.clear } | |
| 14 | case .split(let axis, let first, let second, let fraction): | |
| 15 | GeometryReader { geometry in | |
| 16 | let total = axis == .horizontal ? geometry.size.width : geometry.size.height | |
| 17 | let firstSize = max(80, min(max(80, total - 80), total * fraction)) | |
| 18 | let divider = SplitDivider(axis: axis, firstSize: firstSize) { size in | |
| 19 | window.setFraction(size / max(total, 1), ofSplitBetween: first.panes[first.panes.count - 1], and: second.panes[0]) | |
| 20 | } | |
| 21 | if axis == .horizontal { | |
| 22 | HStack(spacing: 0) { | |
| 23 | PaneLayoutView(layout: first, window: window, content: content).frame(width: firstSize) | |
| 24 | divider | |
| 25 | PaneLayoutView(layout: second, window: window, content: content).frame(maxWidth: .infinity) | |
| 26 | } | |
| 27 | } else { | |
| 28 | VStack(spacing: 0) { | |
| 29 | PaneLayoutView(layout: first, window: window, content: content).frame(height: firstSize) | |
| 30 | divider | |
| 31 | PaneLayoutView(layout: second, window: window, content: content).frame(maxHeight: .infinity) | |
| 32 | } | |
| 33 | } | |
| 34 | } | |
| 35 | } | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | /// The line between two panes; dragging it resizes the first. | |
| 40 | struct SplitDivider: View { | |
| 41 | let axis: PaneLayout.Axis | |
| 42 | let firstSize: CGFloat | |
| 43 | let resize: (CGFloat) -> Void | |
| 44 | @State private var start: CGFloat? | |
| 45 | ||
| 46 | var body: some View { | |
| 47 | let horizontal = axis == .horizontal | |
| 48 | Rectangle() | |
| 49 | .fill(Color(nsColor: .separatorColor)) | |
| 50 | .frame(width: horizontal ? 1 : nil, height: horizontal ? nil : 1) | |
| 51 | .frame(maxWidth: horizontal ? 1 : .infinity, maxHeight: horizontal ? .infinity : 1) | |
| 52 | .overlay(Color.clear.frame(width: horizontal ? 7 : nil, height: horizontal ? nil : 7).contentShape(Rectangle()).onHover { inside in | |
| 53 | if inside { (horizontal ? NSCursor.resizeLeftRight : NSCursor.resizeUpDown).push() } else { NSCursor.pop() } | |
| 54 | } | |
| 55 | .gesture(DragGesture(minimumDistance: 1).onChanged { drag in | |
| 56 | let base = start ?? firstSize | |
| 57 | start = base | |
| 58 | resize(base + (horizontal ? drag.translation.width : drag.translation.height)) | |
| 59 | }.onEnded { _ in start = nil })) | |
| 60 | .accessibilityHidden(true) | |
| 61 | } | |
| 62 | } | |
| 63 | ||
| 64 | /// One pane: its tabs, its editor, or a placeholder while it shows nothing. A thin bar marks | |
| 65 | /// the focused pane when there are several. | |
| 66 | struct PaneCell: View { | |
| 67 | let pane: EditorPane | |
| 68 | let window: WindowModel | |
| 69 | let session: DocumentSession | |
| 70 | let commands: AppCommands | |
| 71 | let showTabBar: Bool | |
| 72 | let onAppCommand: (String) -> Void | |
| 73 | ||
| 74 | var body: some View { | |
| 75 | VStack(spacing: 0) { | |
| 76 | if showTabBar { BufferTabs(session: session, pane: pane) } | |
| 77 | if pane.path != nil { | |
| 78 | PaneView(pane: pane, session: session, commands: commands, settings: commands.editorSettings, onAppCommand: onAppCommand) | |
| 79 | } else { | |
| 80 | ContentUnavailableView("No buffer", systemImage: "rectangle.dashed", description: Text("Choose a file, or press ⌘P.")) | |
| 81 | .contentShape(Rectangle()) | |
| 82 | .onTapGesture { | |
| 83 | window.focus(pane.id) | |
| 84 | NSApp.keyWindow?.makeFirstResponder(nil) | |
| 85 | commands.editor = nil | |
| 86 | } | |
| 87 | } | |
| 88 | } | |
| 89 | .overlay(alignment: .top) { | |
| 90 | if window.paneCount > 1, window.focused == pane.id { | |
| 91 | Rectangle().fill(Color.accentColor).frame(height: 2).accessibilityHidden(true) | |
| 92 | } | |
| 93 | } | |
| 94 | } | |
| 95 | } | |
Sources/Orgstar/PaneView.swift added +136
| @@ -0,0 +1,136 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgApp | |
| 3 | import OrgCore | |
| 4 | import OrgEditorAppKit | |
| 5 | import OrgPresentation | |
| 6 | import OrgHighlight | |
| 7 | import SwiftUI | |
| 8 | ||
| 9 | /// What every editor view is set up with, from the settings. | |
| 10 | struct EditorSettings: Equatable { | |
| 11 | var keymap = KeymapPreset.emacs.keymap | |
| 12 | var modal = false | |
| 13 | var optionAsMeta = OptionAsMeta.left | |
| 14 | var options = EditingOptions.org | |
| 15 | var showMarkup = false | |
| 16 | var showLineNumbers = true | |
| 17 | var theme = ThemeSpec.default | |
| 18 | } | |
| 19 | ||
| 20 | /// One pane's editor: the text view of the buffer the pane shows, from the store, which keeps | |
| 21 | /// one editor per open file and one text view per pane showing it. A new editor becomes its | |
| 22 | /// buffer's live state; the pane's reveal requests go to its text view. | |
| 23 | struct PaneView: NSViewRepresentable { | |
| 24 | /// One highlighter for every editor: it caches compiled grammars and results. | |
| 25 | static let highlighter = TreeSitterHighlighter() | |
| 26 | ||
| 27 | let pane: EditorPane | |
| 28 | let session: DocumentSession | |
| 29 | let commands: AppCommands | |
| 30 | let settings: EditorSettings | |
| 31 | let onAppCommand: (String) -> Void | |
| 32 | ||
| 33 | final class Coordinator { | |
| 34 | var path: String? | |
| 35 | var textView: NSTextView? | |
| 36 | var revealID = 0 | |
| 37 | } | |
| 38 | ||
| 39 | func makeCoordinator() -> Coordinator { Coordinator() } | |
| 40 | ||
| 41 | func makeNSView(context: Context) -> NSView { NSView() } | |
| 42 | ||
| 43 | func updateNSView(_ container: NSView, context: Context) { | |
| 44 | let coordinator = context.coordinator | |
| 45 | let store = commands.store | |
| 46 | if coordinator.path != pane.path { | |
| 47 | coordinator.path = pane.path | |
| 48 | container.subviews.forEach { $0.removeFromSuperview() } | |
| 49 | coordinator.textView = nil | |
| 50 | if let path = pane.path, let shown = store.view(for: pane, path: path, make: { makeEditor(path, container) }) { | |
| 51 | shown.scroll.frame = container.bounds | |
| 52 | container.addSubview(shown.scroll) | |
| 53 | coordinator.textView = shown.textView | |
| 54 | if session.focused === pane { | |
| 55 | container.window?.makeFirstResponder(shown.textView) | |
| 56 | commands.editor = shown.editor | |
| 57 | } | |
| 58 | } else if session.focused === pane { | |
| 59 | commands.editor = nil | |
| 60 | } | |
| 61 | } | |
| 62 | if let path = pane.path, let editor = store.editor(for: path) { | |
| 63 | if editor.keymap != settings.keymap { editor.keymap = settings.keymap } | |
| 64 | editor.modal = settings.modal | |
| 65 | editor.optionAsMeta = settings.optionAsMeta | |
| 66 | editor.options = settings.options | |
| 67 | editor.showMarkup = settings.showMarkup | |
| 68 | editor.showLineNumbers = settings.showLineNumbers | |
| 69 | editor.themeSpec = settings.theme | |
| 70 | } | |
| 71 | container.window?.isDocumentEdited = !session.dirtyPaths.isEmpty | |
| 72 | if let request = pane.revealRequest, request.id != coordinator.revealID, let textView = coordinator.textView, let path = pane.path, let editor = store.editor(for: path) { | |
| 73 | coordinator.revealID = request.id | |
| 74 | // The editor reveals in its active view: this pane's, once it has focus. | |
| 75 | textView.window?.makeFirstResponder(textView) | |
| 76 | editor.reveal(request.offset) | |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | /// An editor for `path`, which becomes the buffer's live state. | |
| 81 | private func makeEditor(_ path: String, _ container: NSView) -> OrgEditor? { | |
| 82 | guard let entry = session.openDocuments.first(where: { $0.path == path }) else { return nil } | |
| 83 | let document = entry.document | |
| 84 | let mode: OrgEditor.Mode = DocumentSession.isOrgPath(path) ? .org : .plain(language: FileTypes.language(path)) | |
| 85 | let editor = OrgEditor(document: document, frame: container.bounds, editable: document.isEditable, highlighter: Self.highlighter, mode: mode, options: settings.options) | |
| 86 | let store = commands.store | |
| 87 | editor.onChange = { [weak session] in session?.bufferChanged(path) } | |
| 88 | editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent() | |
| 89 | editor.onMessage = { [weak commands] in commands?.show($0) } | |
| 90 | editor.onKeysPending = { [weak commands] keys, next in | |
| 91 | commands?.pendingKeys = keys | |
| 92 | commands?.keyHints = next.map { KeyHint(key: $0.key, title: $0.title) } | |
| 93 | } | |
| 94 | editor.onModeChange = { [weak commands] in commands?.editorState = $0 } | |
| 95 | editor.onSelectionChange = { [weak commands] in commands?.selection = $0 } | |
| 96 | editor.onFocus = { [weak session, weak commands, weak editor] textView in | |
| 97 | guard let session, let commands, let editor else { return } | |
| 98 | commands.editor = editor | |
| 99 | if let pane = store.pane(of: textView) { | |
| 100 | session.focused = pane | |
| 101 | store.window(of: pane.id)?.focused = pane.id | |
| 102 | } | |
| 103 | } | |
| 104 | editor.onAppCommand = onAppCommand | |
| 105 | editor.onOpenFile = { [weak session, weak commands] typed in | |
| 106 | let expanded = (typed as NSString).expandingTildeInPath | |
| 107 | let base = URL(fileURLWithPath: path).deletingLastPathComponent() | |
| 108 | let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path | |
| 109 | guard FileManager.default.fileExists(atPath: target) else { | |
| 110 | commands?.show("No file \(typed)") | |
| 111 | return | |
| 112 | } | |
| 113 | session?.open(target) | |
| 114 | } | |
| 115 | editor.onJumpToEditor = { [weak session] other, offset in | |
| 116 | guard let session, let path = store.editors.first(where: { $0.value === other })?.key else { return } | |
| 117 | session.open(path) | |
| 118 | session.reveal(offset) | |
| 119 | } | |
| 120 | editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) } | |
| 121 | editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } } | |
| 122 | editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) } | |
| 123 | editor.onEffect = { [weak commands, weak session] effect in | |
| 124 | switch effect { | |
| 125 | case .storedLinkUsed(let link): commands?.storedLinks.removeAll { $0.link == link } | |
| 126 | case .copy(let text): | |
| 127 | NSPasteboard.general.clearContents() | |
| 128 | NSPasteboard.general.setString(text, forType: .string) | |
| 129 | case .refreshSetup: session?.refreshSetup() | |
| 130 | case .message, .sparseTree, .fold: break | |
| 131 | } | |
| 132 | } | |
| 133 | session.attach(editor, for: path) | |
| 134 | return editor | |
| 135 | } | |
| 136 | } | |
Sources/Orgstar/WindowModel.swift added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgApp | |
| 3 | ||
| 4 | /// One editor window's panes: how they divide the window and which has focus. The panes | |
| 5 | /// themselves belong to the session, which keeps them in step with the buffers. | |
| 6 | @MainActor | |
| 7 | @Observable | |
| 8 | final class WindowModel: Identifiable { | |
| 9 | let id = UUID() | |
| 10 | let session: DocumentSession | |
| 11 | private(set) var layout: PaneLayout | |
| 12 | private(set) var panes: [PaneID: EditorPane] | |
| 13 | var focused: PaneID | |
| 14 | ||
| 15 | /// A window around `pane`, which the session already has. | |
| 16 | init(session: DocumentSession, pane: EditorPane) { | |
| 17 | self.session = session | |
| 18 | layout = .pane(pane.id) | |
| 19 | panes = [pane.id: pane] | |
| 20 | focused = pane.id | |
| 21 | } | |
| 22 | ||
| 23 | func pane(_ id: PaneID) -> EditorPane? { panes[id] } | |
| 24 | var focusedPane: EditorPane { panes[focused] ?? panes[layout.panes[0]] ?? panes.values.first ?? session.focused } | |
| 25 | var paneCount: Int { layout.panes.count } | |
| 26 | ||
| 27 | /// A new pane after the focused one, showing the same buffer, as `split-window` does. The | |
| 28 | /// focus stays where it was. | |
| 29 | @discardableResult | |
| 30 | func split(_ axis: PaneLayout.Axis) -> EditorPane { | |
| 31 | let current = focusedPane | |
| 32 | let pane = session.makePane() | |
| 33 | panes[pane.id] = pane | |
| 34 | layout = layout.splitting(current.id, axis: axis, new: pane.id) | |
| 35 | if let path = current.path { session.open(path, in: pane) } | |
| 36 | return pane | |
| 37 | } | |
| 38 | ||
| 39 | /// Removes `id` from the window; its buffers stay open. The only pane stays. | |
| 40 | func close(_ id: PaneID) { | |
| 41 | guard let pane = panes[id], let rest = layout.removing(id) else { return } | |
| 42 | layout = rest | |
| 43 | panes[id] = nil | |
| 44 | session.closePane(pane) | |
| 45 | if focused == id { focus(rest.panes[0]) } | |
| 46 | } | |
| 47 | ||
| 48 | /// Removes every pane but the focused one. | |
| 49 | func closeOthers() { | |
| 50 | for id in layout.panes where id != focused { close(id) } | |
| 51 | } | |
| 52 | ||
| 53 | /// Focuses the pane after the focused one in reading order, wrapping. | |
| 54 | func focusNext() { | |
| 55 | focus(layout.next(after: focused)) | |
| 56 | } | |
| 57 | ||
| 58 | func focus(_ id: PaneID) { | |
| 59 | guard let pane = panes[id] else { return } | |
| 60 | focused = id | |
| 61 | session.focused = pane | |
| 62 | } | |
| 63 | ||
| 64 | func setFraction(_ fraction: Double, ofSplitBetween before: PaneID, and after: PaneID) { | |
| 65 | layout = layout.settingFraction(fraction, ofSplitBetween: before, and: after) | |
| 66 | } | |
| 67 | ||
| 68 | /// Takes every pane out of the session, as the window closes. The panes stay listed here | |
| 69 | /// so views still on screen can read them. | |
| 70 | func closeAll() { | |
| 71 | for pane in panes.values { session.closePane(pane) } | |
| 72 | } | |
| 73 | } | |
Tests/OrgAppTests/EditorPaneTests.swift added +87
| @@ -0,0 +1,87 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import OrgDocument | |
| 4 | import Testing | |
| 5 | @testable import OrgApp | |
| 6 | ||
| 7 | @MainActor | |
| 8 | struct EditorPaneTests { | |
| 9 | func session(_ notes: Folder) -> DocumentSession { | |
| 10 | DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 11 | } | |
| 12 | ||
| 13 | @Test func aFileOpenInTwoPanesIsOneBuffer() throws { | |
| 14 | let notes = try Folder() | |
| 15 | let a = try notes.write("a.org", "* A\n").path | |
| 16 | let session = session(notes) | |
| 17 | let first = session.focused | |
| 18 | let second = session.makePane() | |
| 19 | session.open(a) | |
| 20 | session.open(a, in: second) | |
| 21 | #expect(session.openPaths == [a]) | |
| 22 | #expect(first.path == a && second.path == a) | |
| 23 | #expect(session.panes.count == 2) | |
| 24 | } | |
| 25 | ||
| 26 | @Test func killingABufferEmptiesEveryPaneShowingIt() throws { | |
| 27 | let notes = try Folder() | |
| 28 | let a = try notes.write("a.org", "* A\n").path | |
| 29 | let b = try notes.write("b.org", "* B\n").path | |
| 30 | let session = session(notes) | |
| 31 | let first = session.focused | |
| 32 | let second = session.makePane() | |
| 33 | session.open(a) | |
| 34 | session.open(b) | |
| 35 | session.open(b, in: second) | |
| 36 | session.kill(b) | |
| 37 | #expect(first.path == a) | |
| 38 | #expect(second.path == a) | |
| 39 | #expect(first.shown == [a] && second.shown == [a]) | |
| 40 | session.kill(a) | |
| 41 | #expect(first.path == nil && second.path == nil && session.path == nil) | |
| 42 | } | |
| 43 | ||
| 44 | @Test func revealGoesToOnePane() throws { | |
| 45 | let notes = try Folder() | |
| 46 | let a = try notes.write("a.org", "* A\n* B\n").path | |
| 47 | let session = session(notes) | |
| 48 | let first = session.focused | |
| 49 | let second = session.makePane() | |
| 50 | session.open(a) | |
| 51 | session.open(a, in: second) | |
| 52 | session.reveal(4, in: second) | |
| 53 | #expect(second.revealRequest?.offset == 4) | |
| 54 | #expect(first.revealRequest == nil) | |
| 55 | session.focused = second | |
| 56 | #expect(session.revealRequest?.offset == 4) | |
| 57 | } | |
| 58 | ||
| 59 | @Test func dirtyPathsCountABufferOnce() throws { | |
| 60 | let notes = try Folder() | |
| 61 | let a = try notes.write("a.org", "* A\n").path | |
| 62 | let session = session(notes) | |
| 63 | session.saveMode = .explicit | |
| 64 | let second = session.makePane() | |
| 65 | session.open(a) | |
| 66 | session.open(a, in: second) | |
| 67 | let result = EditResult(baseRevision: session.document!.revision, edits: [TextEdit(range: 0..<0, replacement: "x")]) | |
| 68 | _ = session.perform(PrecomputedEdit(result), path: a, at: 0, expect: nil) | |
| 69 | #expect(session.dirtyPaths == [a]) | |
| 70 | #expect(session.focused.isDirty && second.isDirty) | |
| 71 | } | |
| 72 | ||
| 73 | @Test func closingAPaneKeepsTheBufferAndTheFocus() throws { | |
| 74 | let notes = try Folder() | |
| 75 | let a = try notes.write("a.org", "* A\n").path | |
| 76 | let session = session(notes) | |
| 77 | let first = session.focused | |
| 78 | let second = session.makePane() | |
| 79 | session.open(a, in: second) | |
| 80 | session.focused = second | |
| 81 | session.closePane(second) | |
| 82 | #expect(session.panes.count == 1 && session.focused === first) | |
| 83 | #expect(session.isOpen(a)) | |
| 84 | session.closePane(first) | |
| 85 | #expect(session.panes.count == 1) | |
| 86 | } | |
| 87 | } | |
Tests/OrgAppTests/PaneLayoutTests.swift added +42
| @@ -0,0 +1,42 @@ | ||
| 1 | import Testing | |
| 2 | @testable import OrgApp | |
| 3 | ||
| 4 | struct PaneLayoutTests { | |
| 5 | @Test func splitsNestAndReadInOrder() { | |
| 6 | let a = PaneID(), b = PaneID(), c = PaneID() | |
| 7 | var layout = PaneLayout.pane(a) | |
| 8 | layout = layout.splitting(a, axis: .horizontal, new: b) | |
| 9 | layout = layout.splitting(b, axis: .vertical, new: c) | |
| 10 | #expect(layout.panes == [a, b, c]) | |
| 11 | #expect(layout == .split(axis: .horizontal, first: .pane(a), second: .split(axis: .vertical, first: .pane(b), second: .pane(c), fraction: 0.5), fraction: 0.5)) | |
| 12 | } | |
| 13 | ||
| 14 | @Test func removingAPaneCollapsesItsSplit() { | |
| 15 | let a = PaneID(), b = PaneID(), c = PaneID() | |
| 16 | let layout = PaneLayout.pane(a).splitting(a, axis: .horizontal, new: b).splitting(b, axis: .vertical, new: c) | |
| 17 | #expect(layout.removing(b) == .split(axis: .horizontal, first: .pane(a), second: .pane(c), fraction: 0.5)) | |
| 18 | #expect(layout.removing(a)?.panes == [b, c]) | |
| 19 | #expect(PaneLayout.pane(a).removing(a) == nil) | |
| 20 | } | |
| 21 | ||
| 22 | @Test func settingAFractionFindsTheSplitByItsFirstPane() { | |
| 23 | let a = PaneID(), b = PaneID(), c = PaneID() | |
| 24 | let layout = PaneLayout.pane(a).splitting(a, axis: .horizontal, new: b).splitting(b, axis: .vertical, new: c) | |
| 25 | let inner = layout.settingFraction(0.3, ofSplitBetween: b, and: c) | |
| 26 | #expect(inner == .split(axis: .horizontal, first: .pane(a), second: .split(axis: .vertical, first: .pane(b), second: .pane(c), fraction: 0.3), fraction: 0.5)) | |
| 27 | #expect(layout.settingFraction(2, ofSplitBetween: a, and: b) == .split(axis: .horizontal, first: .pane(a), second: .split(axis: .vertical, first: .pane(b), second: .pane(c), fraction: 0.5), fraction: 0.9)) | |
| 28 | // A nested split on the first side shares its first pane with the outer split. | |
| 29 | let nestedFirst = PaneLayout.pane(a).splitting(a, axis: .horizontal, new: b).splitting(a, axis: .vertical, new: c) | |
| 30 | #expect(nestedFirst.settingFraction(0.3, ofSplitBetween: a, and: c) == .split(axis: .horizontal, first: .split(axis: .vertical, first: .pane(a), second: .pane(c), fraction: 0.3), second: .pane(b), fraction: 0.5)) | |
| 31 | #expect(nestedFirst.settingFraction(0.3, ofSplitBetween: c, and: b) == .split(axis: .horizontal, first: .split(axis: .vertical, first: .pane(a), second: .pane(c), fraction: 0.5), second: .pane(b), fraction: 0.3)) | |
| 32 | } | |
| 33 | ||
| 34 | @Test func onlyAndNext() { | |
| 35 | let a = PaneID(), b = PaneID(), c = PaneID() | |
| 36 | let layout = PaneLayout.pane(a).splitting(a, axis: .horizontal, new: b).splitting(b, axis: .vertical, new: c) | |
| 37 | #expect(layout.only(b) == .pane(b)) | |
| 38 | #expect(layout.next(after: a) == b) | |
| 39 | #expect(layout.next(after: c) == a) | |
| 40 | #expect(layout.next(after: PaneID()) == a) | |
| 41 | } | |
| 42 | } | |
Tests/OrgAppTests/WindowModelTests.swift added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgDocument | |
| 3 | import Testing | |
| 4 | @testable import OrgApp | |
| 5 | ||
| 6 | /// `WindowModel` lives in the app target; this is its contract over the session, checked with | |
| 7 | /// the session alone: a split is a new pane showing the focused buffer; closing a pane leaves | |
| 8 | /// its buffer open; the last pane stays. | |
| 9 | @MainActor | |
| 10 | struct WindowModelContractTests { | |
| 11 | @Test func aSplitShowsTheSameBufferInANewPane() throws { | |
| 12 | let notes = try Folder() | |
| 13 | let a = try notes.write("a.org", "* A\n").path | |
| 14 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 15 | session.open(a) | |
| 16 | let pane = session.makePane() | |
| 17 | session.open(a, in: pane) | |
| 18 | #expect(pane.path == a && session.openPaths == [a]) | |
| 19 | session.closePane(pane) | |
| 20 | #expect(session.panes.count == 1 && session.isOpen(a)) | |
| 21 | } | |
| 22 | } | |
Tests/OrgEditorAppKitTests/MultiViewTests.swift added +110
| @@ -0,0 +1,110 @@ | ||
| 1 | import AppKit | |
| 2 | import OrgCore | |
| 3 | import OrgDocument | |
| 4 | import OrgPresentation | |
| 5 | import 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 | |
| 11 | struct 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 narrowingMovesEveryViewsCaretIntoTheRegion() { | |
| 85 | let two = Two("* a\nbody\n* b\nmore\n") | |
| 86 | two.second.setSelectedRange(NSRange(location: 0, length: 0)) | |
| 87 | two.editor.setCaret(9) | |
| 88 | two.editor.run("org.narrow.subtree") | |
| 89 | #expect(two.editor.narrowed?.lowerBound == 9) | |
| 90 | #expect(two.second.selectedRange().location >= 9) | |
| 91 | } | |
| 92 | ||
| 93 | @Test func aViewTakingFocusLeavesHiddenText() { | |
| 94 | let two = Two("* a\nbody\n* b\nmore\n") | |
| 95 | two.second.setSelectedRange(NSRange(location: 5, length: 0)) | |
| 96 | two.editor.setCaret(0) | |
| 97 | _ = two.editor.cycleAtCaret() | |
| 98 | two.windows[1].makeFirstResponder(two.second) | |
| 99 | #expect(two.editor.hidden.containing(two.second.selectedRange().location) == nil) | |
| 100 | } | |
| 101 | ||
| 102 | @Test func removingAViewDetachesItsLayoutManager() { | |
| 103 | let two = Two("* a\n") | |
| 104 | let storage = two.editor.textView.textLayoutManager!.textContentManager! | |
| 105 | #expect(storage.textLayoutManagers.count == 2) | |
| 106 | two.editor.removeView(two.second) | |
| 107 | #expect(storage.textLayoutManagers.count == 1) | |
| 108 | #expect(two.editor.textViews.count == 1) | |
| 109 | } | |
| 110 | } | |
Tests/OrgEditorAppKitTests/TwoViewsSpikeTests.swift added +117
| @@ -0,0 +1,117 @@ | ||
| 1 | import AppKit | |
| 2 | import Testing | |
| 3 | ||
| 4 | /// Spike for windows and panes (docs/plans/2026-10-10-windows-and-panes.md, Task 0): two | |
| 5 | /// `NSTextView`s, each with its own `NSTextLayoutManager`, on one `NSTextContentStorage`. | |
| 6 | /// Findings are the test names. Two more: the layout manager's delegate must be in place before | |
| 7 | /// its first layout (`invalidateLayout(for:)` afterwards kept the old fragments here), and IME | |
| 8 | /// composition is not covered headlessly. | |
| 9 | @MainActor | |
| 10 | struct TwoViewsSpikeTests { | |
| 11 | @MainActor final class Shared: NSObject, NSTextViewDelegate { | |
| 12 | let undo = UndoManager() | |
| 13 | override init() { super.init() } | |
| 14 | func undoManager(for view: NSTextView) -> UndoManager? { undo } | |
| 15 | } | |
| 16 | ||
| 17 | final class MarkedFragment: NSTextLayoutFragment, @unchecked Sendable {} | |
| 18 | ||
| 19 | final class FirstMarked: NSObject, NSTextLayoutManagerDelegate, @unchecked Sendable { | |
| 20 | nonisolated func textLayoutManager(_ manager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in element: NSTextElement) -> NSTextLayoutFragment { | |
| 21 | let content = manager.textContentManager! | |
| 22 | if content.offset(from: content.documentRange.location, to: location) == 0 { | |
| 23 | return MarkedFragment(textElement: element, range: element.elementRange) | |
| 24 | } | |
| 25 | return NSTextLayoutFragment(textElement: element, range: element.elementRange) | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | @MainActor struct Pair { | |
| 30 | let storage: NSTextContentStorage | |
| 31 | let shared: Shared | |
| 32 | let a: NSTextView | |
| 33 | let b: NSTextView | |
| 34 | let windows: [NSWindow] | |
| 35 | ||
| 36 | init(_ text: String, delegateForB: NSTextLayoutManagerDelegate? = nil) { | |
| 37 | _ = NSApplication.shared | |
| 38 | storage = NSTextContentStorage() | |
| 39 | shared = Shared() | |
| 40 | let storage = self.storage | |
| 41 | storage.textStorage?.setAttributedString(NSAttributedString(string: text)) | |
| 42 | func view(_ delegate: NSTextLayoutManagerDelegate? = nil) -> NSTextView { | |
| 43 | let layout = NSTextLayoutManager() | |
| 44 | layout.delegate = delegate | |
| 45 | storage.addTextLayoutManager(layout) | |
| 46 | let container = NSTextContainer(size: CGSize(width: 600, height: 100_000)) | |
| 47 | layout.textContainer = container | |
| 48 | let view = NSTextView(frame: NSRect(x: 0, y: 0, width: 600, height: 800), textContainer: container) | |
| 49 | view.allowsUndo = true | |
| 50 | return view | |
| 51 | } | |
| 52 | a = view(); b = view(delegateForB) | |
| 53 | a.delegate = shared; b.delegate = shared | |
| 54 | windows = [a, b].map { view in | |
| 55 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 800), styleMask: [.titled], backing: .buffered, defer: false) | |
| 56 | window.contentView = view | |
| 57 | window.makeFirstResponder(view) | |
| 58 | return window | |
| 59 | } | |
| 60 | for view in [a, b] { view.textLayoutManager!.ensureLayout(for: view.textLayoutManager!.documentRange) } | |
| 61 | } | |
| 62 | } | |
| 63 | ||
| 64 | @Test func typingInOneViewShowsInTheOther() { | |
| 65 | let pair = Pair("* a\nbody\n") | |
| 66 | pair.a.insertText("X", replacementRange: NSRange(location: 0, length: 0)) | |
| 67 | #expect(pair.b.string == "X* a\nbody\n") | |
| 68 | #expect(pair.b.textLayoutManager!.textContentManager === pair.a.textLayoutManager!.textContentManager) | |
| 69 | } | |
| 70 | ||
| 71 | @Test func undoFromTheOtherViewRevertsTyping() { | |
| 72 | let pair = Pair("* a\nbody\n") | |
| 73 | pair.a.insertText("X", replacementRange: NSRange(location: 0, length: 0)) | |
| 74 | #expect(pair.shared.undo.canUndo) | |
| 75 | pair.b.undoManager?.undo() | |
| 76 | #expect(pair.a.string == "* a\nbody\n") | |
| 77 | #expect(pair.b.string == "* a\nbody\n") | |
| 78 | } | |
| 79 | ||
| 80 | @Test func fragmentsDifferPerLayoutManager() { | |
| 81 | let delegate = FirstMarked() | |
| 82 | let pair = Pair("* a\nbody\n", delegateForB: delegate) | |
| 83 | func kinds(_ view: NSTextView) -> [String] { | |
| 84 | let layout = view.textLayoutManager! | |
| 85 | layout.ensureLayout(for: layout.documentRange) | |
| 86 | var out: [String] = [] | |
| 87 | layout.enumerateTextLayoutFragments(from: layout.documentRange.location, options: [.ensuresLayout]) { out.append(String(describing: type(of: $0))); return true } | |
| 88 | return out | |
| 89 | } | |
| 90 | #expect(kinds(pair.b).first == "MarkedFragment") | |
| 91 | #expect(kinds(pair.a).first == "NSTextLayoutFragment") | |
| 92 | } | |
| 93 | ||
| 94 | @Test func renderingAttributesStayWithTheirLayoutManager() { | |
| 95 | let pair = Pair("* a\nbody\n") | |
| 96 | let layoutA = pair.a.textLayoutManager!, layoutB = pair.b.textLayoutManager! | |
| 97 | let range = NSTextRange(location: layoutA.documentRange.location, end: layoutA.location(layoutA.documentRange.location, offsetBy: 3))! | |
| 98 | layoutA.addRenderingAttribute(.foregroundColor, value: NSColor.red, for: range) | |
| 99 | func hasRed(_ layout: NSTextLayoutManager) -> Bool { | |
| 100 | var found = false | |
| 101 | layout.enumerateRenderingAttributes(from: layout.documentRange.location, reverse: false) { _, attributes, _ in | |
| 102 | if attributes[.foregroundColor] as? NSColor == .red { found = true } | |
| 103 | return !found | |
| 104 | } | |
| 105 | return found | |
| 106 | } | |
| 107 | #expect(hasRed(layoutA)) | |
| 108 | #expect(!hasRed(layoutB)) | |
| 109 | } | |
| 110 | ||
| 111 | @Test func selectionInTheOtherViewMovesWithAnInsertionBeforeIt() { | |
| 112 | let pair = Pair("* a\nbody\n") | |
| 113 | pair.b.setSelectedRange(NSRange(location: 5, length: 0)) | |
| 114 | pair.a.insertText("XY", replacementRange: NSRange(location: 0, length: 0)) | |
| 115 | #expect(pair.b.selectedRange() == NSRange(location: 7, length: 0)) | |
| 116 | } | |
| 117 | } | |
docs/design.md +1 −1
| @@ -166,7 +166,7 @@ struct TextEdit { let range: Range<Int>; let replacement: String } // UTF-16 | ||
| 166 | 166 | |
| 167 | 167 | **Document session** |
| 168 | 168 | |
| 169 | One 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. | |
| 169 | One 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 | 171 | **Keymap format** |
| 172 | 172 | |
docs/manual/guide/01-files-and-folders.org +2 −2
| @@ -166,10 +166,10 @@ These names show in the window title, the tab bar and Switch to Buffer. | ||
| 166 | 166 | |
| 167 | 167 | ** The tab bar |
| 168 | 168 | |
| 169 | View ▸ Show Tab Bar shows a row of tabs above the editor, one per open buffer, in buffer order. It is off by default; the setting is =tab-bar= in =config.toml=. | |
| 169 | View ▸ Show Tab Bar shows a row of tabs above each pane, one per buffer that pane has shown, in the order it first showed them. It is off by default; the setting is =tab-bar= in =config.toml=. | |
| 170 | 170 | |
| 171 | 171 | - Click a tab to show its buffer. Hover to see the file's full path. |
| 172 | - Click =×= to close a buffer. A dot replaces the =×= while the buffer has unsaved edits; clicking it also closes the buffer, with the same unsaved-changes handling as Close Buffer. | |
| 172 | - Click =×= to close a buffer, in every pane. A dot replaces the =×= while the buffer has unsaved edits; clicking it also closes the buffer, with the same unsaved-changes handling as Close Buffer. | |
| 173 | 173 | |
| 174 | 174 | * Searching your notes |
| 175 | 175 | |
docs/manual/guide/02-the-editor.org +8
| @@ -148,6 +148,14 @@ When the file sets a visibility (=overview=, =content=, =showall=, =showNlevels= | ||
| 148 | 148 | |
| 149 | 149 | Narrowing to a subtree or block, and sparse trees, also hide text; see [[file:04-outlines.org][Outlines]]. |
| 150 | 150 | |
| 151 | * Panes and windows | |
| 152 | ||
| 153 | A window can show more than one buffer at once, or one buffer in more than one place, as Emacs windows do. Split Pane Below (=C-x 2=) and Split Pane Right (=C-x 3=) divide the pane with the focus in two; the new pane shows the same buffer, and the focus stays where it was. Drag the line between two panes to resize them. Close Pane (=C-x 0=) removes the focused pane, Close Other Panes (=C-x 1=) leaves only it, and Next Pane (=C-x o=) moves the focus through the panes in reading order. With several panes, a bar along the top marks the one with the focus. The sidebar, the outline and the title follow the focused pane. In the Doom preset these are =SPC w s=, =SPC w v=, =SPC w d=, =SPC w o= and =SPC w w=, and =C-w= with the same letters in normal state; the Mac preset and the View menu use =⌃⌘2=, =⌃⌘3=, =⌃⌘0=, =⌃⌘1= and =⌥⌘`=. | |
| 154 | ||
| 155 | Each pane has its own caret, selection and scroll position, and its own tabs (see [[file:01-files-and-folders.org][Files and folders]]): the buffers it has shown. Everything else about a buffer is the buffer's, as in Emacs: its text and undo, its folds, narrowing and sparse tree, its evil state and mark, shrunk table columns and inline images. Two panes on one buffer therefore show the same folds, and a fold made in one shows in the other. Closing a pane leaves its buffers open; closing a buffer (=C-x k=) takes it out of every pane, which falls back to the buffer it showed before. | |
| 156 | ||
| 157 | New Window (=C-x 5 2=, =⌥⌘N=, File ▸ New Window) opens a window of panes alone, without the sidebar or search, on the buffer the focused pane shows, as a second Emacs frame. Commands act on the pane with the focus whichever window it is in; Quick Open, the palette and search open from the main window and show their result in the focused pane. Closing the window closes its panes and leaves the buffers open. | |
| 158 | ||
| 151 | 159 | * The modeline |
| 152 | 160 | |
| 153 | 161 | The line under the editor shows, from the left: |
docs/manual/guide/03-keys.org +19
| @@ -123,12 +123,18 @@ These come from the menu bar and work in every preset. In the Doom preset, keys | ||
| 123 | 123 | | Edit | Search Notes | =⇧⌘F= | |
| 124 | 124 | | View | Show Markup | =⇧⌘M= | |
| 125 | 125 | | View | Show Line Numbers | =⇧⌘L= | |
| 126 | | View | Split Pane Below | =⌃⌘2= | | |
| 127 | | View | Split Pane Right | =⌃⌘3= | | |
| 128 | | View | Close Pane | =⌃⌘0= | | |
| 129 | | View | Close Other Panes | =⌃⌘1= | | |
| 130 | | View | Next Pane | =⌥⌘`= | | |
| 126 | 131 | | View | Show or Hide Outline | =⌥⌘O= | |
| 127 | 132 | | View | Show or Hide Columns and Clock | =⌥⌘I= | |
| 128 | 133 | | Window | Agenda | =⇧⌘A= | |
| 129 | 134 | | Window | Board | =⇧⌘B= | |
| 130 | 135 | | Window | Next Buffer | =⇧⌘]= | |
| 131 | 136 | | Window | Previous Buffer | =⇧⌘[= | |
| 137 | | File | New Window | =⌥⌘N= | | |
| 132 | 138 | |
| 133 | 139 | View ▸ Show or Hide Backlinks and Show Tab Bar, Window ▸ Switch to Buffer…, and the items of File ▸ Export have no shortcut. |
| 134 | 140 | |
| @@ -558,6 +564,13 @@ Besides the leader, the preset binds these evil-org and Doom keys in normal stat | ||
| 558 | 564 | | =SPC h r r= | Reload Keymap (=app.reload-keymap=) | |
| 559 | 565 | | =SPC n l= | Store Link (=org.link.store=) | |
| 560 | 566 | | =SPC o a= | Agenda (=app.agenda=) | |
| 567 | | =SPC w c= | Close Pane (=app.pane-close=) | | |
| 568 | | =SPC w d= | Close Pane (=app.pane-close=) | | |
| 569 | | =SPC w n= | New Window (=app.window-new=) | | |
| 570 | | =SPC w o= | Close Other Panes (=app.pane-only=) | | |
| 571 | | =SPC w s= | Split Pane Below (=app.split-below=) | | |
| 572 | | =SPC w v= | Split Pane Right (=app.split-right=) | | |
| 573 | | =SPC w w= | Next Pane (=app.pane-next=) | | |
| 561 | 574 | | =SPC q q= | Quit orgstar (=app.quit=) | |
| 562 | 575 | | =SPC s p= | Search Notes (=app.search=) | |
| 563 | 576 | | =SPC s s= | Find (=edit.find=) | |
| @@ -960,6 +973,12 @@ When a key appears in several rows, it runs the command whose condition holds at | ||
| 960 | 973 | | Last Buffer (=app.buffer.last=) | — | — | =SPC `= (N) | Shows the buffer you were in before this one. | |
| 961 | 974 | | Close Buffer (=app.buffer.kill=) | =C-x k= | — | =SPC b k= (N), =SPC b d= (N) | Closes the buffer, asking about unsaved changes in explicit save mode (=kill-buffer=). | |
| 962 | 975 | | Close Other Buffers (=app.buffer.kill-others=) | — | — | =SPC b O= (N) | Closes every other buffer. | |
| 976 | | Split Pane Below (=app.split-below=) | =C-x 2= | =⌃⌘2= | =SPC w s= (N), =C-w s= (N) | Divides the focused pane in two, one above the other, both showing its buffer (=split-window-below=). | | |
| 977 | | Split Pane Right (=app.split-right=) | =C-x 3= | =⌃⌘3= | =SPC w v= (N), =C-w v= (N) | Divides the focused pane in two, side by side (=split-window-right=). | | |
| 978 | | Close Pane (=app.pane-close=) | =C-x 0= | =⌃⌘0= | =SPC w d= (N), =SPC w c= (N), =C-w c= (N) | Removes the focused pane; its buffers stay open (=delete-window=). | | |
| 979 | | Close Other Panes (=app.pane-only=) | =C-x 1= | =⌃⌘1= | =SPC w o= (N), =C-w o= (N) | Leaves only the focused pane (=delete-other-windows=). | | |
| 980 | | Next Pane (=app.pane-next=) | =C-x o= | =⌥⌘`= | =SPC w w= (N), =C-w w= (N) | Moves the focus to the next pane in reading order (=other-window=). | | |
| 981 | | New Window (=app.window-new=) | =C-x 5 2= | =⌥⌘N= | =SPC w n= (N) | Opens a window of panes on the focused buffer, without the sidebar (=make-frame-command=). | | |
| 963 | 982 | | Close All Buffers (=app.buffer.kill-all=) | — | — | =SPC b K= (N) | Closes every buffer. | |
| 964 | 983 | | Command Palette… (=app.palette=) | =M-x= | — | =SPC := (N) | Opens the command palette (=execute-extended-command=). | |
| 965 | 984 | | Search Notes (=app.search=) | — | — | =SPC /= (N), =SPC s p= (N) | Moves to the search field for searching your notes. | |
docs/plans/2026-10-10-windows-and-panes.md +49 −42
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 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 | 9 | **Tech Stack:** TextKit 2 (several `NSTextLayoutManager`s on one `NSTextContentStorage`), SwiftUI `WindowGroup`, Swift Testing. |
| 10 | 10 | |
| @@ -24,8 +24,9 @@ | ||
| 24 | 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 | 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 | 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 | | |
| 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 | | |
| 29 | 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 | 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 | 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 | 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 | 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 | 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 | 40 | - Killing a buffer shown in two panes of two windows: both panes fall back, neither crashes on a stale editor. |
| @@ -51,39 +52,31 @@ | ||
| 51 | 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 | 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 | 57 | **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) | |
| 60 | 60 | |
| 61 | 61 | **Interfaces:** |
| 62 | 62 | - Produces: |
| 63 | 63 | |
| 64 | 64 | ```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 | |
| 65 | extension 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 | |
| 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). | |
| 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". | |
| 85 | 78 | |
| 86 | ### Task 2: `EditorPane` and the session | |
| 79 | ### Task 2: `EditorPane` and the session (done) | |
| 87 | 80 | |
| 88 | 81 | **Files:** |
| 89 | 82 | - Create: `Sources/OrgApp/EditorPane.swift`, `Sources/OrgApp/PaneLayout.swift` |
| @@ -120,18 +113,18 @@ public indirect enum PaneLayout: Equatable, Sendable { | ||
| 120 | 113 | |
| 121 | 114 | - `DocumentSession` gains `panes: [PaneID: EditorPane]`, `focused: EditorPane?`, `makePane() -> EditorPane`, `closePane(_:)`, `open(_ path: String, in pane: EditorPane)`, `show(_ path:, in:)`, `reveal(_ offset:, in:)`; `kill(path)` updates every pane. The old `path`, `outline`, `isDirty`, `conflict`, `revealRequest`, `editVersion`, `document`, `bufferChanged()` forward to `focused` with a doc comment saying so. |
| 122 | 115 | |
| 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. | |
| 124 | - [ ] 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. | |
| 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). | |
| 127 | - [ ] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders. | |
| 128 | - [ ] Commit "Editor panes and pane layout in the session". | |
| 116 | - [x] 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. | |
| 117 | - [x] Implement `PaneLayout`; run the tests. | |
| 118 | - [x] 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. | |
| 119 | - [x] 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). | |
| 120 | - [x] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders. | |
| 121 | - [x] Commit "Editor panes and pane layout in the session". | |
| 129 | 122 | |
| 130 | ### Task 3: Panes in the main window | |
| 123 | ### Task 3: Panes in the main window (done) | |
| 131 | 124 | |
| 132 | 125 | **Files:** |
| 133 | 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 | 129 | **Interfaces:** |
| 137 | 130 | |
| @@ -146,11 +139,25 @@ public indirect enum PaneLayout: Equatable, Sendable { | ||
| 146 | 139 | |
| 147 | 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. | |
| 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`). | |
| 151 | - [ ] 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`. | |
| 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, ⌃⌘`. | |
| 154 | - [ ] Manual: a "Windows and panes" section in `docs/manual/guide/02-the-editor.org` and the keys in `03-keys.org`'s reference table. | |
| 155 | - [ ] Check by hand against the review focus list; the `ORGSTAR_SNAPSHOT` hook in `DevelopmentHooks.swift` gets a two-pane snapshot. | |
| 156 | - [ ] Commit "Windows and panes". | |
| 142 | - [x] `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 | - [x] `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`). | |
| 144 | - [x] Outline column and sidebar selection follow `session.focused`. | |
| 145 | - [x] 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`. | |
| 146 | - [x] 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, after checking `macBindings`: ⌃⌘2, ⌃⌘3, ⌃⌘0, ⌃⌘1, ⌥⌘` and ⌥⌘N (⌃⌘W was Refile, ⌃⌘O Open Link). | |
| 147 | - [x] Manual: a "Windows and panes" section in `docs/manual/guide/02-the-editor.org` and the keys in `03-keys.org`'s reference table. | |
| 148 | - [x] Check by hand against the review focus list; the `ORGSTAR_SNAPSHOT` hook in `DevelopmentHooks.swift` gets a two-pane snapshot. | |
| 149 | - [x] Commit "Windows and panes". | |
| 150 | ||
| 151 | ## As built | |
| 152 | ||
| 153 | - A second window is an editor-only window (`EditorWindowView`, `WindowGroup("Editor")`): panes, tabs, modeline and echo area, no sidebar or search. The main window stays a single `Window`, since its body carries the app's lifecycle (buffer restore, reminders, the global hotkey, development hooks), which must run once. Quick Open, the palette and the sheets stay on the main window and act on the focused pane wherever it is. | |
| 154 | - `EditorStore` (app) keeps one `OrgEditor` per open file and one text view per pane showing it; the first text view of an editor belongs to the first pane that showed the file and is handed on when that pane moves off it. | |
| 155 | - `WindowModel` (app) holds a window's `PaneLayout`, its panes and the focused one; `AppCommands.store.windows` lists them so pane commands find the window of the focused pane. | |
| 156 | - A split shows the same buffer in the new pane and keeps the focus, as `split-window` does. A pane with no buffer shows a placeholder. | |
| 157 | - Checked: `swift test` (691 tests); the main window with three panes and a fold shared by all of them, by snapshot; the window and pane commands run to completion under the development hooks. | |
| 158 | ||
| 159 | ## Review | |
| 160 | ||
| 161 | A fresh review of the branch found, and the fix pass closed: a nested split's inner divider resized the outer split (splits are now keyed by the two panes either side of the divider, with a test); the main window had no close-time cleanup, so reopening it drove a stale model (it now registers a fresh model on appear and releases its panes on disappear); the editor window's app commands did nothing with the main window closed (it reopens it first, and a request made before the window appeared runs when it does); narrowing and sparse trees left other views' carets in hidden text, and a view taking focus kept such a caret (every view's caret is moved, and a view taking focus runs the selection check); the palette and Quick Open acted on the main window's pane when opened from an editor window (they act on the pane that had the focus when they opened); the empty-pane placeholder left the keyboard with another pane; `WindowModel.closeAll` emptied the panes under views still on screen. | |
| 162 | ||
| 163 | Deferred, minor: `kill` and `showPrevious` may fall back to a buffer another pane already shows (Emacs prefers one not visible); a split's new view starts at the top rather than at the point, and `truncatesLines` is per view and not copied to a new view; detached text views keep observing key-window changes (pre-existing, now common); `Theme.focusedLayouts` can keep a released primary view's id; `previousSelection` is per editor, so the first caret fix after switching views may jump the wrong way; `.onChange(of: session.path)` runs the sync-conflict scan on every focus change between panes showing different files. | |