Sources/OrgCore/Export/MarkdownExport.swift

8dea72acea277d24d8a83e0843087d50d5af8667
orgstar/Sources/OrgCore/Export/MarkdownExport.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form