docs/plans/2026-10-10-windows-and-panes.md
163 lines · 16212 bytes
Windows and Panes Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
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.
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.
Tech Stack: TextKit 2 (several NSTextLayoutManagers on one NSTextContentStorage), SwiftUI WindowGroup, Swift Testing.
Spec: docs/design.md, Commands ▸ Document session ("Each window or split has its own selection, fold state and narrowing, mapped through every edit").
Global constraints
- The buffer is the file: one text storage, one undo stack and one revision per open file, however many views show it.
- Byte fidelity and the save path are untouched; only who owns the storage changes.
- The iOS editor (
MobileEditor) is not restructured by this plan; iPad multi-window is a later piece. - Mac preset shortcuts for the new commands are checked against the existing Mac bindings in
Presets.swiftbefore being chosen, and must not take system shortcuts.
Decisions
| Question | Decision | Reason |
|---|---|---|
| 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 |
| 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 |
| Killing a buffer | Removed from every pane; a pane showing it falls back to its previous buffer, else empty | Emacs behaviour |
| 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 |
| Shrunk table columns, inline-image toggle, markup toggle, evil state, mark | Per buffer | They are buffer-local in Org and evil |
| Caret, selection, scroll position, focus | Per view | What a window owns in Emacs |
| Undo | One UndoManager per buffer, returned from every view's undoManager(for:) |
C-/ in either view undoes the last edit to the file |
| Quick Open, search field, palette, conflict sheet | Per window (moved from AppCommands to WindowModel) |
Global booleans would present them in every window at once |
| 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 |
| Sidebar | Per window; its file selection follows the window's focused pane | Nothing shared to keep in step |
Review focus
- 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.
- 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.
- 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.
- Killing a buffer shown in two panes of two windows: both panes fall back, neither crashes on a stale editor.
- A command run from the palette or a menu must act on the focused pane's editor, not whichever editor was created last.
Task 0: Spike: two text views on one content storage
Files:
-
Create:
Sources/OrgstarSpike/TwoViews.swift(throwaway, under the existing spike target) -
One
NSTextContentStorage, twoNSTextLayoutManagers each with anNSTextContainerand anNSTextView(frame:textContainer:), in one window side by side. A sharedUndoManagerreturned by both views' delegateundoManager(for:). -
Check and write the findings at the top of the file: typing in A shows in B; undo from B reverts A's typing; each layout manager's delegate can return a different
NSTextLayoutFragmentfor the same element (fold shown in A only); rendering attributes set on one layout manager do not appear in the other; IME composition in A does not disturb B's selection; selection in B survives an insertion before it in A. -
If any check fails, stop and amend this plan before Task 1: the fallback is per-view
NSTextStorages kept in step by replaying edits, which is a different Task 1. -
Commit "Spike: two text views on one content storage".
Task 1: Several text views on one editor (done)
Files:
- Modify:
Sources/OrgEditorAppKit/OrgEditor.swift,Keys.swift,OrgEditor+Folding.swift,OrgEditor+Images.swift,OrgEditor+Shrink.swift,Modal.swift,ViewToggles.swift - Test:
Tests/OrgEditorAppKitTests/MultiViewTests.swift,TwoViewsSpikeTests.swift(Task 0)
Interfaces:
- Produces:
extension OrgEditor {
public var textView: NSTextView { get } // the view with focus, or the last to have had it
public private(set) var textViews: [NSTextView] // the first made with the editor
public let undoManager: UndoManager // shared by every view
public func addView(frame: NSRect = ...) -> NSTextView
public func removeView(_ view: NSTextView) // never the first
public func makeScrollView(for view: NSTextView? = nil) -> NSScrollView
}
- 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.
-
activefollows 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;textViewDidChangeSelectionignores other views' carets. - Commit "One editor, several text views".
Task 2: EditorPane and the session (done)
Files:
- Create:
Sources/OrgApp/EditorPane.swift,Sources/OrgApp/PaneLayout.swift - Modify:
Sources/OrgApp/DocumentSession.swift - Test:
Tests/OrgAppTests/PaneLayoutTests.swift,Tests/OrgAppTests/EditorPaneTests.swift
Interfaces:
- Produces:
public struct PaneID: Hashable, Sendable { }
public indirect enum PaneLayout: Equatable, Sendable {
case pane(PaneID)
case split(axis: Axis, first: PaneLayout, second: PaneLayout, fraction: Double) // Axis: .horizontal (side by side) / .vertical
public func splitting(_ id: PaneID, axis: Axis, new: PaneID) -> PaneLayout // new pane after `id`, fraction 0.5
public func removing(_ id: PaneID) -> PaneLayout? // nil when it was the only pane
public func only(_ id: PaneID) -> PaneLayout
public var panes: [PaneID] // in reading order
public func next(after id: PaneID) -> PaneID // wraps
}
@MainActor @Observable public final class EditorPane: Identifiable {
public let id: PaneID
public private(set) var path: String?
public private(set) var shown: [String] // buffers this pane has shown, tab order
public private(set) var outline: [OutlineEntry]
public private(set) var editVersion: Int
public private(set) var revealRequest: (offset: Int, id: Int)?
public var isDirty: Bool { get } // from the session's entry
public var conflict: String? { get }
public var document: DocumentState? { get }
}
-
DocumentSessiongainspanes: [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 oldpath,outline,isDirty,conflict,revealRequest,editVersion,document,bufferChanged()forward tofocusedwith a doc comment saying so. -
Write the failing
PaneLayouttests: 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;onlycollapses;nextwraps; removing the only pane returns nil. -
Implement
PaneLayout; run the tests. -
Write the failing
EditorPanetests with aDocumentSessionover an in-memoryFileSystem(asDocumentSessionTestsdo): opening a path in pane A then showing it in pane B leaves oneEntry; killing it empties both panes'pathandshown; a pane'sshownkeeps order and drops killed paths;reveal(_:in:)bumps only that pane's request;dirtyPathscounts a buffer once however many panes show it. -
Implement
EditorPaneand the session changes:Entrykeeps itsbuffer(theOrgEditor, attached once per path;attachbecomesattach(_ buffer:, for path:)),currentis replaced byfocused,historymoves 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). -
Run the whole suite.
AppTeststhat readsession.pathkeep passing through the forwarders. -
Commit "Editor panes and pane layout in the session".
Task 3: Panes in the main window (done)
Files:
- Create:
Sources/Orgstar/PaneView.swift(one pane:BufferTabs+EditorViewfor that pane),Sources/Orgstar/PaneLayoutView.swift(recursiveHSplitView/VSplitViewoverPaneLayout, usingPaneDividerfor the fraction),Sources/Orgstar/WindowModel.swift - Modify:
Sources/Orgstar/EditorView.swift(takes anEditorPane; oneOrgEditorper path, shared by panes, and one text view per (pane, path) fromaddView),Sources/Orgstar/ContentView.swift,Sources/Orgstar/BufferTabs.swift,Sources/Orgstar/OrgstarApp.swift
Interfaces:
@MainActor @Observable final class WindowModel {
let id = UUID()
var layout: PaneLayout
var focused: PaneID
var showingQuickOpen = false, focusSearch = false, showingPalette = false, showingConflict = false
}
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.
-
WindowGroup("orgstar", id: "main")replacesWindow("orgstar", id: "main"); the root view creates itsWindowModeland one pane (session.makePane()) inonAppear, registers the model withcommands, and on disappear closes its panes (session.closePane) so their text views are removed (editor.removeView). Buffers stay in the session. -
EditorViewkeeps oneOrgEditorper path and one text view per(pane.id, path)fromaddView, removed withremoveViewwhen the pane closes; a text view becoming first responder setscommands.editorandsession.focused = pane(anonFocuscallback onOrgEditor, frombecomeFirstResponderonOrgTextViewinSources/OrgEditorAppKit/Keys.swift). - Outline column and sidebar selection follow
session.focused. - 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 firstonAppear. - Commands, as
app.*ids dispatched whereapp.quick-openis 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, andC-w s/v/c/o/win normal state. Mac, after checkingmacBindings: ⌃⌘2, ⌃⌘3, ⌃⌘0, ⌃⌘1, ⌥⌘` and ⌥⌘N (⌃⌘W was Refile, ⌃⌘O Open Link). - Manual: a "Windows and panes" section in
docs/manual/guide/02-the-editor.organd the keys in03-keys.org's reference table. - Check by hand against the review focus list; the
ORGSTAR_SNAPSHOThook inDevelopmentHooks.swiftgets a two-pane snapshot. - Commit "Windows and panes".
As built
- 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 singleWindow, 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. EditorStore(app) keeps oneOrgEditorper 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.WindowModel(app) holds a window'sPaneLayout, its panes and the focused one;AppCommands.store.windowslists them so pane commands find the window of the focused pane.- A split shows the same buffer in the new pane and keeps the focus, as
split-windowdoes. A pane with no buffer shows a placeholder. - 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.
Review
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.
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.