Sources/OrgCore/Export/ExportScope.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Export/ExportScope.swift history · blame · raw

96 lines · 6522 bytes

6 symbols in this file
 1import Foundation
 2
 3/// What an export covers and where it goes, as Org's export dispatcher decides them: the whole
 4/// file or the subtree at point (`org-export-as` with SUBTREEP), and `#+EXPORT_FILE_NAME` or
 5/// the subtree's `EXPORT_FILE_NAME` (`org-export-output-file-name`).
 6public enum ExportScope {
 7    /// Subtree properties that stand in for the file's keywords, as `org-export-options-alist`
 8    /// and the backends' options name them.
 9    static let overrides: [(property: String, keyword: String)] = [
10        ("EXPORT_TITLE", "TITLE"), ("EXPORT_AUTHOR", "AUTHOR"), ("EXPORT_DATE", "DATE"), ("EXPORT_EMAIL", "EMAIL"),
11        ("EXPORT_OPTIONS", "OPTIONS"), ("EXPORT_SELECT_TAGS", "SELECT_TAGS"), ("EXPORT_EXCLUDE_TAGS", "EXCLUDE_TAGS"),
12        ("EXPORT_HTML_HEAD", "HTML_HEAD"), ("EXPORT_HTML_HEAD_EXTRA", "HTML_HEAD_EXTRA"),
13        ("EXPORT_SUBTITLE", "SUBTITLE"), ("EXPORT_KEYWORDS", "KEYWORDS"), ("EXPORT_DESCRIPTION", "DESCRIPTION"), ("EXPORT_LANGUAGE", "LANGUAGE"),
14        ("EXPORT_LATEX_CLASS", "LATEX_CLASS"), ("EXPORT_LATEX_CLASS_OPTIONS", "LATEX_CLASS_OPTIONS"), ("EXPORT_LATEX_HEADER", "LATEX_HEADER"),
15        ("EXPORT_LATEX_HEADER_EXTRA", "LATEX_HEADER_EXTRA"), ("EXPORT_LATEX_COMPILER", "LATEX_COMPILER"),
16        ("EXPORT_LATEX_CLASS_PRE", "LATEX_CLASS_PRE"), ("EXPORT_LATEX_FOOTNOTE_COMMAND", "LATEX_FOOTNOTE_COMMAND"), ("EXPORT_CITE_EXPORT", "CITE_EXPORT"),
17    ]
18
19    /// The subtree containing `offset` as a document of its own: the file's keyword lines, then
20    /// the heading's title as `#+TITLE` and its `EXPORT_*` properties as keywords, then the
21    /// heading's body without its planning line and property drawer, its children promoted so
22    /// the first is level 1. Nil before the first heading.
23    public static func subtree(_ text: String, at offset: Int, settings: OrgSettings = .default) -> String? {
24        let tree = OrgParser.parse(text, defaults: settings)
25        let model = DocumentModel(tree: tree)
26        guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) else { return nil }
27        let heading = model.headings[index]
28        let ns = text as NSString
29        let end = model.headings[(index + 1)...].first { $0.level <= heading.level }?.headingRange.lowerBound ?? ns.length
30        let bodyStart = NSMaxRange(ns.lineRange(for: NSRange(location: heading.headingRange.lowerBound, length: 0)))
31        var body = bodyStart < end ? ns.substring(with: NSRange(location: bodyStart, length: end - bodyStart)) : ""
32        body = body.replacing(#/^(?:[ \t]*(?:SCHEDULED|DEADLINE|CLOSED):[^\n]*\n)?(?:[ \t]*:PROPERTIES:[ \t]*\n(?:[^\n]*\n)*?[ \t]*:END:[ \t]*(?:\n|$))?/#, with: "", maxReplacements: 1)
33        body = ExportPreprocess.shift(body, to: 1)
34
35        // `org-entry-get`: the last `KEY` value, then each `KEY+` value, joined with spaces;
36        // "nil" is no value.
37        let property = { (key: String) -> String? in
38            let matching = heading.properties.filter { $0.key.uppercased() == key }
39            let base = matching.last { !$0.additive }?.value
40            let values = [base == "nil" ? nil : base] + matching.filter(\.additive).map(\.value)
41            guard values.contains(where: { $0 != nil }) else { return nil }
42            let value = values.compactMap { $0 }.joined(separator: " ")
43            return value == "nil" ? nil : value
44        }
45        // What the subtree sets replaces the file's keywords; `EXPORT_OPTIONS` only the items
46        // it names.
47        let replaced = Set(overrides.filter { $0.property == "EXPORT_TITLE" || ($0.property != "EXPORT_OPTIONS" && property($0.property) != nil) }.map(\.keyword))
48        var lines = preamble(tree).filter { line in
49            guard let m = line.firstMatch(of: #/^#\+([^:\s]+):/#) else { return true }
50            return !replaced.contains(m.1.uppercased())
51        }
52        lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)))
53        for (key, keyword) in overrides where key != "EXPORT_TITLE" {
54            if let value = property(key) { lines.append("#+\(keyword): \(value)") }
55        }
56        return lines.joined(separator: "\n") + "\n" + body
57    }
58
59    /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree
60    /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set.
61    public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
62        fileName(OrgParser.parse(text, defaults: settings), subtreeAt: offset, settings: settings)
63    }
64
65    /// The export's name from a parsed file; `settings` gives the setup files' keywords.
66    public static func fileName(_ tree: OrgTree, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
67        if let offset {
68            let model = DocumentModel(tree: tree)
69            if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }),
70               let name = model.headings[index].properties.last(where: { $0.key.uppercased() == "EXPORT_FILE_NAME" })?.value, !name.isEmpty {
71                return name
72            }
73        }
74        var name: String?
75        for line in (settings.setupKeywords.split(separator: "\n").map(String.init) + preamble(tree)) {
76            if let m = line.firstMatch(of: #/(?i)^#\+EXPORT_FILE_NAME:[ \t]*(.*?)[ \t]*$/#), !m.1.isEmpty { name = String(m.1) }
77        }
78        return name
79    }
80
81    /// Where the export of `source` is written: `name` (relative to the source's folder, `~`
82    /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
83    public static func output(for source: URL, name: String?, extension ext: String) -> URL {
84        guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
85        let expanded = OrgPaths.expandingTilde(name)
86        let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
87        return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
88    }
89
90    /// The keyword lines before the first heading.
91    static func preamble(_ tree: OrgTree) -> [String] {
92        tree.root.children.filter { $0.kind == .zerothSection }
93            .flatMap { $0.children.filter { $0.kind == .keyword } }
94            .map { $0.text.trimmingCharacters(in: .newlines) }
95    }
96}