feat(prose): list shortcuts — S5 (#115)
CI / ci (push) Canceled after 0s

Markdown lists in the prose editor become structural: Tab/⇧Tab
indent/outdent the item under the caret (wrapped lines ride along,
caret follows), ⌥↑/⌥↓ move the item with its subtree among siblings.
Every structural edit is one range replacement — a single undo step
over the plain mode-B store (ADR-0010 stands).

List parents fold visually: a gutter chevron collapses children to
near-zero height with a rust ▸ and a "⋯ N" summary after the parent's
line. Folding is view state — the buffer never changes (ADR-0013's
posture carried to prose).

Field findings baked in: SwiftUI-hosted TextKit2 never calls
NSTextView.draw(_:) and every NSTextLayoutManager fragment query
returns empty, so the chrome renders offscreen into a layer-contents
image and geometry comes from firstRect(forCharacterRange:) (screen →
window → view). Includes the finish-audit round: sibling block-for-
block ⌥-move swap (was stealing the sibling's subtree), blank-line
indent dirt, fold-key dedupe, hidden-parent chevron filtering,
plain-click-only hit zone, no-parents raster skip.

Closes #115

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-10-19 12:31:35 +02:00
1 parent c0513aae85
commit c5c8749df4
12 files changed
+1142 -6

No files matched your search

+2 -3
View File
@@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) |
| 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) |
| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) |
| 2026-10-15 | [20261015-issue111-outline-guard_log.md](docs/devlog/20261015-issue111-outline-guard_log.md) |
@@ -185,6 +186,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-13 | [20261013-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) |
| 2026-10-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) |
| 2026-10-09 | [20261009-issue88-calibration-gate_log.md](docs/devlog/20261009-issue88-calibration-gate_log.md) |
| 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) |
| 2026-10-08 | [20261008-issue84-view-menu-doubled_log.md](docs/devlog/20261008-issue84-view-menu-doubled_log.md) |
| 2026-10-08 | [20261008-issue83-save-indicator-honesty_log.md](docs/devlog/20261008-issue83-save-indicator-honesty_log.md) |<!-- write-log: window-end -->
| 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) |<!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added
- **prose:** list shortcuts (v1.2 S5) — when the caret sits on a markdown list line, Tab/⇧Tab indent/outdent the item (wrapped lines ride along, the caret follows), and ⌥↑/⌥↓ move the item with its subtree among siblings; every structural edit is one undo step over the plain text store. List parents fold visually: a gutter chevron collapses the children to a rust `▸` with a `⋯ N` summary after the parent's line — folding is view state and never edits the buffer (issue #115)
- **outline:** Convert to Post (v1.2 S4) — a Convert to Post… command on outline pieces (library row menu, Archive pane included): the piece keeps its name, project, and Pass State while `type` flips to post; at the ask the writer picks the body — Verbatim Bullets (default, keeps every line) or Headings (top-level blocks become section headings, deeper levels step down to the `######` floor, deeper still stays bullets; the ask warns when the ladder would drop paragraph lines between bullets); the open session flushes first and reopens in prose; an outline changed on disk behind the ask aborts the convert rather than dropping unconsented prose; one-way in v1 (issue #114)
- **outline:** drag-reorder + zoom-in (v1.2 S6) — pointer-drag a block run into any sibling seam or onto a block to nest as its child (the block selection rides the drag, a 30/40/30 fat-gap hit test resolves seams vs onto, and a dropped run on an invalid target leaves the document untouched); Esc cancels mid-drag, the moved run becomes the selection; double-click any bullet zooms to its children with breadcrumbs back out, and zoom keeps only fully-visible selections (issue #112)
+1
View File
@@ -31,6 +31,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting.
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
+6 -2
View File
@@ -347,7 +347,7 @@ struct ProseTextView: NSViewRepresentable {
}
func makeNSView(context: Context) -> NSScrollView {
let tv = NSTextView()
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
tv.isRichText = false // plain source of truth; attributes are presentation
tv.allowsUndo = true
tv.isAutomaticQuoteSubstitutionEnabled = false
@@ -391,7 +391,7 @@ struct ProseTextView: NSViewRepresentable {
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let tv = scroll.documentView as? NSTextView else { return }
guard let tv = scroll.documentView as? ProseListTextView else { return }
// #77: posture toggle while editing — cheap idempotent set.
tv.isContinuousSpellCheckingEnabled = spellChecking
// #21: the ground follows focus in/out without a remount.
@@ -414,6 +414,7 @@ struct ProseTextView: NSViewRepresentable {
// have flushed it over the user's real content (#71 fix).
tv.textStorage?.setAttributedString(ProsePresenter.attribute(session.text))
context.coordinator.fenceDelims = ProsePresenter.fenceDelimCount(session.text)
tv.refreshFolds() // #115: re-key folds over the swapped content
// #66: restore cursor (clamped) + scroll.
let length = (tv.string as NSString).length
var cursor = session.restoreCursor ?? PostStore.CursorState()
@@ -433,6 +434,7 @@ struct ProseTextView: NSViewRepresentable {
// Echo guard: our own keystroke round-trips through the model —
// only reload when the textview genuinely diverges (new draft).
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
tv.refreshFolds() // #115: re-key folds over the swapped content
}
// #71: flip-back caret — apply once per token, after any load above.
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
@@ -499,6 +501,8 @@ struct ProseTextView: NSViewRepresentable {
} else {
onEdit?(storage.string)
}
// #115: fold maintenance LAST — hidden styling over the refreshed presentation.
(tv as? ProseListTextView)?.refreshFolds()
}
func textViewDidChangeSelection(_ notification: Notification) {
+406
View File
@@ -0,0 +1,406 @@
//
// ProseList.swift
// Museion
//
// #115 (S5): prose-list model — pure, UTF-16-safe scan and structural
// edits over the ONE plain buffer (ADR-0010 mode B: no secondary model).
// A list "item" is its marker line plus wrapped lines and nested list
// lines (indent > the item's). Tab/⇧Tab re-indent, ⌥↑/⌥↓ swap with an
// adjacent sibling — each ONE range replacement, one undo step. Honest
// v1: indent unit = the previous sibling's content column (never a
// blind 2); moves are sibling-adjacent; fences end a block.
//
import Foundation
nonisolated enum ProseList {
// MARK: Scan
struct Line {
let range: NSRange // content + terminator
let content: NSRange
let text: String
let indent: Int // leading whitespace columns (tab = 2)
let isList: Bool
let isBlank: Bool
var end: Int {
range.location + range.length
}
}
struct Item: Equatable {
/// The marker line incl. terminator — its `location` is the fold key.
let markerLine: NSRange
/// End of the marker line's content (caret park when its subtree folds).
let markerEnd: Int
let contentOffset: Int // UTF-16 offset of the first content column
/// Marker line through the last subtree line's terminator.
let block: NSRange
/// The fold-hidden range; nil = no children.
let foldScope: NSRange?
let hiddenLineCount: Int
let indent: Int
}
/// One scan into lines, fence-aware via the presenter's classifier
/// (list lines inside a fence are never .listMarker).
static func lines(in text: String) -> [Line] {
let buffer = text as NSString
var out: [Line] = []
var loc = 0
let total = buffer.length
var inFence = false
while loc < total {
let full = buffer.lineRange(for: NSRange(location: loc, length: 0))
if full.length == 0 {
break
}
var len = full.length
while len > 0 {
let unit = buffer.character(at: full.location + len - 1)
if unit == 0x0A || unit == 0x0D {
len -= 1
} else {
break
}
}
let content = NSRange(location: full.location, length: len)
let lineText = len > 0 ? buffer.substring(with: content) : ""
let kind = ProsePresenter.classify(lineText, inFence: inFence)
if kind == .fence {
inFence.toggle()
}
out.append(Line(
range: full,
content: content,
text: lineText,
indent: leadingColumns(lineText),
isList: kind == .listMarker,
isBlank: kind == .blank,
))
loc = full.location + full.length
}
return out
}
static func item(at caret: Int, in text: String) -> Item? {
let buffer = text as NSString
guard buffer.length > 0 else { return nil }
let scanned = lines(in: text)
let caretLoc = min(max(0, caret), buffer.length - 1)
guard let idx = scanned.firstIndex(where: { NSLocationInRange(caretLoc, $0.range) }) else { return nil }
guard scanned[idx].isList else { return nil }
let indent = scanned[idx].indent
let bounds = blockBounds(scanned, from: idx, indent: indent)
let blockEnd = scanned[bounds.end].end
let block = NSRange(location: scanned[idx].range.location, length: blockEnd - scanned[idx].range.location)
let scope: NSRange?
var hidden = 0
if let foldStart = bounds.foldStart, let scopeStartIdx = bounds.scopeStartIdx {
scope = NSRange(location: foldStart, length: blockEnd - foldStart)
hidden = bounds.end - scopeStartIdx + 1
} else {
scope = nil
}
return Item(
markerLine: scanned[idx].range,
markerEnd: scanned[idx].content.location + scanned[idx].content.length,
contentOffset: contentOffset(of: scanned[idx]),
block: block,
foldScope: scope,
hiddenLineCount: hidden,
indent: indent,
)
}
/// Every list line that has children (the fold chevron targets).
struct ParentHint: Equatable {
let markerLine: NSRange
let markerEnd: Int
let contentOffset: Int
let foldScope: NSRange
let hiddenLineCount: Int
}
static func parents(in text: String) -> [ParentHint] {
let scanned = lines(in: text)
var out: [ParentHint] = []
for (idx, line) in scanned.enumerated() where line.isList {
let bounds = blockBounds(scanned, from: idx, indent: line.indent)
guard let foldStart = bounds.foldStart, let scopeStartIdx = bounds.scopeStartIdx else { continue }
let blockEnd = scanned[bounds.end].end
out.append(ParentHint(
markerLine: line.range,
markerEnd: line.content.location + line.content.length,
contentOffset: contentOffset(of: line),
foldScope: NSRange(location: foldStart, length: blockEnd - foldStart),
hiddenLineCount: bounds.end - scopeStartIdx + 1,
))
}
return out
}
}
nonisolated extension ProseList {
// MARK: Edits (one range replacement each — one undo step)
struct Edit: Equatable {
let range: NSRange
let replacement: String
let caret: Int
}
/// Tab: nest under the previous sibling — delta = its content column
/// minus our indent. No previous sibling → nil (boundary no-op).
static func indent(_ item: Item, caret: Int, in text: String) -> Edit? {
let scanned = lines(in: text)
guard let idx = lineIndex(of: item.markerLine.location, in: scanned) else { return nil }
guard let sibIdx = adjacentSiblingLine(scanned, from: idx, through: idx, indent: item.indent, direction: -1) else { return nil }
let delta = contentColumn(scanned[sibIdx].text) - item.indent
guard delta > 0 else { return nil }
let body = blockBody(text, item.block)
let terminated = body.terminated
let shifted = body.lines.map { $0.isEmpty ? $0 : String(repeating: " ", count: delta) + $0 }.joined(separator: "\n")
+ (terminated ? "\n" : "")
return Edit(range: item.block, replacement: shifted, caret: caret + delta)
}
/// ⇧Tab: remove up to 2 columns from every line of the block. The caret
/// rides its line's shift (parks at the new line start inside it).
static func outdent(_ item: Item, caret: Int, in text: String) -> Edit? {
guard item.indent > 0 else { return nil }
let stripWidth = min(2, item.indent)
let body = blockBody(text, item.block)
var outLines: [String] = []
var lineStart = item.block.location // utf16 start of this line in the OLD text
var caretShift = 0
var found = false
for line in body.lines {
let (removed, rest) = stripLeading(line, columns: stripWidth)
let into = caret - lineStart
if !found, into >= 0, into <= line.utf16.count {
caretShift = -min(removed.utf16.count, max(0, into))
found = true
}
outLines.append(rest)
lineStart += line.utf16.count + 1 // +1 for the joined \n
}
let replacement = outLines.joined(separator: "\n") + (body.terminated ? "\n" : "")
let newCaret = max(item.block.location, caret + caretShift)
return Edit(range: item.block, replacement: replacement, caret: newCaret)
}
/// ⌥↑/⌥↓: swap the item's block with the adjacent sibling's BLOCK
/// (children and continuations ride WITH their own item — a marker-line
/// swap would steal the sibling's subtree, #115 audit); the text between
/// rides unchanged. Boundary or paragraph-interrupted → nil.
static func move(_ item: Item, caret: Int, direction: Int, in text: String) -> Edit? {
let scanned = lines(in: text)
guard let idx = lineIndex(of: item.markerLine.location, in: scanned) else { return nil }
let bounds = blockBounds(scanned, from: idx, indent: item.indent)
guard
let sibIdx = adjacentSiblingLine(scanned, from: idx, through: bounds.end, indent: item.indent, direction: direction)
else { return nil }
let sibStart = scanned[sibIdx].range.location
let sibEnd = NSMaxRange(scanned[blockBounds(scanned, from: sibIdx, indent: item.indent).end].range)
let sib = NSRange(location: sibStart, length: sibEnd - sibStart)
let itemText = substring(text, item.block)
let sibText = substring(text, sib)
if direction > 0 {
let range = NSRange(location: item.block.location, length: NSMaxRange(sib) - item.block.location)
let between = substring(text, NSRange(location: NSMaxRange(item.block), length: sib.location - NSMaxRange(item.block)))
let replacement = sibText + between + itemText
// the item lands after the sibling + the between-text
let newCaret = range.location + sibText.utf16.count + between.utf16.count + (caret - item.block.location)
return Edit(range: range, replacement: replacement, caret: newCaret)
} else {
let range = NSRange(location: sib.location, length: NSMaxRange(item.block) - sib.location)
let between = substring(text, NSRange(location: NSMaxRange(sib), length: item.block.location - NSMaxRange(sib)))
let replacement = itemText + between + sibText
let newCaret = sib.location + (caret - item.block.location)
return Edit(range: range, replacement: replacement, caret: newCaret)
}
}
// MARK: Block geometry
/// blockBounds result: last belonging line, fold-scope start (nil = no
/// children), and the scope-start line's index.
private struct BlockBounds {
let end: Int
let foldStart: Int?
let scopeStartIdx: Int?
}
/// Block walk from the marker line: lines belong while deeper (any
/// kind) or a lazy continuation (prose, no blank between); blanks ride
/// inside only when a belonging line follows.
private static func blockBounds(_ scanned: [Line], from idx: Int, indent: Int) -> BlockBounds {
var end = idx
var pendingBlanks = 0
var scanIndex = idx + 1
while scanIndex < scanned.count {
let candidate = scanned[scanIndex]
if candidate.isBlank {
pendingBlanks += 1
scanIndex += 1
continue
}
let deep = candidate.indent > indent
// ponytail: lazy continuation treats ANY non-list line as item content —
// CommonMark restricts it to paragraphs, so a heading/fence after an
// item rides its block; exclude those kinds if fidelity bites.
let lazy = !candidate.isList && pendingBlanks == 0
if deep || lazy {
end = scanIndex
pendingBlanks = 0
scanIndex += 1
} else {
break
}
}
var foldStart: Int?
var scopeStartIdx: Int?
var probeIndex = idx + 1
while probeIndex <= end {
if scanned[probeIndex].indent > indent {
var source = probeIndex
while source - 1 > idx, scanned[source - 1].isBlank {
source -= 1
} // blanks before the first child hide too
foldStart = scanned[source].range.location
scopeStartIdx = source
break
}
probeIndex += 1
}
return BlockBounds(end: end, foldStart: foldStart, scopeStartIdx: scopeStartIdx)
}
// MARK: Sibling searches
/// Adjacent sibling LINE INDEX at the same indent (direction -1 = previous,
/// +1 = next), or nil at any boundary. Backward: skip blanks, deeper
/// list lines (the sibling's subtree), and lazy prose; a standalone
/// paragraph or a shallower list line is a boundary. Forward: prose
/// always ends the walk (adjacent prose would be inside the block).
private static func adjacentSiblingLine(_ scanned: [Line], from idx: Int, through end: Int, indent: Int, direction: Int) -> Int? {
if direction < 0 {
var pendingBlanks = 0
var probeIndex = idx - 1
while probeIndex >= 0 {
let candidate = scanned[probeIndex]
if candidate.isBlank {
pendingBlanks += 1; probeIndex -= 1; continue
}
if candidate.isList {
if candidate.indent == indent {
return probeIndex
}
if candidate.indent < indent {
return nil
}
probeIndex -= 1 // deeper: subtree of the sibling, keep walking
continue
}
if pendingBlanks > 0 || (probeIndex - 1 >= 0 && scanned[probeIndex - 1].isBlank) {
return nil
}
probeIndex -= 1
}
return nil
}
var probeIndex = end + 1
while probeIndex < scanned.count {
let candidate = scanned[probeIndex]
if candidate.isBlank {
probeIndex += 1; continue
}
if candidate.isList, candidate.indent == indent {
return probeIndex
}
return nil // prose, or a list at another indent: boundary
}
return nil
}
// MARK: Helpers
private static func lineIndex(of location: Int, in scanned: [Line]) -> Int? {
scanned.firstIndex { $0.range.location == location }
}
/// Leading whitespace columns (space = 1, tab = 2 — OutlineTree's rule).
private static func leadingColumns(_ source: String) -> Int {
var cols = 0
for unit in source {
if unit == " " {
cols += 1
} else if unit == "\t" {
cols += 2
} else {
break
}
}
return cols
}
/// Content column of a list line: indent + marker + following whitespace.
/// CommonMark's nesting anchor ("1. " → 3, "10. " → 4).
private static func contentColumn(_ source: String) -> Int {
var cols = 0
var scanIndex = source.startIndex
while scanIndex < source.endIndex, source[scanIndex] == " " || source[scanIndex] == "\t" {
cols += source[scanIndex] == "\t" ? 2 : 1
scanIndex = source.index(after: scanIndex)
}
while scanIndex < source.endIndex, source[scanIndex] != " ", source[scanIndex] != "\t" {
cols += 1
scanIndex = source.index(after: scanIndex)
}
while scanIndex < source.endIndex, source[scanIndex] == " " || source[scanIndex] == "\t" {
cols += source[scanIndex] == "\t" ? 2 : 1
scanIndex = source.index(after: scanIndex)
}
return cols
}
/// UTF-16 offset of the first content character (after "\source*marker\source+").
private static func contentOffset(of line: Line) -> Int {
guard let match = line.text.firstMatch(of: ProsePresenter.listMarkerPattern) else { return line.range.location }
let utf16 = match.range.utf16Range(in: line.text)
return line.range.location + min(utf16.upperBound, line.content.length)
}
private static func substring(_ text: String, _ range: NSRange) -> String {
(text as NSString).substring(with: range)
}
/// Block text split into lines; `terminated` = block ends with \n.
private static func blockBody(_ text: String, _ block: NSRange) -> (lines: [String], terminated: Bool) {
let raw = substring(text, block)
let terminated = raw.hasSuffix("\n")
let body = terminated ? String(raw.dropLast()) : raw
let lines = body.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
return (lines, terminated)
}
/// Remove up to `columns` of leading whitespace (tab = 2, consumed
/// whole). Returns (removed prefix, rest).
private static func stripLeading(_ line: String, columns: Int) -> (removed: Substring, rest: String) {
var removed = 0
var scanIndex = line.startIndex
while scanIndex < line.endIndex, removed < columns {
let unit = line[scanIndex]
if unit == " " {
removed += 1
} else if unit == "\t" {
removed += 2
} else {
break
}
scanIndex = line.index(after: scanIndex)
}
return (line[..<scanIndex], String(line[scanIndex...]))
}
}
+341
View File
@@ -0,0 +1,341 @@
//
// ProseListTextView.swift
// Museion
//
// #115 (S5): the prose editor's list machinery — an NSTextView subclass
// ProseTextView installs in place of the plain stock view. Tab/⇧Tab
// indent/outdent the list item under the caret, ⌥↑/⌥↓ move it among
// siblings (ProseList does the math; every edit is ONE undoable range
// replacement through the plain mode-B store — ADR-0010 stands, no
// secondary model). Lists get visual collapse: fold state is VIEW state
// keyed by the marker line's buffer position (re-derived on edit —
// simplest honest rule: nearest parent line with the same marker text),
// hidden scopes are styled to near-zero height (ProseTypography.folded
// Attributes), a chevron in the left gutter toggles by click, and a
// folded parent shows "⋯ N" after its line. Folding never dirties the
// document (ADR-0013's posture, carried to prose).
//
// Key-delivery facts: arrows arrive as the function-key scalars
// \u{F700}/\u{F701} carrying .function/.numericPad device bits (strip
// before comparing modifiers); ⇧⇥ arrives as backtab \u{19}, sometimes
// via insertBacktab instead of keyDown — both paths are covered (the
// outliner's RowTextView proved the set behind NSHostingView).
//
import AppKit
import SwiftUI
/// The chrome overlay: a click-through layer-host whose `contents` image the
/// text view renders offscreen (SwiftUI-hosted TextKit2 views never reliably
/// route through draw(_:) — layer contents sidestep the whole question).
final class ProseChromeView: NSView {
weak var owner: ProseListTextView?
override func hitTest(_: NSPoint) -> NSView? {
nil
} // clicks reach the text view
/// Re-render the owner's chrome into a fresh image and install it as the
/// layer's contents. Deferred one main-queue tick: refresh points fire
/// inside textDidChange, after TextKit2 invalidated layout but before
/// re-layout — querying fragments synchronously finds none (#115).
func refresh() {
guard bounds.width > 0, bounds.height > 0 else { return }
DispatchQueue.main.async { [weak self] in
guard let self, let owner else { return }
// No parents anywhere and nothing painted → skip the raster.
// ponytail: the image is document-sized per refresh — rasterize the
// visible height instead if tall docs measurably chug.
if owner.proseParentCount == 0, layer?.contents == nil {
return
}
guard let image = owner.renderChromeImage(size: bounds.size) else { return }
wantsLayer = true
layer?.contents = image
}
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
if newSize != .zero {
refresh()
}
}
}
final class ProseListTextView: NSTextView {
/// A fold: the marker line's buffer position + its text (the re-key
/// identity when an edit above shifts offsets).
struct Fold: Equatable {
let key: Int
let lineText: String
}
var folds: [Fold] = []
// MARK: Structural keys
override func keyDown(with event: NSEvent) {
let key = event.charactersIgnoringModifiers ?? ""
let modifiers = event.modifierFlags
.intersection(.deviceIndependentFlagsMask)
.subtracting([.function, .numericPad])
let upKey = "\u{F700}" // NSUpArrowFunctionKey
let downKey = "\u{F701}" // NSDownArrowFunctionKey
if key == upKey || key == downKey {
if modifiers == .option, let item = currentItem() {
performMove(item, direction: key == downKey ? 1 : -1)
return
}
super.keyDown(with: event)
return
}
if key == "\t" || key == "\u{19}" { // NSBackTabCharacter
if let item = currentItem() {
if key == "\u{19}" || modifiers.contains(.shift) {
performOutdent(item)
} else {
performIndent(item)
}
return
}
super.keyDown(with: event)
return
}
super.keyDown(with: event)
}
/// Some AppKit paths deliver ⇧⇥ here instead of keyDown.
override func insertBacktab(_: Any?) {
if let item = currentItem() {
performOutdent(item)
} else {
super.insertBacktab(nil)
}
}
private func currentItem() -> ProseList.Item? {
guard (string as NSString).length > 0 else { return nil }
return ProseList.item(at: selectedRange().location, in: string)
}
// MARK: Edit application (one undo step each)
private func performIndent(_ item: ProseList.Item) {
guard let edit = ProseList.indent(item, caret: selectedRange().location, in: string) else { return }
apply(edit)
}
private func performOutdent(_ item: ProseList.Item) {
guard let edit = ProseList.outdent(item, caret: selectedRange().location, in: string) else { return }
apply(edit)
}
private func performMove(_ item: ProseList.Item, direction: Int) {
guard let edit = ProseList.move(item, caret: selectedRange().location, direction: direction, in: string) else { return }
apply(edit)
}
/// One range replacement through the text stack: shouldChangeText
/// registers undo, didChangeText drives the delegate (paragraph
/// reattribute + session edit). Multi-line replacements span more than
/// the caret's paragraph, so a full presentation pass follows — unless
/// folds are open, where the post-edit fold refresh already does it.
private func apply(_ edit: ProseList.Edit) {
guard shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return }
textStorage?.replaceCharacters(in: edit.range, with: edit.replacement)
didChangeText()
let length = (string as NSString).length
setSelectedRange(NSRange(location: min(max(0, edit.caret), length), length: 0))
guard folds.isEmpty else { return } // textDidChange refreshed everything
let sel = selectedRange()
textStorage?.setAttributedString(ProsePresenter.attribute(string))
setSelectedRange(sel)
}
// MARK: Fold maintenance
/// One maintenance entry point for every refresh path — the coordinator's
/// textDidChange calls it LAST (after its paragraph reattribute and
/// session.edit, so hidden styling lands on top of the refreshed
/// presentation) and the wholesale content swaps (generation load, draft
/// echo — no textDidChange fires for those) call it directly. No folds →
/// chrome-only refresh; refreshFoldRendering ends in its own refresh.
func refreshFolds() {
guard !folds.isEmpty else {
chrome.refresh()
return
}
refreshFoldRendering()
}
func toggleFold(_ parent: ProseList.ParentHint) {
if let idx = folds.firstIndex(where: { $0.key == parent.markerLine.location }) {
folds.remove(at: idx)
} else {
folds.append(Fold(key: parent.markerLine.location, lineText: lineText(of: parent.markerLine)))
}
refreshFoldRendering()
}
/// Re-key folds against the current text (nearest parent line with the
/// same marker text; no match → the fold dies), restyle the document,
/// re-hide every live scope, and park a caret that landed inside a
/// hidden scope at its parent's marker end.
func refreshFoldRendering() {
let parents = ProseList.parents(in: string)
// ponytail: nearest-same-marker re-key can move a fold across duplicate
// marker texts — track the edit delta in shouldChangeText if that bites.
var seenKeys = Set<Int>()
folds = folds.compactMap { fold in
parents
.filter { lineText(of: $0.markerLine) == fold.lineText }
.min { abs($0.markerLine.location - fold.key) < abs($1.markerLine.location - fold.key) }
.map { Fold(key: $0.markerLine.location, lineText: fold.lineText) }
}.filter { seenKeys.insert($0.key).inserted } // two folds can't land on one parent
let sel = selectedRange()
textStorage?.setAttributedString(ProsePresenter.attribute(string))
for fold in folds {
guard let parent = parents.first(where: { $0.markerLine.location == fold.key }) else { continue }
textStorage?.setAttributes(ProseTypography.foldedAttributes, range: parent.foldScope)
if NSLocationInRange(sel.location, parent.foldScope) {
setSelectedRange(NSRange(location: min(parent.markerEnd, (string as NSString).length), length: 0))
}
}
chrome.refresh()
}
/// The marker line's text without its terminator.
private func lineText(of line: NSRange) -> String {
let buffer = string as NSString
guard line.length > 0 else { return "" }
var len = line.length
while len > 0 {
let terminator = buffer.character(at: line.location + len - 1)
if terminator == 0x0A || terminator == 0x0D {
len -= 1
} else {
break
}
}
return len > 0 ? buffer.substring(with: NSRange(location: line.location, length: len)) : ""
}
// MARK: Chrome (chevron + ⋯ N)
/// Plain overlay sibling that owns the chrome drawing — TextKit2 views hosted
/// under SwiftUI never route through NSTextView.draw(_:), but a plain NSView
/// subview always draws. Click-through (hitTest nil); document-coordinate
/// space, so it rides the scroll view with the text.
private let chrome = ProseChromeView()
/// Install the overlay once the view reaches a window — the inherited
/// NSTextView inits (which build the full TextKit stack) stay untouched.
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
guard window != nil, chrome.superview == nil else { return }
chrome.owner = self
chrome.frame = bounds
chrome.autoresizingMask = [.width, .height]
addSubview(chrome, positioned: .above, relativeTo: nil)
chrome.refresh()
}
/// Parents count for the chrome's no-parents raster skip.
var proseParentCount: Int {
ProseList.parents(in: string).count
}
/// Render the whole chrome (chevrons + ⋯ N) into an image in the layer.
/// Top-left flipped coordinates — same space as lineRect's output.
func renderChromeImage(size: NSSize) -> NSImage? {
guard let window else { return nil }
let image = NSImage(size: size)
image.lockFocusFlipped(true)
drawListChrome()
image.unlockFocus()
return image
}
/// Parents whose marker line is not hidden inside another fold's scope —
/// hidden ones collapse to ~zero height and would paint phantom chevrons.
private var visibleParents: [ProseList.ParentHint] {
let parents = ProseList.parents(in: string)
let hiddenScopes = folds.compactMap { fold in
parents.first(where: { $0.markerLine.location == fold.key })?.foldScope
}
return parents.filter { parent in
!hiddenScopes.contains { NSLocationInRange(parent.markerLine.location, $0) }
}
}
func drawListChrome() {
for parent in visibleParents {
guard let startRect = lineRect(ofOffset: parent.markerLine.location) else { continue }
let folded = folds.contains { $0.key == parent.markerLine.location }
drawChrome(folded ? "▸" : "▾", folded: folded,
at: NSPoint(x: startRect.minX - 14, y: startRect.midY - chromeSize * 0.62))
if folded {
// ⋯ N after the parent's visible line text, not after the marker.
let text = lineText(of: parent.markerLine) as NSString
let lastChar = parent.markerLine.location + max(0, text.length - 1)
if let endRect = lineRect(ofOffset: lastChar) {
drawChrome("⋯ \(parent.hiddenLineCount)", folded: true,
at: NSPoint(x: endRect.maxX + 6, y: endRect.midY - chromeSize * 0.62))
}
}
}
}
override func mouseDown(with event: NSEvent) {
// Plain single-clicks only — shift-click extends selection, double/
// triple-click select word/paragraph; neither toggles a fold.
if !event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.capsLock).isEmpty || event.clickCount > 1 {
super.mouseDown(with: event)
return
}
let point = convert(event.locationInWindow, from: nil)
for parent in visibleParents {
guard let rect = lineRect(ofOffset: parent.markerLine.location) else { continue }
// Toggle zone: the gutter through the marker span ("- ", "1. ")
// of the marker line's first visual line.
if point.y >= rect.minY - 1, point.y <= rect.maxY + 1, point.x < rect.minX + 12 {
toggleFold(parent)
return
}
}
super.mouseDown(with: event)
}
/// mono-11 chrome, rust when folded, muted open (the outliner's
/// "⋯ N" vocabulary carried to prose).
private let chromeSize: CGFloat = 11
private func drawChrome(_ glyph: String, folded: Bool, at point: NSPoint) {
NSAttributedString(string: glyph, attributes: [
.font: NSFont.monospacedSystemFont(ofSize: chromeSize, weight: .regular),
.foregroundColor: folded ? NSColor(DesignTokens.accent) : NSColor(DesignTokens.muted),
]).draw(at: point)
}
// MARK: Geometry (TextKit2)
/// View-space rect of the character at `offset` via the selection system
/// — `selectionRects(for:)` is TextKit-version-agnostic NSTextView API and
/// geometry the caret already renders from (#115 field finding: every
/// NSTextLayoutManager fragment query — bridge, lookup, enumeration —
/// yields nothing under SwiftUI-hosted viewport layout).
private func lineRect(ofOffset offset: Int) -> NSRect? {
let length = (string as NSString).length
guard length > 0 else { return nil }
let clamped = min(max(0, offset), length - 1)
var actual = NSRange()
// NSTextInputClient returns SCREEN coordinates (IME positioning);
// screen → window → view before using it as geometry.
let screenRect = firstRect(forCharacterRange: NSRange(location: clamped, length: 1), actualRange: &actual)
guard screenRect != .zero else { return nil }
let windowRect = window?.convertFromScreen(screenRect) ?? screenRect
return convert(windowRect, from: nil)
}
}
+3 -1
View File
@@ -405,7 +405,9 @@ nonisolated enum ProsePresenter {
// MARK: Pattern helpers
// Marker patterns (regex literals, like the inline ones below).
private nonisolated(unsafe) static let listMarkerPattern = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)/
// listMarkerPattern is internal — ProseList's marker math must agree
// with classify()'s list detection (#115).
nonisolated(unsafe) static let listMarkerPattern = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)/
private nonisolated(unsafe) static let quoteMarkerPattern = /^(?:\s*>(?:\s|$))*/
/// UTF-16 NSRange of the marker in `lineText`, or nil.
+16
View File
@@ -129,4 +129,20 @@ nonisolated enum ProseTypography {
.foregroundColor: syntaxColor,
]
}
/// #115: fold-hidden lines. The buffer keeps every byte (mode B — folding
/// is rendering, never a text edit); hidden scopes style to near-zero
/// height so the lines vanish (spike-verified: 14pt line → ~0). The text
/// stays selectable/undoable underneath, and reading mode renders it.
nonisolated(unsafe) static let foldedAttributes: [NSAttributedString.Key: Any] = {
let style = NSMutableParagraphStyle()
style.lineHeightMultiple = 0.01
style.paragraphSpacing = 0
style.paragraphSpacingBefore = 0
return [
.font: NSFont.systemFont(ofSize: 0.1),
.foregroundColor: NSColor.clear,
.paragraphStyle: style,
]
}()
}
+1
View File
@@ -33,6 +33,7 @@ Owned by the root AGENTS.md contract.
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`).
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
## Verification
+300
View File
@@ -0,0 +1,300 @@
//
// ProseListTests.swift
// Museion
//
// #115 (S5): the prose-list model pins — item scan (nesting, lazy
// continuation, blanks, fences), Tab/⇧Tab deltas (the content-column
// rule), sibling moves (separators preserved, boundaries no-op), fold
// scopes — plus the view's fold rendering: the buffer never changes,
// hidden scopes carry the folded attributes, folds re-key after edits.
//
import AppKit
@testable import Museion
import Testing
struct ProseListTests {
// MARK: Scan
@Test func `item basics`() throws {
let item = try #require(ProseList.item(at: 0, in: "- a\n- b\n- c\n"))
#expect(item.indent == 0)
#expect(item.block == NSRange(location: 0, length: 4))
#expect(item.foldScope == nil)
#expect(item.markerEnd == 3)
}
@Test func `nested children and scope`() throws {
let text = "- a\n - a1\n - a2\n- b\n"
let parentItem = try #require(ProseList.item(at: 0, in: text))
#expect(parentItem.block == NSRange(location: 0, length: 18)) // "- a\n - a1\n - a2\n"
#expect(parentItem.foldScope == NSRange(location: 4, length: 14))
#expect(parentItem.hiddenLineCount == 2)
let secondItem = try #require(ProseList.item(at: 19, in: text))
#expect(secondItem.block == NSRange(location: 18, length: 4))
#expect(secondItem.foldScope == nil)
}
@Test func `lazy continuation belongs to item`() throws {
let parentItem = try #require(ProseList.item(at: 0, in: "- a\ncont\n- b\n"))
#expect(parentItem.block.length == 9) // "- a\n" + "cont\n"
#expect(parentItem.foldScope == nil) // indent-0 prose is not a fold child
}
@Test func `blank separated child folds blank too`() throws {
let text = "- a\n\n - a1\n- b\n"
let parentItem = try #require(ProseList.item(at: 0, in: text))
#expect(parentItem.block.length == 12) // "- a\n" + "\n" + " - a1\n"
#expect(parentItem.foldScope == NSRange(location: 4, length: 8)) // starts at the blank
#expect(parentItem.hiddenLineCount == 2)
}
@Test func `fence blocks item detection`() {
#expect(ProseList.item(at: 5, in: "```\n- x\n```\n- y\n") == nil)
#expect(ProseList.item(at: 13, in: "```\n- x\n```\n- y\n") != nil)
}
@Test func `caret in leading whitespace still finds item`() {
#expect(ProseList.item(at: 1, in: " - a\n") != nil)
}
@Test func `parents scan`() {
let parentsList = ProseList.parents(in: "- a\n - a1\n- b\n - b1\n")
#expect(parentsList.map(\.markerLine.location) == [0, 11])
#expect(parentsList.allSatisfy { $0.hiddenLineCount == 1 })
}
// MARK: Indent / outdent
@Test func `indent uses dash content column`() throws {
let text = "- a\n- b\n"
let item = try #require(ProseList.item(at: 5, in: text))
let edit = try #require(ProseList.indent(item, caret: 5, in: text))
#expect(edit.range == NSRange(location: 4, length: 4))
#expect(edit.replacement == " - b\n")
#expect(edit.caret == 7)
}
@Test func `indent uses ordered content column`() throws {
let text = "1. one\n1. two\n"
let item = try #require(ProseList.item(at: 8, in: text))
let edit = try #require(ProseList.indent(item, caret: 8, in: text))
#expect(edit.replacement == " 1. two\n") // "1. " content column = 3
}
@Test func `indent shifts subtree`() throws {
let text = "- a\n- b\n - b1\n"
let item = try #require(ProseList.item(at: 5, in: text))
let edit = try #require(ProseList.indent(item, caret: 5, in: text))
#expect(edit.replacement == " - b\n - b1\n")
}
@Test func `indent nests under previous sibling past its children`() throws {
let text = "- a\n - a1\n- b\n"
// walking back from b: a1 (deeper — skip), a (same indent) = sibling
let item = try #require(ProseList.item(at: 11, in: text))
let edit = try #require(ProseList.indent(item, caret: 11, in: text))
#expect(edit.replacement == " - b\n")
}
@Test func `indent boundary after paragraph noop`() throws {
let text = "intro\n\n- a\n- b\n"
let item = try #require(ProseList.item(at: 8, in: text))
#expect(ProseList.indent(item, caret: 8, in: text) == nil)
}
@Test func `indent first child noop`() throws {
let text = "- a\n - a1\n"
let item = try #require(ProseList.item(at: 5, in: text))
#expect(ProseList.indent(item, caret: 5, in: text) == nil)
}
@Test func `indent crosses lazy prose to sibling`() throws {
let text = "- a\ncont\n- b\n"
let item = try #require(ProseList.item(at: 9, in: text))
let edit = try #require(ProseList.indent(item, caret: 9, in: text))
#expect(edit.replacement == " - b\n")
}
@Test func `indent stops at standalone paragraph`() throws {
let text = "- a\n\npara\n\n- b\n"
let item = try #require(ProseList.item(at: 12, in: text))
#expect(ProseList.indent(item, caret: 12, in: text) == nil)
}
@Test func `outdent removes two and shifts caret`() throws {
let text = "- a\n - b1\n"
let item = try #require(ProseList.item(at: 5, in: text))
let edit = try #require(ProseList.outdent(item, caret: 7, in: text))
#expect(edit.range == NSRange(location: 4, length: 7))
#expect(edit.replacement == "- b1\n")
#expect(edit.caret == 5)
}
@Test func `outdent parks caret in stripped prefix`() throws {
let text = "- a\n - b1\n"
let item = try #require(ProseList.item(at: 5, in: text))
let edit = try #require(ProseList.outdent(item, caret: 5, in: text))
#expect(edit.replacement == "- b1\n")
#expect(edit.caret == 4) // caret was inside the stripped spaces
}
@Test func `outdent rides subtree`() throws {
let text = " - b\n - b1\n"
let item = try #require(ProseList.item(at: 2, in: text))
let edit = try #require(ProseList.outdent(item, caret: 4, in: text))
#expect(edit.replacement == "- b\n - b1\n")
}
@Test func `outdent at root noop`() throws {
let item = try #require(ProseList.item(at: 0, in: "- a\n"))
#expect(ProseList.outdent(item, caret: 0, in: "- a\n") == nil)
}
// MARK: Moves
@Test func `move down swaps sibling`() throws {
let text = "- a\n- b\n- c\n"
let item = try #require(ProseList.item(at: 0, in: text))
let edit = try #require(ProseList.move(item, caret: 1, direction: 1, in: text))
#expect(edit.range == NSRange(location: 0, length: 8))
#expect(edit.replacement == "- b\n- a\n")
#expect(edit.caret == 5)
}
@Test func `move down rides subtree`() throws {
let text = "- a\n - a1\n- b\n"
let item = try #require(ProseList.item(at: 0, in: text))
let edit = try #require(ProseList.move(item, caret: 1, direction: 1, in: text))
#expect(edit.replacement == "- b\n- a\n - a1\n")
#expect(edit.caret == 5)
}
@Test func `move down keeps sibling subtree with sibling`() throws {
// #115 audit pin: the SIBLING's children must ride the sibling, not
// get stolen by the moved item (marker-line swap bug).
let text = "- a\n- b\n - b1\n- c\n"
let item = try #require(ProseList.item(at: 0, in: text))
let edit = try #require(ProseList.move(item, caret: 1, direction: 1, in: text))
#expect(edit.replacement == "- b\n - b1\n- a\n")
}
@Test func `move up keeps sibling subtree with sibling`() throws {
let text = "- a\n - a1\n- b\n"
let item = try #require(ProseList.item(at: 11, in: text))
let edit = try #require(ProseList.move(item, caret: 12, direction: -1, in: text))
#expect(edit.replacement == "- b\n- a\n - a1\n")
#expect(edit.caret == 1)
}
@Test func `move up keeps sibling lazy line with sibling`() throws {
let text = "- a\ncont\n- b\n"
let item = try #require(ProseList.item(at: 9, in: text))
let edit = try #require(ProseList.move(item, caret: 9, direction: -1, in: text))
#expect(edit.replacement == "- b\n- a\ncont\n")
}
@Test func `indent leaves blank lines empty`() throws {
// #115 audit pin: blank lines inside the block must not gain
// injected leading spaces.
let text = "- p\n- a\n\n - a1\n"
let item = try #require(ProseList.item(at: 5, in: text))
let edit = try #require(ProseList.indent(item, caret: 6, in: text))
#expect(edit.replacement == " - a\n\n - a1\n")
}
@Test func `move up swaps with previous`() throws {
let text = "- a\n- b\n- c\n"
let item = try #require(ProseList.item(at: 5, in: text))
let edit = try #require(ProseList.move(item, caret: 5, direction: -1, in: text))
#expect(edit.range == NSRange(location: 0, length: 8))
#expect(edit.replacement == "- b\n- a\n")
#expect(edit.caret == 1)
}
@Test func `move boundaries noop`() throws {
let text = "- a\n- b\n"
let firstItem = try #require(ProseList.item(at: 0, in: text))
let lastItem = try #require(ProseList.item(at: 5, in: text))
#expect(ProseList.move(firstItem, caret: 0, direction: -1, in: text) == nil)
#expect(ProseList.move(lastItem, caret: 5, direction: 1, in: text) == nil)
}
@Test func `move at deeper boundary noop`() throws {
// a1's next list line is "- b" at a shallower indent — not a sibling
let boundaryText = "- a\n - a1\n- b\n"
let deepItem = try #require(ProseList.item(at: 5, in: boundaryText))
#expect(ProseList.move(deepItem, caret: 5, direction: 1, in: boundaryText) == nil)
}
@Test func `move preserves blank separators`() throws {
let text = "- a\n\n- b\n\n- c\n"
let item = try #require(ProseList.item(at: 0, in: text))
let edit = try #require(ProseList.move(item, caret: 1, direction: 1, in: text))
#expect(edit.replacement == "- b\n\n- a\n")
}
@Test func `move stops at paragraph boundary`() throws {
let paraText = "- a\n\npara\n\n- b\n"
let paraItem = try #require(ProseList.item(at: 0, in: paraText))
#expect(ProseList.move(paraItem, caret: 1, direction: 1, in: paraText) == nil)
}
}
@MainActor
struct ProseFoldRenderingTests {
private func makeView(_ text: String) -> ProseListTextView {
let textView = ProseListTextView()
textView.isRichText = false
textView.textStorage?.setAttributedString(ProsePresenter.attribute(text))
return textView
}
@Test func `fold hides scope without touching buffer`() throws {
let text = "- parent\n - child one\n - child two\n- next\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
#expect(textView.string == text) // folding never edits the buffer
#expect(textView.folds.count == 1)
// hidden scope carries the folded attributes
let hiddenFont = try #require(
textView.textStorage?.attribute(.font, at: parent.foldScope.location, effectiveRange: nil) as? NSFont,
)
#expect(hiddenFont.pointSize < 1)
// the parent line itself stays body-size
let bodyFont = try #require(textView.textStorage?.attribute(.font, at: 0, effectiveRange: nil) as? NSFont)
#expect(bodyFont.pointSize > 10)
// unfold restores body presentation
let parentAgain = try #require(ProseList.parents(in: textView.string).first)
textView.toggleFold(parentAgain)
let restored = try #require(
textView.textStorage?.attribute(.font, at: parent.foldScope.location, effectiveRange: nil) as? NSFont,
)
#expect(restored.pointSize > 10)
#expect(textView.folds.isEmpty)
}
@Test func `folds rekey after edit above`() throws {
let text = "- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
// an edit above shifts every line down by 3 ("x\n\n" prefix)
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n")
textView.refreshFoldRendering()
#expect(textView.folds == [ProseListTextView.Fold(key: 3, lineText: "- parent")])
let font = try #require(textView.textStorage?.attribute(.font, at: 13, effectiveRange: nil) as? NSFont)
#expect(font.pointSize < 1) // the shifted child stays hidden
}
@Test func `fold dies when marker text vanishes`() throws {
let text = "- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 8), with: "# head\n")
textView.refreshFoldRendering()
#expect(textView.folds.isEmpty)
}
}
@@ -0,0 +1,63 @@
# Build S5 (#115): prose-list shortcuts — Tab/⇧Tab, ⌥ moves, visual collapse
> **Date:** 2026-10-19
> **Type:** issue
> **Reference:** Museion #115 (map #110), git.babylondreams.de/AlexKucera/Museion
## Goal
Ticket #115 (Build S5, last open slice of wayfinder map #110 "Outliner II"): in the prose editor, when the caret sits on a markdown list line, Tab/⇧Tab indent/outdent the item (wrapped lines ride along), ⌥↑/⌥↓ move the item with its subtree among siblings, and list parents get visual collapse (fold chevron + "⋯ N" summary). All edits are plain text edits through the mode-B store (ADR-0010); fold is view state, never a text edit (ADR-0013 posture in prose).
## What Was Done
- `Museion/ProseList.swift` (new, pure nonisolated model): line scan (`Line`), `Item` (marker line/end, block, fold scope, hidden-line count, indent), `ParentHint` + `parents(in:)` for fold targets, `Edit` = one range replacement per structural action (single undo step). Indent derives the unit from the previous sibling's content column (CommonMark: "- "→2, "1. "→3); outdent strips ≤2 columns with the caret riding the shift; move = sibling-adjacent swap preserving between-text; fences end blocks; lazy continuations belong to the item; blank lines before the first child fold too.
- `Museion/ProseListTextView.swift` (new): NSTextView subclass installed by `ProseTextView.makeNSView`. `keyDown`/`insertBacktab` intercept Tab/⇧Tab/⌥↑/⌥↓ (function-key scalars \u{F700}/\u{F701} with .function/.numericPad device bits stripped); edits apply through `shouldChangeText`/`didChangeText` so undo + coordinator reattribute stay native. Folds: `Fold` keyed by marker-line location, re-keyed on edit to the nearest parent with the same marker text (no match → dies), hidden scopes styled near-zero height via `ProseTypography.foldedAttributes`, caret landing inside a hidden scope parks at the marker end.
- Chrome (chevrons ▾/▸ in the gutter, rust "⋯ N" after the folded parent's text): rendered offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, installed in `viewDidMoveToWindow`, refreshed on every edit/geometry change, deferred one main-queue tick). Fold toggle via gutter/marker click in `mouseDown` (plain single-clicks only).
- `Museion/ProseTypography.swift`: added `foldedAttributes` (0.1pt clear font, lineHeightMultiple 0.01, zero spacing). `Museion/ProsePresenter.swift`: `listMarkerPattern` made internal so ProseList's marker math agrees with classify. `Museion/PostEditorView.swift`: `ProseListTextView()` in place of the stock view; coordinator calls `refreshFolds()` after every textDidChange.
- `MuseionTests/ProseListTests.swift` (new): scan/indent/outdent/move pins + `ProseFoldRenderingTests` (@MainActor): buffer never changes on fold, hidden scopes carry folded attrs, unfold restores, folds re-key after an edit above, fold dies when marker text vanishes.
- Finish-audit pass (3-reviewer fanout) fixed: ⌥-move sibling-subtree theft (block-for-block swap), indent blank-line space injection, fold-key dedupe, hidden-parent chevron/hit filtering, shift/double-click hit-zone over-capture, no-parents raster skip + double-render elimination.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Chrome via `layer.contents` image, not `draw(_:)` | SwiftUI-hosted TextKit2 never calls NSTextView.draw(_:) — field-verified with probes (zero calls while the window renders). A plain overlay subview's draw was never invoked either; a layer background proved the layer pipeline composites. Offscreen NSImage → layer.contents is the only path that displays. |
| Line geometry via `firstRect(forCharacterRange:)` (screen → `window.convertFromScreen` → view) | Every NSTextLayoutManager fragment query (location bridge, `textLayoutFragment(for:)`, `enumerateTextLayoutFragments`) returns nothing under this hosting — live counters showed P=3 E=0 F=0 while the text visibly rendered. The selection/caret pipeline is the only geometry source that answers. Screen coords cost one convert. |
| Refresh deferred one main-queue tick | Refresh points fire inside textDidChange, after TextKit2 invalidated layout but before re-layout — synchronous queries find nothing. |
| Fold re-key = nearest parent with same marker text | Simplest honest rule under plain-text edits; documented ceiling (duplicate marker texts can mis-attach) with edit-delta capture as the upgrade path, key dedupe added by audit. |
| Marker regex shared with ProsePresenter | ProseList's indent math must agree with classify's list detection — one pattern, internal visibility. |
| Structural edits as ONE range replacement | Single undo step; caret rides natively; ADR-0010's plain store stays the source of truth. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| NSLog probes never appeared in unified log (even lldb-injected NSLog) — "code never runs" conclusions were wrong | Log capture for this process is dead on this machine; AppKit os_log lines DO appear | Switched to visual in-app probes (rendered counters "P= E= R=") + lldb live inspection of the running process |
| `ProseListTextView()` convenience init re-route through `init(frame:textContainer: nil)` gutted the view (textStorage nil, `string =` silent no-op) — crashed 3 fold tests | NSTextView's TextKit stack is only built by its own designated init path | Install chrome in `viewDidMoveToWindow`; never override inits |
| Stale app bundle: "BUILD SUCCEEDED" while the Products dylib kept a 10:14 object (old probe strings inside) — user tested the wrong binary twice | Incremental xcodebuild skipped externally-edited sources (fs-synced groups + external tool edits) | Delete the .app + touch sources + rebuild; verify via `grep` for new strings in the dylib and its mtime before every handoff |
| User typed into an existing outline post → zero probes | Outline posts route to OutlineEditorView (different surface) | Test on File ▸ New Post drafts (prose path) |
| Classis (terminal app) kept stealing focus mid-automation | Other agent sessions actively drive this machine | Atomic osascript blocks (raise + frontmost + click + capture); finally the user drove the app manually |
| Swift Testing suites emit no "Test Case" lines — grep-based pass counts measured nothing | XCTest-style greps don't match Swift Testing output | `xcodebuild -resultBundlePath` + `xcresulttool get test-results summary` |
| Parallel test shards crash the host at 0.000s on this machine | Pre-known flakiness | Always `-parallel-testing-enabled NO` |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ProseList.swift` | new — pure list scan/mutation model |
| `Museion/ProseListTextView.swift` | new — key interception, folds, layer-contents chrome, firstRect geometry |
| `Museion/ProseTypography.swift` | + `foldedAttributes` |
| `Museion/ProsePresenter.swift` | `listMarkerPattern` internal |
| `Museion/PostEditorView.swift` | installs ProseListTextView; coordinator `refreshFolds()` |
| `MuseionTests/ProseListTests.swift` | new — 39 pins incl. audit repros |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX rows for the new files |
## Open Items & Next Steps
- [ ] Map #110 close: record Decisions and close (all slices landed — S4 #114, P1 #113, S6 #112, S7 #111, S5 #115)
- [ ] Deferred (ponytail-review, next time these files are open): `ParentHint`→`Item` consolidation, `contentLines` reuse, `performIndent`/`performMove` inlining (~50 lines)
- [ ] Ceiling comments mark: fold re-key delta capture, visible-height chrome raster, CommonMark lazy-continuation fidelity (headings/fences)
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-10-19 | issue | [20261019-issue115-prose-list-shortcuts_log.md](20261019-issue115-prose-list-shortcuts_log.md) | #115 prose list Tab/⇧Tab/⌥-moves + layer-contents fold chrome (draw(_:) never fires under SwiftUI hosting); 3-reviewer audit round, 239 tests green |
| 2026-10-16 | issue | [20261016-issue114-convert-to-post_log.md](20261016-issue114-convert-to-post_log.md) | #114 Convert to Post: in-place type flip + verbatim/headings-ladder ask, prose re-route via proseOverridePostID — 206 tests green (audit round included) |
| 2026-10-16 | issue | [20261016-issue112-outline-interaction-ii_log.md](20261016-issue112-outline-interaction-ii_log.md) | S6 landed: drag-reorder + zoom in the outliner per wf113 verdict A; AppKit-tree hit-testing; tests un-broken for target 27.0 |
| 2026-10-15 | issue | [20261015-issue111-outline-guard_log.md](20261015-issue111-outline-guard_log.md) | #111 mixed-content outline guard: parsesWithLoss + open ask, audit round (reselect/displacement holes pinned) — 179 tests green |