From 803682f3f07995b5b9e43cf559390d2374efc507 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 19 Oct 2026 12:31:35 +0200 Subject: [PATCH] =?UTF-8?q?feat(prose):=20list=20shortcuts=20=E2=80=94=20S?= =?UTF-8?q?5=20(#115)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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] --- AGENTS.md | 9 +- CHANGELOG.md | 2 + Museion/AGENTS.md | 1 + Museion/PostEditorView.swift | 8 +- Museion/ProseList.swift | 406 ++++++++++++++++++ Museion/ProseListTextView.swift | 341 +++++++++++++++ Museion/ProsePresenter.swift | 4 +- Museion/ProseTypography.swift | 16 + MuseionTests/AGENTS.md | 1 + MuseionTests/ProseListTests.swift | 300 +++++++++++++ ...61019-issue115-prose-list-shortcuts_log.md | 63 +++ docs/devlog/INDEX.md | 1 + 12 files changed, 1145 insertions(+), 7 deletions(-) create mode 100644 Museion/ProseList.swift create mode 100644 Museion/ProseListTextView.swift create mode 100644 MuseionTests/ProseListTests.swift create mode 100644 docs/devlog/20261019-issue115-prose-list-shortcuts_log.md diff --git a/AGENTS.md b/AGENTS.md index 5966227..35b9ebc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,8 @@ Museion — the Agentic Writing Environment (AWE): a native SwiftUI macOS app wh - **Forge**: Gitea @ git.babylondreams.de (`tea` CLI), CI via Gitea Actions (ADR-0003) — needs a self-hosted macOS runner. - **License**: GPL-3.0-or-later (ADR-0002). +When working on Swift or SwiftUI code, consult SwiftFairy for relevant API, framework, or domain guidance and examples before making changes. Audit the affected code with SwiftFairy after meaningful edits. Read the cited guidance and assess findings against the project context before applying them. + Commands: ```bash @@ -129,7 +131,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (3258 symbols, 9633 relationships, 279 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (3467 symbols, 10578 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -177,6 +179,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 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 +188,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) | +| 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d6537d..dfbdc4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index d7509b6..e0a7686 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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/` 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 `` 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 ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , 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 `
    ` (#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.
    diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift
    index 40108e0..66bcd35 100644
    --- a/Museion/PostEditorView.swift
    +++ b/Museion/PostEditorView.swift
    @@ -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) {
    diff --git a/Museion/ProseList.swift b/Museion/ProseList.swift
    new file mode 100644
    index 0000000..ba33228
    --- /dev/null
    +++ b/Museion/ProseList.swift
    @@ -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[..