Sources/OrgCore/Export/MarkdownExport.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/OrgCore/Export/MarkdownExport.swift history · blame · raw

370 lines · 19073 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    /// As the HTML page: `#+INCLUDE`, macros, `#+OPTIONS` and the select and exclude tags.
  7    /// `path` is the file's, for `#+INCLUDE`, `{{{input-file}}}` and `#+bibliography:`.
  8    /// `bodyOnly` leaves out the title heading.
  9    public static func document(
 10        _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false
 11    ) -> String {
 12        let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
 13        let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
 14        let options = ExportOptions.parse(settings.setupKeywords + text)
 15        let renderer = MarkdownRenderer(settings: settings, options: options)
 16        var out = ""
 17        renderer.inTitle = true
 18        if options.title, !bodyOnly, let title = HTMLExport.metadata(text, settings: settings).title { out = "# " + renderer.inlineString(title) + "\n\n" }
 19        renderer.inTitle = false
 20        renderer.citations = CiteProcessor(text: text, directory: directory)
 21        out += renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
 22        return out.trimmingCharacters(in: .newlines) + "\n"
 23    }
 24}
 25
 26final class MarkdownRenderer {
 27    let settings: OrgSettings
 28    let options: ExportOptions
 29    /// With select tags in the document: the sections to export, by heading start.
 30    private var selected: Set<Int>?
 31    private var definitions: [String: String] = [:]
 32    private var numbers: [String: Int] = [:]
 33    private var notes: [(Int, String)] = []
 34    private var anonymous = 0
 35    /// Citations and the bibliography, as `oc-basic` exports them.
 36    var citations: CiteProcessor?
 37    /// Rendering the title, where Org exports citations as nothing.
 38    var inTitle = false
 39
 40    init(settings: OrgSettings, options: ExportOptions) {
 41        self.settings = settings
 42        self.options = options
 43    }
 44
 45    func document(_ text: String) -> String {
 46        let tree = OrgParser.parse(text, defaults: settings)
 47        for node in tree.root.descendants() where node.kind == .footnoteDefinition {
 48            if let m = node.text.firstMatch(of: /^\[fn:([^\]]+)\][ \t]*/) {
 49                definitions[String(m.1)] = String(node.text[m.range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines)
 50            }
 51        }
 52        selected = HTMLRenderer.selection(tree, tags: options.selectTags)
 53        var out = rendering(tree, text) { blocks(tree.root) }
 54        if !notes.isEmpty {
 55            out += notes.map { "[^\($0.0)]: " + $0.1 }.joined(separator: "\n") + "\n"
 56        }
 57        return out
 58    }
 59
 60    func inlineString(_ text: String) -> String {
 61        let tree = OrgParser.parse(text, defaults: settings)
 62        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return text }
 63        return rendering(tree, text) { inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines) }
 64    }
 65
 66    private var source: ExportSource?
 67
 68    /// `body` with `tree` as the source of `:exports`.
 69    private func rendering<T>(_ tree: OrgTree, _ text: String, _ body: () -> T) -> T {
 70        let saved = source
 71        source = ExportSource(tree: tree, text: text)
 72        defer { source = saved }
 73        return body()
 74    }
 75
 76    private var lastExports = "code"
 77    private var results = false
 78
 79    private func blocks(_ node: SyntaxNode, indent: String = "") -> String {
 80        let parts = node.children.map { child -> String in
 81            // Results show for `:exports results` and `both`, as in the HTML export.
 82            if child.kind == .affiliatedKeyword {
 83                if child.text.trimmingCharacters(in: .whitespaces).uppercased().hasPrefix("#+RESULTS") { results = true }
 84                return ""
 85            }
 86            defer { results = false }
 87            if results {
 88                defer { lastExports = "code" }
 89                if lastExports != "results", lastExports != "both" { return "" }
 90            }
 91            if child.kind == .block || child.kind == .keyword, let exports = source?.exports(at: child.range.lowerBound) {
 92                lastExports = exports
 93                if exports == "results" || exports == "none" { return "" }
 94            }
 95            return element(child, indent: indent)
 96        }.filter { !$0.isEmpty }
 97        return parts.isEmpty ? "" : parts.joined(separator: "\n\n") + "\n\n"
 98    }
 99
100    private func blocks(text: String) -> String {
101        let tree = OrgParser.parse(text, defaults: settings)
102        return rendering(tree, text) { blocks(tree.root) }
103    }
104
105    private func element(_ node: SyntaxNode, indent: String) -> String {
106        switch node.kind {
107        case .zerothSection, .section:
108            if node.kind == .section, let heading = node.firstChild(.heading) {
109                switch HTMLRenderer.sectionExport(heading, options: options, selected: selected) {
110                case .nothing: return ""
111                case .heading: return element(heading, indent: indent)
112                case .all: break
113                }
114            }
115            return blocks(node, indent: indent).trimmingCharacters(in: .newlines)
116        case .heading:
117            let level = node.tokens.first { $0.kind == .stars }?.text.count ?? 1
118            var parts: [String] = []
119            if options.todo, let todo = node.tokens.first(where: { $0.kind == .todoKeyword })?.text { parts.append(todo) }
120            if options.priority, let priority = node.tokens.first(where: { $0.kind == .priority })?.text { parts.append(priority) }
121            if let title = node.firstChild(.title) { parts.append(inline(title).trimmingCharacters(in: .whitespaces)) }
122            if options.tags, let tags = node.tokens.first(where: { $0.kind == .tags })?.text {
123                parts.append(tags.split(separator: ":").map { "`\($0)`" }.joined(separator: " "))
124            }
125            return String(repeating: "#", count: min(level + 1, 6)) + " " + parts.filter { !$0.isEmpty }.joined(separator: " ")
126        case .keyword where citations != nil && node.text.range(of: "^[ \\t]*#\\+print_bibliography:", options: [.regularExpression, .caseInsensitive]) != nil:
127            return citations!.bibliography.map { indent + render($0) }.joined(separator: "\n\n")
128        case .paragraph:
129            return indent + inline(node).trimmingCharacters(in: .whitespacesAndNewlines)
130                .components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: "\n" + indent)
131        case .plainList:
132            return list(node, indent: indent)
133        case .table:
134            return table(node, indent: indent)
135        case .block:
136            return block(node, indent: indent)
137        case .horizontalRule:
138            return indent + "---"
139        case .tableEl:
140            let lines = node.text.components(separatedBy: "\n").filter { !$0.isEmpty && !$0.lowercased().contains("#+tblfm") }
141            return fence(lines, language: "", indent: indent)
142        case .fixedWidth:
143            let lines = node.text.split(separator: "\n").map { line -> String in
144                let trimmed = line.drop { $0 == " " || $0 == "\t" }
145                return trimmed.hasPrefix(": ") ? String(trimmed.dropFirst(2)) : String(trimmed.dropFirst(trimmed.hasPrefix(":") ? 1 : 0))
146            }
147            return fence(lines, language: "", indent: indent)
148        default:
149            return ""
150        }
151    }
152
153    private func fence(_ lines: [String], language: String, indent: String) -> String {
154        let longest = lines.map { $0.prefix { $0 == "`" }.count }.max() ?? 0
155        let ticks = String(repeating: "`", count: max(3, longest + 1))
156        return ([indent + ticks + language] + lines.map { indent + $0 } + [indent + ticks]).joined(separator: "\n")
157    }
158
159    private func list(_ node: SyntaxNode, indent: String) -> String {
160        var out: [String] = []
161        var number = 0
162        for item in node.children where item.kind == .item {
163            let bullet = item.tokens.first { $0.kind == .bullet }?.text ?? "-"
164            let ordered = bullet.first.map { $0.isNumber || $0.isLetter } ?? false
165            number += 1
166            var marker = ordered ? "\(number)." : "-"
167            if let box = item.tokens.first(where: { $0.kind == .checkbox })?.text {
168                marker += box == "[X]" || box == "[x]" ? " [x]" : " [ ]"
169            }
170            let childIndent = indent + String(repeating: " ", count: (ordered ? "\(number). " : "- ").count)
171            var parts: [String] = []
172            let term = item.firstChild(.itemTag).map { "**" + inline($0).trimmingCharacters(in: .whitespaces) + "**: " }
173            for (index, child) in item.children.filter({ $0.kind != .itemTag }).enumerated() {
174                if index == 0, child.kind == .paragraph {
175                    let text = inline(child).trimmingCharacters(in: .whitespacesAndNewlines)
176                        .components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.joined(separator: "\n" + childIndent)
177                    parts.append((term ?? "") + text)
178                } else {
179                    parts.append(element(child, indent: childIndent))
180                }
181            }
182            if let term, parts.first.map({ !$0.hasPrefix(term) }) ?? true { parts.insert(term.trimmingCharacters(in: .whitespaces), at: 0) }
183            let body = parts.isEmpty ? "" : parts[0].trimmingCharacters(in: .whitespaces) + parts.dropFirst().map { "\n" + $0 }.joined()
184            out.append(indent + marker + " " + body)
185        }
186        return out.joined(separator: "\n")
187    }
188
189    private func table(_ node: SyntaxNode, indent: String) -> String {
190        var rows: [[String]] = []
191        var ruleAfter: Int?
192        for row in node.children where row.kind == .tableRow {
193            let cells = row.children.filter { $0.kind == .tableCell }
194            if cells.isEmpty {
195                if ruleAfter == nil, !rows.isEmpty { ruleAfter = rows.count }
196                continue
197            }
198            rows.append(cells.map { inline($0).trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "|", with: "\\|") })
199        }
200        guard !rows.isEmpty else { return "" }
201        let columns = rows.map(\.count).max() ?? 0
202        rows = rows.map { $0 + Array(repeating: "", count: columns - $0.count) }
203        var header: [String]
204        var body: [[String]]
205        if ruleAfter == 1 {
206            header = rows[0]
207            body = Array(rows.dropFirst())
208        } else {
209            header = Array(repeating: "", count: columns)
210            body = rows
211        }
212        func line(_ cells: [String]) -> String { indent + "| " + cells.joined(separator: " | ") + " |" }
213        return ([line(header), indent + "|" + Array(repeating: "---", count: columns).joined(separator: "|") + "|"] + body.map(line)).joined(separator: "\n")
214    }
215
216    private func block(_ node: SyntaxNode, indent: String) -> String {
217        var lines = node.text.components(separatedBy: "\n")
218        if lines.last == "" { lines.removeLast() }
219        guard let first = lines.first, let m = first.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)[ \t]*(.*)$/) else { return "" }
220        let type = m.1.lowercased()
221        let parameters = String(m.2)
222        var body = Array(lines.dropFirst().dropLast()).map {
223            $0.replacingOccurrences(of: "^([ \\t]*),([,*]|#\\+)", with: "$1$2", options: .regularExpression)
224        }
225        let common = body.filter { $0.contains(where: { !$0.isWhitespace }) }.map { $0.prefix { $0 == " " }.count }.min() ?? 0
226        body = body.map { String($0.dropFirst(min(common, $0.prefix { $0 == " " }.count))) }
227        switch type {
228        case "src":
229            return fence(body, language: parameters.split(separator: " ").first.map(String.init) ?? "", indent: indent)
230        case "example":
231            return fence(body, language: "", indent: indent)
232        case "quote":
233            return blocks(text: body.joined(separator: "\n")).trimmingCharacters(in: .newlines)
234                .components(separatedBy: "\n").map { indent + ($0.isEmpty ? ">" : "> " + $0) }.joined(separator: "\n")
235        case "verse":
236            return body.map { indent + inlineString($0) + "  " }.joined(separator: "\n")
237        case "export":
238            let backend = parameters.lowercased()
239            return backend.hasPrefix("markdown") || backend.hasPrefix("md") || backend.hasPrefix("html") ? body.joined(separator: "\n") : ""
240        case "comment":
241            return ""
242        default:
243            return blocks(text: body.joined(separator: "\n")).trimmingCharacters(in: .newlines)
244        }
245    }
246
247    func inline(_ node: SyntaxNode) -> String {
248        var out = ""
249        for element in node.elements {
250            switch element {
251            case .token(let token):
252                switch token.kind {
253                case .marker, .stars, .bullet, .checkbox, .tags, .todoKeyword, .priority: continue
254                default: out += token.text
255                }
256            case .node(let child):
257                out += object(child)
258            }
259        }
260        return out
261    }
262
263    /// A citation's or a bibliography entry's pieces, prefixes and suffixes as Org markup.
264    private func render(_ pieces: [CiteProcessor.Piece]) -> String {
265        pieces.map { piece in
266            switch piece {
267            case .text(let s): s
268            case .italic(let s): "*" + s + "*"
269            case .org(let s) where s.allSatisfy(\.isWhitespace): s
270            case .org(let s):
271                String(s.prefix { $0.isWhitespace }) + inlineString(s) + (s.allSatisfy(\.isWhitespace) ? "" : String(s.reversed().prefix { $0.isWhitespace }))
272            }
273        }.joined()
274    }
275
276    private func code(_ text: String) -> String {
277        let ticks = text.contains("`") ? "``" : "`"
278        return ticks + (ticks == "``" ? " " + text + " " : text) + ticks
279    }
280
281    private func object(_ node: SyntaxNode) -> String {
282        switch node.kind {
283        case .bold: return "**\(inline(node))**"
284        case .italic: return "*\(inline(node))*"
285        case .underline: return "<u>\(inline(node))</u>"
286        case .strikeThrough: return "~~\(inline(node))~~"
287        case .verbatim, .code: return code(inline(node))
288        case .link: return link(node)
289        case .linkDescription: return inline(node)
290        case .timestamp:
291            guard let stamp = Timestamp.parse(node.text) else { return node.text }
292            func show(_ p: Timestamp.Point) -> String {
293                String(format: "%04d-%02d-%02d", p.year, p.month, p.day) + (p.hour.map { String(format: " %02d:%02d", $0, p.minute ?? 0) } ?? "")
294            }
295            return show(stamp.start) + (stamp.end.map { "–" + show($0) } ?? "")
296        case .footnoteReference: return footnote(node.text)
297        case .entity:
298            let name = node.text.dropFirst().replacingOccurrences(of: "{}", with: "")
299            return OrgEntities.display[name] ?? node.text
300        case .radioTarget:
301            return String(node.text.dropFirst(3).dropLast(3))
302        case .superscript, .subscript:
303            let body = node.text.dropFirst()
304            let braced = body.hasPrefix("{") && body.hasSuffix("}")
305            if options.scripts == .off || (options.scripts == .braces && !braced) { return node.text }
306            let inner = braced ? String(body.dropFirst().dropLast()) : String(body)
307            return node.text.hasPrefix("_") ? "<sub>\(inner)</sub>" : "<sup>\(inner)</sup>"
308        case .lineBreak: return "  \n"
309        case .macro:
310            guard case .some(let value) = source?.resultsMacro(node) else { return "" }
311            return value.map(inlineString) ?? ""
312        case .target: return ""
313        case .inlineSourceBlock:
314            let exports = source?.exports(at: node.range.lowerBound) ?? "results"
315            source?.inlineResults = exports == "results" || exports == "both"
316            guard exports == "code" || exports == "both" else { return "" }
317            if let m = node.text.firstMatch(of: /\{(.*)\}$/) { return code(String(m.1)) }
318            return node.text
319        // ox-md uses ox-html's translator: only HTML snippets.
320        case .exportSnippet:
321            guard node.tokens.first?.text == "@@html:" else { return "" }
322            return node.tokens.filter { $0.kind != .marker }.map(\.text).joined()
323        case .citation:
324            if inTitle { return "" }
325            guard let pieces = citations?.next(node.text) else { return node.text }
326            return render(pieces)
327        case .inlineBabelCall:
328            source?.inlineResults = (source?.exports(at: node.range.lowerBound) ?? "results") == "results"
329            return ""
330        default: return inline(node)
331        }
332    }
333
334    private func link(_ node: SyntaxNode) -> String {
335        guard let path = node.tokens.first(where: { $0.kind == .linkPath })?.text else {
336            // A radio link is its text.
337            if !node.text.hasPrefix("<"), !node.text.contains(":") { return node.text }
338            var target = node.text
339            if target.hasPrefix("<"), target.hasSuffix(">") { target = String(target.dropFirst().dropLast()) }
340            return "<\(target)>"
341        }
342        var href = path
343        if path.hasPrefix("file:") {
344            // ox-md drops the search option and, as `org-md-link-org-files-as-md`, writes .org as .md.
345            href = String(path.dropFirst(5))
346            if let search = href.range(of: "::") { href = String(href[..<search.lowerBound]) }
347        }
348        if path.hasPrefix("id:") { href = "#" + path.dropFirst(3) }
349        if !path.contains(":") || path.hasPrefix("file:"), href.lowercased().hasSuffix(".org") { href = String(href.dropLast(4)) + ".md" }
350        if let description = node.firstChild(.linkDescription) { return "[\(inline(description))](\(href))" }
351        let ext = href.split(separator: ".").last.map { $0.lowercased() } ?? ""
352        if HTMLRenderer.imageExtensions.contains(ext) { return "![](\(href))" }
353        return path.contains("://") ? "<\(href)>" : "[\(href)](\(href))"
354    }
355
356    private func footnote(_ text: String) -> String {
357        guard let m = text.firstMatch(of: /^\[fn:([^:\]]*)(?::(.*))?\]$/) else { return text }
358        var label = String(m.1)
359        if label.isEmpty {
360            anonymous += 1
361            label = "anonymous-\(anonymous)"
362        }
363        if let n = numbers[label] { return "[^\(n)]" }
364        guard let content = m.2.map(String.init) ?? definitions[label] else { return text }
365        let n = notes.count + 1
366        numbers[label] = n
367        notes.append((n, inlineString(content.replacingOccurrences(of: "\n", with: " "))))
368        return "[^\(n)]"
369    }
370}