Sources/OrgCore/Export/ExportOptions.swift
cmc Match ox-odt on included links, blank src lines, local TOCs and Babel defaults
f4b1fe8a56 6 days ago428 lines · 22386 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 /// `#+LATEX_CLASS`, the last one.
37 public var latexClass: String?
38 /// `#+LATEX_CLASS_OPTIONS`, the last one.
39 public var latexClassOptions: String?
40 /// `#+LATEX_HEADER` lines, in order.
41 public var latexHeader: [String] = []
42 /// `#+LATEX_HEADER_EXTRA` lines, in order.
43 public var latexHeaderExtra: [String] = []
44 /// `#+LATEX_COMPILER`, the first one.
45 public var latexCompiler: String?
46 /// Every `#+OPTIONS` item as written, the last value of each.
47 public var items: [String: String] = [:]
48
49 /// `org-export-with-*` defaults.
50 public static let org = ExportOptions(toc: 3, num: 3)
51
52 /// The shape the conformance corpus holds: no table of contents or numbers, priorities
53 /// shown.
54 public static let orgo: ExportOptions = {
55 var options = ExportOptions(toc: nil, num: nil)
56 options.priority = true
57 return options
58 }()
59
60 /// `defaults` with the document's `#+OPTIONS`, `#+EXCLUDE_TAGS`, `#+SELECT_TAGS`,
61 /// `#+HTML_HEAD` and `#+LATEX_*` applied.
62 public static func parse(_ text: String, defaults: ExportOptions = .org) -> ExportOptions {
63 var options = defaults
64 var tocSet: String?
65 var numSet: String?
66 for m in text.matches(of: #/(?mi)^[ \t]*#\+(OPTIONS|EXCLUDE_TAGS|SELECT_TAGS|HTML_HEAD|HTML_HEAD_EXTRA|LATEX_CLASS|LATEX_CLASS_OPTIONS|LATEX_HEADER|LATEX_HEADER_EXTRA|LATEX_COMPILER):[ \t]*(.*?)[ \t]*$/#) {
67 let value = String(m.2)
68 switch m.1.uppercased() {
69 case "EXCLUDE_TAGS": options.excludeTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
70 case "SELECT_TAGS": options.selectTags = value.split(whereSeparator: \.isWhitespace).map(String.init)
71 case "HTML_HEAD", "HTML_HEAD_EXTRA": options.htmlHead.append(value)
72 case "LATEX_CLASS": options.latexClass = value
73 case "LATEX_CLASS_OPTIONS": options.latexClassOptions = value
74 case "LATEX_HEADER": options.latexHeader.append(value)
75 case "LATEX_HEADER_EXTRA": options.latexHeaderExtra.append(value)
76 case "LATEX_COMPILER": if options.latexCompiler == nil { options.latexCompiler = value }
77 default:
78 for item in value.matches(of: /(\S+?):(\S+)/) {
79 let key = String(item.1)
80 let v = String(item.2)
81 options.items[key] = v
82 let on = v != "nil"
83 switch key {
84 case "toc": tocSet = v
85 case "num": numSet = v
86 case "tags":
87 options.tags = on
88 options.tagsInTOC = v != "not-in-toc"
89 case "todo": options.todo = on
90 case "pri": options.priority = on
91 case "^": options.scripts = v == "{}" ? .braces : on ? .on : .off
92 case "H": if let n = Int(v) { options.headlineLevels = n }
93 case "tex": options.tex = on
94 case "author": options.author = on
95 case "date": options.date = on
96 case "title": options.title = on
97 case "-": options.specialStrings = on
98 case "<": options.timestamps = v
99 default: break
100 }
101 }
102 }
103 }
104 // `toc` and `num` as t (to H), nil or a depth.
105 func depth(_ v: String?, _ current: Int?) -> Int? {
106 guard let v else { return current.map { _ in options.headlineLevels } }
107 if v == "nil" { return nil }
108 return Int(v).map { min($0, options.headlineLevels) } ?? options.headlineLevels
109 }
110 options.toc = depth(tocSet, options.toc)
111 options.num = depth(numSet, options.num)
112 return options
113 }
114}
115
116/// What happens to the text before it's parsed for export: `#+INCLUDE` (ox.el's
117/// `org-export-expand-include-keyword`) and macros (`org-macro-replace-all`).
118public enum ExportPreprocess {
119 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
120 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
121 /// `includer` is the exported file's directory, `directory` at the top.
122 public static func includes(_ text: String, directory: URL?, depth: Int = 0, includer: URL? = nil) -> String {
123 let includer = depth == 0 ? directory : includer
124 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text }
125 var lines: [String] = []
126 for line in text.components(separatedBy: "\n") {
127 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"(.*)$/#) else {
128 lines.append(line)
129 continue
130 }
131 let spec = String(m.1)
132 let rest = String(m.2)
133 var file = spec
134 var target: String?
135 if let r = spec.range(of: "::") {
136 file = String(spec[..<r.lowerBound])
137 target = String(spec[r.upperBound...])
138 }
139 let url = includeURL(file, directory: directory)
140 guard var included = try? String(contentsOf: url, encoding: .utf8) else {
141 lines.append("")
142 continue
143 }
144 if let target { included = subtree(included, target) ?? "" }
145 if let range = rest.firstMatch(of: /:lines[ \t]+"([0-9]*)-([0-9]*)"/) {
146 let all = included.components(separatedBy: "\n")
147 let low = max(1, Int(range.1) ?? 1)
148 let high = min(all.count, (Int(range.2).map { $0 - 1 }) ?? all.count)
149 included = low <= high ? all[(low - 1)..<high].joined(separator: "\n") : ""
150 }
151 let words = rest.replacingOccurrences(of: ":[a-z-]+[ \\t]+(\"[^\"]*\"|\\S+)", with: "", options: .regularExpression)
152 .split(whereSeparator: \.isWhitespace).map(String.init)
153 if let kind = words.first?.lowercased(), ["src", "example", "export", "quote", "verse", "center", "comment"].contains(kind) {
154 // The words after the kind, as written, up to the first option.
155 var parameter = rest.drop { $0 == " " || $0 == "\t" }.dropFirst(kind.count).drop { $0 == " " || $0 == "\t" }
156 if let option = parameter.firstIndex(of: ":") { parameter = parameter[..<option] }
157 let body = included.hasSuffix("\n") ? String(included.dropLast()) : included
158 let escaped = kind == "src" || kind == "example" ? BlockEdit.escape(body) : body
159 lines.append("#+BEGIN_\(kind)" + (parameter.isEmpty ? "" : " " + parameter))
160 lines.append(escaped)
161 lines.append("#+END_\(kind)")
162 continue
163 }
164 if let includer { included = rebasingLinks(included, from: url.deletingLastPathComponent(), to: includer) }
165 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) {
166 included = shift(included, to: minLevel)
167 }
168 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1, includer: includer)
169 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded)
170 }
171 return lines.joined(separator: "\n")
172 }
173
174 /// The files `#+INCLUDE` names in `text`, and in the files they include, that can't be read.
175 public static func unreadableIncludes(_ text: String, directory: URL?, depth: Int = 0) -> [String] {
176 guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return [] }
177 var unreadable: [String] = []
178 for line in text.components(separatedBy: "\n") {
179 guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"/#) else { continue }
180 let spec = String(m.1)
181 let url = includeURL(spec.range(of: "::").map { String(spec[..<$0.lowerBound]) } ?? spec, directory: directory)
182 guard let included = try? String(contentsOf: url, encoding: .utf8) else {
183 if !unreadable.contains(url.path) { unreadable.append(url.path) }
184 continue
185 }
186 for path in unreadableIncludes(included, directory: url.deletingLastPathComponent(), depth: depth + 1) where !unreadable.contains(path) {
187 unreadable.append(path)
188 }
189 }
190 return unreadable
191 }
192
193 /// `org-export--update-included-link`: the relative `file` links of a file in `directory`,
194 /// relative to `includer` instead. Links in descriptions too; `plain` for those, which
195 /// can only be plain or angle links.
196 static func rebasingLinks(_ text: String, from directory: URL, to includer: URL, plain: Bool = false) -> String {
197 guard plain || directory.resolvingSymlinksInPath().path != includer.resolvingSymlinksInPath().path else { return text }
198 let ns = text as NSString
199 var edits: [(range: Range<Int>, text: String)] = []
200 for node in OrgParser.parse(text).root.descendants() where node.kind == .link {
201 let whole = node.text
202 if whole.hasPrefix("[[") {
203 guard !plain else { continue }
204 if let description = node.firstChild(.linkDescription) {
205 let rebased = rebasingLinks(description.text, from: directory, to: includer, plain: true)
206 if rebased != description.text { edits.append((description.range, rebased)) }
207 }
208 if let path = node.tokens.first(where: { $0.kind == .linkPath }), let rebased = rebasedPath(path.text, from: directory, to: includer, bracket: true) {
209 edits.append((path.range, rebased))
210 }
211 } else if whole.hasPrefix("<"), whole.hasSuffix(">") {
212 if let rebased = rebasedPath(String(whole.dropFirst().dropLast()), from: directory, to: includer, bracket: false) {
213 edits.append((node.range, "<" + rebased + ">"))
214 }
215 } else if let rebased = rebasedPath(whole, from: directory, to: includer, bracket: false) {
216 edits.append((node.range, rebased))
217 }
218 }
219 guard !edits.isEmpty else { return text }
220 let out = NSMutableString(string: ns)
221 for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
222 out.replaceCharacters(in: NSRange(location: edit.range.lowerBound, length: edit.range.count), with: edit.text)
223 }
224 return out as String
225 }
226
227 /// A link's path rewritten as `org-element-link-interpreter` writes it back: the type only
228 /// when it was written. Nil when it isn't a relative file link.
229 static func rebasedPath(_ raw: String, from directory: URL, to includer: URL, bracket: Bool) -> String? {
230 var type = ""
231 var rest = raw
232 if let m = raw.firstMatch(of: /^(file(?:\+[^:]+)?|[^:\/]+\+file):/) {
233 type = String(m.0)
234 rest = String(raw[m.0.endIndex...])
235 } else if !(bracket && ["/", "./", "../", "~"].contains(where: raw.hasPrefix)) {
236 return nil
237 }
238 var path = rest
239 var search = ""
240 if let r = rest.range(of: "::") {
241 path = String(rest[..<r.lowerBound])
242 search = String(rest[r.lowerBound...])
243 }
244 guard !path.hasPrefix("/"), !path.hasPrefix("~") else { return nil }
245 // `file-relative-name` of `expand-file-name`.
246 func components(_ path: String) -> [String] {
247 var out: [String] = []
248 for part in path.split(separator: "/", omittingEmptySubsequences: true) {
249 if part == "." { continue }
250 if part == ".." { if !out.isEmpty { out.removeLast() } } else { out.append(String(part)) }
251 }
252 return out
253 }
254 let target = components(directory.path + "/" + path)
255 let base = components(includer.path)
256 var common = 0
257 while common < min(target.count, base.count), target[common] == base[common] { common += 1 }
258 let relative = (Array(repeating: "..", count: base.count - common) + target[common...]).joined(separator: "/")
259 return type + (relative.isEmpty ? "." : relative) + search
260 }
261
262 /// An include's file, relative to `directory`.
263 static func includeURL(_ file: String, directory: URL?) -> URL {
264 (file as NSString).isAbsolutePath || directory == nil
265 ? URL(fileURLWithPath: OrgPaths.expandingTilde(file))
266 : directory!.appendingPathComponent(file)
267 }
268
269 /// The subtree of `text` at `*Heading` or `#custom-id`.
270 static func subtree(_ text: String, _ target: String) -> String? {
271 let tree = OrgParser.parse(text)
272 let model = DocumentModel(tree: tree)
273 let found: Int?
274 if target.hasPrefix("#") {
275 let id = String(target.dropFirst())
276 found = model.headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
277 } else {
278 let title = target.hasPrefix("*") ? String(target.dropFirst()) : target
279 found = model.headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
280 }
281 guard let index = found else { return nil }
282 let start = model.headings[index].headingRange.lowerBound
283 let end = model.headings[(index + 1)...].first { $0.level <= model.headings[index].level }?.headingRange.lowerBound ?? (text as NSString).length
284 return (text as NSString).substring(with: NSRange(location: start, length: end - start))
285 }
286
287 /// Headings moved so the shallowest is at `level`.
288 static func shift(_ text: String, to level: Int) -> String {
289 let levels = text.matches(of: #/(?m)^(\*+) /#).map { $0.1.count }
290 guard let shallowest = levels.min() else { return text }
291 let delta = level - shallowest
292 guard delta != 0 else { return text }
293 return text.components(separatedBy: "\n").map { line in
294 guard let m = line.firstMatch(of: #/^(\*+) /#) else { return line }
295 return String(repeating: "*", count: max(1, m.1.count + delta)) + line[m.1.endIndex...]
296 }.joined(separator: "\n")
297 }
298
299 /// `{{{name(arg, …)}}}` replaced: `#+MACRO` definitions with `$1`… and the built-in title,
300 /// author, date, email, input-file, keyword, property, n and time macros. Others become
301 /// empty, as Lisp ones do here.
302 /// `setup` is the setup files' keyword lines, whose definitions count too.
303 public static func macros(_ text: String, path: String?, now: Date = Date(), setup: String = "") -> String {
304 guard text.contains("{{{") else { return text }
305 var definitions: [String: String] = [:]
306 var keywords: [String: String] = [:]
307 for m in (setup + text).matches(of: #/(?mi)^[ \t]*#\+([A-Z_]+):[ \t]*(.*?)[ \t]*$/#) {
308 let key = m.1.uppercased()
309 let value = String(m.2)
310 if key == "MACRO", let d = value.firstMatch(of: /^(\S+)[ \t]*(.*)$/) {
311 definitions[d.1.lowercased()] = String(d.2)
312 } else if keywords[key] == nil {
313 keywords[key] = value
314 }
315 }
316 var counters: [String: Int] = [:]
317 var model: DocumentModel?
318 /// `org-entry-get` with `selective` inheritance at the heading holding `location`, or
319 /// at the entry `search` finds (`*Title`, `#custom-id` or a title).
320 func property(_ name: String, _ search: String?, at location: Int) -> String {
321 if model == nil { model = DocumentModel(tree: OrgParser.parse(text)) }
322 let headings = model!.headings
323 let index: Int?
324 if let search, !search.isEmpty {
325 if search.hasPrefix("#") {
326 let id = String(search.dropFirst())
327 index = headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
328 } else {
329 let title = search.hasPrefix("*") ? String(search.dropFirst()) : search
330 index = headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
331 }
332 } else {
333 index = headings.lastIndex { $0.headingRange.lowerBound <= location }
334 }
335 guard let index else { return "" }
336 if name.uppercased() == "ITEM" { return headings[index].title }
337 return model!.property(name, of: index)?.value ?? ""
338 }
339 let regex = try! NSRegularExpression(pattern: "\\{\\{\\{([-A-Za-z0-9_]+)(?:\\((.*?)\\))?\\}\\}\\}")
340 var out = ""
341 var at = 0
342 let ns = text as NSString
343 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
344 out += ns.substring(with: NSRange(location: at, length: m.range.location - at))
345 at = NSMaxRange(m.range)
346 // Not on #+MACRO lines themselves.
347 let lineStart = ns.lineRange(for: NSRange(location: m.range.location, length: 0)).location
348 if ns.substring(from: lineStart).range(of: "^[ \\t]*#\\+MACRO:", options: [.regularExpression, .caseInsensitive]) != nil {
349 out += ns.substring(with: m.range)
350 continue
351 }
352 let name = ns.substring(with: m.range(at: 1)).lowercased()
353 // Inline results stay for the exporter, which shows them as `:exports` says.
354 if name == "results", definitions[name] == nil {
355 out += ns.substring(with: m.range)
356 continue
357 }
358 let args = m.range(at: 2).location == NSNotFound ? [] : arguments(ns.substring(with: m.range(at: 2)))
359 let location = m.range.location
360 out += expand(name, args, definitions: definitions, keywords: keywords, counters: &counters, path: path, now: now) {
361 property($0, $1, at: location)
362 }
363 }
364 out += ns.substring(from: at)
365 return out
366 }
367
368 /// Macro arguments: split on commas, `\,` for a literal one, blanks around trimmed.
369 static func arguments(_ s: String) -> [String] {
370 var args: [String] = []
371 var current = ""
372 var escaped = false
373 for c in s {
374 if escaped {
375 current.append(c == "," ? "," : "\\")
376 if c != "," { current.append(c) }
377 escaped = false
378 } else if c == "\\" {
379 escaped = true
380 } else if c == "," {
381 args.append(current)
382 current = ""
383 } else {
384 current.append(c)
385 }
386 }
387 if escaped { current.append("\\") }
388 args.append(current)
389 return args.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
390 }
391
392 static func expand(_ name: String, _ args: [String], definitions: [String: String], keywords: [String: String],
393 counters: inout [String: Int], path: String?, now: Date, property: (String, String?) -> String) -> String {
394 if let template = definitions[name] {
395 guard !template.hasPrefix("(eval") else { return "" }
396 var result = template
397 for (i, arg) in args.enumerated().reversed() { result = result.replacingOccurrences(of: "$\(i + 1)", with: arg) }
398 return result.replacingOccurrences(of: "\\$[0-9]+", with: "", options: .regularExpression)
399 }
400 switch name {
401 case "title", "author", "date", "email": return keywords[name.uppercased()] ?? ""
402 case "keyword": return args.first.flatMap { keywords[$0.uppercased()] } ?? ""
403 case "input-file": return path.map { ($0 as NSString).lastPathComponent } ?? ""
404 case "property": return args.first.map { property($0, args.count > 1 ? args[1] : nil) } ?? ""
405 case "n":
406 let counter = args.first ?? ""
407 let action = args.count > 1 ? args[1] : ""
408 if action == "-" { return String(counters[counter] ?? 0) }
409 let value = Int(action) ?? ((counters[counter] ?? 0) + 1)
410 counters[counter] = value
411 return String(value)
412 case "time":
413 guard let format = args.first else { return "" }
414 return strftime(format, now)
415 default: return ""
416 }
417 }
418
419 /// `format-time-string` for the common directives.
420 static func strftime(_ format: String, _ date: Date) -> String {
421 var t = time_t(date.timeIntervalSince1970)
422 var tm = tm()
423 localtime_r(&t, &tm)
424 var buffer = [Int8](repeating: 0, count: 256)
425 let count = Foundation.strftime(&buffer, buffer.count, format, &tm)
426 return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self)
427 }
428}