Sources/OrgCore/Parser/Parser.swift
501 lines · 19263 bytes
1public enum OrgParser {
2 public static func parse(_ text: String, defaults: OrgSettings = .default) -> OrgTree {
3 var parser = Parser(text: text, defaults: defaults)
4 return parser.run()
5 }
6}
7
8struct Parser {
9 let lines: [RawLine]
10 let info: [ClassifiedLine]
11 /// Begin line → end line, for blocks, dynamic blocks and drawers that are closed before the
12 /// next heading.
13 let blockEnds: [Int: Int]
14 let settings: OrgSettings
15 var builder = GreenBuilder()
16 var i = 0
17 /// Table rows from a previous version, by their line text. A row parses from its own line
18 /// alone, so a row with the same text can be reused instead of scanned again.
19 var reusableRows: [Substring: GreenNode] = [:]
20
21 init(text: String, defaults: OrgSettings) {
22 let lines = splitRawLines(text)
23 let info = lines.map { classifyLine($0.content, alphabetical: defaults.listAllowAlphabetical) }
24 let ends = Parser.matchEnds(info, lines)
25 let settings = SettingsScanner.scan(lines: lines, info: info, blockEnds: ends, defaults: defaults)
26 self.init(lines: lines, info: info, blockEnds: ends, settings: settings)
27 }
28
29 /// Parses part of a document with the settings already read from the whole file.
30 init(text: String, settings: OrgSettings) {
31 let lines = splitRawLines(text)
32 let info = lines.map { classifyLine($0.content, alphabetical: settings.listAllowAlphabetical) }
33 self.init(lines: lines, info: info, blockEnds: Parser.matchEnds(info, lines), settings: settings)
34 }
35
36 private init(lines: [RawLine], info: [ClassifiedLine], blockEnds: [Int: Int], settings: OrgSettings) {
37 self.lines = lines
38 self.info = info
39 self.blockEnds = blockEnds
40 self.settings = settings
41 }
42
43 static func matchEnds(_ info: [ClassifiedLine], _ lines: [RawLine]) -> [Int: Int] {
44 var ends: [Int: Int] = [:]
45 var k = 0
46 while k < info.count {
47 let isEnd: ((LineClass) -> Bool)?
48 switch info[k].cls {
49 case .blockBegin(let name): isEnd = { $0 == .blockEnd(name: name) }
50 case .latexBegin(let name):
51 // `\end{NAME}` ending a line, the first line's own included.
52 let closer = "\\end{" + name + "}"
53 var j = k
54 while j < info.count {
55 if j > k, case .heading = info[j].cls { break }
56 let content = lines[j].content.trimmingTrailingWhitespace
57 if content.hasSuffix(closer), j > k || content.count > closer.count + 7 + name.count { ends[k] = j; break }
58 j += 1
59 }
60 k += 1
61 continue
62 case .dynamicBegin: isEnd = { $0 == .dynamicEnd }
63 case .drawerBegin: isEnd = { $0 == .drawerEnd }
64 default: isEnd = nil
65 }
66 if let isEnd {
67 var j = k + 1
68 while j < info.count {
69 if case .heading = info[j].cls { break }
70 if isEnd(info[j].cls) { ends[k] = j; break }
71 j += 1
72 }
73 // Block contents are verbatim, so nothing inside starts another element.
74 if let end = ends[k], !isDrawer(info[k].cls) { k = end }
75 }
76 k += 1
77 }
78 return ends
79 }
80
81 static func isDrawer(_ cls: LineClass) -> Bool {
82 if case .drawerBegin = cls { return true }
83 return false
84 }
85
86 mutating func run() -> OrgTree {
87 builder.start(.document)
88 if !lines.isEmpty, !isHeading(0) {
89 builder.start(.zerothSection)
90 // A property drawer first in the file, after comments and blank lines, holds the
91 // file's properties.
92 while i < lines.count, info[i].cls == .blank || info[i].cls == .comment {
93 if info[i].cls == .blank { line(i); i += 1 } else { consecutive(.comment, limit: lines.count, floor: nil) { $0 == .comment } }
94 }
95 if i < lines.count, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES", let end = blockEnds[i] {
96 propertyDrawer(end: end)
97 }
98 parseContent(limit: lines.count)
99 builder.finish()
100 }
101 while i < lines.count, case .heading(let level) = info[i].cls {
102 parseSection(level: level)
103 }
104 builder.finish()
105 return OrgTree(green: builder.build(), settings: settings)
106 }
107
108 func isHeading(_ k: Int) -> Bool {
109 if case .heading = info[k].cls { return true }
110 return false
111 }
112
113 mutating func parseSection(level: Int) {
114 builder.start(.section)
115 headingLine(lines[i])
116 i += 1
117 if i < lines.count, info[i].cls == .planning {
118 single(.planning)
119 }
120 if i < lines.count, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES",
121 let end = blockEnds[i] {
122 propertyDrawer(end: end)
123 }
124 parseContent(limit: lines.count)
125 while i < lines.count, case .heading(let child) = info[i].cls, child > level {
126 parseSection(level: child)
127 }
128 builder.finish()
129 }
130
131 mutating func propertyDrawer(end: Int) {
132 builder.start(.propertyDrawer)
133 line(i)
134 i += 1
135 while i < end {
136 if info[i].cls == .blank {
137 line(i)
138 } else {
139 builder.start(.nodeProperty)
140 line(i)
141 builder.finish()
142 }
143 i += 1
144 }
145 line(i)
146 i += 1
147 builder.finish()
148 }
149
150 /// Elements until `limit` or the next heading.
151 mutating func parseContent(limit: Int) {
152 while i < limit, !isHeading(i) {
153 element(limit: limit, floor: nil)
154 }
155 }
156
157 static let affiliatedKeys: Set<String> = ["NAME", "CAPTION", "RESULTS", "HEADER", "PLOT"]
158
159 /// One element starting at `i`. `floor` is the indent of the enclosing list item, if any:
160 /// non-blank lines at or left of it end the element.
161 mutating func element(limit: Int, floor: Int?) {
162 switch info[i].cls {
163 case .blank:
164 line(i)
165 i += 1
166 case .blockBegin, .dynamicBegin, .latexBegin:
167 if let end = blockEnds[i], end < limit {
168 let kind: SyntaxKind = switch info[i].cls {
169 case .dynamicBegin: .dynamicBlock
170 case .latexBegin: .latexEnvironment
171 default: .block
172 }
173 builder.start(kind)
174 while i <= end {
175 line(i)
176 i += 1
177 }
178 builder.finish()
179 } else {
180 paragraph(limit: limit, floor: floor)
181 }
182 case .drawerBegin:
183 if let end = blockEnds[i], end < limit {
184 builder.start(.drawer)
185 line(i)
186 i += 1
187 parseContent(limit: end)
188 line(i)
189 i += 1
190 builder.finish()
191 } else {
192 paragraph(limit: limit, floor: floor)
193 }
194 case .inlineTask:
195 inlineTask(limit: limit)
196 case .keyword(let key):
197 let affiliated = Self.affiliatedKeys.contains(key) || key.hasPrefix("ATTR_")
198 single(affiliated ? .affiliatedKeyword : .keyword)
199 case .comment:
200 consecutive(.comment, limit: limit, floor: floor) { $0 == .comment }
201 case .fixedWidth:
202 consecutive(.fixedWidth, limit: limit, floor: floor) { $0 == .fixedWidth }
203 case .horizontalRule:
204 single(.horizontalRule)
205 case .clock:
206 single(.clock)
207 case .tableRow:
208 table(limit: limit, floor: floor)
209 case .footnoteDefinition:
210 footnoteDefinition(limit: limit)
211 case .listItem:
212 list(limit: limit, floor: floor)
213 default:
214 paragraph(limit: limit, floor: floor)
215 }
216 }
217
218 /// An inline task: its heading line, and with an END line before the next heading, the
219 /// elements up to it and that line.
220 mutating func inlineTask(limit: Int) {
221 builder.start(.inlineTask)
222 headingLine(lines[i])
223 i += 1
224 var end: Int?
225 var k = i
226 while k < limit, !isHeading(k) {
227 if info[k].cls == .inlineTaskEnd { end = k; break }
228 if case .inlineTask = info[k].cls { break }
229 k += 1
230 }
231 if let end {
232 if i < end, info[i].cls == .planning { single(.planning) }
233 if i < end, case .drawerBegin(let name) = info[i].cls, name.uppercased() == "PROPERTIES", let drawerEnd = blockEnds[i], drawerEnd < end {
234 propertyDrawer(end: drawerEnd)
235 }
236 parseContent(limit: end)
237 headingLine(lines[i])
238 i += 1
239 }
240 builder.finish()
241 }
242
243 /// Kinds whose single line holds inline objects (timestamps on planning and clock lines).
244 static let inlineLineKinds: Set<SyntaxKind> = [.planning, .clock]
245
246 mutating func single(_ kind: SyntaxKind) {
247 builder.start(kind)
248 if Self.inlineLineKinds.contains(kind) {
249 let rest = whitespace(lines[i].content)
250 inline(rest)
251 builder.token(.newline, lines[i].ending)
252 } else {
253 line(i)
254 }
255 i += 1
256 builder.finish()
257 }
258
259 /// Source text from `start` through the end of line `last`, including its line ending.
260 func span(from start: Substring.Index, through last: Int) -> Substring {
261 let base = lines[last].ending.base
262 return base[start..<lines[last].ending.endIndex]
263 }
264
265 mutating func consecutive(_ kind: SyntaxKind, limit: Int, floor: Int?, matching: (LineClass) -> Bool) {
266 builder.start(kind)
267 repeat {
268 line(i)
269 i += 1
270 } while i < limit && matching(info[i].cls) && within(floor, i)
271 builder.finish()
272 }
273
274 mutating func table(limit: Int, floor: Int?) {
275 builder.start(.table)
276 while i < limit, info[i].cls == .tableRow, within(floor, i) {
277 tableRow()
278 }
279 while i < limit, info[i].cls == .keyword(key: "TBLFM"), within(floor, i) {
280 single(.tableFormula)
281 }
282 builder.finish()
283 }
284
285 /// A rule row (`|---+---|`) is one text token. Other rows alternate `|` markers and cells;
286 /// every pair of pipes gets a cell, even an empty one, so columns line up.
287 mutating func tableRow() {
288 if !reusableRows.isEmpty {
289 let content = lines[i].content
290 if let row = reusableRows[content.base[content.startIndex..<lines[i].ending.endIndex]] {
291 builder.node(row)
292 i += 1
293 return
294 }
295 }
296 builder.start(.tableRow)
297 let rest = whitespace(lines[i].content)
298 if rest.hasPrefix("|-") {
299 builder.token(.text, rest)
300 } else {
301 var cellStart = rest.startIndex
302 var index = rest.startIndex
303 while index < rest.endIndex {
304 if rest[index] == "|" {
305 if index > rest.startIndex { tableCell(rest[cellStart..<index]) }
306 builder.token(.marker, "|")
307 cellStart = rest.index(after: index)
308 }
309 index = rest.index(after: index)
310 }
311 if cellStart < rest.endIndex { tableCell(rest[cellStart...]) }
312 }
313 builder.token(.newline, lines[i].ending)
314 builder.finish()
315 i += 1
316 }
317
318 mutating func tableCell(_ text: Substring) {
319 builder.start(.tableCell)
320 inline(text)
321 builder.finish()
322 }
323
324 mutating func footnoteDefinition(limit: Int) {
325 var end = i + 1
326 while end < limit, info[end].cls == .plain { end += 1 }
327 let content = lines[i].content
328 let close = content.firstIndex(of: "]")!
329 builder.start(.footnoteDefinition)
330 builder.token(.marker, content[...close])
331 inline(span(from: content.index(after: close), through: end - 1))
332 builder.finish()
333 i = end
334 }
335
336 mutating func list(limit: Int, floor: Int?) {
337 let base = info[i].indent
338 builder.start(.plainList)
339 while i < limit, info[i].cls == .listItem, info[i].indent == base, within(floor, i) {
340 item(base: base, limit: limit)
341 }
342 builder.finish()
343 }
344
345 /// An item's first line, then everything indented past its bullet. One blank line stays
346 /// inside the item when the item or list continues after it; two end the list.
347 mutating func item(base: Int, limit: Int) {
348 builder.start(.item)
349 var rest = whitespace(lines[i].content)
350 let bullet = rest.prefix { $0 != " " && $0 != "\t" }
351 builder.token(.bullet, bullet)
352 rest = whitespace(rest.dropFirst(bullet.count))
353 if let box = checkbox(rest) {
354 builder.token(.checkbox, box)
355 rest = whitespace(rest.dropFirst(box.count))
356 }
357 // The rest of the bullet line and its continuation lines are the item's first paragraph.
358 var end = i + 1
359 while end < limit, within(base, end), continuesParagraph(end) { end += 1 }
360 if rest.isEmpty, end == i + 1 {
361 builder.token(.newline, lines[i].ending)
362 } else {
363 builder.start(.paragraph)
364 inline(span(from: rest.startIndex, through: end - 1))
365 builder.finish()
366 }
367 i = end
368 while i < limit, !isHeading(i) {
369 if info[i].cls == .blank {
370 var j = i
371 while j < limit, info[j].cls == .blank { j += 1 }
372 guard j - i < 2, j < limit else { break }
373 let continuesItem = info[j].indent > base
374 let nextSibling = info[j].cls == .listItem && info[j].indent == base
375 guard continuesItem || nextSibling else { break }
376 line(i)
377 i += 1
378 if nextSibling { break }
379 continue
380 }
381 guard info[i].indent > base else { break }
382 element(limit: limit, floor: base)
383 }
384 builder.finish()
385 }
386
387 /// `[ ]`, `[X]`, `[x]` or `[-]`, followed by whitespace or end of line.
388 func checkbox(_ s: Substring) -> Substring? {
389 guard s.count >= 3, s.first == "[", "Xx -".contains(s.dropFirst().first!),
390 s.dropFirst(2).first == "]" else { return nil }
391 let after = s.dropFirst(3)
392 guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
393 return s.prefix(3)
394 }
395
396 /// The paragraph's lines are one inline run, so emphasis and links can cross a line break.
397 mutating func paragraph(limit: Int, floor: Int?) {
398 var end = i + 1
399 while end < limit, within(floor, end), continuesParagraph(end) { end += 1 }
400 builder.start(.paragraph)
401 inline(span(from: lines[i].content.startIndex, through: end - 1))
402 builder.finish()
403 i = end
404 }
405
406 /// Lines that don't start an element of their own.
407 func continuesParagraph(_ k: Int) -> Bool {
408 switch info[k].cls {
409 case .plain, .planning, .blockEnd, .dynamicEnd, .drawerEnd, .latexEnd:
410 return true
411 case .blockBegin, .dynamicBegin, .drawerBegin, .latexBegin:
412 return blockEnds[k] == nil
413 default:
414 return false
415 }
416 }
417
418 func within(_ floor: Int?, _ k: Int) -> Bool {
419 guard let floor else { return true }
420 return info[k].indent > floor
421 }
422
423 // MARK: - Tokens
424
425 /// A whole line as leading whitespace, content and line ending.
426 mutating func line(_ k: Int) {
427 let rest = whitespace(lines[k].content)
428 builder.token(.text, rest)
429 builder.token(.newline, lines[k].ending)
430 }
431
432 mutating func whitespace(_ s: Substring) -> Substring {
433 let ws = s.prefix { $0 == " " || $0 == "\t" }
434 builder.token(.whitespace, ws)
435 return s.dropFirst(ws.count)
436 }
437
438 mutating func headingLine(_ raw: RawLine) {
439 builder.start(.heading)
440 var rest = raw.content
441 let stars = rest.prefix { $0 == "*" }
442 builder.token(.stars, stars)
443 rest = whitespace(rest.dropFirst(stars.count))
444
445 // As org: a keyword counts only before a space or the end of the line, not a tab.
446 let word = rest.prefix { $0 != " " && $0 != "\t" }
447 let afterWord = rest.dropFirst(word.count).first
448 if !word.isEmpty, afterWord == nil || afterWord == " ", settings.todoKeywordNames.contains(String(word)) {
449 builder.token(.todoKeyword, word)
450 rest = whitespace(rest.dropFirst(word.count))
451 }
452
453 if let cookie = priorityCookie(rest) {
454 builder.token(.priority, cookie)
455 rest = whitespace(rest.dropFirst(cookie.count))
456 }
457
458 let parts = splitTags(rest)
459 if !parts.title.isEmpty {
460 builder.start(.title)
461 inline(parts.title)
462 builder.finish()
463 }
464 builder.token(.whitespace, parts.gap)
465 builder.token(.tags, parts.tags)
466 builder.token(.whitespace, parts.trailing)
467 builder.token(.newline, raw.ending)
468 builder.finish()
469 }
470
471 /// `[#A]` or `[#10]`, followed by whitespace or end of line.
472 func priorityCookie(_ s: Substring) -> Substring? {
473 guard s.hasPrefix("[#"), let close = s.firstIndex(of: "]") else { return nil }
474 let value = s[s.index(s.startIndex, offsetBy: 2)..<close]
475 let valid = (value.count == 1 && value.first!.isLetter && value.first!.isUppercase)
476 || (!value.isEmpty && value.allSatisfy { $0.isASCII && $0.isNumber })
477 guard valid else { return nil }
478 let after = s[s.index(after: close)...]
479 guard after.isEmpty || after.first == " " || after.first == "\t" else { return nil }
480 return s[...close]
481 }
482
483 func splitTags(_ s: Substring) -> (title: Substring, gap: Substring, tags: Substring, trailing: Substring) {
484 let trimmed = s.trimmingTrailingWhitespace
485 let trailing = s[trimmed.endIndex...]
486 let none = (title: trimmed, gap: Substring(), tags: Substring(), trailing: trailing)
487 guard trimmed.last == ":" else { return none }
488 let tagStart = trimmed.lastIndex { $0 == " " || $0 == "\t" }.map { trimmed.index(after: $0) } ?? trimmed.startIndex
489 let tags = trimmed[tagStart...]
490 guard tags.count >= 3, tags.first == ":", isTagString(tags) else { return none }
491 let before = trimmed[..<tagStart]
492 let title = before.trimmingTrailingWhitespace
493 return (title, before[title.endIndex...], tags, trailing)
494 }
495
496 func isTagString(_ tags: Substring) -> Bool {
497 tags.dropFirst().dropLast().split(separator: ":", omittingEmptySubsequences: false).allSatisfy { tag in
498 !tag.isEmpty && tag.allSatisfy { $0.isLetter || $0.isNumber || "_@#%".contains($0) }
499 }
500 }
501}