Sources/OrgCore/Export/ExportOptions.swift
338 lines · 17180 bytes
1import Foundation
2
3/// What an export includes, from `#+OPTIONS` and the export keywords (ox.el, Org 9.8.7).
4public struct ExportOptions: Sendable, Equatable {
5 public enum Scripts: Sendable, Equatable {
6 case on
7 /// `^:{}`: only `_{…}` and `^{…}`.
8 case braces
9 case off
10 }
11
12 /// `toc`: the table of contents' depth, nil for none.
13 public var toc: Int?
14 /// `num`: section numbers to this depth, nil for none.
15 public var num: Int?
16 public var tags = true
17 /// `tags:not-in-toc`.
18 public var tagsInTOC = true
19 public var todo = true
20 public var priority = false
21 public var scripts = Scripts.on
22 /// `H`: the deepest heading level the TOC and numbering count.
23 public var headlineLevels = 3
24 public var tex = true
25 public var author = true
26 public var date = true
27 public var title = true
28 /// `-`: `--`, `---`, `...` and `\-` as special strings.
29 public var specialStrings = true
30 /// `<`, as written: nil, t, active, inactive; nil when not given.
31 public var timestamps: String?
32 public var excludeTags = ["noexport"]
33 public var selectTags = ["export"]
34 /// `#+HTML_HEAD` and `#+HTML_HEAD_EXTRA` lines, in order.
35 public var htmlHead: [String] = []
36
37 /// `org-export-with-*` defaults.
38 public static let org = ExportOptions(toc: 3, num: 3)
39
40 /// The shape the conformance corpus holds: no table of contents or numbers, priorities
41 /// shown.
42 public static let orgo: ExportOptions = {
43 var options = ExportOptions(toc: nil, num: nil)
44 options.priority = true
45 return options
46 }()
47
48 /// `defaults` with the document's `#+OPTIONS`, `#+EXCLUDE_TAGS`, `#+SELECT_TAGS` and
49 /// `#+HTML_HEAD` applied.
50 public static func parse(_ text: String, defaults: ExportOptions = .org) -> ExportOptions {
51 var options = defaults
52 var tocSet: String?
53 var numSet: String?
54 for m in text.matches(of: #/(?mi)^[ \t]*#\+(OPTIONS|EXCLUDE_TAGS|SELECT_TAGS|HTML_HEAD|HTML_HEAD_EXTRA):[ \t]*(.*?)[ \t]*$/#) {
55 let value = String(m.2)
56 switch m.1.uppercased() {
57 case "EXCLUDE_TAGS": options.excludeTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
58 case "SELECT_TAGS": options.selectTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
59 case "HTML_HEAD", "HTML_HEAD_EXTRA": options.htmlHead.append(value)
60 default:
61 for item in value.matches(of: /(\S+?):(\S+)/) {
62 let key = String(item.1)
63 let v = String(item.2)
64 let on = v != "nil"
65 switch key {
66 case "toc": tocSet = v
67 case "num": numSet = v
68 case "tags":
69 options.tags = on
70 options.tagsInTOC = v != "not-in-toc"
71 case "todo": options.todo = on
72 case "pri": options.priority = on
73 case "^": options.scripts = v == "{}" ? .braces : on ? .on : .off
74 case "H": if let n = Int(v) { options.headlineLevels = n }
75 case "tex": options.tex = on
76 case "author": options.author = on
77 case "date": options.date = on
78 case "title": options.title = on
79 case "-": options.specialStrings = on
80 case "<": options.timestamps = v
81 default: break
82 }
83 }
84 }
85 }
86 // `toc` and `num` as t (to H), nil or a depth.
87 func depth(_ v: String?, _ current: Int?) -> Int? {
88 guard let v else { return current.map { _ in options.headlineLevels } }
89 if v == "nil" { return nil }
90 return Int(v).map { min($0, options.headlineLevels) } ?? options.headlineLevels
91 }
92 options.toc = depth(tocSet, options.toc)
93 options.num = depth(numSet, options.num)
94 return options
95 }
96}
97
98/// What happens to the text before it's parsed for export: `#+INCLUDE` (ox.el's
99/// `org-export-expand-include-keyword`) and macros (`org-macro-replace-all`).
100public enum ExportPreprocess {
101 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
102 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
103 public static func includes(_ text: String, directory: URL?, depth: Int = 0) -> String {
104 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text }
105 var lines: [String] = []
106 for line in text.components(separatedBy: "\n") {
107 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"(.*)$/#) else {
108 lines.append(line)
109 continue
110 }
111 let spec = String(m.1)
112 let rest = String(m.2)
113 var file = spec
114 var target: String?
115 if let r = spec.range(of: "::") {
116 file = String(spec[..<r.lowerBound])
117 target = String(spec[r.upperBound...])
118 }
119 let url = includeURL(file, directory: directory)
120 guard var included = try? String(contentsOf: url, encoding: .utf8) else {
121 lines.append("")
122 continue
123 }
124 if let target { included = subtree(included, target) ?? "" }
125 if let range = rest.firstMatch(of: /:lines[ \t]+"([0-9]*)-([0-9]*)"/) {
126 let all = included.components(separatedBy: "\n")
127 let low = max(1, Int(range.1) ?? 1)
128 let high = min(all.count, (Int(range.2).map { $0 - 1 }) ?? all.count)
129 included = low <= high ? all[(low - 1)..<high].joined(separator: "\n") : ""
130 }
131 let words = rest.replacingOccurrences(of: ":[a-z-]+[ \\t]+(\"[^\"]*\"|\\S+)", with: "", options: .regularExpression)
132 .split(whereSeparator: \.isWhitespace).map(String.init)
133 if let kind = words.first?.lowercased(), ["src", "example", "export", "quote", "verse", "center", "comment"].contains(kind) {
134 // The words after the kind, as written, up to the first option.
135 var parameter = rest.drop { $0 == " " || $0 == "\t" }.dropFirst(kind.count).drop { $0 == " " || $0 == "\t" }
136 if let option = parameter.firstIndex(of: ":") { parameter = parameter[..<option] }
137 let body = included.hasSuffix("\n") ? String(included.dropLast()) : included
138 let escaped = kind == "src" || kind == "example" ? BlockEdit.escape(body) : body
139 lines.append("#+BEGIN_\(kind)" + (parameter.isEmpty ? "" : " " + parameter))
140 lines.append(escaped)
141 lines.append("#+END_\(kind)")
142 continue
143 }
144 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) {
145 included = shift(included, to: minLevel)
146 }
147 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1)
148 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded)
149 }
150 return lines.joined(separator: "\n")
151 }
152
153 /// The files `#+INCLUDE` names in `text`, and in the files they include, that can't be read.
154 public static func unreadableIncludes(_ text: String, directory: URL?, depth: Int = 0) -> [String] {
155 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return [] }
156 var unreadable: [String] = []
157 for line in text.components(separatedBy: "\n") {
158 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"/#) else { continue }
159 let spec = String(m.1)
160 let url = includeURL(spec.range(of: "::").map { String(spec[..<$0.lowerBound]) } ?? spec, directory: directory)
161 guard let included = try? String(contentsOf: url, encoding: .utf8) else {
162 if !unreadable.contains(url.path) { unreadable.append(url.path) }
163 continue
164 }
165 for path in unreadableIncludes(included, directory: url.deletingLastPathComponent(), depth: depth + 1) where !unreadable.contains(path) {
166 unreadable.append(path)
167 }
168 }
169 return unreadable
170 }
171
172 /// An include's file, relative to `directory`.
173 static func includeURL(_ file: String, directory: URL?) -> URL {
174 (file as NSString).isAbsolutePath || directory == nil
175 ? URL(fileURLWithPath: OrgPaths.expandingTilde(file))
176 : directory!.appendingPathComponent(file)
177 }
178
179 /// The subtree of `text` at `*Heading` or `#custom-id`.
180 static func subtree(_ text: String, _ target: String) -> String? {
181 let tree = OrgParser.parse(text)
182 let model = DocumentModel(tree: tree)
183 let found: Int?
184 if target.hasPrefix("#") {
185 let id = String(target.dropFirst())
186 found = model.headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
187 } else {
188 let title = target.hasPrefix("*") ? String(target.dropFirst()) : target
189 found = model.headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
190 }
191 guard let index = found else { return nil }
192 let start = model.headings[index].headingRange.lowerBound
193 let end = model.headings[(index + 1)...].first { $0.level <= model.headings[index].level }?.headingRange.lowerBound ?? (text as NSString).length
194 return (text as NSString).substring(with: NSRange(location: start, length: end - start))
195 }
196
197 /// Headings moved so the shallowest is at `level`.
198 static func shift(_ text: String, to level: Int) -> String {
199 let levels = text.matches(of: #/(?m)^(\*+) /#).map { $0.1.count }
200 guard let shallowest = levels.min() else { return text }
201 let delta = level - shallowest
202 guard delta != 0 else { return text }
203 return text.components(separatedBy: "\n").map { line in
204 guard let m = line.firstMatch(of: #/^(\*+) /#) else { return line }
205 return String(repeating: "*", count: max(1, m.1.count + delta)) + line[m.1.endIndex...]
206 }.joined(separator: "\n")
207 }
208
209 /// `{{{name(arg, …)}}}` replaced: `#+MACRO` definitions with `$1`… and the built-in title,
210 /// author, date, email, input-file, keyword, property, n and time macros. Others become
211 /// empty, as Lisp ones do here.
212 /// `setup` is the setup files' keyword lines, whose definitions count too.
213 public static func macros(_ text: String, path: String?, now: Date = Date(), setup: String = "") -> String {
214 guard text.contains("{{{") else { return text }
215 var definitions: [String: String] = [:]
216 var keywords: [String: String] = [:]
217 for m in (setup + text).matches(of: #/(?mi)^[ \t]*#\+([A-Z_]+):[ \t]*(.*?)[ \t]*$/#) {
218 let key = m.1.uppercased()
219 let value = String(m.2)
220 if key == "MACRO", let d = value.firstMatch(of: /^(\S+)[ \t]*(.*)$/) {
221 definitions[d.1.lowercased()] = String(d.2)
222 } else if keywords[key] == nil {
223 keywords[key] = value
224 }
225 }
226 var counters: [String: Int] = [:]
227 var model: DocumentModel?
228 /// `org-entry-get` with `selective` inheritance at the heading holding `location`, or
229 /// at the entry `search` finds (`*Title`, `#custom-id` or a title).
230 func property(_ name: String, _ search: String?, at location: Int) -> String {
231 if model == nil { model = DocumentModel(tree: OrgParser.parse(text)) }
232 let headings = model!.headings
233 let index: Int?
234 if let search, !search.isEmpty {
235 if search.hasPrefix("#") {
236 let id = String(search.dropFirst())
237 index = headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
238 } else {
239 let title = search.hasPrefix("*") ? String(search.dropFirst()) : search
240 index = headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
241 }
242 } else {
243 index = headings.lastIndex { $0.headingRange.lowerBound <= location }
244 }
245 guard let index else { return "" }
246 if name.uppercased() == "ITEM" { return headings[index].title }
247 return model!.property(name, of: index)?.value ?? ""
248 }
249 let regex = try! NSRegularExpression(pattern: "\\{\\{\\{([-A-Za-z0-9_]+)(?:\\((.*?)\\))?\\}\\}\\}")
250 var out = ""
251 var at = 0
252 let ns = text as NSString
253 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
254 out += ns.substring(with: NSRange(location: at, length: m.range.location - at))
255 at = NSMaxRange(m.range)
256 // Not on #+MACRO lines themselves.
257 let lineStart = ns.lineRange(for: NSRange(location: m.range.location, length: 0)).location
258 if ns.substring(from: lineStart).range(of: "^[ \\t]*#\\+MACRO:", options: [.regularExpression, .caseInsensitive]) != nil {
259 out += ns.substring(with: m.range)
260 continue
261 }
262 let name = ns.substring(with: m.range(at: 1)).lowercased()
263 // Inline results stay for the exporter, which shows them as `:exports` says.
264 if name == "results", definitions[name] == nil {
265 out += ns.substring(with: m.range)
266 continue
267 }
268 let args = m.range(at: 2).location == NSNotFound ? [] : arguments(ns.substring(with: m.range(at: 2)))
269 let location = m.range.location
270 out += expand(name, args, definitions: definitions, keywords: keywords, counters: &counters, path: path, now: now) {
271 property($0, $1, at: location)
272 }
273 }
274 out += ns.substring(from: at)
275 return out
276 }
277
278 /// Macro arguments: split on commas, `\,` for a literal one, blanks around trimmed.
279 static func arguments(_ s: String) -> [String] {
280 var args: [String] = []
281 var current = ""
282 var escaped = false
283 for c in s {
284 if escaped {
285 current.append(c == "," ? "," : "\\")
286 if c != "," { current.append(c) }
287 escaped = false
288 } else if c == "\\" {
289 escaped = true
290 } else if c == "," {
291 args.append(current)
292 current = ""
293 } else {
294 current.append(c)
295 }
296 }
297 if escaped { current.append("\\") }
298 args.append(current)
299 return args.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
300 }
301
302 static func expand(_ name: String, _ args: [String], definitions: [String: String], keywords: [String: String],
303 counters: inout [String: Int], path: String?, now: Date, property: (String, String?) -> String) -> String {
304 if let template = definitions[name] {
305 guard !template.hasPrefix("(eval") else { return "" }
306 var result = template
307 for (i, arg) in args.enumerated().reversed() { result = result.replacingOccurrences(of: "$\(i + 1)", with: arg) }
308 return result.replacingOccurrences(of: "\\$[0-9]+", with: "", options: .regularExpression)
309 }
310 switch name {
311 case "title", "author", "date", "email": return keywords[name.uppercased()] ?? ""
312 case "keyword": return args.first.flatMap { keywords[$0.uppercased()] } ?? ""
313 case "input-file": return path.map { ($0 as NSString).lastPathComponent } ?? ""
314 case "property": return args.first.map { property($0, args.count > 1 ? args[1] : nil) } ?? ""
315 case "n":
316 let counter = args.first ?? ""
317 let action = args.count > 1 ? args[1] : ""
318 if action == "-" { return String(counters[counter] ?? 0) }
319 let value = Int(action) ?? ((counters[counter] ?? 0) + 1)
320 counters[counter] = value
321 return String(value)
322 case "time":
323 guard let format = args.first else { return "" }
324 return strftime(format, now)
325 default: return ""
326 }
327 }
328
329 /// `format-time-string` for the common directives.
330 static func strftime(_ format: String, _ date: Date) -> String {
331 var t = time_t(date.timeIntervalSince1970)
332 var tm = tm()
333 localtime_r(&t, &tm)
334 var buffer = [Int8](repeating: 0, count: 256)
335 let count = Foundation.strftime(&buffer, buffer.count, format, &tm)
336 return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self)
337 }
338}