Sources/OrgCore/Export/MarkdownExport.swift

0e58e1b1ae285390762ec1b8bf93c882ecc94a02
orgstar/Sources/OrgCore/Export/MarkdownExport.swift history · blame · raw

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