Sources/OrgCore/Export/ExportScope.swift
79 lines · 5167 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 let property = { (key: String) in heading.properties.last { $0.key.uppercased() == key }?.value }
32 // The title, author and date the subtree sets replace the file's, which Org would
33 // otherwise join.
34 let replaced = Set(overrides.prefix(4).filter { $0.property == "EXPORT_TITLE" || property($0.property) != nil }.map(\.keyword))
35 var lines = preamble(tree).filter { line in
36 guard let m = line.firstMatch(of: #/^#\+([^:\s]+):/#) else { return true }
37 return !replaced.contains(m.1.uppercased())
38 }
39 lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)))
40 for (key, keyword) in overrides where key != "EXPORT_TITLE" {
41 if let value = property(key) { lines.append("#+\(keyword): \(value)") }
42 }
43 return lines.joined(separator: "\n") + "\n" + body
44 }
45
46 /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree
47 /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set.
48 public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
49 let tree = OrgParser.parse(text, defaults: settings)
50 if let offset {
51 let model = DocumentModel(tree: tree)
52 if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }),
53 let name = model.headings[index].properties.last(where: { $0.key.uppercased() == "EXPORT_FILE_NAME" })?.value, !name.isEmpty {
54 return name
55 }
56 }
57 var name: String?
58 for line in (settings.setupKeywords.split(separator: "\n").map(String.init) + preamble(tree)) {
59 if let m = line.firstMatch(of: #/(?i)^#\+EXPORT_FILE_NAME:[ \t]*(.*?)[ \t]*$/#), !m.1.isEmpty { name = String(m.1) }
60 }
61 return name
62 }
63
64 /// Where the export of `source` is written: `name` (relative to the source's folder, `~`
65 /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
66 public static func output(for source: URL, name: String?, extension ext: String) -> URL {
67 guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
68 let expanded = OrgPaths.expandingTilde(name)
69 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
70 return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
71 }
72
73 /// The keyword lines before the first heading.
74 static func preamble(_ tree: OrgTree) -> [String] {
75 tree.root.children.filter { $0.kind == .zerothSection }
76 .flatMap { $0.children.filter { $0.kind == .keyword } }
77 .map { $0.text.trimmingCharacters(in: .newlines) }
78 }
79}