Format-only pass over spikes, the gate prototype, and three app
files (brace style, wrapping — no semantic change), plus the 4-line
pbxproj alignment finishing the Xcode 27 settings pass (test-target
deployment target parity with 8e70f69).
[Generated by AI]
401 lines
16 KiB
Swift
401 lines
16 KiB
Swift
// Spike A (#52) — THROWAWAY. CodeEditSourceEditor fork as prose editor (mode B), anchor proof.
|
||
// Question: can the presumptive-leader code substrate present prose source as calm writing?
|
||
// Run: spike/codeedit/run.sh (from repo root, branch spike/editor-presentation)
|
||
import AppKit
|
||
@preconcurrency import CodeEditLanguages
|
||
@preconcurrency import CodeEditSourceEditor
|
||
@preconcurrency import CodeEditTextView
|
||
import SwiftUI
|
||
|
||
// MARK: - Prose theme (uniform-font compromise documented in the resolution)
|
||
|
||
enum ProseTheme {
|
||
/// Iowan Old Style like Spike B / the web proto; falls back to system serif.
|
||
static var bodyFont: NSFont {
|
||
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
||
?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard)
|
||
}
|
||
|
||
static let ink = NSColor(srgbRed: 0.10, green: 0.10, blue: 0.09, alpha: 1)
|
||
static let dim = NSColor(srgbRed: 0.55, green: 0.55, blue: 0.55, alpha: 1)
|
||
static let paper = NSColor(srgbRed: 0.98, green: 0.98, blue: 0.98, alpha: 1)
|
||
static let accent = NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 1)
|
||
|
||
static var theme: EditorTheme {
|
||
EditorTheme(
|
||
text: .init(color: ink),
|
||
insertionPoint: ink,
|
||
invisibles: .init(color: dim),
|
||
background: paper,
|
||
lineHighlight: NSColor(srgbRed: 0.955, green: 0.955, blue: 0.955, alpha: 1),
|
||
selection: NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18),
|
||
keywords: .init(color: dim), // markdown markers route here via prosePass below
|
||
commands: .init(color: ink),
|
||
types: .init(color: ink, bold: true), // headings: bold, same size (substrate limit)
|
||
attributes: .init(color: ink),
|
||
variables: .init(color: ink),
|
||
values: .init(color: ink),
|
||
numbers: .init(color: ink),
|
||
strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint
|
||
characters: .init(color: ink),
|
||
comments: .init(color: dim),
|
||
)
|
||
}
|
||
}
|
||
|
||
// MARK: - Prose highlight pass (helm's MonokaiHighlighter pattern: wrap tree-sitter, add regex passes)
|
||
|
||
/// Wraps the stock TreeSitterClient; after its captures, adds prose passes over markdown:
|
||
/// heading lines → bold capture, marker+inline-syntax runs → dim capture. Emphasis/anchor is NOT
|
||
/// done here — layer-backed Emphasis handles it.
|
||
final class ProseHighlighter: HighlightProviding {
|
||
private let wrapped = TreeSitterClient()
|
||
|
||
func setUp(textView: TextView, codeLanguage: CodeLanguage) {
|
||
wrapped.setUp(textView: textView, codeLanguage: codeLanguage)
|
||
}
|
||
|
||
func applyEdit(
|
||
textView: TextView,
|
||
range: NSRange,
|
||
delta: Int,
|
||
completion: @escaping @MainActor (Result<IndexSet, Error>) -> Void,
|
||
) {
|
||
wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion)
|
||
}
|
||
|
||
func queryHighlightsFor(
|
||
textView: TextView,
|
||
range: NSRange,
|
||
completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void,
|
||
) {
|
||
wrapped.queryHighlightsFor(textView: textView, range: range) { result in
|
||
switch result {
|
||
case let .failure(error):
|
||
completion(.failure(error))
|
||
case let .success(tsRanges):
|
||
var out = tsRanges
|
||
let ns = textView.string as NSString
|
||
let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
|
||
out += Self.proseRanges(in: ns, range: safe)
|
||
completion(.success(out))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Pure: heading text → .type (bold via theme), heading marker + inline marks → .keyword (dim).
|
||
/// ponytail: line-scan regex, not an AST — corpus is plain prose markdown; enough for the spike.
|
||
static func proseRanges(in ns: NSString, range: NSRange) -> [HighlightRange] {
|
||
var out: [HighlightRange] = []
|
||
ns.enumerateSubstrings(in: range, options: [.byLines]) { line, lineRange, _, _ in
|
||
guard let line, !line.isEmpty else { return }
|
||
if let markerLen = Self.headingMarkerLen(line) {
|
||
// heading text (after marker, same line) → bold capture
|
||
let textLen = lineRange.length - markerLen
|
||
if textLen > 0 {
|
||
out.append(HighlightRange(
|
||
range: NSRange(location: lineRange.location + markerLen, length: textLen),
|
||
capture: .type,
|
||
))
|
||
}
|
||
// marker → dim
|
||
out.append(HighlightRange(
|
||
range: NSRange(location: lineRange.location, length: markerLen),
|
||
capture: .keyword,
|
||
))
|
||
} else if line.hasPrefix(">") {
|
||
// quote line: text → tinted .string, markers dimmed
|
||
let textLen = lineRange.length - 1
|
||
if textLen > 0 {
|
||
out.append(HighlightRange(range: NSRange(location: lineRange.location + 1, length: textLen), capture: .string))
|
||
}
|
||
out.append(HighlightRange(range: NSRange(location: lineRange.location, length: 1), capture: .keyword))
|
||
} else {
|
||
// inline syntax chars → dim, one run per char (runs merge at render)
|
||
let marks: Set<UInt16> = [0x2A, 0x5F, 0x60, 0x5B, 0x5D, 0x28, 0x29, 0x21, 0x3C, 0x3E] // * _ ` [ ] ( ) ! < >
|
||
for (off, ch) in line.utf16.enumerated() where marks.contains(ch) {
|
||
out.append(HighlightRange(
|
||
range: NSRange(location: lineRange.location + off, length: 1),
|
||
capture: .keyword,
|
||
))
|
||
}
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
private static func headingMarkerLen(_ line: String) -> Int? {
|
||
guard line.hasPrefix("#") else { return nil }
|
||
let hashes = line.prefix { $0 == "#" }.count
|
||
guard hashes <= 6, line.dropFirst(hashes).hasPrefix(" ") else { return nil }
|
||
return hashes + 1
|
||
}
|
||
}
|
||
|
||
// MARK: - Quote anchor (identical algorithm to Spike B — same feasibility question)
|
||
|
||
nonisolated enum AnchorSearch {
|
||
private struct Word { let norm: String; let range: Range<String.Index> }
|
||
private static func words(_ s: String) -> [Word] {
|
||
s.split(whereSeparator: \.isWhitespace).map { sub in
|
||
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), range: sub.startIndex ..< sub.endIndex)
|
||
}
|
||
}
|
||
|
||
/// Word-tokenized whitespace/punctuation-tolerant search. nil = stale anchor.
|
||
static func range(of quote: String, in text: String) -> NSRange? {
|
||
let textWords = words(text)
|
||
let quoteWords = words(quote)
|
||
guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil }
|
||
for start in 0 ... (textWords.count - quoteWords.count) {
|
||
if (start ..< start + quoteWords.count).allSatisfy({
|
||
textWords[$0].norm == quoteWords[$0 - start].norm
|
||
}) {
|
||
let from = textWords[start].range.lowerBound
|
||
let to = textWords[start + quoteWords.count - 1].range.upperBound
|
||
return NSRange(
|
||
location: text.utf16.distance(from: text.startIndex, to: from),
|
||
length: text.utf16.distance(from: from, to: to),
|
||
)
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// MARK: - App shell
|
||
|
||
@main
|
||
struct SpikeApp: App {
|
||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||
var body: some Scene {
|
||
Window("Spike A — CodeEdit fork", id: "main") {
|
||
ContentView()
|
||
.frame(minWidth: 900, minHeight: 640)
|
||
.onAppear { NSApp.activate(ignoringOtherApps: true) }
|
||
}
|
||
.windowStyle(.hiddenTitleBar)
|
||
}
|
||
|
||
// ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check`
|
||
init() {
|
||
if CommandLine.arguments.contains("--check") {
|
||
Self.selfCheck(); exit(0)
|
||
}
|
||
}
|
||
|
||
static func selfCheck() {
|
||
// Repo root from compile-time path (self-check must not depend on cwd).
|
||
let root = URL(fileURLWithPath: #filePath)
|
||
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||
let text = (try? String(contentsOf: root.appendingPathComponent("spike/prose/the-expected-value-of-showing.md"), encoding: .utf8)) ?? ""
|
||
assert(!text.isEmpty, "FAIL: corpus missing — run from repo root")
|
||
let ns = text as NSString
|
||
let full = NSRange(location: 0, length: ns.length)
|
||
let ranges = ProseHighlighter.proseRanges(in: ns, range: full)
|
||
// headings detected (calibration piece has H1 + H2s)
|
||
let headingTexts = ranges.filter { $0.capture == .type }
|
||
assert(headingTexts.count >= 3, "FAIL: expected headings, got \(headingTexts.count)")
|
||
assert(headingTexts.allSatisfy { (ns.substring(with: $0.range) as NSString).range(of: "#").location == NSNotFound },
|
||
"FAIL: marker leaked into heading text")
|
||
// markers dimmed
|
||
assert(ranges.contains { $0.capture == .keyword && ns.substring(with: $0.range).hasPrefix("#") },
|
||
"FAIL: heading marker not dimmed")
|
||
// anchor: live quote found; stale → nil; whitespace-tolerant
|
||
let quote = "\"I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.\""
|
||
guard let r = AnchorSearch.range(of: quote, in: text) else { assertionFailure("FAIL: live quote not found"); return }
|
||
assert((ns.substring(with: r) as NSString).length > 50)
|
||
let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
|
||
assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance")
|
||
assert(AnchorSearch.range(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
|
||
// perf smoke: PERF-3k anchor timing
|
||
let perfURL = root.appendingPathComponent("spike/prose/PERF-3k.md")
|
||
if let perf = try? String(contentsOf: perfURL, encoding: .utf8) {
|
||
let t0 = DispatchTime.now()
|
||
_ = AnchorSearch.range(of: "The odds are better than they look", in: perf)
|
||
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
|
||
print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms")
|
||
} else {
|
||
print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k not found")
|
||
}
|
||
}
|
||
}
|
||
|
||
struct ContentView: View {
|
||
@State private var text: String
|
||
@State private var editorState = SourceEditorState()
|
||
@State private var reading = false
|
||
@State private var staleShown = false
|
||
@State private var loadMs: Double = 0
|
||
@State private var anchorNote: String?
|
||
/// Captured controller — the path to Emphasis/setCursorPositions (helm #160 pattern).
|
||
/// Reference box, not @State: writes during makeNSViewController are dropped (see ControllerBox).
|
||
private let box = ControllerBox()
|
||
|
||
init() {
|
||
// Repo root from compile-time path — launchd cwd is "/", so relative paths never hit.
|
||
let repoRoot = URL(fileURLWithPath: #filePath) // <root>/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
|
||
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||
let corpus = repoRoot.appendingPathComponent("spike/prose/the-expected-value-of-showing.md")
|
||
let arg = CommandLine.arguments.first(where: { $0.hasSuffix(".md") })
|
||
let url = arg.map { URL(fileURLWithPath: $0, relativeTo: repoRoot) } ?? corpus
|
||
let t = (try? String(contentsOf: url, encoding: .utf8))
|
||
?? (try? String(contentsOf: corpus, encoding: .utf8))
|
||
?? "# Spike A\n\n(No corpus file found at \(corpus.path).)"
|
||
_text = State(initialValue: t)
|
||
}
|
||
|
||
var body: some View {
|
||
VStack(spacing: 0) {
|
||
bar
|
||
Divider()
|
||
if reading {
|
||
// Reading toggle: same per-block renderer stance as Spike B (its resolution is the map's reference)
|
||
ScrollView(.vertical) {
|
||
VStack(alignment: .leading, spacing: 14) {
|
||
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
|
||
Text(block.text)
|
||
.font(block.level > 0
|
||
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
|
||
: .system(size: 17))
|
||
}
|
||
}
|
||
.frame(maxWidth: 720, alignment: .leading)
|
||
.padding(.horizontal, 40)
|
||
.padding(.vertical, 24)
|
||
}
|
||
} else {
|
||
editor
|
||
}
|
||
}
|
||
.alert("Anchor not found", isPresented: $staleShown) {
|
||
Button("OK", role: .cancel) {}
|
||
} message: {
|
||
Text("The Post changed after this Fix Card was issued; no text was selected or changed.")
|
||
}
|
||
}
|
||
|
||
private var editor: some View {
|
||
// Centered measure via maxWidth (iA-Writer approach; no GeometryReader — it proposes
|
||
// 0×0 to the AppKit leaf on first pass and the window never places in this shell).
|
||
SourceEditor(
|
||
$text,
|
||
language: .markdown,
|
||
configuration: config,
|
||
state: $editorState,
|
||
highlightProviders: [ProseHighlighter()],
|
||
coordinators: [ControllerCapture(onCapture: { box.controller = $0 })],
|
||
)
|
||
.frame(maxWidth: 720)
|
||
.frame(maxWidth: .infinity)
|
||
.padding(.horizontal, 24)
|
||
}
|
||
|
||
private var config: SourceEditorConfiguration {
|
||
SourceEditorConfiguration(
|
||
appearance: .init(
|
||
theme: ProseTheme.theme,
|
||
font: ProseTheme.bodyFont,
|
||
lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate)
|
||
wrapLines: true,
|
||
),
|
||
behavior: .init(reformatAtColumn: 10000), // never hard-wrap prose
|
||
peripherals: .init(
|
||
showGutter: false, // no line numbers in a writing app
|
||
showMinimap: false,
|
||
showReformattingGuide: false,
|
||
showFoldingRibbon: false,
|
||
invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
|
||
warningCharacters: [],
|
||
),
|
||
)
|
||
}
|
||
|
||
private var bar: some View {
|
||
HStack(spacing: 12) {
|
||
Toggle("Reading", isOn: $reading)
|
||
Divider().frame(height: 14)
|
||
Button("Anchor: DM quote") { applyAnchor("\"I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.\"") }
|
||
Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
|
||
if let note = anchorNote {
|
||
Text(note).foregroundStyle(.secondary).font(.caption)
|
||
}
|
||
Spacer()
|
||
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
|
||
}
|
||
.padding(.horizontal, 16)
|
||
.padding(.vertical, 8)
|
||
}
|
||
|
||
private func applyAnchor(_ quote: String) {
|
||
let controller = box.controller
|
||
let t0 = DispatchTime.now()
|
||
let r = AnchorSearch.range(of: quote, in: text)
|
||
loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
|
||
guard let r else {
|
||
anchorNote = nil
|
||
staleShown = true
|
||
return
|
||
}
|
||
anchorNote = "anchored @ \(r.location)–\(r.location + r.length)\(controller == nil ? " (no ctrl!)" : "")"
|
||
guard let controller else { return }
|
||
// Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection.
|
||
controller.textView.emphasisManager?.replaceEmphases(
|
||
[Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))],
|
||
for: "fix-card-anchor",
|
||
)
|
||
controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true)
|
||
}
|
||
}
|
||
|
||
/// Captures the live TextViewController at prepareCoordinator (helm #160's captured-controller pattern).
|
||
/// Reference box, NOT @State: prepareCoordinator fires inside makeNSViewController — during SwiftUI's
|
||
/// view update — and @State writes there are silently dropped (root cause of the "(no ctrl!)" case).
|
||
final class ControllerBox: @unchecked Sendable {
|
||
var controller: TextViewController?
|
||
}
|
||
|
||
final class ControllerCapture: TextViewCoordinator {
|
||
let onCapture: (TextViewController) -> Void
|
||
init(onCapture: @escaping (TextViewController) -> Void) {
|
||
self.onCapture = onCapture
|
||
}
|
||
|
||
func prepareCoordinator(controller: TextViewController) {
|
||
onCapture(controller)
|
||
}
|
||
}
|
||
|
||
// MARK: - Reading blocks (Spike B's proven per-block renderer; .full syntax)
|
||
|
||
extension SpikeApp {
|
||
// ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none.
|
||
static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] {
|
||
md.components(separatedBy: "\n\n").map { para in
|
||
var level = 0
|
||
var p = para.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
if p.hasPrefix("#") {
|
||
let hashes = p.prefix { $0 == "#" }.count
|
||
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
|
||
level = hashes
|
||
}
|
||
let attr = (try? AttributedString(
|
||
markdown: p,
|
||
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
|
||
)) ?? AttributedString(p)
|
||
return (level, attr)
|
||
}
|
||
}
|
||
}
|
||
|
||
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
|
||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||
func applicationWillFinishLaunching(_: Notification) {
|
||
NSApp.setActivationPolicy(.regular)
|
||
}
|
||
|
||
func applicationDidFinishLaunching(_: Notification) {
|
||
NSApp.activate(ignoringOtherApps: true)
|
||
}
|
||
}
|