Sources/OrgCore/Markdown/MarkdownStructure.swift
272 lines · 12260 bytes
25 symbols in this file
1import Foundation
2
3/// Markdown as far as highlighting, heading folding, the outline and the index need it: front
4/// matter, fenced code and ATX headings line by line, and inline markup within a line. Not a
5/// CommonMark parser: setext headings, indented code blocks, HTML blocks and emphasis across
6/// lines aren't recognised, and fences may be indented by any amount. Offsets are UTF-16.
7public enum Markdown {
8 /// Whether `path` names a Markdown file (`.md`, `.markdown`).
9 public static func isPath(_ path: String) -> Bool {
10 let ext = (path as NSString).pathExtension.lowercased()
11 return ext == "md" || ext == "markdown"
12 }
13
14 /// Whether `path` names a plain text file (`.txt`).
15 public static func isPlainTextPath(_ path: String) -> Bool {
16 (path as NSString).pathExtension.lowercased() == "txt"
17 }
18
19 public struct Heading: Sendable, Equatable {
20 /// Start of the heading line.
21 public let start: Int
22 /// Start of the line after it, or the end of the text.
23 public let lineEnd: Int
24 public let level: Int
25 public let title: String
26 }
27
28 /// A fenced code block, from its opening line to after its closing line; an unclosed one
29 /// runs to the end of the text.
30 public struct Fence: Sendable, Equatable {
31 public let range: Range<Int>
32 /// The opening line, with its newline.
33 public let opening: Range<Int>
34 /// The closing line, with its newline.
35 public let closing: Range<Int>?
36 /// The first word of the info string.
37 public let language: String?
38
39 public var body: Range<Int> { opening.upperBound..<(closing?.lowerBound ?? range.upperBound) }
40 }
41
42 /// YAML front matter between `---` lines, or TOML between `+++` lines, on the first line.
43 public struct FrontMatter: Sendable, Equatable {
44 public enum Format: String, Sendable { case yaml, toml }
45 public let format: Format
46 public let range: Range<Int>
47 public let opening: Range<Int>
48 public let closing: Range<Int>
49
50 public var body: Range<Int> { opening.upperBound..<closing.lowerBound }
51 }
52
53 public struct Structure: Sendable, Equatable {
54 public var frontMatter: FrontMatter?
55 public var fences: [Fence] = []
56 public var headings: [Heading] = []
57
58 public init() {}
59
60 /// The ranges that aren't Markdown text: front matter and fences, in order.
61 public var blocks: [Range<Int>] { (frontMatter.map { [$0.range] } ?? []) + fences.map(\.range) }
62 }
63
64 public static func structure(_ text: String) -> Structure {
65 structure(Array(text.utf16))
66 }
67
68 public static func structure(_ u: [UInt16]) -> Structure {
69 var result = Structure()
70 let n = u.count
71 var i = 0
72 if let front = frontMatter(u) {
73 result.frontMatter = front
74 i = front.range.upperBound
75 }
76 var open: (start: Int, opening: Range<Int>, char: UInt16, count: Int, language: String?)?
77 while i < n {
78 let end = lineEnd(u, i)
79 let next = end < n ? end + 1 : n
80 if let fence = open {
81 if isClosingFence(u, i, end, char: fence.char, count: fence.count) {
82 result.fences.append(Fence(range: fence.start..<next, opening: fence.opening, closing: i..<next, language: fence.language))
83 open = nil
84 }
85 } else if let fence = openingFence(u, i, end) {
86 open = (i, i..<next, fence.char, fence.count, fence.language)
87 } else if let heading = atxHeading(u, i, end) {
88 result.headings.append(Heading(start: i, lineEnd: next, level: heading.level, title: string(u, heading.title)))
89 }
90 i = next
91 }
92 if let fence = open {
93 result.fences.append(Fence(range: fence.start..<n, opening: fence.opening, closing: nil, language: fence.language))
94 }
95 return result
96 }
97
98 /// The structure of `new`, which is `old` with `edit` made, from `structure` without reading
99 /// the whole text again: offsets after the edit move, and the edited lines are read for
100 /// headings. Nil when the edit may start or end front matter or a fence, which needs a
101 /// fresh read.
102 public static func structure(_ structure: Structure, old: [UInt16], new: [UInt16], after edit: TextEdit) -> Structure? {
103 let lower = edit.range.lowerBound
104 let upper = edit.range.upperBound
105 let delta = new.count - old.count
106 var start = lower
107 while start > 0, old[start - 1] != newline { start -= 1 }
108 let oldEnd = lineEnd(old, upper)
109 let newEnd = lineEnd(new, upper + delta)
110 func mayFence(_ u: [UInt16], _ range: Range<Int>) -> Bool {
111 var run = 0
112 for c in u[range] {
113 run = c == backtick || c == tilde ? run + 1 : 0
114 if run >= 3 { return true }
115 }
116 return false
117 }
118 if start == 0 || mayFence(old, start..<oldEnd) || mayFence(new, start..<newEnd) { return nil }
119 if let front = structure.frontMatter, start < front.range.upperBound { return nil }
120 // An unclosed `---` or `+++` first line may be closed by the edit.
121 let first = lineEnd(new, 0)
122 if structure.frontMatter == nil, isLine(new, 0, first, "---") || isLine(new, 0, first, "+++") { return nil }
123 // No front matter or fence line is edited, so their bounds are at or before the edited
124 // lines' start, or after their end; an unclosed fence runs on to the end of the text.
125 func map(_ offset: Int) -> Int { offset <= start ? offset : offset + delta }
126 func map(_ range: Range<Int>) -> Range<Int> { map(range.lowerBound)..<map(range.upperBound) }
127 var result = Structure()
128 result.frontMatter = structure.frontMatter
129 result.fences = structure.fences.map { fence in
130 let range = fence.closing == nil ? map(fence.range.lowerBound)..<new.count : map(fence.range)
131 return Fence(range: range, opening: map(fence.opening), closing: fence.closing.map(map), language: fence.language)
132 }
133 let inFence = result.fences.contains { $0.range.lowerBound < start && start < $0.range.upperBound }
134 var headings = structure.headings.filter { $0.start < start }
135 if !inFence {
136 var i = start
137 repeat {
138 let end = lineEnd(new, i)
139 if let heading = atxHeading(new, i, end) {
140 headings.append(Heading(start: i, lineEnd: end < new.count ? end + 1 : end, level: heading.level, title: string(new, heading.title)))
141 }
142 i = end + 1
143 } while i <= newEnd && i < new.count
144 }
145 for heading in structure.headings where heading.start > oldEnd {
146 headings.append(Heading(start: heading.start + delta, lineEnd: heading.lineEnd + delta, level: heading.level, title: heading.title))
147 }
148 result.headings = headings
149 return result
150 }
151
152 /// The front matter's `title`, else the first heading's.
153 public static func title(_ text: String) -> String? {
154 let u = Array(text.utf16)
155 return title(u, structure(u))
156 }
157
158 public static func title(_ u: [UInt16], _ structure: Structure) -> String? {
159 if let front = structure.frontMatter {
160 let body = string(u, front.body)
161 let pattern = front.format == .yaml ? /(?m)^title[ \t]*:[ \t]*(.*?)[ \t\r]*$/ : /(?m)^title[ \t]*=[ \t]*(.*?)[ \t\r]*$/
162 if let match = body.firstMatch(of: pattern) {
163 var value = Substring(match.1)
164 if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first {
165 value = value.dropFirst().dropLast()
166 }
167 if !value.isEmpty { return String(value) }
168 }
169 }
170 return structure.headings.first { !$0.title.isEmpty }?.title
171 }
172
173 // MARK: - Lines
174
175 static let newline: UInt16 = 10
176 static let space: UInt16 = 32
177 static let tab: UInt16 = 9
178 static let cr: UInt16 = 13
179 static let hash: UInt16 = 35
180 static let backtick: UInt16 = 96
181 static let tilde: UInt16 = 126
182
183 /// The offset of the newline ending the line at `start`, or the end of the text.
184 static func lineEnd(_ u: [UInt16], _ start: Int) -> Int {
185 var i = start
186 while i < u.count, u[i] != newline { i += 1 }
187 return i
188 }
189
190 static func isBlank(_ c: UInt16) -> Bool { c == space || c == tab || c == cr }
191
192 static func string(_ u: [UInt16], _ range: Range<Int>) -> String {
193 String(decoding: u[range], as: UTF16.self)
194 }
195
196 /// The line without trailing spaces, tabs and carriage return.
197 static func trimmedEnd(_ u: [UInt16], _ start: Int, _ end: Int) -> Int {
198 var e = end
199 while e > start, isBlank(u[e - 1]) { e -= 1 }
200 return e
201 }
202
203 static func isLine(_ u: [UInt16], _ start: Int, _ end: Int, _ marker: String) -> Bool {
204 let e = trimmedEnd(u, start, end)
205 return Array(marker.utf16) == Array(u[start..<e])
206 }
207
208 static func frontMatter(_ u: [UInt16]) -> FrontMatter? {
209 let end = lineEnd(u, 0)
210 let format: FrontMatter.Format
211 if isLine(u, 0, end, "---") { format = .yaml } else if isLine(u, 0, end, "+++") { format = .toml } else { return nil }
212 guard end < u.count else { return nil }
213 let opening = 0..<(end + 1)
214 var i = end + 1
215 while i < u.count {
216 let e = lineEnd(u, i)
217 let next = e < u.count ? e + 1 : e
218 if format == .yaml ? (isLine(u, i, e, "---") || isLine(u, i, e, "...")) : isLine(u, i, e, "+++") {
219 return FrontMatter(format: format, range: 0..<next, opening: opening, closing: i..<next)
220 }
221 i = next
222 }
223 return nil
224 }
225
226 static func openingFence(_ u: [UInt16], _ start: Int, _ end: Int) -> (char: UInt16, count: Int, language: String?)? {
227 var i = start
228 while i < end, u[i] == space || u[i] == tab { i += 1 }
229 guard i < end, u[i] == backtick || u[i] == tilde else { return nil }
230 let char = u[i]
231 var count = 0
232 while i < end, u[i] == char { i += 1; count += 1 }
233 guard count >= 3 else { return nil }
234 let info = i..<trimmedEnd(u, i, end)
235 if char == backtick, u[info].contains(backtick) { return nil }
236 var word = info.lowerBound
237 while word < info.upperBound, isBlank(u[word]) || u[word] == 123 || u[word] == 46 { word += 1 } // `{`, `.`
238 var wordEnd = word
239 while wordEnd < info.upperBound, !isBlank(u[wordEnd]), u[wordEnd] != 125, u[wordEnd] != 44 { wordEnd += 1 } // `}`, `,`
240 return (char, count, wordEnd > word ? string(u, word..<wordEnd) : nil)
241 }
242
243 static func isClosingFence(_ u: [UInt16], _ start: Int, _ end: Int, char: UInt16, count: Int) -> Bool {
244 var i = start
245 while i < end, u[i] == space || u[i] == tab { i += 1 }
246 var run = 0
247 while i < end, u[i] == char { i += 1; run += 1 }
248 return run >= count && trimmedEnd(u, i, end) == i
249 }
250
251 /// An ATX heading: up to three spaces, one to six `#`, then a space, a tab or the end of
252 /// the line. The title leaves out a closing run of `#`.
253 static func atxHeading(_ u: [UInt16], _ start: Int, _ end: Int) -> (level: Int, title: Range<Int>)? {
254 var i = start
255 var indent = 0
256 while i < end, u[i] == space, indent < 4 { i += 1; indent += 1 }
257 guard indent < 4, i < end, u[i] == hash else { return nil }
258 var level = 0
259 while i < end, u[i] == hash { i += 1; level += 1 }
260 guard level <= 6, i == end || isBlank(u[i]) else { return nil }
261 while i < end, isBlank(u[i]) { i += 1 }
262 var e = trimmedEnd(u, i, end)
263 var closing = e
264 while closing > i, u[closing - 1] == hash { closing -= 1 }
265 if closing == i {
266 e = i
267 } else if closing < e, isBlank(u[closing - 1]) {
268 e = trimmedEnd(u, i, closing)
269 }
270 return (level, i..<e)
271 }
272}