Sources/OrgCore/Export/MarkdownExport.swift

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