Skip to content

Replace the Markdown preview with a Live editor and list editing keys - #110

Merged
yansfil merged 14 commits into
mainfrom
prd/markdown-live-preview
Sep 19, 2026
Merged

yansfil merged 14 commits into
mainfrom
prd/markdown-live-preview

Conversation

@yansfil

@yansfil yansfil commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

Summary

  • A Markdown file now opens in a Live editor: one editable NSTextView whose text storage is the source, with headings, bold, italic, strikethrough, inline code, fenced code blocks, lists, quotes, links and thematic breaks drawn in place and their markup glyphs hidden by an NSLayoutManager subclass. The caret line and every line a selection touches show the raw markup; the rest stays formatted. The read-only Preview mode (MarkdownPreview.swift, MarkdownDocumentTests) is gone; the toolbar group is "Live / Source" and the core's per-tab field is markdown_live (runtime only, a reopened tab starts Live).
  • Parsing uses Foundation's AttributedString(markdown:) with source positions (MarkdownLiveSource.plan(for:)), runs off the main thread once per change with pending changes coalesced, and applies attributes on the main thread without touching the string. A file over 256 KB opens in Source with both mode buttons disabled and the notice "Live preview is off for files over 256 KB". A parse failure keeps the source monospaced, puts the reason in the notice and does not block input.
  • List editing rules (PRD amendment 1, D-14, ported from orca's rules, not its code): Enter continues a - / n. item, Enter on an empty item clears the marker and renumbers below, Tab and Shift-Tab move one level (two spaces) with renumbering, Backspace on an empty item removes the marker only, a lone 1. line stays as typed, and none of it runs during a Korean composition. MarkdownListEditing is pure functions over the text; MarkdownListKeys wires them into the Live text view and, only for Markdown, into the Source editor (CodeEditorTextView).
  • Draft, autosave, "Unsaved", conflict banner, Find and text-scale chord are the Source editor's existing paths; nothing in the Live view has its own authority. Cmd-click on a link goes through openDocumentLink (http(s) external, checkout-relative files revealed, otherwise the existing notice); a plain click places the caret.
  • Assistant-turn rendering that shared MarkdownPreview.swift moved to ConversationMarkdown.swift unchanged in behavior. DESIGN.md describes the two modes and the list rules; design/hide.pen gains Screen / Editor / Markdown live (formatted, caret line, code block, empty document, over 256 KB) on eight new tokens (Editor.headingFontSizes, Editor.quoteRuleWidth, Editor.italicSkew) added to HideTheme.
  • Two suite fixes that surfaced while shipping, not Markdown-specific: the vendored Highlightr batches its per-run setAttributes inside stringStorage.beginEditing/endEditing (each run was running processEditing over the whole document, seconds on a few hundred KB), and FileDocumentStateTests polls for the autosave instead of sleeping a fixed 700 ms past a 450 ms debounce.

Related

Breaking change

  • The editor tab snapshot field markdown_preview is renamed markdown_live and the file_view event payload with it. The value was never persisted (per tab, runtime only), so no state directory or saved setting changes; a shell and core are always built together from this tree.

Review focus

  • 사람이 판단할 것:
    • D-04 reveal rule: markup shows on the caret line and on every line a selection touches, and a fenced code block reveals as a whole block when the caret is inside it. Obsidian's behavior was the assumption.
    • The Live view is always wrapped at the 720 pt reading measure with no line-number ruler; Wrap and the ruler exist only in Source (D-05).
    • D-06 outcome: Foundation's parser gave exact source ranges for every D-03 item, so apple/swift-markdown was not vendored. One quirk handled in MarkdownLiveSource: after a multi-line code span Foundation keeps reporting the same line number while the byte offsets stay right, so the plan builder trusts offsets, not lines.
    • List rules chosen where the PRD left room: a sole top-level empty ordered item on Enter is kept as text (B20) while any other empty item clears its marker (B17); Shift-Tab at indent 0 consumes the key and changes nothing; task boxes (- [ ]) are not treated as list items so they stay raw source (B6).
    • HighlightedCodeEditor gained markdownListEditing so Source mode of a Markdown file follows the same keys (B22); other languages are untouched.
  • 위험한 파일:
    • macos/Sources/HerdrMacOS/MarkdownLiveEditor.swift: the text view is rich text (isRichText = true) with readablePasteboardTypes = [.string]; a plain-text NSTextView applies typing attributes to the whole storage after an edit, which rewrote the document in the H1 font once during native QA and is now pinned by editingInsideAHeadingLeavesTheBodyAtItsOwnSize and pastingRichTextBringsOnlyItsCharacters. The parse is versioned so a stale result never applies, and a result arriving during an IME composition is dropped and re-parsed on commit.
    • macos/Sources/HerdrMacOS/MarkdownLiveSource.swift: the span/marker plan built from Foundation's source positions (1-based lines, UTF-8 byte columns) mapped to UTF-16 ranges; thematic breaks carry their newline so the hairline draws from the paragraph's first glyph.
    • macos/Sources/HerdrMacOS/MarkdownListEditing.swift: the renumbering column logic (renumber(_:column:around:)) bounded by shallower items and blank lines, and Context.init, which reads the caret line through NSString and carries a CRLF line's \r into every rewritten line (the Code review found the first version dropping a character on CRLF files; fixed in 17058c5 with tests).
    • macos/Vendor/Highlightr/src/classes/CodeAttributedString.swift: five lines in vendored code; the outer beginEditing was already there, the inner storage's was not.
  • 리뷰어에게 묻는 것: on this merged head, Explorer rows clicked through synthesized events (single, double, row body) highlighted the row but opened nothing, while ⌘P opened the same files; the Explorer code is main's from PR Open Explorer single clicks in a replaceable preview tab #108. Does a physical single click open a preview tab on main for you? If not, that is Open Explorer single clicks in a replaceable preview tab #108's, not this branch's, but it is worth knowing before both land.

Risk surface

  • Runtime mutex: nothing new under Mutex<Runtime>; the core change is the field rename. Parsing and styling live in the shell.
  • Snapshot wire: editor.tabs[].markdown_live rides the existing revisioned editor tab record where markdown_preview rode; the file_view event carries {tab_id, markdown_live, wrap}.
  • Ownership: the core owns the mode per tab and the shell dispatches file_view when the user changes it; the Live view reads the draft and writes it back through the same updateDraft/scheduleFileSave path as Source, and holds no mirrored state.
  • Herdr contract: no method or field beyond the schema; Herdr is not involved.
  • Failure path: a parse failure is the notice with localizedDescription under the toolbar and the source stays monospaced and editable; an over-limit file is the fixed notice with both mode buttons disabled; a link that cannot open is the existing openDocumentLink notice. Nothing is logged for a parse failure beyond the notice, because it is per keystroke and recoverable.
  • High-frequency path: per keystroke the Live view does one text-storage edit, one plan(for:) on a worker thread (coalesced: at most one in flight and one pending), one attribute restyle of the changed region and one hidden-marker refresh on the main thread. Measured on a 10,000-line / 224,706-byte document in the debug build (agents/runs/markdown-live-preview/perf/REPORT.md, 60 keystrokes with a caret move each): main-thread insert p50 6.6 ms / p95 10.6 ms / max 16.8 ms, caret move p50 4.7 ms / p95 4.9 ms, changed-region apply p50 5.9 ms, keystroke-to-formatted p50 238 ms (parse-bound; -O parse is ~65 ms). Physical footprint peak stays at the process baseline (377 MB) across the burst; before the fixes in 37ca71f and 5c55a3a an insert cost 57 ms p50 and sixty keystrokes grew the process by a gigabyte. Native: idle 1.4% CPU with the document open, 125% CPU during the driven burst. Regression owners: MarkdownLiveEditorTests (formatting, reveal, IME, paste, list keys) and MarkdownLiveSourceTests (plan ranges), plus the threshold recorded in the report (insert and caret p95 under 16 ms at 10,000 lines, flat footprint).

Evidence

  • 확인한 것 (dev bundles of b45a67d, 1bdce49, eb14476 and c9e36b6, isolated Herdr 0.9.1 server, fixture with notes.md, README.md, empty.md, big.md 300 KB, long.md 10,000 lines; 39 registered artifacts in the local run directory, fonts read through AXAttributedStringForRange, text and caret through AX, key semantics through CGEvents with the app frontmost):
    • B1/B5/B6: notes.md opens Live with the "Live / Source" group; H1 SemiBold 28, H2 SemiBold 24, body Inter 15, bold Inter-Bold, inline code monospaced 12 with the backticks hidden, • bullets and numbers with indent, the quote rule, the --- hairline, and the table, task box and image kept as monospaced source.
    • B2/B3/B4: the caret line reveals # , **, backticks and fences (inside a block the whole block reveals; outside, the fence lines collapse); typing Korean and English mid-line lands at the caret and the neighbouring lines stay formatted; Source shows the typed source verbatim; every typed character reached the file through autosave.
    • B7: a plain click on a link placed the caret; Cmd-click on ./README.md switched to the README tab; Cmd-click on ./nope.md showed "The linked file is missing or outside this checkout."
    • B8: Source shows the ruler, Wrap and the monospaced font; ⌘= twice scaled the Live body 15 → 18 pt and the heading 28 → 33.6 pt, ⌘0 restored.
    • B9: empty.md opens as an empty Live view and a typed heading and italic render.
    • B10: big.md opens Source with both mode buttons disabled and the notice (also on both merged heads).
    • B11: README opened Live in its own tab while notes.md kept Source; a reopened tab starts Live.
    • B13: the numbers above; long.md open and 60-keystroke burst in the native app sampled idle and driven.
    • B16-B20, B22: real Return/Tab/Shift-Tab/Delete events in Live and Source on - one and 1. one lists produced the PRD's outcomes and the saved file is plain Markdown (bytes checked with od); CRLF documents are covered by crlfLinesKeepTheirEndingsAndEveryCharacter (value tests), not driven live.
    • B14/B15: no markdown_preview, MarkdownPreview.swift or MarkdownDocumentTests in the tree; node scripts/check-design-contract.mjs, gen-pen/check-pen pass with the board present.
    • Gates at 310b29a: verify-cargo.sh test 786 passed, verify-swift.sh test 484 passed (4.2 s), verify-cargo.sh lint, every CONTRIBUTING check script that runs unattended (design contract, pin single source, schema-only contract, no-attribution, no-workstation-identity, core-bridge structure, typed contract generated/structure, and the rest), check-hide-copy.mjs against 0a138f9: the only inventory change is markdown-preview → markdown-live plus markdown-live-unavailable (accessibility identifiers).
  • 확인하지 못한 것과 그 이유:
    • B12 (parse failure notice) only in the hosted test aFailedParseLeavesTheSourceMonospacedWithTheReason; Foundation's parser did not fail on any fixture, so it was injected.
    • B21 (composition) only in the hosted test through setMarkedText; a live Korean composition was typed, but Enter/Tab during an uncommitted composition was not driven by synthetic events.
    • B7's http(s) branch was not clicked live, to avoid opening the workstation's browser; the branch is openDocumentLink's existing code.
    • B13 release-build timings: the dev bundle is a debug build; only plan(for:) was timed with -O (65 ms p50). Scrolling and selection drag on the 10,000-line document were not measured.
    • Explorer click-to-open on the c9e36b6 bundle under synthetic input (see the reviewer question); files were opened through ⌘P instead.
    • One stray Return during native QA landed in the operator's own hide window when it took focus between my frontmost check and the key event; nothing in this branch was affected, noted for honesty.
  • 화면 증거: the captures show the workstation's home directory in the terminal title and breadcrumbs, so they stay in the local run directory (agents/runs/markdown-live-preview/live/shots/, indexed in INDEX.md, registered in the verification report by name, sha256 and observation); none is attached to this public PR.

Deterministic verification

  • Status: PASS (agents/runs/markdown-live-preview/verification-report.json, attempt 9 at head 310b29a, generated 2026-09-19)
  • PRD SHA 58088e7a1ed0e13a02a6807a2ea99ce5ac940d2454ed81a1d9178f317e02db68, base a233c6a (implement start), head 310b29a (merged with origin/main 0a138f9 at c9e36b6)
  • S1 GREEN bash scripts/verify-cargo.sh test, S2 GREEN bash scripts/verify-swift.sh test, S3 GREEN bash scripts/verify-cargo.sh lint

Agent review

  • Availability: Fidelity review completed and Code review completed (native subagents, read-only, against 1bdce49, re-confirmed for f98a6e3, c9e36b6 and 310b29a; both report no Fix-now item at 310b29a, the Fidelity reviewer moved B20 to MET on the orca citation, and the Code reviewer reran its CRLF reproductions against the fix).
  • Fix now:
    • Code review, MarkdownListEditing.Context.init CRLF corruption: String.dropLast(2) on a line ending in dropped one Character (the CRLF grapheme) plus the last content character, so every list key on a CRLF file lost a character and flattened the line ending. Fixed in 17058c5: the line content comes from NSString.getLineStart(_:end:contentsEnd:for:), the carriage return is re-appended to every rewritten line, any other terminator makes the key fall through to the text view, and MarkdownListEditingTests gained CRLF and foreign-terminator cases (the reviewer's two reproductions included).
    • Fidelity review, B20 narrower than the PRD sentence (1. kept as text only for a sole top-level item): kept as implemented. D-14 rule 6 names orca's handling as the rule; orca's commitEmptyOrderedListMarkerAsText (rich-markdown-list-continuation.ts) applies only when the ordered list has one item and is not nested in a list item, which is the shipped guard. The PRD sentence summarises that rule without the qualifier; a human may overrule by broadening the guard.
  • Follow-up improvements (advisory, not in this PR):
    • MarkdownListEditing.renumber/belongs walk the contiguous run of the column on every list key (O(n) in the list's length, main thread); fine for ordinary lists, worth a cap if very long ordered lists turn out common (Code).
    • isSoleItem inspects only the adjacent lines, an engineering reading of orca's childCount === 1 over a source text; a human with orca open may want to confirm (Fidelity).
    • The H5/H6 comment mismatch in HideTheme was reworded in 310b29a; H5 and H6 remain the same size and weight, which no requirement distinguishes (Fidelity).

AI tooling

  • 사람이 직접 작성 - [ ] 일부를 AI 도구로 작성 - [x] 대부분을 AI 도구로 작성

손으로 확인한 것: the font runs, caret positions and saved bytes quoted above were read from the running app through the accessibility API and compared against the PRD's strings and the DESIGN.md sizes; the PR text was checked against the diff, not the PRD's intent.

Markdown file tabs open in a Live view: one editable text view over the
source, formatting applied as attributes from Foundation's parser with
source positions, and markup glyphs left ungenerated on every line the
caret is not on. Source keeps the monospaced editor with its ruler and
Wrap toggle. The core tab field is markdown_live; the read-only preview,
its empty-document state and its tests are gone, and the conversation
ledger keeps its own renderer as ConversationMarkdown.

Documents over 256 KB open in Source with Live disabled and a notice.
Parsing runs off the main thread, one in flight, with a burst of edits
coalescing into one more; attributes are re-applied only where the plan
changed. Heading sizes, the quote rule and the italic skew are HideTheme
tokens, and the design canvas carries the Live board.
A plain-text NSTextView keeps one attribute set for its whole storage and
re-applies its typing attributes to all of it, which turned a document
into the heading the caret was in. The view is rich text now, with paste
and drop limited to plain strings so a clipboard's fonts never reach it.
Glyph generation asked for the first hidden marker with a linear scan on
every call, which cost 57 ms of main-thread time per keystroke on a
10,000-line document; the search it already had brings that to 7 ms.
Opening a 10,000-line document peaked at two gigabytes: every span
resolved its font by descriptor and copied a paragraph style, and the
background parse autoreleased tens of megabytes that a worker thread
never drained. Attribute sets are cached per style, and both the parse
and a whole-document apply run inside an autorelease pool; the peak is
now flat across the open and sixty keystrokes.
…arkdown

Enter after an item's text starts the next item with the same marker or
the next number; on an empty item it removes the marker and leaves the
list; a lone numbered marker stays as typed. Tab and Shift-Tab move an
item one level and a numbered item counts in the column it joins, while
the column it left renumbers. Backspace on an empty item removes only
its marker. A marked composition falls through to the composer. The
rules are pure functions over the source text shared by the Live and
Source views, so the file ends up as ordinary Markdown.
Keeps the document-kind adapters from main and replaces their Preview
branch with the Live editor; the design canvas carries both the document
kinds board and the Markdown live board.
The test slept a fixed 700 ms for a 450 ms debounce and failed when a
loaded machine stretched the save past the wait. Poll the file with the
suite's eventually helper so the assertion follows the save.
Opening the 8000-paragraph fixture in Source blocked the main thread for
about ten seconds: the highlighter applied every run without batching the
backing storage, so each setAttributes ran processEditing over the whole
document, and the layout of 32,000 lines followed. Every other main-actor
test's timer landed behind that block, which is what made the autosave
test fail. Batch the highlighter's storage edits and build the fixture
from wide paragraphs so the test stays over the byte limit at 240 lines.
…view

# Conflicts:
#	design/hide.pen
#	docs/README.md
#	scripts/pen-token-map.json
Context trimmed the caret line's ending with a Character-based dropLast,
and Swift treats CRLF as one Character, so a CRLF file lost the last
character of the line on every list key and the rewritten lines came
back with LF. Read the line content through NSString, carry the
carriage return into every rewritten line, and leave a line ending the
"\n"-indexed lines cannot place to the text view.
Every heading level is semibold, so h5 and h6 differ from the body by
weight and not from each other; the comment claimed weight carried the
level.
@yansfil
yansfil merged commit eb66e4d into main Sep 19, 2026
5 checks passed
@yansfil
yansfil deleted the prd/markdown-live-preview branch September 19, 2026 10:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant