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