Sources/OrgCore/Export/ExportScope.swift
120 lines · 8278 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 ("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 /// Keywords of the file that name it or its export, left out of a shared entry.
60 static let fileOnlyKeywords: Set<String> = ["TITLE", "SUBTITLE", "EXPORT_FILE_NAME"]
61
62 /// The subtree containing `offset` as it is in the file, to share as an org file of its own:
63 /// the file's keyword lines (but its title and export name), then the heading and
64 /// everything under it, promoted so the heading is level 1. Its range in `text` and the
65 /// heading's title, links as their descriptions, come with it. Nil before the first heading.
66 public static func entry(_ text: String, at offset: Int, settings: OrgSettings = .default) -> (text: String, range: Range<Int>, title: String)? {
67 let tree = OrgParser.parse(text, defaults: settings)
68 let model = DocumentModel(tree: tree)
69 guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) else { return nil }
70 let heading = model.headings[index]
71 let ns = text as NSString
72 let start = heading.headingRange.lowerBound
73 let end = model.headings[(index + 1)...].first { $0.level <= heading.level }?.headingRange.lowerBound ?? ns.length
74 let subtree = ExportPreprocess.shift(ns.substring(with: NSRange(location: start, length: end - start)), to: 1)
75 let lines = preamble(tree).filter { line in
76 guard let m = line.firstMatch(of: #/^#\+([^:\s]+):/#) else { return true }
77 return !fileOnlyKeywords.contains(m.1.uppercased())
78 }
79 let body = subtree.replacing(#/\s+$/#, with: "") + "\n"
80 return ((lines.isEmpty ? "" : lines.joined(separator: "\n") + "\n\n") + body, start..<end, Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces))
81 }
82
83 /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree
84 /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set.
85 public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
86 fileName(OrgParser.parse(text, defaults: settings), subtreeAt: offset, settings: settings)
87 }
88
89 /// The export's name from a parsed file; `settings` gives the setup files' keywords.
90 public static func fileName(_ tree: OrgTree, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
91 if let offset {
92 let model = DocumentModel(tree: tree)
93 if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }),
94 let name = model.headings[index].properties.last(where: { $0.key.uppercased() == "EXPORT_FILE_NAME" })?.value, !name.isEmpty {
95 return name
96 }
97 }
98 var name: String?
99 for line in (settings.setupKeywords.split(separator: "\n").map(String.init) + preamble(tree)) {
100 if let m = line.firstMatch(of: #/(?i)^#\+EXPORT_FILE_NAME:[ \t]*(.*?)[ \t]*$/#), !m.1.isEmpty { name = String(m.1) }
101 }
102 return name
103 }
104
105 /// Where the export of `source` is written: `name` (relative to the source's folder, `~`
106 /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
107 public static func output(for source: URL, name: String?, extension ext: String) -> URL {
108 guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
109 let expanded = OrgPaths.expandingTilde(name)
110 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
111 return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
112 }
113
114 /// The keyword lines before the first heading.
115 static func preamble(_ tree: OrgTree) -> [String] {
116 tree.root.children.filter { $0.kind == .zerothSection }
117 .flatMap { $0.children.filter { $0.kind == .keyword } }
118 .map { $0.text.trimmingCharacters(in: .newlines) }
119 }
120}