Sources/OrgCore/Export/ExportScope.swift

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

73 lines · 4753 bytes

 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    ]
14
15    /// The subtree containing `offset` as a document of its own: the file's keyword lines, then
16    /// the heading's title as `#+TITLE` and its `EXPORT_*` properties as keywords, then the
17    /// heading's body without its planning line and property drawer, its children promoted so
18    /// the first is level 1. Nil before the first heading.
19    public static func subtree(_ text: String, at offset: Int, settings: OrgSettings = .default) -> String? {
20        let tree = OrgParser.parse(text, defaults: settings)
21        let model = DocumentModel(tree: tree)
22        guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) else { return nil }
23        let heading = model.headings[index]
24        let ns = text as NSString
25        let end = model.headings[(index + 1)...].first { $0.level <= heading.level }?.headingRange.lowerBound ?? ns.length
26        let bodyStart = NSMaxRange(ns.lineRange(for: NSRange(location: heading.headingRange.lowerBound, length: 0)))
27        var body = bodyStart < end ? ns.substring(with: NSRange(location: bodyStart, length: end - bodyStart)) : ""
28        body = body.replacing(#/^(?:[ \t]*(?:SCHEDULED|DEADLINE|CLOSED):[^\n]*\n)?(?:[ \t]*:PROPERTIES:[ \t]*\n(?:[^\n]*\n)*?[ \t]*:END:[ \t]*(?:\n|$))?/#, with: "", maxReplacements: 1)
29        body = ExportPreprocess.shift(body, to: 1)
30
31        var lines = preamble(tree)
32        let property = { (key: String) in heading.properties.last { $0.key.uppercased() == key }?.value }
33        lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)))
34        for (key, keyword) in overrides where key != "EXPORT_TITLE" {
35            if let value = property(key) { lines.append("#+\(keyword): \(value)") }
36        }
37        return lines.joined(separator: "\n") + "\n" + body
38    }
39
40    /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree
41    /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set.
42    public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
43        let tree = OrgParser.parse(text, defaults: settings)
44        if let offset {
45            let model = DocumentModel(tree: tree)
46            if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }),
47               let name = model.headings[index].properties.last(where: { $0.key.uppercased() == "EXPORT_FILE_NAME" })?.value, !name.isEmpty {
48                return name
49            }
50        }
51        var name: String?
52        for line in (settings.setupKeywords.split(separator: "\n").map(String.init) + preamble(tree)) {
53            if let m = line.firstMatch(of: #/(?i)^#\+EXPORT_FILE_NAME:[ \t]*(.*?)[ \t]*$/#), !m.1.isEmpty { name = String(m.1) }
54        }
55        return name
56    }
57
58    /// Where the export of `source` is written: `name` (relative to the source's folder, `~`
59    /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
60    public static func output(for source: URL, name: String?, extension ext: String) -> URL {
61        guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
62        let expanded = (name as NSString).expandingTildeInPath
63        let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
64        return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
65    }
66
67    /// The keyword lines before the first heading.
68    static func preamble(_ tree: OrgTree) -> [String] {
69        tree.root.children.filter { $0.kind == .zerothSection }
70            .flatMap { $0.children.filter { $0.kind == .keyword } }
71            .map { $0.text.trimmingCharacters(in: .newlines) }
72    }
73}