Sources/OrgCore/Export/ExportOptions.swift
314 lines · 15916 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 = (file as NSString).isAbsolutePath || directory == nil
120 ? URL(fileURLWithPath: (file as NSString).expandingTildeInPath)
121 : directory!.appendingPathComponent(file)
122 guard var included = try? String(contentsOf: url, encoding: .utf8) else {
123 lines.append("")
124 continue
125 }
126 if let target { included = subtree(included, target) ?? "" }
127 if let range = rest.firstMatch(of: /:lines[ \t]+"([0-9]*)-([0-9]*)"/) {
128 let all = included.components(separatedBy: "\n")
129 let low = max(1, Int(range.1) ?? 1)
130 let high = min(all.count, (Int(range.2).map { $0 - 1 }) ?? all.count)
131 included = low <= high ? all[(low - 1)..<high].joined(separator: "\n") : ""
132 }
133 let words = rest.replacingOccurrences(of: ":[a-z-]+[ \\t]+(\"[^\"]*\"|\\S+)", with: "", options: .regularExpression)
134 .split(whereSeparator: \.isWhitespace).map(String.init)
135 if let kind = words.first?.lowercased(), ["src", "example", "export", "quote", "verse", "center", "comment"].contains(kind) {
136 // The words after the kind, as written, up to the first option.
137 var parameter = rest.drop { $0 == " " || $0 == "\t" }.dropFirst(kind.count).drop { $0 == " " || $0 == "\t" }
138 if let option = parameter.firstIndex(of: ":") { parameter = parameter[..<option] }
139 let body = included.hasSuffix("\n") ? String(included.dropLast()) : included
140 let escaped = kind == "src" || kind == "example" ? BlockEdit.escape(body) : body
141 lines.append("#+BEGIN_\(kind)" + (parameter.isEmpty ? "" : " " + parameter))
142 lines.append(escaped)
143 lines.append("#+END_\(kind)")
144 continue
145 }
146 if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) {
147 included = shift(included, to: minLevel)
148 }
149 let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1)
150 lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded)
151 }
152 return lines.joined(separator: "\n")
153 }
154
155 /// The subtree of `text` at `*Heading` or `#custom-id`.
156 static func subtree(_ text: String, _ target: String) -> String? {
157 let tree = OrgParser.parse(text)
158 let model = DocumentModel(tree: tree)
159 let found: Int?
160 if target.hasPrefix("#") {
161 let id = String(target.dropFirst())
162 found = model.headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
163 } else {
164 let title = target.hasPrefix("*") ? String(target.dropFirst()) : target
165 found = model.headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
166 }
167 guard let index = found else { return nil }
168 let start = model.headings[index].headingRange.lowerBound
169 let end = model.headings[(index + 1)...].first { $0.level <= model.headings[index].level }?.headingRange.lowerBound ?? (text as NSString).length
170 return (text as NSString).substring(with: NSRange(location: start, length: end - start))
171 }
172
173 /// Headings moved so the shallowest is at `level`.
174 static func shift(_ text: String, to level: Int) -> String {
175 let levels = text.matches(of: #/(?m)^(\*+) /#).map { $0.1.count }
176 guard let shallowest = levels.min() else { return text }
177 let delta = level - shallowest
178 guard delta != 0 else { return text }
179 return text.components(separatedBy: "\n").map { line in
180 guard let m = line.firstMatch(of: #/^(\*+) /#) else { return line }
181 return String(repeating: "*", count: max(1, m.1.count + delta)) + line[m.1.endIndex...]
182 }.joined(separator: "\n")
183 }
184
185 /// `{{{name(arg, …)}}}` replaced: `#+MACRO` definitions with `$1`… and the built-in title,
186 /// author, date, email, input-file, keyword, property, n and time macros. Others become
187 /// empty, as Lisp ones do here.
188 /// `setup` is the setup files' keyword lines, whose definitions count too.
189 public static func macros(_ text: String, path: String?, now: Date = Date(), setup: String = "") -> String {
190 guard text.contains("{{{") else { return text }
191 var definitions: [String: String] = [:]
192 var keywords: [String: String] = [:]
193 for m in (setup + text).matches(of: #/(?mi)^[ \t]*#\+([A-Z_]+):[ \t]*(.*?)[ \t]*$/#) {
194 let key = m.1.uppercased()
195 let value = String(m.2)
196 if key == "MACRO", let d = value.firstMatch(of: /^(\S+)[ \t]*(.*)$/) {
197 definitions[d.1.lowercased()] = String(d.2)
198 } else if keywords[key] == nil {
199 keywords[key] = value
200 }
201 }
202 var counters: [String: Int] = [:]
203 var model: DocumentModel?
204 /// `org-entry-get` with `selective` inheritance at the heading holding `location`, or
205 /// at the entry `search` finds (`*Title`, `#custom-id` or a title).
206 func property(_ name: String, _ search: String?, at location: Int) -> String {
207 if model == nil { model = DocumentModel(tree: OrgParser.parse(text)) }
208 let headings = model!.headings
209 let index: Int?
210 if let search, !search.isEmpty {
211 if search.hasPrefix("#") {
212 let id = String(search.dropFirst())
213 index = headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
214 } else {
215 let title = search.hasPrefix("*") ? String(search.dropFirst()) : search
216 index = headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
217 }
218 } else {
219 index = headings.lastIndex { $0.headingRange.lowerBound <= location }
220 }
221 guard let index else { return "" }
222 if name.uppercased() == "ITEM" { return headings[index].title }
223 return model!.property(name, of: index)?.value ?? ""
224 }
225 let regex = try! NSRegularExpression(pattern: "\\{\\{\\{([-A-Za-z0-9_]+)(?:\\((.*?)\\))?\\}\\}\\}")
226 var out = ""
227 var at = 0
228 let ns = text as NSString
229 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
230 out += ns.substring(with: NSRange(location: at, length: m.range.location - at))
231 at = NSMaxRange(m.range)
232 // Not on #+MACRO lines themselves.
233 let lineStart = ns.lineRange(for: NSRange(location: m.range.location, length: 0)).location
234 if ns.substring(from: lineStart).range(of: "^[ \\t]*#\\+MACRO:", options: [.regularExpression, .caseInsensitive]) != nil {
235 out += ns.substring(with: m.range)
236 continue
237 }
238 let name = ns.substring(with: m.range(at: 1)).lowercased()
239 // Inline results stay for the exporter, which shows them as `:exports` says.
240 if name == "results", definitions[name] == nil {
241 out += ns.substring(with: m.range)
242 continue
243 }
244 let args = m.range(at: 2).location == NSNotFound ? [] : arguments(ns.substring(with: m.range(at: 2)))
245 let location = m.range.location
246 out += expand(name, args, definitions: definitions, keywords: keywords, counters: &counters, path: path, now: now) {
247 property($0, $1, at: location)
248 }
249 }
250 out += ns.substring(from: at)
251 return out
252 }
253
254 /// Macro arguments: split on commas, `\,` for a literal one, blanks around trimmed.
255 static func arguments(_ s: String) -> [String] {
256 var args: [String] = []
257 var current = ""
258 var escaped = false
259 for c in s {
260 if escaped {
261 current.append(c == "," ? "," : "\\")
262 if c != "," { current.append(c) }
263 escaped = false
264 } else if c == "\\" {
265 escaped = true
266 } else if c == "," {
267 args.append(current)
268 current = ""
269 } else {
270 current.append(c)
271 }
272 }
273 if escaped { current.append("\\") }
274 args.append(current)
275 return args.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
276 }
277
278 static func expand(_ name: String, _ args: [String], definitions: [String: String], keywords: [String: String],
279 counters: inout [String: Int], path: String?, now: Date, property: (String, String?) -> String) -> String {
280 if let template = definitions[name] {
281 guard !template.hasPrefix("(eval") else { return "" }
282 var result = template
283 for (i, arg) in args.enumerated().reversed() { result = result.replacingOccurrences(of: "$\(i + 1)", with: arg) }
284 return result.replacingOccurrences(of: "\\$[0-9]+", with: "", options: .regularExpression)
285 }
286 switch name {
287 case "title", "author", "date", "email": return keywords[name.uppercased()] ?? ""
288 case "keyword": return args.first.flatMap { keywords[$0.uppercased()] } ?? ""
289 case "input-file": return path.map { ($0 as NSString).lastPathComponent } ?? ""
290 case "property": return args.first.map { property($0, args.count > 1 ? args[1] : nil) } ?? ""
291 case "n":
292 let counter = args.first ?? ""
293 let action = args.count > 1 ? args[1] : ""
294 if action == "-" { return String(counters[counter] ?? 0) }
295 let value = Int(action) ?? ((counters[counter] ?? 0) + 1)
296 counters[counter] = value
297 return String(value)
298 case "time":
299 guard let format = args.first else { return "" }
300 return strftime(format, now)
301 default: return ""
302 }
303 }
304
305 /// `format-time-string` for the common directives.
306 static func strftime(_ format: String, _ date: Date) -> String {
307 var t = time_t(date.timeIntervalSince1970)
308 var tm = tm()
309 localtime_r(&t, &tm)
310 var buffer = [Int8](repeating: 0, count: 256)
311 let count = Foundation.strftime(&buffer, buffer.count, format, &tm)
312 return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self)
313 }
314}