docs/plans/2026-10-04-orgcore-parser.md
1602 lines · 55781 bytes
1# OrgCore Parser Foundation Implementation Plan
2
3Shipped as one squashed commit, f4591a4 "OrgCore parser foundation (!1)"; the commit names below are the steps as planned.
4
5> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
6
7**Goal:** A Swift package, `OrgCore`, that turns org file bytes into a lossless syntax tree of block-level elements, with the byte and encoding contract from the design.
8
9**Architecture:** Bytes decode into `SourceText` (UTF-8 only, BOM kept, invalid input read-only). The parser splits lines without normalizing endings, classifies each line once, matches block and drawer ends, scans in-buffer TODO settings outside blocks, then builds an immutable green tree through `GreenBuilder`. `SyntaxNode` gives offset-aware red views. Every input byte ends up in exactly one token, so the tree text always equals the source.
10
11**Tech Stack:** Swift 6.2 tools, Swift Testing, Foundation only. No third-party dependencies.
12
13**Spec:** `docs/design.md` (sections "OrgCore data model", "Testing", "Phases").
14
15## Global Constraints
16
17- Platforms: macOS 26, iOS 26.
18- `OrgCore` imports Foundation only; never AppKit, UIKit or SwiftUI.
19- Ranges and offsets exposed by the tree are UTF-16 code units.
20- Supported encoding: UTF-8 with or without BOM. Anything else is read-only and never converted.
21- Round trip: tree text equals source text for every input, and encoding unchanged text returns the original bytes.
22- License 0BSD. No attribution lines in code, commits or docs.
23
24## Out of scope for this plan
25
26Inline objects (emphasis, links, timestamps), the semantic layer, incremental reparse, conformance rendering, and the private-corpus benchmarks. Each gets its own plan.
27
28## File structure
29
30| File | Responsibility |
31| --- | --- |
32| `Package.swift` | Package with `OrgCore` library and `OrgCoreTests` |
33| `Sources/OrgCore/SourceText.swift` | Byte decoding, BOM, validity, encoding back to bytes |
34| `Sources/OrgCore/Syntax/SyntaxKind.swift` | Token and node kinds |
35| `Sources/OrgCore/Syntax/GreenTree.swift` | `GreenToken`, `GreenNode`, `GreenElement`, `GreenBuilder` |
36| `Sources/OrgCore/Syntax/SyntaxNode.swift` | Red nodes, tokens, `OrgTree` |
37| `Sources/OrgCore/Parser/Lines.swift` | Line splitting and classification |
38| `Sources/OrgCore/Parser/Settings.swift` | TODO sequences, priorities, settings scan |
39| `Sources/OrgCore/Parser/Parser.swift` | Tree construction |
40| `Tests/OrgCoreTests/*.swift` | One test file per source file, plus round-trip fuzz and corpus tests |
41
42---
43
44### Task 1: Package and SourceText
45
46**Files:**
47- Create: `Package.swift`
48- Create: `Sources/OrgCore/SourceText.swift`
49- Test: `Tests/OrgCoreTests/SourceTextTests.swift`
50
51**Interfaces:**
52- Produces: `SourceText(bytes: [UInt8])`, `SourceText(_ text: String)`, properties `originalBytes`, `hasBOM`, `isValidUTF8`, `isEditable`, `text`; `encode(_ newText: String) -> [UInt8]`.
53
54- [x] **Step 1: Create the package**
55
56```swift
57// swift-tools-version: 6.2
58import PackageDescription
59
60let package = Package(
61 name: "Orgstar",
62 platforms: [.macOS(.v26), .iOS(.v26)],
63 products: [
64 .library(name: "OrgCore", targets: ["OrgCore"])
65 ],
66 targets: [
67 .target(name: "OrgCore"),
68 .testTarget(name: "OrgCoreTests", dependencies: ["OrgCore"])
69 ]
70)
71```
72
73- [x] **Step 2: Write the failing tests**
74
75```swift
76import Testing
77@testable import OrgCore
78
79struct SourceTextTests {
80 @Test func plainUTF8() {
81 let source = SourceText(bytes: Array("* a\n".utf8))
82 #expect(source.text == "* a\n")
83 #expect(!source.hasBOM)
84 #expect(source.isEditable)
85 }
86
87 @Test func bomIsStrippedAndRestored() {
88 let bytes: [UInt8] = [0xEF, 0xBB, 0xBF] + Array("x\n".utf8)
89 let source = SourceText(bytes: bytes)
90 #expect(source.hasBOM)
91 #expect(source.text == "x\n")
92 #expect(source.encode(source.text) == bytes)
93 #expect(source.encode("y\n") == [0xEF, 0xBB, 0xBF] + Array("y\n".utf8))
94 }
95
96 @Test func crlfAndMixedEndingsSurvive() {
97 let bytes = Array("a\r\nb\nc\r\n".utf8)
98 let source = SourceText(bytes: bytes)
99 #expect(source.encode(source.text) == bytes)
100 }
101
102 @Test func invalidUTF8IsReadOnlyAndUnchanged() {
103 let bytes: [UInt8] = [0x61, 0xFF, 0x0A]
104 let source = SourceText(bytes: bytes)
105 #expect(!source.isValidUTF8)
106 #expect(!source.isEditable)
107 #expect(source.encode(source.text) == bytes)
108 }
109
110 @Test func nonBMPAndCombiningSurvive() {
111 let bytes = Array("😀 e\u{301}\n".utf8)
112 let source = SourceText(bytes: bytes)
113 #expect(source.encode(source.text) == bytes)
114 }
115}
116```
117
118- [x] **Step 3: Run tests to verify they fail**
119
120Run: `swift test --filter SourceTextTests`
121Expected: build failure, `cannot find 'SourceText' in scope`.
122
123- [x] **Step 4: Implement**
124
125```swift
126import Foundation
127
128/// A file's bytes and their decoded text. Only UTF-8 (with or without a BOM) is editable;
129/// anything else decodes with replacement characters for display and is never written back.
130public struct SourceText: Sendable {
131 public let originalBytes: [UInt8]
132 public let hasBOM: Bool
133 public let isValidUTF8: Bool
134 /// Decoded text without the BOM.
135 public let text: String
136
137 private static let bom: [UInt8] = [0xEF, 0xBB, 0xBF]
138
139 public init(bytes: [UInt8]) {
140 originalBytes = bytes
141 hasBOM = bytes.starts(with: Self.bom)
142 let body = hasBOM ? Array(bytes.dropFirst(3)) : bytes
143 if let decoded = String(validating: body, as: UTF8.self) {
144 text = decoded
145 isValidUTF8 = true
146 } else {
147 text = String(decoding: body, as: UTF8.self)
148 isValidUTF8 = false
149 }
150 }
151
152 public init(_ text: String) {
153 self.init(bytes: Array(text.utf8))
154 }
155
156 public var isEditable: Bool { isValidUTF8 }
157
158 /// Bytes to write for `newText`. Unchanged text returns the original bytes. Valid UTF-8
159 /// round-trips through `String` unchanged, so untouched spans keep their exact bytes.
160 public func encode(_ newText: String) -> [UInt8] {
161 if newText == text { return originalBytes }
162 precondition(isEditable, "a read-only document cannot be re-encoded")
163 return (hasBOM ? Self.bom : []) + Array(newText.utf8)
164 }
165}
166```
167
168- [x] **Step 5: Run tests to verify they pass**
169
170Run: `swift test --filter SourceTextTests`
171Expected: 5 tests pass.
172
173- [x] **Step 6: Commit**
174
175```bash
176git add Package.swift Sources Tests
177git commit -m "Add OrgCore package and SourceText byte contract"
178```
179
180---
181
182### Task 2: Green and red syntax tree
183
184**Files:**
185- Create: `Sources/OrgCore/Syntax/SyntaxKind.swift`
186- Create: `Sources/OrgCore/Syntax/GreenTree.swift`
187- Create: `Sources/OrgCore/Syntax/SyntaxNode.swift`
188- Test: `Tests/OrgCoreTests/SyntaxTreeTests.swift`
189
190**Interfaces:**
191- Produces: `SyntaxKind` (enum, `String` raw values), `GreenToken(kind:text:)`, `GreenNode(kind:children:)` with `.length`, `.text`; `GreenElement` (`.node`, `.token`); internal `GreenBuilder` with `start(_:)`, `token(_:_:)`, `finish()`, `build()`; `SyntaxNode` with `kind`, `range`, `text`, `children`, `tokens`, `descendants()`; `SyntaxToken`. `OrgTree` depends on `OrgSettings` (Task 4), so it is added in Task 5.
192
193- [x] **Step 1: Write the failing tests**
194
195```swift
196import Testing
197@testable import OrgCore
198
199struct SyntaxTreeTests {
200 func sample() -> GreenNode {
201 var b = GreenBuilder()
202 b.start(.document)
203 b.start(.paragraph)
204 b.token(.text, "hé😀")
205 b.token(.newline, "\n")
206 b.finish()
207 b.token(.newline, "\r\n")
208 b.finish()
209 return b.build()
210 }
211
212 @Test func lengthsAreUTF16() {
213 let green = sample()
214 #expect(green.length == 4 + 1 + 2)
215 #expect(green.text == "hé😀\n\r\n")
216 }
217
218 @Test func redNodesCarryOffsets() {
219 let root = SyntaxNode(green: sample(), offset: 0, parent: nil)
220 let paragraph = root.children[0]
221 #expect(paragraph.kind == .paragraph)
222 #expect(paragraph.range == 0..<5)
223 #expect(paragraph.parent === root)
224 #expect(root.tokens.map(\.range) == [5..<7])
225 #expect(paragraph.tokens.map(\.kind) == [.text, .newline])
226 }
227
228 @Test func builderSkipsEmptyTokens() {
229 var b = GreenBuilder()
230 b.start(.document)
231 b.token(.whitespace, "")
232 b.finish()
233 #expect(b.build().children.isEmpty)
234 }
235
236 @Test func descendantsArePreorder() {
237 let root = SyntaxNode(green: sample(), offset: 0, parent: nil)
238 #expect(root.descendants().map(\.kind) == [.document, .paragraph])
239 }
240}
241```
242
243- [x] **Step 2: Run tests to verify they fail**
244
245Run: `swift test --filter SyntaxTreeTests`
246Expected: build failure, `cannot find 'GreenBuilder' in scope`.
247
248- [x] **Step 3: Implement `SyntaxKind.swift`**
249
250```swift
251public enum SyntaxKind: String, Sendable {
252 // Tokens
253 case text, newline, whitespace
254 case stars, todoKeyword, priority, title, tags
255
256 // Nodes
257 case document, zerothSection, section, heading
258 case planning, propertyDrawer, nodeProperty, drawer, clock
259 case paragraph, plainList, item, table, tableRow, tableFormula
260 case block, dynamicBlock, keyword, affiliatedKeyword
261 case comment, fixedWidth, horizontalRule, footnoteDefinition
262}
263```
264
265- [x] **Step 4: Implement `GreenTree.swift`**
266
267```swift
268public struct GreenToken: Sendable, Equatable {
269 public let kind: SyntaxKind
270 public let text: String
271 /// Length in UTF-16 code units.
272 public let length: Int
273
274 public init(kind: SyntaxKind, text: String) {
275 self.kind = kind
276 self.text = text
277 self.length = text.utf16.count
278 }
279}
280
281/// An immutable node. Stores only kind, children and length, so unchanged subtrees can be
282/// shared between versions of a document.
283public final class GreenNode: Sendable, Equatable {
284 public let kind: SyntaxKind
285 public let children: [GreenElement]
286 /// Length in UTF-16 code units.
287 public let length: Int
288
289 public init(kind: SyntaxKind, children: [GreenElement]) {
290 self.kind = kind
291 self.children = children
292 self.length = children.reduce(0) { $0 + $1.length }
293 }
294
295 public static func == (lhs: GreenNode, rhs: GreenNode) -> Bool {
296 lhs === rhs || (lhs.kind == rhs.kind && lhs.children == rhs.children)
297 }
298
299 public var text: String {
300 var out = ""
301 write(to: &out)
302 return out
303 }
304
305 func write(to out: inout String) {
306 for child in children {
307 switch child {
308 case .node(let node): node.write(to: &out)
309 case .token(let token): out += token.text
310 }
311 }
312 }
313}
314
315public enum GreenElement: Sendable, Equatable {
316 case node(GreenNode)
317 case token(GreenToken)
318
319 public var length: Int {
320 switch self {
321 case .node(let node): node.length
322 case .token(let token): token.length
323 }
324 }
325}
326
327struct GreenBuilder {
328 private var stack: [(kind: SyntaxKind, children: [GreenElement])] = []
329 private var root: GreenNode?
330
331 mutating func start(_ kind: SyntaxKind) {
332 stack.append((kind, []))
333 }
334
335 mutating func token(_ kind: SyntaxKind, _ text: some StringProtocol) {
336 guard !text.isEmpty else { return }
337 stack[stack.count - 1].children.append(.token(GreenToken(kind: kind, text: String(text))))
338 }
339
340 mutating func finish() {
341 let (kind, children) = stack.removeLast()
342 let node = GreenNode(kind: kind, children: children)
343 if stack.isEmpty {
344 root = node
345 } else {
346 stack[stack.count - 1].children.append(.node(node))
347 }
348 }
349
350 func build() -> GreenNode {
351 precondition(stack.isEmpty, "unfinished nodes")
352 return root!
353 }
354}
355```
356
357- [x] **Step 5: Implement `SyntaxNode.swift`**
358
359```swift
360/// A view of a green node at an absolute offset, with a parent link. Created on demand.
361public final class SyntaxNode: Sendable {
362 public let green: GreenNode
363 public let offset: Int
364 public let parent: SyntaxNode?
365
366 init(green: GreenNode, offset: Int, parent: SyntaxNode?) {
367 self.green = green
368 self.offset = offset
369 self.parent = parent
370 }
371
372 public var kind: SyntaxKind { green.kind }
373 public var range: Range<Int> { offset..<(offset + green.length) }
374 public var text: String { green.text }
375
376 public var children: [SyntaxNode] {
377 var result: [SyntaxNode] = []
378 var at = offset
379 for child in green.children {
380 if case .node(let node) = child {
381 result.append(SyntaxNode(green: node, offset: at, parent: self))
382 }
383 at += child.length
384 }
385 return result
386 }
387
388 public var tokens: [SyntaxToken] {
389 var result: [SyntaxToken] = []
390 var at = offset
391 for child in green.children {
392 if case .token(let token) = child {
393 result.append(SyntaxToken(kind: token.kind, text: token.text, range: at..<(at + token.length)))
394 }
395 at += child.length
396 }
397 return result
398 }
399
400 /// This node and every node below it, in document order.
401 public func descendants() -> [SyntaxNode] {
402 [self] + children.flatMap { $0.descendants() }
403 }
404}
405
406public struct SyntaxToken: Sendable, Equatable {
407 public let kind: SyntaxKind
408 public let text: String
409 public let range: Range<Int>
410}
411```
412
413- [x] **Step 6: Run tests to verify they pass**
414
415Run: `swift test --filter SyntaxTreeTests`
416Expected: 4 tests pass.
417
418- [x] **Step 7: Commit**
419
420```bash
421git add Sources Tests
422git commit -m "Add green and red syntax tree"
423```
424
425---
426
427### Task 3: Line splitting and classification
428
429**Files:**
430- Create: `Sources/OrgCore/Parser/Lines.swift`
431- Test: `Tests/OrgCoreTests/LinesTests.swift`
432
433**Interfaces:**
434- Produces (internal): `RawLine(content: Substring, ending: Substring)`, `splitRawLines(_ text: String) -> [RawLine]`, `LineClass` enum, `ClassifiedLine(cls:indent:)`, `classifyLine(_ line: Substring) -> ClassifiedLine`, `Substring.trimmingTrailingWhitespace`.
435
436- [x] **Step 1: Write the failing tests**
437
438```swift
439import Testing
440@testable import OrgCore
441
442struct LinesTests {
443 @Test func splitKeepsEveryEnding() {
444 let lines = splitRawLines("a\r\nb\n\nc")
445 #expect(lines.map { String($0.content) } == ["a", "b", "", "c"])
446 #expect(lines.map { String($0.ending) } == ["\r\n", "\n", "\n", ""])
447 #expect(splitRawLines("").isEmpty)
448 #expect(splitRawLines("x\n").count == 1)
449 }
450
451 @Test func splitIsLossless() {
452 let text = "\r\n\n a\r b\r\n😀\n"
453 #expect(splitRawLines(text).map { String($0.content) + String($0.ending) }.joined() == text)
454 }
455
456 @Test(arguments: [
457 ("", LineClass.blank),
458 (" \t", .blank),
459 ("* a", .heading(level: 1)),
460 ("*** ", .heading(level: 3)),
461 ("*", .heading(level: 1)),
462 ("*bold* text", .plain),
463 (" * a", .listItem),
464 ("#+BEGIN_SRC sh :results output", .blockBegin(name: "src")),
465 ("#+end_src", .blockEnd(name: "src")),
466 ("#+BEGIN: clocktable :scope file", .dynamicBegin),
467 ("#+END:", .dynamicEnd),
468 ("#+TITLE: x", .keyword(key: "TITLE")),
469 ("#+tblfm: $2=$1", .keyword(key: "TBLFM")),
470 ("# comment", .comment),
471 ("#", .comment),
472 ("#hashtag", .plain),
473 (": fixed", .fixedWidth),
474 (":", .fixedWidth),
475 (":PROPERTIES:", .drawerBegin(name: "PROPERTIES")),
476 (" :LOGBOOK:", .drawerBegin(name: "LOGBOOK")),
477 (":END:", .drawerEnd),
478 ("| a | b |", .tableRow),
479 ("-----", .horizontalRule),
480 ("----", .plain),
481 ("[fn:1] note", .footnoteDefinition),
482 ("CLOCK: [2026-10-04 Sun 10:00]", .clock),
483 ("SCHEDULED: <2026-10-04 Sun>", .planning),
484 ("- item", .listItem),
485 ("+ item", .listItem),
486 ("1. item", .listItem),
487 ("2) item", .listItem),
488 ("-", .listItem),
489 ("-x", .plain),
490 ("1.5 apples", .plain),
491 ("plain text", .plain),
492 ])
493 func classify(line: String, expected: LineClass) {
494 #expect(classifyLine(line[...]).cls == expected)
495 }
496
497 @Test func indentCountsTabsToEight() {
498 #expect(classifyLine("\t- a").indent == 8)
499 #expect(classifyLine(" \t- a").indent == 8)
500 #expect(classifyLine(" - a").indent == 3)
501 }
502}
503```
504
505- [x] **Step 2: Run tests to verify they fail**
506
507Run: `swift test --filter LinesTests`
508Expected: build failure, `cannot find 'splitRawLines' in scope`.
509
510- [x] **Step 3: Implement**
511
512```swift
513/// One line of source: its content and its terminator ("", "\n" or "\r\n"), both as slices of
514/// the original text.
515struct RawLine {
516 let content: Substring
517 let ending: Substring
518}
519
520/// Splits on "\n" without normalizing anything. Works on unicode scalars, because String
521/// treats "\r\n" as a single Character.
522func splitRawLines(_ text: String) -> [RawLine] {
523 var lines: [RawLine] = []
524 let scalars = text.unicodeScalars
525 var lineStart = scalars.startIndex
526 var i = lineStart
527 while i != scalars.endIndex {
528 if scalars[i] == "\n" {
529 var contentEnd = i
530 if contentEnd > lineStart, scalars[scalars.index(before: i)] == "\r" {
531 contentEnd = scalars.index(before: i)
532 }
533 let next = scalars.index(after: i)
534 lines.append(RawLine(content: text[lineStart..<contentEnd], ending: text[contentEnd..<next]))
535 lineStart = next
536 i = next
537 } else {
538 i = scalars.index(after: i)
539 }
540 }
541 if lineStart != scalars.endIndex {
542 lines.append(RawLine(content: text[lineStart...], ending: ""))
543 }
544 return lines
545}
546
547enum LineClass: Equatable {
548 case blank
549 case heading(level: Int)
550 case blockBegin(name: String)
551 case blockEnd(name: String)
552 case dynamicBegin
553 case dynamicEnd
554 case drawerBegin(name: String)
555 case drawerEnd
556 case keyword(key: String)
557 case comment
558 case fixedWidth
559 case horizontalRule
560 case tableRow
561 case footnoteDefinition
562 case clock
563 case planning
564 case listItem
565 case plain
566}
567
568struct ClassifiedLine {
569 let cls: LineClass
570 /// Column of the first non-blank character, with tabs advancing to the next multiple of 8.
571 let indent: Int
572}
573
574func classifyLine(_ line: Substring) -> ClassifiedLine {
575 var column = 0
576 var rest = line
577 while let c = rest.first, c == " " || c == "\t" {
578 column = c == "\t" ? (column / 8 + 1) * 8 : column + 1
579 rest = rest.dropFirst()
580 }
581 if rest.isEmpty { return ClassifiedLine(cls: .blank, indent: column) }
582 return ClassifiedLine(cls: lineClass(rest, columnZero: column == 0), indent: column)
583}
584
585private func lineClass(_ rest: Substring, columnZero: Bool) -> LineClass {
586 let trimmed = rest.trimmingTrailingWhitespace
587
588 if columnZero, rest.first == "*" {
589 let stars = rest.prefix { $0 == "*" }
590 let after = rest.dropFirst(stars.count)
591 if after.isEmpty || after.first == " " || after.first == "\t" {
592 return .heading(level: stars.count)
593 }
594 }
595
596 if rest.hasPrefix("#+") {
597 let lower = trimmed.lowercased()
598 if lower.hasPrefix("#+begin_") {
599 let name = lower.dropFirst(8).prefix { !$0.isWhitespace }
600 if !name.isEmpty { return .blockBegin(name: String(name)) }
601 }
602 if lower.hasPrefix("#+end_") {
603 let name = lower.dropFirst(6)
604 if !name.isEmpty, !name.contains(where: \.isWhitespace) { return .blockEnd(name: String(name)) }
605 }
606 if lower.hasPrefix("#+begin:") { return .dynamicBegin }
607 if lower == "#+end:" { return .dynamicEnd }
608 if let colon = rest.firstIndex(of: ":") {
609 let key = rest[rest.index(rest.startIndex, offsetBy: 2)..<colon]
610 if !key.isEmpty, !key.contains(where: \.isWhitespace) { return .keyword(key: key.uppercased()) }
611 }
612 }
613
614 if trimmed == "#" || rest.hasPrefix("# ") || rest.hasPrefix("#\t") { return .comment }
615
616 if rest.first == ":" {
617 if trimmed == ":" || rest.hasPrefix(": ") || rest.hasPrefix(":\t") { return .fixedWidth }
618 if trimmed.uppercased() == ":END:" { return .drawerEnd }
619 if trimmed.count >= 3, trimmed.last == ":" {
620 let name = trimmed.dropFirst().dropLast()
621 if name.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) {
622 return .drawerBegin(name: String(name))
623 }
624 }
625 }
626
627 if rest.first == "|" { return .tableRow }
628 if trimmed.count >= 5, trimmed.allSatisfy({ $0 == "-" }) { return .horizontalRule }
629
630 if columnZero, rest.hasPrefix("[fn:"), let close = rest.firstIndex(of: "]"),
631 close > rest.index(rest.startIndex, offsetBy: 4) {
632 return .footnoteDefinition
633 }
634
635 if rest.hasPrefix("CLOCK:") { return .clock }
636 if rest.hasPrefix("SCHEDULED:") || rest.hasPrefix("DEADLINE:") || rest.hasPrefix("CLOSED:") { return .planning }
637 if isListBullet(rest, indented: !columnZero) { return .listItem }
638 return .plain
639}
640
641/// `-`, `+`, `*` (indented only), `1.` or `1)`, followed by whitespace or end of line.
642/// Alphabetical bullets are off, as in org's default.
643private func isListBullet(_ rest: Substring, indented: Bool) -> Bool {
644 guard let first = rest.first else { return false }
645 let afterBullet: Substring
646 if first == "-" || first == "+" || (first == "*" && indented) {
647 afterBullet = rest.dropFirst()
648 } else if first.isASCII, first.isNumber {
649 let digits = rest.prefix { $0.isASCII && $0.isNumber }
650 let tail = rest.dropFirst(digits.count)
651 guard let separator = tail.first, separator == "." || separator == ")" else { return false }
652 afterBullet = tail.dropFirst()
653 } else {
654 return false
655 }
656 return afterBullet.isEmpty || afterBullet.first == " " || afterBullet.first == "\t"
657}
658
659extension Substring {
660 var trimmingTrailingWhitespace: Substring {
661 var s = self
662 while let last = s.last, last == " " || last == "\t" { s = s.dropLast() }
663 return s
664 }
665}
666```
667
668- [x] **Step 4: Run tests to verify they pass**
669
670Run: `swift test --filter LinesTests`
671Expected: all pass.
672
673- [x] **Step 5: Commit**
674
675```bash
676git add Sources Tests
677git commit -m "Add line splitting and classification"
678```
679
680---
681
682### Task 4: In-buffer settings
683
684**Files:**
685- Create: `Sources/OrgCore/Parser/Settings.swift`
686- Test: `Tests/OrgCoreTests/SettingsTests.swift`
687
688**Interfaces:**
689- Consumes: `RawLine`, `ClassifiedLine`, `LineClass` (Task 3).
690- Produces: `TodoKeyword`, `TodoSequence`, `Priorities`, `OrgSettings` with `.default`, `todoKeywordNames: Set<String>`, `isDone(_:)`; internal `SettingsScanner.scan(lines:info:blockEnds:defaults:) -> OrgSettings`, where `blockEnds: [Int: Int]` maps a block's begin line index to its end line index.
691
692- [x] **Step 1: Write the failing tests**
693
694```swift
695import Testing
696@testable import OrgCore
697
698struct SettingsTests {
699 func scan(_ text: String, blockEnds: [Int: Int] = [:]) -> OrgSettings {
700 let lines = splitRawLines(text)
701 let info = lines.map { classifyLine($0.content) }
702 return SettingsScanner.scan(lines: lines, info: info, blockEnds: blockEnds, defaults: .default)
703 }
704
705 @Test func defaultsWithoutKeywords() {
706 let settings = scan("* TODO a\n")
707 #expect(settings.todoKeywordNames == ["TODO", "DONE"])
708 #expect(settings.isDone("DONE"))
709 }
710
711 @Test func fileKeywordsReplaceDefaults() {
712 let settings = scan("#+TODO: NEXT(n) WAIT(w@/!) | DONE(d!) CANCELED(c@)\n")
713 #expect(settings.todoKeywordNames == ["NEXT", "WAIT", "DONE", "CANCELED"])
714 let sequence = settings.todoSequences[0]
715 #expect(sequence.active.map(\.name) == ["NEXT", "WAIT"])
716 #expect(sequence.done.map(\.name) == ["DONE", "CANCELED"])
717 #expect(sequence.active[1] == TodoKeyword(name: "WAIT", fastKey: "w", logOnEnter: "@", logOnLeave: "!"))
718 #expect(sequence.done[0] == TodoKeyword(name: "DONE", fastKey: "d", logOnEnter: "!", logOnLeave: nil))
719 }
720
721 @Test func lastWordIsDoneWithoutSeparator() {
722 let settings = scan("#+SEQ_TODO: A B C\n")
723 #expect(settings.todoSequences[0].active.map(\.name) == ["A", "B"])
724 #expect(settings.todoSequences[0].done.map(\.name) == ["C"])
725 }
726
727 @Test func severalLinesMakeSeveralSequences() {
728 let settings = scan("#+TODO: A | B\n#+TYP_TODO: X | Y\n")
729 #expect(settings.todoSequences.count == 2)
730 #expect(settings.todoSequences[1].kind == .type)
731 }
732
733 @Test func keywordsInsideBlocksAreIgnored() {
734 let text = "#+begin_example\n#+TODO: X | Y\n#+end_example\n"
735 #expect(scan(text, blockEnds: [0: 2]).todoKeywordNames == ["TODO", "DONE"])
736 }
737
738 @Test func priorities() {
739 #expect(scan("#+PRIORITIES: 1 10 5\n").priorities == Priorities(highest: "1", lowest: "10", default: "5"))
740 #expect(scan("").priorities == Priorities(highest: "A", lowest: "C", default: "B"))
741 }
742}
743```
744
745- [x] **Step 2: Run tests to verify they fail**
746
747Run: `swift test --filter SettingsTests`
748Expected: build failure, `cannot find 'SettingsScanner' in scope`.
749
750- [x] **Step 3: Implement**
751
752```swift
753public struct TodoKeyword: Sendable, Hashable {
754 public var name: String
755 public var fastKey: Character?
756 /// Logging flag when entering the state (`!` or `@`), from `NAME(k!/@)`.
757 public var logOnEnter: String?
758 /// Logging flag when leaving the state.
759 public var logOnLeave: String?
760
761 public init(name: String, fastKey: Character? = nil, logOnEnter: String? = nil, logOnLeave: String? = nil) {
762 self.name = name
763 self.fastKey = fastKey
764 self.logOnEnter = logOnEnter
765 self.logOnLeave = logOnLeave
766 }
767}
768
769public struct TodoSequence: Sendable, Equatable {
770 public enum Kind: Sendable, Equatable { case sequence, type }
771
772 public var kind: Kind
773 public var active: [TodoKeyword]
774 public var done: [TodoKeyword]
775
776 public init(kind: Kind, active: [TodoKeyword], done: [TodoKeyword]) {
777 self.kind = kind
778 self.active = active
779 self.done = done
780 }
781}
782
783public struct Priorities: Sendable, Equatable {
784 public var highest: String
785 public var lowest: String
786 public var `default`: String
787
788 public init(highest: String, lowest: String, default: String) {
789 self.highest = highest
790 self.lowest = lowest
791 self.default = `default`
792 }
793}
794
795public struct OrgSettings: Sendable, Equatable {
796 public var todoSequences: [TodoSequence]
797 public var priorities: Priorities
798
799 public init(todoSequences: [TodoSequence], priorities: Priorities) {
800 self.todoSequences = todoSequences
801 self.priorities = priorities
802 }
803
804 public static let `default` = OrgSettings(
805 todoSequences: [TodoSequence(kind: .sequence, active: [TodoKeyword(name: "TODO")], done: [TodoKeyword(name: "DONE")])],
806 priorities: Priorities(highest: "A", lowest: "C", default: "B")
807 )
808
809 public var todoKeywordNames: Set<String> {
810 Set(todoSequences.flatMap { ($0.active + $0.done).map(\.name) })
811 }
812
813 public func isDone(_ name: String) -> Bool {
814 todoSequences.contains { $0.done.contains { $0.name == name } }
815 }
816}
817
818enum SettingsScanner {
819 /// Reads `#+TODO`, `#+SEQ_TODO`, `#+TYP_TODO` and `#+PRIORITIES` outside blocks. Any TODO
820 /// line replaces the default sequences, as in org.
821 static func scan(lines: [RawLine], info: [ClassifiedLine], blockEnds: [Int: Int], defaults: OrgSettings) -> OrgSettings {
822 var sequences: [TodoSequence] = []
823 var priorities = defaults.priorities
824 var k = 0
825 while k < lines.count {
826 switch info[k].cls {
827 case .blockBegin, .dynamicBegin:
828 if let end = blockEnds[k] { k = end }
829 case .keyword(let key):
830 let value = keywordValue(lines[k].content)
831 switch key {
832 case "TODO", "SEQ_TODO":
833 if let s = todoSequence(value, kind: .sequence) { sequences.append(s) }
834 case "TYP_TODO":
835 if let s = todoSequence(value, kind: .type) { sequences.append(s) }
836 case "PRIORITIES":
837 let words = value.split(whereSeparator: \.isWhitespace)
838 if words.count == 3 {
839 priorities = Priorities(highest: String(words[0]), lowest: String(words[1]), default: String(words[2]))
840 }
841 default:
842 break
843 }
844 default:
845 break
846 }
847 k += 1
848 }
849 return OrgSettings(todoSequences: sequences.isEmpty ? defaults.todoSequences : sequences, priorities: priorities)
850 }
851
852 static func keywordValue(_ line: Substring) -> Substring {
853 guard let colon = line.firstIndex(of: ":") else { return "" }
854 return line[line.index(after: colon)...]
855 }
856
857 static func todoSequence(_ value: Substring, kind: TodoSequence.Kind) -> TodoSequence? {
858 let words = value.split(whereSeparator: \.isWhitespace)
859 guard !words.isEmpty else { return nil }
860 if let bar = words.firstIndex(of: "|") {
861 return TodoSequence(kind: kind, active: words[..<bar].map(todoKeyword), done: words[(bar + 1)...].map(todoKeyword))
862 }
863 return TodoSequence(kind: kind, active: words.dropLast().map(todoKeyword), done: [todoKeyword(words.last!)])
864 }
865
866 /// `NAME`, or `NAME(spec)` where spec is an optional fast key followed by `enter/leave`
867 /// logging flags.
868 static func todoKeyword(_ word: Substring) -> TodoKeyword {
869 guard let open = word.firstIndex(of: "("), word.last == ")" else { return TodoKeyword(name: String(word)) }
870 var spec = word[word.index(after: open)..<word.index(before: word.endIndex)]
871 var fastKey: Character?
872 if let first = spec.first, first != "!", first != "@", first != "/" {
873 fastKey = first
874 spec = spec.dropFirst()
875 }
876 let parts = spec.split(separator: "/", omittingEmptySubsequences: false)
877 let enter = parts.first.flatMap { $0.isEmpty ? nil : String($0) }
878 let leave = parts.count > 1 && !parts[1].isEmpty ? String(parts[1]) : nil
879 return TodoKeyword(name: String(word[..<open]), fastKey: fastKey, logOnEnter: enter, logOnLeave: leave)
880 }
881}
882```
883
884- [x] **Step 4: Run tests to verify they pass**
885
886Run: `swift test --filter SettingsTests`
887Expected: all pass.
888
889- [x] **Step 5: Commit**
890
891```bash
892git add Sources Tests
893git commit -m "Add in-buffer TODO and priority settings"
894```
895
896---
897
898### Task 5: Parser — document, sections and headings
899
900**Files:**
901- Create: `Sources/OrgCore/Parser/Parser.swift`
902- Modify: `Sources/OrgCore/Syntax/SyntaxNode.swift` (append `OrgTree`)
903- Test: `Tests/OrgCoreTests/ParserSectionTests.swift`
904
905**Interfaces:**
906- Consumes: Tasks 2–4.
907- Produces: `public enum OrgParser { static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree }`; `public struct OrgTree { green: GreenNode; settings: OrgSettings; root: SyntaxNode; text: String }`; internal `struct Parser` with `element(limit:floor:)` that Task 6 fills in. In this task `element` handles every class as a paragraph or a blank line.
908
909- [x] **Step 1: Write the failing tests**
910
911```swift
912import Testing
913@testable import OrgCore
914
915func nodeKinds(_ text: String) -> [SyntaxKind] {
916 OrgParser.parse(text).root.descendants().map(\.kind)
917}
918
919func tokens(of kind: SyntaxKind, in text: String) -> [SyntaxToken] {
920 OrgParser.parse(text).root.descendants().filter { $0.kind == kind }.flatMap(\.tokens)
921}
922
923struct ParserSectionTests {
924 @Test func emptyDocument() {
925 let tree = OrgParser.parse("")
926 #expect(tree.text == "")
927 #expect(nodeKinds("") == [.document])
928 }
929
930 @Test func zerothSectionHoldsPreamble() {
931 #expect(nodeKinds("text\n* a\n") == [.document, .zerothSection, .paragraph, .section, .heading])
932 }
933
934 @Test func sectionsNestByLevel() {
935 let text = "* a\n** b\n*** c\n** d\n* e\n"
936 let root = OrgParser.parse(text).root
937 let top = root.children
938 #expect(top.map(\.kind) == [.section, .section])
939 #expect(top[0].children.map(\.kind) == [.heading, .section, .section])
940 #expect(top[0].children[1].children.map(\.kind) == [.heading, .section])
941 }
942
943 @Test func headingTokens() {
944 let parts = tokens(of: .heading, in: "** TODO [#A] Write the plan :work:urgent: \n")
945 #expect(parts.map(\.kind) == [.stars, .whitespace, .todoKeyword, .whitespace, .priority, .whitespace, .title, .whitespace, .tags, .whitespace, .newline])
946 #expect(parts.first { $0.kind == .tags }?.text == ":work:urgent:")
947 #expect(parts.first { $0.kind == .title }?.text == "Write the plan")
948 }
949
950 @Test func todoKeywordsComeFromSettings() {
951 let text = "#+TODO: NEXT | DONE\n* NEXT a\n* TODO b\n"
952 let todo = tokens(of: .heading, in: text).filter { $0.kind == .todoKeyword }.map(\.text)
953 #expect(todo == ["NEXT"])
954 }
955
956 @Test func priorityNeedsValidValueAndSpace() {
957 #expect(tokens(of: .heading, in: "* [#B] x\n").contains { $0.kind == .priority })
958 #expect(tokens(of: .heading, in: "* [#10] x\n").contains { $0.kind == .priority })
959 #expect(!tokens(of: .heading, in: "* [#AB] x\n").contains { $0.kind == .priority })
960 #expect(!tokens(of: .heading, in: "* [#A]x\n").contains { $0.kind == .priority })
961 }
962
963 @Test func tagsNeedValidCharacters() {
964 #expect(tokens(of: .heading, in: "* a :b@c_1:\n").contains { $0.kind == .tags })
965 #expect(!tokens(of: .heading, in: "* a :b c:\n").contains { $0.kind == .tags })
966 #expect(!tokens(of: .heading, in: "* a :b:c\n").contains { $0.kind == .tags })
967 }
968
969 @Test func headingWithoutNewlineAtEnd() {
970 #expect(OrgParser.parse("* a").text == "* a")
971 }
972
973 @Test(arguments: ["* a\n", "*\n", "* TODO\n", "text\r\n* a\r\n** b\r\n", "\n\n* a\n\n"])
974 func roundTrip(text: String) {
975 #expect(OrgParser.parse(text).text == text)
976 }
977}
978```
979
980- [x] **Step 2: Run tests to verify they fail**
981
982Run: `swift test --filter ParserSectionTests`
983Expected: build failure, `cannot find 'OrgParser' in scope`.
984
985- [x] **Step 3: Append `OrgTree` to `SyntaxNode.swift`**
986
987```swift
988public struct OrgTree: Sendable {
989 public let green: GreenNode
990 public let settings: OrgSettings
991
992 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) }
993 public var text: String { green.text }
994}
995```
996
997- [x] **Step 4: Implement `Parser.swift`**
998
999```swift
1000public enum OrgParser {
1001 public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree {
1002 var parser = Parser(text: text, defaults: defaults)
1003 return parser.run()
1004 }
1005}
1006
1007struct Parser {
1008 let lines: [RawLine]
1009 let info: [ClassifiedLine]
1010 /// Begin line → end line, for blocks, dynamic blocks and drawers that are closed before the
1011 /// next heading.
1012 let blockEnds: [Int: Int]
1013 let settings: OrgSettings
1014 var builder = GreenBuilder()
1015 var i = 0
1016
1017 init(text: String, defaults: OrgSettings) {
1018 lines = splitRawLines(text)
1019 info = lines.map { classifyLine($0.content) }
1020 blockEnds = Parser.matchEnds(info)
1021 settings = SettingsScanner.scan(lines: lines, info: info, blockEnds: blockEnds, defaults: defaults)
1022 }
1023
1024 static func matchEnds(_ info: [ClassifiedLine]) -> [Int: Int] {
1025 var ends: [Int: Int] = [:]
1026 var k = 0
1027 while k < info.count {
1028 let isEnd: ((LineClass) -> Bool)?
1029 switch info[k].cls {
1030 case .blockBegin(let name): isEnd = { $0 == .blockEnd(name: name) }
1031 case .dynamicBegin: isEnd = { $0 == .dynamicEnd }
1032 case .drawerBegin: isEnd = { $0 == .drawerEnd }
1033 default: isEnd = nil
1034 }
1035 if let isEnd {
1036 var j = k + 1
1037 while j < info.count {
1038 if case .heading = info[j].cls { break }
1039 if isEnd(info[j].cls) { ends[k] = j; break }
1040 j += 1
1041 }
1042 // Block contents are verbatim, so nothing inside starts another element.
1043 if let end = ends[k], !isDrawer(info[k].cls) { k = end }
1044 }
1045 k += 1
1046 }
1047 return ends
1048 }
1049
1050 static func isDrawer(_ cls: LineClass) -> Bool {
1051 if case .drawerBegin = cls { return true }
1052 return false
1053 }
1054
1055 mutating func run() -> OrgTree {
1056 builder.start(.document)
1057 if !lines.isEmpty, !isHeading(0) {
1058 builder.start(.zerothSection)
1059 parseContent(limit: lines.count)
1060 builder.finish()
1061 }
1062 while i < lines.count, case .heading(let level) = info[i].cls {
1063 parseSection(level: level)
1064 }
1065 builder.finish()
1066 return OrgTree(green: builder.build(), settings: settings)
1067 }
1068
1069 func isHeading(_ k: Int) -> Bool {
1070 if case .heading = info[k].cls { return true }
1071 return false
1072 }
1073
1074 mutating func parseSection(level: Int) {
1075 builder.start(.section)
1076 headingLine(lines[i])
1077 i += 1
1078 if i < lines.count, info[i].cls == .planning {
1079 builder.start(.planning)
1080 line(i)
1081 i += 1
1082 builder.finish()
1083 }
1084 if i < lines.count, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES",
1085 let end = blockEnds[i] {
1086 propertyDrawer(end: end)
1087 }
1088 parseContent(limit: lines.count)
1089 while i < lines.count, case .heading(let child) = info[i].cls, child > level {
1090 parseSection(level: child)
1091 }
1092 builder.finish()
1093 }
1094
1095 mutating func propertyDrawer(end: Int) {
1096 builder.start(.propertyDrawer)
1097 line(i)
1098 i += 1
1099 while i < end {
1100 if info[i].cls == .blank {
1101 line(i)
1102 } else {
1103 builder.start(.nodeProperty)
1104 line(i)
1105 builder.finish()
1106 }
1107 i += 1
1108 }
1109 line(i)
1110 i += 1
1111 builder.finish()
1112 }
1113
1114 /// Elements until `limit` or the next heading.
1115 mutating func parseContent(limit: Int) {
1116 while i < limit, !isHeading(i) {
1117 element(limit: limit, floor: nil)
1118 }
1119 }
1120
1121 /// One element starting at `i`. `floor` is the indent of the enclosing list item, if any:
1122 /// non-blank lines at or left of it end the element.
1123 mutating func element(limit: Int, floor: Int?) {
1124 if info[i].cls == .blank {
1125 line(i)
1126 i += 1
1127 } else {
1128 paragraph(limit: limit, floor: floor)
1129 }
1130 }
1131
1132 mutating func paragraph(limit: Int, floor: Int?) {
1133 builder.start(.paragraph)
1134 line(i)
1135 i += 1
1136 while i < limit, within(floor, i), continuesParagraph(i) {
1137 line(i)
1138 i += 1
1139 }
1140 builder.finish()
1141 }
1142
1143 func continuesParagraph(_ k: Int) -> Bool {
1144 switch info[k].cls {
1145 case .blank, .heading: return false
1146 default: return true
1147 }
1148 }
1149
1150 func within(_ floor: Int?, _ k: Int) -> Bool {
1151 guard let floor else { return true }
1152 return info[k].indent > floor
1153 }
1154
1155 // MARK: - Tokens
1156
1157 /// A whole line as leading whitespace, content and line ending.
1158 mutating func line(_ k: Int) {
1159 let content = lines[k].content
1160 let rest = whitespace(content)
1161 builder.token(.text, rest)
1162 builder.token(.newline, lines[k].ending)
1163 }
1164
1165 mutating func whitespace(_ s: Substring) -> Substring {
1166 let ws = s.prefix { $0 == " " || $0 == "\t" }
1167 builder.token(.whitespace, ws)
1168 return s.dropFirst(ws.count)
1169 }
1170
1171 mutating func headingLine(_ raw: RawLine) {
1172 builder.start(.heading)
1173 var rest = raw.content
1174 let stars = rest.prefix { $0 == "*" }
1175 builder.token(.stars, stars)
1176 rest = whitespace(rest.dropFirst(stars.count))
1177
1178 let word = rest.prefix { $0 != " " && $0 != "\t" }
1179 if !word.isEmpty, settings.todoKeywordNames.contains(String(word)) {
1180 builder.token(.todoKeyword, word)
1181 rest = whitespace(rest.dropFirst(word.count))
1182 }
1183
1184 if let cookie = priorityCookie(rest) {
1185 builder.token(.priority, cookie)
1186 rest = whitespace(rest.dropFirst(cookie.count))
1187 }
1188
1189 let parts = splitTags(rest)
1190 builder.token(.title, parts.title)
1191 builder.token(.whitespace, parts.gap)
1192 builder.token(.tags, parts.tags)
1193 builder.token(.whitespace, parts.trailing)
1194 builder.token(.newline, raw.ending)
1195 builder.finish()
1196 }
1197
1198 /// `[#A]` or `[#10]`, followed by whitespace or end of line.
1199 func priorityCookie(_ s: Substring) -> Substring? {
1200 guard s.hasPrefix("[#"), let close = s.firstIndex(of: "]") else { return nil }
1201 let value = s[s.index(s.startIndex, offsetBy: 2)..<close]
1202 let valid = (value.count == 1 && value.first!.isLetter && value.first!.isUppercase)
1203 || (!value.isEmpty && value.allSatisfy { $0.isASCII && $0.isNumber })
1204 guard valid else { return nil }
1205 let after = s[s.index(after: close)...]
1206 guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
1207 return s[...close]
1208 }
1209
1210 func splitTags(_ s: Substring) -> (title: Substring, gap: Substring, tags: Substring, trailing: Substring) {
1211 let trimmed = s.trimmingTrailingWhitespace
1212 let trailing = s[trimmed.endIndex...]
1213 let none = (title: trimmed, gap: Substring(), tags: Substring(), trailing: trailing)
1214 guard trimmed.last == ":" else { return none }
1215 let tagStart = trimmed.lastIndex { $0 == " " || $0 == "\t" }.map { trimmed.index(after: $0) } ?? trimmed.startIndex
1216 let tags = trimmed[tagStart...]
1217 guard tags.count >= 3, tags.first == ":", isTagString(tags) else { return none }
1218 let before = trimmed[..<tagStart]
1219 let title = before.trimmingTrailingWhitespace
1220 return (title, before[title.endIndex...], tags, trailing)
1221 }
1222
1223 func isTagString(_ tags: Substring) -> Bool {
1224 tags.dropFirst().dropLast().split(separator: ":", omittingEmptySubsequences: false).allSatisfy { tag in
1225 !tag.isEmpty && tag.allSatisfy { $0.isLetter || $0.isNumber || "_@#%".contains($0) }
1226 }
1227 }
1228}
1229```
1230
1231- [x] **Step 5: Run tests to verify they pass**
1232
1233Run: `swift test --filter ParserSectionTests`
1234Expected: all pass.
1235
1236- [x] **Step 6: Commit**
1237
1238```bash
1239git add Sources Tests
1240git commit -m "Parse document, sections and headings"
1241```
1242
1243---
1244
1245### Task 6: Parser — elements
1246
1247**Files:**
1248- Modify: `Sources/OrgCore/Parser/Parser.swift` (replace `element`, `continuesParagraph`; add `list`, `item`, `table`, `consecutive`, `footnoteDefinition`)
1249- Test: `Tests/OrgCoreTests/ParserElementTests.swift`
1250
1251**Interfaces:**
1252- Consumes: Task 5's `Parser`.
1253- Produces: nodes `block`, `dynamicBlock`, `drawer`, `keyword`, `affiliatedKeyword`, `comment`, `fixedWidth`, `horizontalRule`, `table`/`tableRow`/`tableFormula`, `footnoteDefinition`, `clock`, `plainList`/`item`, `planning` (after heading only), `propertyDrawer`/`nodeProperty`.
1254
1255- [x] **Step 1: Write the failing tests**
1256
1257```swift
1258import Testing
1259@testable import OrgCore
1260
1261func childKinds(_ text: String) -> [SyntaxKind] {
1262 let root = OrgParser.parse(text).root
1263 let container = root.children.first { $0.kind == .zerothSection || $0.kind == .section }!
1264 return container.children.map(\.kind)
1265}
1266
1267struct ParserElementTests {
1268 @Test func planningAndPropertiesFollowHeading() {
1269 let text = "* a\nSCHEDULED: <2026-10-04 Sun>\n:PROPERTIES:\n:ID: x\n:END:\nbody\n"
1270 #expect(childKinds(text) == [.heading, .planning, .propertyDrawer, .paragraph])
1271 }
1272
1273 @Test func planningElsewhereIsText() {
1274 #expect(childKinds("SCHEDULED: <2026-10-04 Sun>\n") == [.paragraph])
1275 }
1276
1277 @Test func blocks() {
1278 #expect(childKinds("#+begin_src sh\n,* escaped\n:END:\n#+end_src\nafter\n") == [.block, .paragraph])
1279 #expect(childKinds("#+BEGIN: clocktable\n#+END:\n") == [.dynamicBlock])
1280 }
1281
1282 @Test func headingsEndBlocks() {
1283 #expect(childKinds("#+begin_src sh\n* heading\n#+end_src\n") == [.paragraph])
1284 }
1285
1286 @Test func unclosedBlockIsParagraph() {
1287 #expect(childKinds("#+begin_src sh\necho\n") == [.paragraph])
1288 }
1289
1290 @Test func drawersHoldElements() {
1291 let root = OrgParser.parse(":LOGBOOK:\nCLOCK: [2026-10-04 Sun 10:00]\n:END:\n").root
1292 let drawer = root.children[0].children[0]
1293 #expect(drawer.kind == .drawer)
1294 #expect(drawer.children.map(\.kind) == [.clock])
1295 }
1296
1297 @Test func keywords() {
1298 #expect(childKinds("#+TITLE: x\n#+NAME: t\n#+ATTR_HTML: :width 10\n") == [.keyword, .affiliatedKeyword, .affiliatedKeyword])
1299 }
1300
1301 @Test func commentsAndFixedWidthGroup() {
1302 #expect(childKinds("# a\n# b\n: c\n: d\n-----\n") == [.comment, .fixedWidth, .horizontalRule])
1303 }
1304
1305 @Test func tableWithFormulas() {
1306 let root = OrgParser.parse("| a |\n|---|\n| 1 |\n#+TBLFM: $1=2\n#+TBLFM: $1=3\n").root
1307 let table = root.children[0].children[0]
1308 #expect(table.kind == .table)
1309 #expect(table.children.map(\.kind) == [.tableRow, .tableRow, .tableRow, .tableFormula, .tableFormula])
1310 }
1311
1312 @Test func footnoteDefinition() {
1313 #expect(childKinds("[fn:1] note\ncontinued\n\nafter\n") == [.footnoteDefinition, .paragraph])
1314 }
1315
1316 @Test func listsNestByIndent() {
1317 let text = "- a\n more\n - b\n- c\n\nafter\n"
1318 let root = OrgParser.parse(text).root
1319 let list = root.children[0].children[0]
1320 #expect(list.kind == .plainList)
1321 #expect(list.children.map(\.kind) == [.item, .item])
1322 #expect(list.children[0].children.map(\.kind) == [.paragraph, .plainList])
1323 #expect(childKinds(text) == [.plainList, .paragraph])
1324 }
1325
1326 @Test func twoBlankLinesEndAList() {
1327 #expect(childKinds("- a\n\n\n- b\n") == [.plainList, .plainList])
1328 #expect(childKinds("- a\n\n- b\n") == [.plainList])
1329 }
1330
1331 @Test func paragraphStopsAtElementStart() {
1332 #expect(childKinds("text\n| a |\n") == [.paragraph, .table])
1333 #expect(childKinds("text\n#+begin_quote\nq\n#+end_quote\n") == [.paragraph, .block])
1334 #expect(childKinds("text\n#+begin_quote\nq\n") == [.paragraph])
1335 }
1336}
1337```
1338
1339- [x] **Step 2: Run tests to verify they fail**
1340
1341Run: `swift test --filter ParserElementTests`
1342Expected: failures; every element parses as a paragraph.
1343
1344- [x] **Step 3: Replace `element` and `continuesParagraph`, add the element parsers**
1345
1346```swift
1347 static let affiliatedKeys: Set<String> = ["NAME", "CAPTION", "RESULTS", "HEADER", "PLOT"]
1348
1349 mutating func element(limit: Int, floor: Int?) {
1350 switch info[i].cls {
1351 case .blank:
1352 line(i)
1353 i += 1
1354 case .blockBegin, .dynamicBegin:
1355 if let end = blockEnds[i], end < limit {
1356 builder.start(info[i].cls == .dynamicBegin ? .dynamicBlock : .block)
1357 while i <= end {
1358 line(i)
1359 i += 1
1360 }
1361 builder.finish()
1362 } else {
1363 paragraph(limit: limit, floor: floor)
1364 }
1365 case .drawerBegin:
1366 if let end = blockEnds[i], end < limit {
1367 builder.start(.drawer)
1368 line(i)
1369 i += 1
1370 parseContent(limit: end)
1371 line(i)
1372 i += 1
1373 builder.finish()
1374 } else {
1375 paragraph(limit: limit, floor: floor)
1376 }
1377 case .keyword(let key):
1378 let affiliated = Self.affiliatedKeys.contains(key) || key.hasPrefix("ATTR_")
1379 single(affiliated ? .affiliatedKeyword : .keyword)
1380 case .comment:
1381 consecutive(.comment, limit: limit, floor: floor) { $0 == .comment }
1382 case .fixedWidth:
1383 consecutive(.fixedWidth, limit: limit, floor: floor) { $0 == .fixedWidth }
1384 case .horizontalRule:
1385 single(.horizontalRule)
1386 case .clock:
1387 single(.clock)
1388 case .tableRow:
1389 table(limit: limit, floor: floor)
1390 case .footnoteDefinition:
1391 footnoteDefinition(limit: limit)
1392 case .listItem:
1393 list(limit: limit, floor: floor)
1394 default:
1395 paragraph(limit: limit, floor: floor)
1396 }
1397 }
1398
1399 /// Lines that don't start an element of their own.
1400 func continuesParagraph(_ k: Int) -> Bool {
1401 switch info[k].cls {
1402 case .plain, .planning, .blockEnd, .dynamicEnd, .drawerEnd:
1403 return true
1404 case .blockBegin, .dynamicBegin, .drawerBegin:
1405 return blockEnds[k] == nil
1406 default:
1407 return false
1408 }
1409 }
1410
1411 mutating func single(_ kind: SyntaxKind) {
1412 builder.start(kind)
1413 line(i)
1414 i += 1
1415 builder.finish()
1416 }
1417
1418 mutating func consecutive(_ kind: SyntaxKind, limit: Int, floor: Int?, matching: (LineClass) -> Bool) {
1419 builder.start(kind)
1420 repeat {
1421 line(i)
1422 i += 1
1423 } while i < limit && matching(info[i].cls) && within(floor, i)
1424 builder.finish()
1425 }
1426
1427 mutating func table(limit: Int, floor: Int?) {
1428 builder.start(.table)
1429 while i < limit, info[i].cls == .tableRow, within(floor, i) {
1430 single(.tableRow)
1431 }
1432 while i < limit, info[i].cls == .keyword(key: "TBLFM"), within(floor, i) {
1433 single(.tableFormula)
1434 }
1435 builder.finish()
1436 }
1437
1438 mutating func footnoteDefinition(limit: Int) {
1439 builder.start(.footnoteDefinition)
1440 line(i)
1441 i += 1
1442 while i < limit, info[i].cls == .plain {
1443 line(i)
1444 i += 1
1445 }
1446 builder.finish()
1447 }
1448
1449 mutating func list(limit: Int, floor: Int?) {
1450 let base = info[i].indent
1451 builder.start(.plainList)
1452 while i < limit, info[i].cls == .listItem, info[i].indent == base, within(floor, i) {
1453 item(base: base, limit: limit)
1454 }
1455 builder.finish()
1456 }
1457
1458 /// An item's first line, then everything indented past its bullet. One blank line stays
1459 /// inside the item when the item or list continues after it; two end the list.
1460 mutating func item(base: Int, limit: Int) {
1461 builder.start(.item)
1462 line(i)
1463 i += 1
1464 while i < limit, !isHeading(i) {
1465 if info[i].cls == .blank {
1466 var j = i
1467 while j < limit, info[j].cls == .blank { j += 1 }
1468 guard j - i < 2, j < limit else { break }
1469 let continuesItem = info[j].indent > base
1470 let nextSibling = info[j].cls == .listItem && info[j].indent == base
1471 guard continuesItem || nextSibling else { break }
1472 line(i)
1473 i += 1
1474 if nextSibling { break }
1475 continue
1476 }
1477 guard info[i].indent > base else { break }
1478 element(limit: limit, floor: base)
1479 }
1480 builder.finish()
1481 }
1482```
1483
1484- [x] **Step 4: Run all tests**
1485
1486Run: `swift test`
1487Expected: all pass, including Task 5's tests.
1488
1489- [x] **Step 5: Commit**
1490
1491```bash
1492git add Sources Tests
1493git commit -m "Parse block-level elements"
1494```
1495
1496---
1497
1498### Task 7: Round-trip fuzz, encoding fixtures and corpus test
1499
1500**Files:**
1501- Test: `Tests/OrgCoreTests/RoundTripTests.swift`
1502
1503**Interfaces:**
1504- Consumes: `SourceText`, `OrgParser`, `SyntaxNode`.
1505- Produces: a seeded fuzz test (2,000 documents), a structural invariant check, and an opt-in corpus test driven by `ORGSTAR_CORPUS`.
1506
1507- [x] **Step 1: Write the tests**
1508
1509```swift
1510import Foundation
1511import Testing
1512@testable import OrgCore
1513
1514/// SplitMix64, so failures reproduce from the seed.
1515struct SeededGenerator: RandomNumberGenerator {
1516 var state: UInt64
1517 mutating func next() -> UInt64 {
1518 state &+= 0x9E37_79B9_7F4A_7C15
1519 var z = state
1520 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
1521 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
1522 return z ^ (z >> 31)
1523 }
1524}
1525
1526let fragments = [
1527 "* ", "** TODO [#A] title :a:b:", "*** DONE", "#+TODO: NEXT | DONE", "#+begin_src sh", "#+end_src",
1528 "#+BEGIN_QUOTE", "#+end_quote", "#+BEGIN: clocktable", "#+END:", ":PROPERTIES:", ":ID: x", ":END:",
1529 ":LOGBOOK:", "CLOCK: [2026-10-04 Sun 10:00]", "SCHEDULED: <2026-10-04 Sun>", "- item", " - nested",
1530 "\t+ tab", "1. one", "| a | b |", "|---+---|", "#+TBLFM: $2=$1", "# comment", ": fixed", "-----",
1531 "[fn:1] note", "#+NAME: x", "plain text", "é", "😀", "e\u{301}", " ", "\t", "\n", "\n", "\r\n", "\r", "",
1532]
1533
1534func randomDocument(_ rng: inout SeededGenerator) -> String {
1535 (0..<Int.random(in: 0...40, using: &rng)).map { _ in
1536 fragments.randomElement(using: &rng)! + (Bool.random(using: &rng) ? "\n" : "")
1537 }.joined()
1538}
1539
1540func checkLengths(_ node: SyntaxNode) -> Bool {
1541 let sum = node.green.children.reduce(0) { $0 + $1.length }
1542 return sum == node.green.length && node.children.allSatisfy(checkLengths)
1543}
1544
1545struct RoundTripTests {
1546 @Test func fuzzedDocumentsRoundTrip() {
1547 var rng = SeededGenerator(state: 20261004)
1548 for n in 0..<2_000 {
1549 let text = randomDocument(&rng)
1550 let tree = OrgParser.parse(text)
1551 #expect(tree.text == text, "document \(n)")
1552 #expect(checkLengths(tree.root), "document \(n)")
1553 }
1554 }
1555
1556 @Test(arguments: [
1557 [0xEF, 0xBB, 0xBF] + Array("* a\r\n".utf8),
1558 Array("* a\r\n- b\n\tc".utf8),
1559 Array("* a".utf8),
1560 Array("😀 e\u{301}\n".utf8),
1561 [0x2A, 0x20, 0xFF, 0x0A] as [UInt8],
1562 ])
1563 func encodingFixturesRoundTrip(bytes: [UInt8]) {
1564 let source = SourceText(bytes: bytes)
1565 let tree = OrgParser.parse(source.text)
1566 #expect(source.encode(tree.text) == bytes)
1567 }
1568
1569 /// Private corpus: `ORGSTAR_CORPUS=/path/to/org swift test --filter corpus`.
1570 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_CORPUS"] != nil))
1571 func corpusRoundTrips() throws {
1572 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_CORPUS"]!)
1573 let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
1574 .compactMap { $0 as? URL }
1575 .filter { ["org", "org_archive"].contains($0.pathExtension) }
1576 #expect(!files.isEmpty)
1577 for file in files {
1578 let bytes = try [UInt8](Data(contentsOf: file))
1579 let source = SourceText(bytes: bytes)
1580 let tree = OrgParser.parse(source.text)
1581 #expect(source.encode(tree.text) == bytes, "\(file.path)")
1582 }
1583 }
1584}
1585```
1586
1587- [x] **Step 2: Run the tests**
1588
1589Run: `swift test`
1590Expected: all pass. The corpus test is skipped.
1591
1592- [x] **Step 3: Run the private corpus locally**
1593
1594Run: `ORGSTAR_CORPUS=~/org swift test --filter corpusRoundTrips`
1595Expected: pass. Any failure names the file; reduce it to a fuzz fragment or a unit test before fixing.
1596
1597- [x] **Step 4: Commit**
1598
1599```bash
1600git add Tests
1601git commit -m "Add round-trip fuzz, encoding and corpus tests"
1602```