Sources/OrgCore/Export/MarkdownExport.swift
296 lines · 14764 bytes
1import Foundation
2
3/// Markdown export, GitHub-flavored: ATX headings, fenced code, pipe tables, task lists and
4/// `[^n]` footnotes. The title, when there is one, becomes the top heading.
5public enum MarkdownExport {
6 public static func document(_ text: String, settings: OrgSettings = .default) -> String {
7 let renderer = MarkdownRenderer(settings: settings)
8 var out = ""
9 if let title = HTMLExport.metadata(text, settings: settings).title { out = "# " + renderer.inlineString(title) + "\n\n" }
10 out += renderer.document(text)
11 return out.trimmingCharacters(in: .newlines) + "\n"
12 }
13}
14
15final class MarkdownRenderer {
16 let settings: OrgSettings
17 private var definitions: [String: String] = [:]
18 private var numbers: [String: Int] = [:]
19 private var notes: [(Int, String)] = []
20 private var anonymous = 0
21
22 init(settings: OrgSettings) {
23 self.settings = settings
24 }
25
26 func document(_ text: String) -> String {
27 let tree = OrgParser.parse(text, defaults: settings)
28 for node in tree.root.descendants() where node.kind == .footnoteDefinition {
29 if let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
30 definitions[String(m.1)] = String(node.text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
31 }
32 }
33 var out = blocks(tree.root)
34 if !notes.isEmpty {
35 out += notes.map { "[^\($0.0)]: " + $0.1 }.joined(separator: "\n") + "\n"
36 }
37 return out
38 }
39
40 func inlineString(_ text: String) -> String {
41 let tree = OrgParser.parse(text, defaults: settings)
42 guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return text }
43 return inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines)
44 }
45
46 private var lastExports = "code"
47 private var results = false
48
49 private func blocks(_ node: SyntaxNode, indent: String = "") -> String {
50 let parts = node.children.map { child -> String in
51 // Results show for `:exports results` and `both`, as in the HTML export.
52 if child.kind == .affiliatedKeyword {
53 if child.text.trimmingCharacters(in: .whitespaces).uppercased().hasPrefix("#+RESULTS") { results = true }
54 return ""
55 }
56 defer { results = false }
57 if results {
58 defer { lastExports = "code" }
59 if lastExports != "results", lastExports != "both" { return "" }
60 }
61 if child.kind == .block, let exports = HTMLRenderer.srcExports(child) {
62 lastExports = exports
63 if exports == "results" || exports == "none" { return "" }
64 }
65 return element(child, indent: indent)
66 }.filter { !$0.isEmpty }
67 return parts.isEmpty ? "" : parts.joined(separator: "\n\n") + "\n\n"
68 }
69
70 private func blocks(text: String) -> String {
71 blocks(OrgParser.parse(text, defaults: settings).root)
72 }
73
74 private func element(_ node: SyntaxNode, indent: String) -> String {
75 switch node.kind {
76 case .zerothSection, .section:
77 return blocks(node, indent: indent).trimmingCharacters(in: .newlines)
78 case .heading:
79 let level = node.tokens.first { $0.kind == .stars }?.text.count ?? 1
80 var parts: [String] = []
81 if let todo = node.tokens.first(where: { $0.kind == .todoKeyword })?.text { parts.append(todo) }
82 if let priority = node.tokens.first(where: { $0.kind == .priority })?.text { parts.append(priority) }
83 if let title = node.firstChild(.title) { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
84 if let tags = node.tokens.first(where: { $0.kind == .tags })?.text {
85 parts.append(tags.split(separator: ":").map { "`\($0)`" }.joined(separator: " "))
86 }
87 return String(repeating: "#", count: min(level + 1, 6)) + " " + parts.filter { !$0.isEmpty }.joined(separator: " ")
88 case .paragraph:
89 return indent + inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
90 .components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: "\n" + indent)
91 case .plainList:
92 return list(node, indent: indent)
93 case .table:
94 return table(node, indent: indent)
95 case .block:
96 return block(node, indent: indent)
97 case .horizontalRule:
98 return indent + "---"
99 case .tableEl:
100 let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty && !$0.lowercased().contains("#+tblfm") }
101 return fence(lines, language: "", indent: indent)
102 case .fixedWidth:
103 let lines = node.text.split(separator: "\n").map { line -> String in
104 let trimmed = line.drop { $0 == " " || $0 == "\t" }
105 return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
106 }
107 return fence(lines, language: "", indent: indent)
108 default:
109 return ""
110 }
111 }
112
113 private func fence(_ lines: [String], language: String, indent: String) -> String {
114 let longest = lines.map { $0.prefix { $0 == "`" }.count }.max() ?? 0
115 let ticks = String(repeating: "`", count: max(3, longest + 1))
116 return ([indent + ticks + language] + lines.map { indent + $0 } + [indent + ticks]).joined(separator: "\n")
117 }
118
119 private func list(_ node: SyntaxNode, indent: String) -> String {
120 var out: [String] = []
121 var number = 0
122 for item in node.children where item.kind == .item {
123 let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
124 let ordered = bullet.first.map { $0.isNumber || $0.isLetter } ?? false
125 number += 1
126 var marker = ordered ? "\(number)." : "-"
127 if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
128 marker += box == "[X]" || box == "[x]" ? " [x]" : " [ ]"
129 }
130 let childIndent = indent + String(repeating: " ", count: (ordered ? "\(number). " : "- ").count)
131 var parts: [String] = []
132 let term = item.firstChild(.itemTag).map { "**" + inline($0).trimmingCharacters(in: .whitespaces) + "**: " }
133 for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
134 if index == 0, child.kind == .paragraph {
135 let text = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
136 .components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: "\n" + childIndent)
137 parts.append((term ?? "") + text)
138 } else {
139 parts.append(element(child, indent: childIndent))
140 }
141 }
142 if let term, parts.first.map({ !$0.hasPrefix(term) }) ?? true { parts.insert(term.trimmingCharacters(in: .whitespaces), at: 0) }
143 let body = parts.isEmpty ? "" : parts[0].trimmingCharacters(in: .whitespaces) + parts.dropFirst().map { "\n" + $0 }.joined()
144 out.append(indent + marker + " " + body)
145 }
146 return out.joined(separator: "\n")
147 }
148
149 private func table(_ node: SyntaxNode, indent: String) -> String {
150 var rows: [[String]] = []
151 var ruleAfter: Int?
152 for row in node.children where row.kind == .tableRow {
153 let cells = row.children.filter { $0.kind == .tableCell }
154 if cells.isEmpty {
155 if ruleAfter == nil, !rows.isEmpty { ruleAfter = rows.count }
156 continue
157 }
158 rows.append(cells.map { inline($0).trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "|", with: "\\|") })
159 }
160 guard !rows.isEmpty else { return "" }
161 let columns = rows.map(\.count).max() ?? 0
162 rows = rows.map { $0 + Array(repeating: "", count: columns - $0.count) }
163 var header: [String]
164 var body: [[String]]
165 if ruleAfter == 1 {
166 header = rows[0]
167 body = Array(rows.dropFirst())
168 } else {
169 header = Array(repeating: "", count: columns)
170 body = rows
171 }
172 func line(_ cells: [String]) -> String { indent + "| " + cells.joined(separator: " | ") + " |" }
173 return ([line(header), indent + "|" + Array(repeating: "---", count: columns).joined(separator: "|") + "|"] + body.map(line)).joined(separator: "\n")
174 }
175
176 private func block(_ node: SyntaxNode, indent: String) -> String {
177 var lines = node.text.components(separatedBy: "\n")
178 if lines.last == "" { lines.removeLast() }
179 guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
180 let type = m.1.lowercased()
181 let parameters = String(m.2)
182 var body = Array(lines.dropFirst().dropLast()).map {
183 $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression)
184 }
185 let common = body.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }.min() ?? 0
186 body = body.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
187 switch type {
188 case "src":
189 return fence(body, language: parameters.split(separator: " ").first.map(String.init) ?? "", indent: indent)
190 case "example":
191 return fence(body, language: "", indent: indent)
192 case "quote":
193 return blocks(text: body.joined(separator: "\n")).trimmingCharacters(in: .newlines)
194 .components(separatedBy: "\n").map { indent + ($0.isEmpty ? ">" : "> " + $0) }.joined(separator: "\n")
195 case "verse":
196 return body.map { indent + inlineString($0) + " " }.joined(separator: "\n")
197 case "export":
198 let backend = parameters.lowercased()
199 return backend.hasPrefix("markdown") || backend.hasPrefix("md") || backend.hasPrefix("html") ? body.joined(separator: "\n") : ""
200 case "comment":
201 return ""
202 default:
203 return blocks(text: body.joined(separator: "\n")).trimmingCharacters(in: .newlines)
204 }
205 }
206
207 func inline(_ node: SyntaxNode) -> String {
208 var out = ""
209 for element in node.elements {
210 switch element {
211 case .token(let token):
212 switch token.kind {
213 case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority: continue
214 default: out += token.text
215 }
216 case .node(let child):
217 out += object(child)
218 }
219 }
220 return out
221 }
222
223 private func code(_ text: String) -> String {
224 let ticks = text.contains("`") ? "``" : "`"
225 return ticks + (ticks == "``" ? " " + text + " " : text) + ticks
226 }
227
228 private func object(_ node: SyntaxNode) -> String {
229 switch node.kind {
230 case .bold: return "**\(inline(node))**"
231 case .italic: return "*\(inline(node))*"
232 case .underline: return "<u>\(inline(node))</u>"
233 case .strikeThrough: return "~~\(inline(node))~~"
234 case .verbatim, .code: return code(inline(node))
235 case .link: return link(node)
236 case .linkDescription: return inline(node)
237 case .timestamp:
238 guard let stamp = Timestamp.parse(node.text) else { return node.text }
239 func show(_ p: Timestamp.Point) -> String {
240 String(format: "%04d-%02d-%02d", p.year, p.month, p.day) + (p.hour.map { String(format: " %02d:%02d", $0, p.minute ?? 0) } ?? "")
241 }
242 return show(stamp.start) + (stamp.end.map { "–" + show($0) } ?? "")
243 case .footnoteReference: return footnote(node.text)
244 case .entity:
245 let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
246 return OrgEntities.display[name] ?? node.text
247 case .radioTarget:
248 return String(node.text.dropFirst(3).dropLast(3))
249 case .superscript, .subscript:
250 let body = node.text.dropFirst()
251 let inner = body.hasPrefix("{") && body.hasSuffix("}") ? String(body.dropFirst().dropLast()) : String(body)
252 return node.text.hasPrefix("_") ? "<sub>\(inner)</sub>" : "<sup>\(inner)</sup>"
253 case .lineBreak: return " \n"
254 case .target, .macro: return ""
255 // ox-md uses ox-html's translator: only HTML snippets.
256 case .exportSnippet:
257 guard node.tokens.first?.text == "@@html:" else { return "" }
258 return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
259 case .citation, .inlineBabelCall: return node.text
260 default: return inline(node)
261 }
262 }
263
264 private func link(_ node: SyntaxNode) -> String {
265 guard let path = node.tokens.first(where: { $0.kind == .linkPath })?.text else {
266 // A radio link is its text.
267 if !node.text.hasPrefix("<"), !node.text.contains(":") { return node.text }
268 var target = node.text
269 if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
270 return "<\(target)>"
271 }
272 var href = path
273 if path.hasPrefix("file:") { href = String(path.dropFirst(5)) }
274 if path.hasPrefix("id:") { href = "#" + path.dropFirst(3) }
275 if !path.contains(":"), href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".md" }
276 if let description = node.firstChild(.linkDescription) { return "[\(inline(description))](\(href))" }
277 let ext = href.split(separator: ".").last.map { $0.lowercased() } ?? ""
278 if HTMLRenderer.imageExtensions.contains(ext) { return ")" }
279 return path.contains("://") ? "<\(href)>" : "[\(href)](\(href))"
280 }
281
282 private func footnote(_ text: String) -> String {
283 guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return text }
284 var label = String(m.1)
285 if label.isEmpty {
286 anonymous += 1
287 label = "anonymous-\(anonymous)"
288 }
289 if let n = numbers[label] { return "[^\(n)]" }
290 guard let content = m.2.map(String.init) ?? definitions[label] else { return text }
291 let n = notes.count + 1
292 numbers[label] = n
293 notes.append((n, inlineString(content.replacingOccurrences(of: "\n", with: " "))))
294 return "[^\(n)]"
295 }
296}