Commit d6defe0dc0

d6defe0dc0a9a2097c50011a25c810644b5ffaef

parent: 06a0f36fc9

Verified · cmc

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

Windows and panes

Layout: unified · split

Sources/OrgApp/PaneLayout.swift +13
@@ -46,6 +46,19 @@ public indirect enum PaneLayout: Equatable, Sendable {
46 } 46 }
47 } 47 }
48 48
49 /// The split whose first pane in reading order is `id`, with `fraction` for its first side.
50 public func settingFraction(_ fraction: Double, ofSplitStartingWith id: PaneID) -> PaneLayout {
51 switch self {
52 case .pane: self
53 case .split(let axis, let first, let second, let old):
54 if first.panes.first == id {
55 .split(axis: axis, first: first, second: second, fraction: min(max(fraction, 0.1), 0.9))
56 } else {
57 .split(axis: axis, first: first.settingFraction(fraction, ofSplitStartingWith: id), second: second.settingFraction(fraction, ofSplitStartingWith: id), fraction: old)
58 }
59 }
60 }
61
49 /// Only `id`, filling the window. 62 /// Only `id`, filling the window.
50 public func only(_ id: PaneID) -> PaneLayout { .pane(id) } 63 public func only(_ id: PaneID) -> PaneLayout { .pane(id) }
51 64
Sources/OrgCore/Keymap/PresetDoom.swift +49
@@ -59,6 +59,55 @@ extension KeymapPreset {
59 keys = "SPC f s" 59 keys = "SPC f s"
60 command = "app.save" 60 command = "app.save"
61 mode = "normal" 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 # Buffers 111 # Buffers
63 [[bind]] 112 [[bind]]
64 keys = "SPC b b" 113 keys = "SPC b b"
Sources/OrgCore/Keymap/PresetEmacs.swift +18
@@ -240,6 +240,24 @@ extension KeymapPreset {
240 keys = "C-x k" 240 keys = "C-x k"
241 command = "app.buffer.kill" 241 command = "app.buffer.kill"
242 [[bind]] 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 keys = "C-x <right>" 261 keys = "C-x <right>"
244 command = "app.buffer.next" 262 command = "app.buffer.next"
245 [[bind]] 263 [[bind]]
Sources/OrgCore/Keymap/PresetMac.swift +18
@@ -7,6 +7,24 @@ extension KeymapPreset {
7 keys = "C-S-TAB" 7 keys = "C-S-TAB"
8 command = "app.buffer.previous" 8 command = "app.buffer.previous"
9 [[bind]] 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 keys = "C-s-t" 28 keys = "C-s-t"
11 command = "org.todo.cycle" 29 command = "org.todo.cycle"
12 [[bind]] 30 [[bind]]
Sources/OrgEditorAppKit/EditorCommands.swift +6
@@ -68,6 +68,12 @@ public enum EditorCommands {
68 EditorCommand(id: "app.buffer.next", title: "Next Buffer", action: .app), 68 EditorCommand(id: "app.buffer.next", title: "Next Buffer", action: .app),
69 EditorCommand(id: "app.buffer.previous", title: "Previous Buffer", action: .app), 69 EditorCommand(id: "app.buffer.previous", title: "Previous Buffer", action: .app),
70 EditorCommand(id: "app.buffer.last", title: "Last Buffer", action: .app), 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 EditorCommand(id: "app.babel.cancel", title: "Cancel Running Task", action: .app), 77 EditorCommand(id: "app.babel.cancel", title: "Cancel Running Task", action: .app),
72 EditorCommand(id: "app.toggle-tab-bar", title: "Show or Hide Tab Bar", action: .app), 78 EditorCommand(id: "app.toggle-tab-bar", title: "Show or Hide Tab Bar", action: .app),
73 EditorCommand(id: "app.toggle-outline", title: "Show or Hide Outline", action: .app), 79 EditorCommand(id: "app.toggle-outline", title: "Show or Hide Outline", action: .app),
Sources/OrgEditorAppKit/OrgEditor.swift +6 −1
@@ -21,6 +21,8 @@ public final class OrgEditor: NSObject {
21 var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) } 21 var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
22 /// One undo history for the buffer, whichever view edits it. 22 /// One undo history for the buffer, whichever view edits it.
23 public let undoManager = UndoManager() 23 public let undoManager = UndoManager()
24 /// A text view of this editor took keyboard focus.
25 public var onFocus: ((NSTextView) -> Void)?
24 public private(set) var document: DocumentState 26 public private(set) var document: DocumentState
25 public internal(set) var view = ViewState() 27 public internal(set) var view = ViewState()
26 /// Called with the time from a character edit to restyled text. 28 /// Called with the time from a character edit to restyled text.
@@ -135,7 +137,10 @@ public final class OrgEditor: NSObject {
135 view.onFocusChange = { [weak self, unowned view] in 137 view.onFocusChange = { [weak self, unowned view] in
136 guard let self, let layout = view.textLayoutManager else { return } 138 guard let self, let layout = view.textLayoutManager else { return }
137 let id = ObjectIdentifier(layout) 139 let id = ObjectIdentifier(layout)
138 if view.window?.firstResponder === view { self.active = view } 140 if view.window?.firstResponder === view {
141 self.active = view
142 self.onFocus?(view)
143 }
139 if let window = view.window, window.isKeyWindow, window.firstResponder === view { 144 if let window = view.window, window.isKeyWindow, window.firstResponder === view {
140 Theme.focusedLayouts.insert(id) 145 Theme.focusedLayouts.insert(id)
141 } else { 146 } else {
Sources/Orgstar/BlockEditorView.swift +1 −1
@@ -46,7 +46,7 @@ struct CodeEditor: NSViewRepresentable {
46 let done: (Bool) -> Void 46 let done: (Bool) -> Void
47 47
48 func makeNSView(context: Context) -> NSScrollView { 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 editor.keymap = Keymap([ 50 editor.keymap = Keymap([
51 KeyBinding(keys: KeySequence.parse("C-c '")!, command: "app.block.save"), 51 KeyBinding(keys: KeySequence.parse("C-c '")!, command: "app.block.save"),
52 KeyBinding(keys: KeySequence.parse("C-c C-k")!, command: "app.block.cancel"), 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.
30struct BufferTabs: View { 31struct BufferTabs: View {
31 let session: DocumentSession 32 let session: DocumentSession
33 let pane: EditorPane
32 @Environment(\.orgTheme) private var theme 34 @Environment(\.orgTheme) private var theme
33 35
34 var body: some View { 36 var body: some View {
35 ScrollView(.horizontal, showsIndicators: false) { 37 ScrollView(.horizontal, showsIndicators: false) {
36 HStack(spacing: 0) { 38 HStack(spacing: 0) {
37 ForEach(session.openPaths, id: \.self) { path in 39 ForEach(pane.shown, id: \.self) { path in
38 tab(path) 40 tab(path)
39 } 41 }
40 } 42 }
@@ -45,19 +47,15 @@ struct BufferTabs: View {
45 } 47 }
46 48
47 private func tab(_ path: String) -> some View { 49 private func tab(_ path: String) -> some View {
48 let current = path == session.path 50 let current = path == pane.path
49 return HStack(spacing: 6) { 51 return HStack(spacing: 6) {
50 Text(session.bufferName(path)) 52 Text(session.bufferName(path))
51 .lineLimit(1) 53 .lineLimit(1)
52 .foregroundStyle(current ? .primary : .secondary) 54 .foregroundStyle(current ? .primary : .secondary)
53 .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton) 55 .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton)
54 .accessibilityAction { session.open(path) } 56 .accessibilityAction { session.open(path, in: pane) }
55 Button { 57 Button {
56 if path == session.path { 58 if UnsavedChanges.resolve(session, paths: [path]) { session.kill(path) }
57 if UnsavedChanges.resolve(session) { session.kill(path) }
58 } else if UnsavedChanges.resolve(session, paths: [path]) {
59 session.kill(path)
60 }
61 } label: { 59 } label: {
62 Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark") 60 Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
63 .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold)) 61 .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
@@ -74,7 +72,7 @@ struct BufferTabs: View {
74 .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) } 72 .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
75 .overlay(alignment: .trailing) { Divider() } 73 .overlay(alignment: .trailing) { Divider() }
76 .contentShape(Rectangle()) 74 .contentShape(Rectangle())
77 .onTapGesture { session.open(path) } 75 .onTapGesture { session.open(path, in: pane) }
78 .help(path) 76 .help(path)
79 } 77 }
80} 78}
Sources/Orgstar/ContentView.swift +60 −8
@@ -97,6 +97,29 @@ struct ContentView: View {
97 @State private var plainOutlineShown = false 97 @State private var plainOutlineShown = false
98 @State private var showingImport = false 98 @State private var showingImport = false
99 @AppStorage("showTabBar") private var showTabBar = false 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 window holding the focused pane: this one, or an editor window.
108 private var paneWindow: WindowModel? {
109 commands.store.window(of: session.focused.id) ?? window
110 }
111
112 /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
113 private func focusPane(_ window: WindowModel) {
114 let pane = window.focusedPane
115 session.focused = pane
116 if let path = pane.path, let textView = commands.store.textView(for: pane.id, path: path) {
117 textView.window?.makeFirstResponder(textView)
118 commands.editor = commands.store.editor(for: path)
119 } else {
120 commands.editor = nil
121 }
122 }
100 /// Carets of restored buffers, shown when each first shows. 123 /// Carets of restored buffers, shown when each first shows.
101 @State private var pendingCarets: [String: Int] = [:] 124 @State private var pendingCarets: [String: Int] = [:]
102 @State private var query = "" 125 @State private var query = ""
@@ -118,10 +141,9 @@ struct ContentView: View {
118 private var detail: some View { 141 private var detail: some View {
119 if let previewPath { 142 if let previewPath {
120 FilePreview(path: previewPath) 143 FilePreview(path: previewPath)
121 } else if session.path != nil { 144 } else if !session.openPaths.isEmpty, let window {
122 VStack(spacing: 0) { 145 PaneLayoutView(layout: window.layout, window: window) { pane in
123 if showTabBar { BufferTabs(session: session) } 146 PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
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()) ?? [] })
125 } 147 }
126 .safeAreaInset(edge: .bottom, spacing: 0) { 148 .safeAreaInset(edge: .bottom, spacing: 0) {
127 VStack(spacing: 0) { 149 VStack(spacing: 0) {
@@ -240,7 +262,20 @@ struct ContentView: View {
240 let copies = session.syncConflictCopies().count 262 let copies = session.syncConflictCopies().count
241 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") } 263 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
242 } 264 }
243 .onChange(of: session.openPaths) { BufferRestore.save(session) } 265 .onChange(of: session.openPaths) { _, paths in
266 BufferRestore.save(session)
267 for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
268 }
269 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
270 .onAppear {
271 commands.externalHandler = runExternal
272 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
273 if window == nil {
274 let model = WindowModel(session: session, pane: session.panes[0])
275 window = model
276 commands.store.windows.append(model)
277 }
278 }
244 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode } 279 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
245 .onChange(of: options, initial: true) { _, options in session.options = options } 280 .onChange(of: options, initial: true) { _, options in session.options = options }
246 .onChange(of: preset, initial: true) { loadKeymap() } 281 .onChange(of: preset, initial: true) { loadKeymap() }
@@ -405,7 +440,7 @@ struct ContentView: View {
405 let url = URL(fileURLWithPath: path) 440 let url = URL(fileURLWithPath: path)
406 let html = HTMLExport.page( 441 let html = HTMLExport.page(
407 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil, 442 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
408 codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme) 443 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
409 ) 444 )
410 do { 445 do {
411 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent()) 446 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
@@ -456,7 +491,7 @@ struct ContentView: View {
456 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly) 491 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
457 : HTMLExport.page( 492 : HTMLExport.page(
458 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly, 493 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
459 codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme) 494 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
460 ) 495 )
461 do { 496 do {
462 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) 497 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
@@ -472,7 +507,7 @@ struct ContentView: View {
472 let target = destination ?? ExportScope.output(for: url, name: name, extension: ext) 507 let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
473 let html = HTMLExport.page( 508 let html = HTMLExport.page(
474 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, 509 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
475 codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme) 510 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
476 ) 511 )
477 let directory = url.deletingLastPathComponent() 512 let directory = url.deletingLastPathComponent()
478 if format == "print-pdf" { commands.show("Exporting to PDF…") } 513 if format == "print-pdf" { commands.show("Exporting to PDF…") }
@@ -651,6 +686,23 @@ struct ContentView: View {
651 let all = session.openPaths 686 let all = session.openPaths
652 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) } 687 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
653 case "app.toggle-tab-bar": showTabBar.toggle() 688 case "app.toggle-tab-bar": showTabBar.toggle()
689 case "app.split-below": paneWindow?.split(.vertical)
690 case "app.split-right": paneWindow?.split(.horizontal)
691 case "app.pane-close":
692 guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
693 commands.store.releasePane(window.focused)
694 window.close(window.focused)
695 focusPane(window)
696 case "app.pane-only":
697 guard let window = paneWindow else { return }
698 for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
699 window.closeOthers()
700 focusPane(window)
701 case "app.pane-next":
702 guard let window = paneWindow else { return }
703 window.focusNext()
704 focusPane(window)
705 case "app.window-new": openWindow(id: "editor")
654 case "app.babel.cancel": 706 case "app.babel.cancel":
655 if session.isRunningBabel { 707 if session.isRunningBabel {
656 session.cancelBabel() 708 session.cancelBabel()
Sources/Orgstar/EditorStore.swift added +80
@@ -0,0 +1,80 @@
1import AppKit
2import OrgApp
3import 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
8final 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 @@
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgHighlight
7import 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.
12struct 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 +45
@@ -0,0 +1,45 @@
1import OrgApp
2import 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.
6struct 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
13 var body: some View {
14 Group {
15 if let window {
16 PaneLayoutView(layout: window.layout, window: window) { pane in
17 PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar) { commands.run($0) }
18 }
19 .safeAreaInset(edge: .bottom, spacing: 0) {
20 VStack(spacing: 0) {
21 ModeLine(session: session, commands: commands, clock: clock) { commands.run($0) }
22 EchoArea(commands: commands)
23 }
24 }
25 }
26 }
27 .navigationTitle(window?.focusedPane.path.map(session.bufferName) ?? "orgstar")
28 .onAppear {
29 guard window == nil else { return }
30 let pane = session.makePane()
31 if let path = session.focused.path { session.open(path, in: pane) }
32 let model = WindowModel(session: session, pane: pane)
33 window = model
34 commands.store.windows.append(model)
35 model.focus(pane.id)
36 }
37 .onDisappear {
38 guard let model = window else { return }
39 for id in model.layout.panes { commands.store.releasePane(id) }
40 model.closeAll()
41 commands.store.windows.removeAll { $0 === model }
42 if let main = commands.store.windows.first { main.focus(main.focused) }
43 }
44 }
45}
Sources/Orgstar/OrgstarApp.swift +29 −1
@@ -20,8 +20,16 @@ final class AppCommands {
20 private var jumpID = 0 20 private var jumpID = 0
21 /// Days the agenda window should show, from a followed timestamp. 21 /// Days the agenda window should show, from a followed timestamp.
22 var agendaRequest: (start: Int, days: Int)? 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 var editor: OrgEditor? 24 var editor: OrgEditor?
25 /// The editors and text views of every pane in every window.
26 let store = EditorStore()
27 /// What every editor is set up with, from the settings; the main window keeps it current.
28 var editorSettings = EditorSettings()
29 /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
30 var externalHandler: ((ExternalRequest) -> Void)?
31 /// Tags used across the workspace, for tag completion; the main window sets it.
32 var knownTags: () -> [String] = { [] }
25 /// The pending key prefix, and what can follow it. 33 /// The pending key prefix, and what can follow it.
26 var pendingKeys: String? 34 var pendingKeys: String?
27 /// The editor's evil state in the Doom preset. 35 /// The editor's evil state in the Doom preset.
@@ -317,6 +325,13 @@ struct OrgstarApp: App {
317 } 325 }
318 } 326 }
319 .defaultSize(width: 1280, height: 860) 327 .defaultSize(width: 1280, height: 860)
328 WindowGroup("Editor", id: "editor") {
329 if case .success = workspace {
330 EditorWindowView(session: session, commands: commands, clock: clock)
331 .environment(\.orgTheme, ConfigSync.shared.theme)
332 }
333 }
334 .defaultSize(width: 900, height: 700)
320 Window("Agenda", id: "agenda") { 335 Window("Agenda", id: "agenda") {
321 if case .success(let model) = workspace { 336 if case .success(let model) = workspace {
322 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock) 337 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
@@ -384,6 +399,17 @@ struct OrgstarApp: App {
384 .disabled(session.dirtyPaths.isEmpty) 399 .disabled(session.dirtyPaths.isEmpty)
385 } 400 }
386 CommandGroup(after: .sidebar) { 401 CommandGroup(after: .sidebar) {
402 Button("Split Pane Below") { commands.run("app.split-below") }
403 .keyboardShortcut("2", modifiers: [.command, .control])
404 Button("Split Pane Right") { commands.run("app.split-right") }
405 .keyboardShortcut("3", modifiers: [.command, .control])
406 Button("Close Pane") { commands.run("app.pane-close") }
407 .keyboardShortcut("0", modifiers: [.command, .control])
408 Button("Close Other Panes") { commands.run("app.pane-only") }
409 .keyboardShortcut("1", modifiers: [.command, .control])
410 Button("Next Pane") { commands.run("app.pane-next") }
411 .keyboardShortcut("`", modifiers: [.command, .option])
412 Divider()
387 Button("Show or Hide Outline") { commands.run("app.toggle-outline") } 413 Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
388 .keyboardShortcut("o", modifiers: [.command, .option]) 414 .keyboardShortcut("o", modifiers: [.command, .option])
389 Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") } 415 Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
@@ -416,6 +442,8 @@ struct OrgstarApp: App {
416 CommandGroup(after: .newItem) { 442 CommandGroup(after: .newItem) {
417 Button("Capture…") { commands.run("app.capture") } 443 Button("Capture…") { commands.run("app.capture") }
418 .keyboardShortcut("n", modifiers: [.command, .shift]) 444 .keyboardShortcut("n", modifiers: [.command, .shift])
445 Button("New Window") { commands.run("app.window-new") }
446 .keyboardShortcut("n", modifiers: [.command, .option])
419 } 447 }
420 } 448 }
421 .commands { 449 .commands {
Sources/Orgstar/PaneLayoutView.swift added +94
@@ -0,0 +1,94 @@
1import OrgApp
2import SwiftUI
3
4/// A window's panes as its layout divides them, with a draggable divider at each split.
5struct 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), ofSplitStartingWith: first.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.
40struct 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.
66struct 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 commands.editor = nil
85 }
86 }
87 }
88 .overlay(alignment: .top) {
89 if window.paneCount > 1, window.focused == pane.id {
90 Rectangle().fill(Color.accentColor).frame(height: 2).accessibilityHidden(true)
91 }
92 }
93 }
94}
Sources/Orgstar/PaneView.swift added +136
@@ -0,0 +1,136 @@
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgHighlight
7import SwiftUI
8
9/// What every editor view is set up with, from the settings.
10struct 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.
23struct 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 @@
1import Foundation
2import 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
8final 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]]! }
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, ofSplitStartingWith id: PaneID) {
65 layout = layout.settingFraction(fraction, ofSplitStartingWith: id)
66 }
67
68 /// Takes every pane out of the session, as the window closes.
69 func closeAll() {
70 for pane in panes.values { session.closePane(pane) }
71 panes = [:]
72 }
73}
Tests/OrgAppTests/PaneLayoutTests.swift +8
@@ -19,6 +19,14 @@ struct PaneLayoutTests {
19 #expect(PaneLayout.pane(a).removing(a) == nil) 19 #expect(PaneLayout.pane(a).removing(a) == nil)
20 } 20 }
21 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, ofSplitStartingWith: b)
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, ofSplitStartingWith: a) == .split(axis: .horizontal, first: .pane(a), second: .split(axis: .vertical, first: .pane(b), second: .pane(c), fraction: 0.5), fraction: 0.9))
28 }
29
22 @Test func onlyAndNext() { 30 @Test func onlyAndNext() {
23 let a = PaneID(), b = PaneID(), c = PaneID() 31 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) 32 let layout = PaneLayout.pane(a).splitting(a, axis: .horizontal, new: b).splitting(b, axis: .vertical, new: c)
Tests/OrgAppTests/WindowModelTests.swift added +22
@@ -0,0 +1,22 @@
1import Foundation
2import OrgDocument
3import 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
10struct 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}
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** The tab bar 167** The tab bar
168 168
169View ▸ 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=. 169View ▸ 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- Click a tab to show its buffer. Hover to see the file's full path. 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* Searching your notes 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
149Narrowing to a subtree or block, and sparse trees, also hide text; see [[file:04-outlines.org][Outlines]]. 149Narrowing to a subtree or block, and sparse trees, also hide text; see [[file:04-outlines.org][Outlines]].
150 150
151* Panes and windows
152
153A 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
155Each 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
157New 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* The modeline 159* The modeline
152 160
153The line under the editor shows, from the left: 161The 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| Edit | Search Notes | =⇧⌘F= | 123| Edit | Search Notes | =⇧⌘F= |
124| View | Show Markup | =⇧⌘M= | 124| View | Show Markup | =⇧⌘M= |
125| View | Show Line Numbers | =⇧⌘L= | 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| View | Show or Hide Outline | =⌥⌘O= | 131| View | Show or Hide Outline | =⌥⌘O= |
127| View | Show or Hide Columns and Clock | =⌥⌘I= | 132| View | Show or Hide Columns and Clock | =⌥⌘I= |
128| Window | Agenda | =⇧⌘A= | 133| Window | Agenda | =⇧⌘A= |
129| Window | Board | =⇧⌘B= | 134| Window | Board | =⇧⌘B= |
130| Window | Next Buffer | =⇧⌘]= | 135| Window | Next Buffer | =⇧⌘]= |
131| Window | Previous Buffer | =⇧⌘[= | 136| Window | Previous Buffer | =⇧⌘[= |
137| File | New Window | =⌥⌘N= |
132 138
133View ▸ Show or Hide Backlinks and Show Tab Bar, Window ▸ Switch to Buffer…, and the items of File ▸ Export have no shortcut. 139View ▸ 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| =SPC h r r= | Reload Keymap (=app.reload-keymap=) | 564| =SPC h r r= | Reload Keymap (=app.reload-keymap=) |
559| =SPC n l= | Store Link (=org.link.store=) | 565| =SPC n l= | Store Link (=org.link.store=) |
560| =SPC o a= | Agenda (=app.agenda=) | 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| =SPC q q= | Quit orgstar (=app.quit=) | 574| =SPC q q= | Quit orgstar (=app.quit=) |
562| =SPC s p= | Search Notes (=app.search=) | 575| =SPC s p= | Search Notes (=app.search=) |
563| =SPC s s= | Find (=edit.find=) | 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| Last Buffer (=app.buffer.last=) | — | — | =SPC `= (N) | Shows the buffer you were in before this one. | 973| Last Buffer (=app.buffer.last=) | — | — | =SPC `= (N) | Shows the buffer you were in before this one. |
961| 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=). | 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| Close Other Buffers (=app.buffer.kill-others=) | — | — | =SPC b O= (N) | Closes every other buffer. | 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| Close All Buffers (=app.buffer.kill-all=) | — | — | =SPC b K= (N) | Closes every buffer. | 982| Close All Buffers (=app.buffer.kill-all=) | — | — | =SPC b K= (N) | Closes every buffer. |
964| Command Palette… (=app.palette=) | =M-x= | — | =SPC := (N) | Opens the command palette (=execute-extended-command=). | 983| Command Palette… (=app.palette=) | =M-x= | — | =SPC := (N) | Opens the command palette (=execute-extended-command=). |
965| Search Notes (=app.search=) | — | — | =SPC /= (N), =SPC s p= (N) | Moves to the search field for searching your notes. | 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 +24 −16
@@ -76,7 +76,7 @@ extension OrgEditor {
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. 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". 77- [x] Commit "One editor, several text views".
78 78
79### Task 2: `EditorPane` and the session 79### Task 2: `EditorPane` and the session (done)
80 80
81**Files:** 81**Files:**
82- Create: `Sources/OrgApp/EditorPane.swift`, `Sources/OrgApp/PaneLayout.swift` 82- Create: `Sources/OrgApp/EditorPane.swift`, `Sources/OrgApp/PaneLayout.swift`
@@ -113,14 +113,14 @@ public indirect enum PaneLayout: Equatable, Sendable {
113 113
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. 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.
115 115
116- [ ] Write the failing `PaneLayout` tests: split right then split below the second pane gives three panes in reading order; removing the middle one leaves a two-pane split with the remaining fraction; `only` collapses; `next` wraps; removing the only pane returns nil. 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- [ ] Implement `PaneLayout`; run the tests. 117- [x] Implement `PaneLayout`; run the tests.
118- [ ] Write the failing `EditorPane` tests with a `DocumentSession` over an in-memory `FileSystem` (as `DocumentSessionTests` do): opening a path in pane A then showing it in pane B leaves one `Entry`; killing it empties both panes' `path` and `shown`; a pane's `shown` keeps order and drops killed paths; `reveal(_:in:)` bumps only that pane's request; `dirtyPaths` counts a buffer once however many panes show it. 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- [ ] 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). 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- [ ] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders. 120- [x] Run the whole suite. `AppTests` that read `session.path` keep passing through the forwarders.
121- [ ] Commit "Editor panes and pane layout in the session". 121- [x] Commit "Editor panes and pane layout in the session".
122 122
123### Task 3: Panes in the main window 123### Task 3: Panes in the main window (done)
124 124
125**Files:** 125**Files:**
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` 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`
@@ -139,11 +139,19 @@ public indirect enum PaneLayout: Equatable, Sendable {
139 139
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`. 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`.
141 141
142- [ ] `WindowGroup("orgstar", id: "main")` replaces `Window("orgstar", id: "main")`; the root view creates its `WindowModel` and one pane (`session.makePane()`) in `onAppear`, registers the model with `commands`, and on disappear closes its panes (`session.closePane`) so their text views are removed (`editor.removeView`). Buffers stay in the session. 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- [ ] `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`). 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- [ ] Outline column and sidebar selection follow `session.focused`. 144- [x] Outline column and sidebar selection follow `session.focused`.
145- [ ] Jump requests (`AppCommands.jumpRequest`) are handled by the key window's root view only: `commands.keyWindow === model`. With no main window open, `openWindow(id: "main")` first, then the request is delivered on the new window's first `onAppear`. 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- [ ] Commands, as `app.*` ids dispatched where `app.quick-open` is today: `app.split-below`, `app.split-right`, `app.pane-close`, `app.pane-only`, `app.pane-next`, `app.window-new`. Menu: File ▸ New Window; View ▸ Split Below, Split Right, Close Pane, Close Other Panes, Next Pane. Emacs preset: `C-x 2`, `C-x 3`, `C-x 0`, `C-x 1`, `C-x o`, `C-x 5 2`. Doom: `SPC w s`, `SPC w v`, `SPC w d`, `SPC w o`, `SPC w w`, and `C-w s/v/c/o/w` in normal state. Mac: shortcuts chosen after checking `macBindings`; proposal ⌥⌘N, ⌥⌘-, ⌥⌘\, ⌃⌘W, ⌃⌘1, ⌃⌘`. 146- [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- [ ] Manual: a "Windows and panes" section in `docs/manual/guide/02-the-editor.org` and the keys in `03-keys.org`'s reference table. 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- [ ] Check by hand against the review focus list; the `ORGSTAR_SNAPSHOT` hook in `DevelopmentHooks.swift` gets a two-pane snapshot. 148- [x] Check by hand against the review focus list; the `ORGSTAR_SNAPSHOT` hook in `DevelopmentHooks.swift` gets a two-pane snapshot.
149- [ ] Commit "Windows and panes". 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.