Sources/OrgCore/Export/ExportOptions.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Export/ExportOptions.swift history · blame · raw

468 lines · 25162 bytes

20 symbols in this file
  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    /// `text` with line ends as Emacs decodes the file: CRLF becomes LF when no line ends in a
120    /// bare LF (dos), CR becomes LF when there is no LF (mac); otherwise every CR stays (unix).
121    public static func decodedLineEnds(_ text: String) -> String {
122        let scalars = Array(text.unicodeScalars)
123        guard scalars.contains("\r") else { return text }
124        guard scalars.contains("\n") else { return text.replacingOccurrences(of: "\r", with: "\n") }
125        for (i, s) in scalars.enumerated() where s == "\n" && (i == 0 || scalars[i - 1] != "\r") { return text }
126        return text.replacingOccurrences(of: "\r\n", with: "\n")
127    }
128
129    /// `org-attach-expand-links`, which Org runs before it parses an export: every `attachment:`
130    /// link of the file at `path` as a `file:` link to the file in its entry's attachment folder,
131    /// or in the file's own folder when the entry has none.
132    public static func attachments(
133        _ text: String, path: String?, settings: OrgSettings,
134        isDirectory: (String) -> Bool = { path in
135            var directory: ObjCBool = false
136            return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
137        }
138    ) -> String {
139        guard let path, text.contains("attachment:") else { return text }
140        let ns = text as NSString
141        let tree = OrgParser.parse(text)
142        var edits: [(range: Range<Int>, link: String)] = []
143        var search = NSRange(location: 0, length: ns.length)
144        while case let found = ns.range(of: "attachment:", range: search), found.location != NSNotFound {
145            search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
146            guard let (link, range) = Links.link(at: found.location, text: text, tree: tree), link.type == "attachment",
147                  range.lowerBound >= (edits.last?.range.upperBound ?? 0),
148                  let file = Links.attachmentFile(link, tree: tree, path: path, idDir: settings.attachIDDir, inherit: settings.attachUseInheritance, isDirectory: isDirectory)
149            else { continue }
150            let written = ns.substring(with: NSRange(location: range.lowerBound, length: range.count))
151            let description = written.hasPrefix("[[") ? written.range(of: "][").map { "[" + written[$0.upperBound...].dropLast(2) + "]" } : nil
152            edits.append((range, "[[file:" + file.path + (file.searchOption.map { "::" + $0 } ?? "") + "]" + (description ?? "") + "]"))
153        }
154        return edits.reversed().reduce(into: NSMutableString(string: text)) {
155            $0.replaceCharacters(in: NSRange(location: $1.range.lowerBound, length: $1.range.count), with: $1.link)
156        } as String
157    }
158
159    /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
160    /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
161    /// `includer` is the exported file's directory, `directory` at the top.
162    public static func includes(_ text: String, directory: URL?, depth: Int = 0, includer: URL? = nil) -> String {
163        let includer = depth == 0 ? directory : includer
164        guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return text }
165        var lines: [String] = []
166        for line in text.components(separatedBy: "\n") {
167            guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"(.*)$/#) else {
168                lines.append(line)
169                continue
170            }
171            let spec = String(m.1)
172            let rest = String(m.2)
173            var file = spec
174            var target: String?
175            if let r = spec.range(of: "::") {
176                file = String(spec[..<r.lowerBound])
177                target = String(spec[r.upperBound...])
178            }
179            let url = includeURL(file, directory: directory)
180            guard var included = (try? String(contentsOf: url, encoding: .utf8)).map(decodedLineEnds) else {
181                lines.append("")
182                continue
183            }
184            if let target { included = subtree(included, target) ?? "" }
185            if let range = rest.firstMatch(of: /:lines[ \t]+"([0-9]*)-([0-9]*)"/) {
186                let all = included.components(separatedBy: "\n")
187                let low = max(1, Int(range.1) ?? 1)
188                let high = min(all.count, (Int(range.2).map { $0 - 1 }) ?? all.count)
189                included = low <= high ? all[(low - 1)..<high].joined(separator: "\n") : ""
190            }
191            let words = rest.replacingOccurrences(of: ":[a-z-]+[ \\t]+(\"[^\"]*\"|\\S+)", with: "", options: .regularExpression)
192                .split(whereSeparator: \.isWhitespace).map(String.init)
193            if let kind = words.first?.lowercased(), ["src", "example", "export", "quote", "verse", "center", "comment"].contains(kind) {
194                // The words after the kind, as written, up to the first option.
195                var parameter = rest.drop { $0 == " " || $0 == "\t" }.dropFirst(kind.count).drop { $0 == " " || $0 == "\t" }
196                if let option = parameter.firstIndex(of: ":") { parameter = parameter[..<option] }
197                let body = included.hasSuffix("\n") ? String(included.dropLast()) : included
198                let escaped = kind == "src" || kind == "example" ? BlockEdit.escape(body) : body
199                lines.append("#+BEGIN_\(kind)" + (parameter.isEmpty ? "" : " " + parameter))
200                lines.append(escaped)
201                lines.append("#+END_\(kind)")
202                continue
203            }
204            if let includer { included = rebasingLinks(included, from: url.deletingLastPathComponent(), to: includer) }
205            if let minLevel = rest.firstMatch(of: /:minlevel[ \t]+([0-9]+)/).flatMap({ Int($0.1) }) {
206                included = shift(included, to: minLevel)
207            }
208            let expanded = includes(included, directory: url.deletingLastPathComponent(), depth: depth + 1, includer: includer)
209            lines.append(expanded.hasSuffix("\n") ? String(expanded.dropLast()) : expanded)
210        }
211        return lines.joined(separator: "\n")
212    }
213
214    /// The files `#+INCLUDE` names in `text`, and in the files they include, that can't be read.
215    public static func unreadableIncludes(_ text: String, directory: URL?, depth: Int = 0) -> [String] {
216        guard depth < 8, text.containsIgnoringASCIICase("#+INCLUDE:") else { return [] }
217        var unreadable: [String] = []
218        for line in text.components(separatedBy: "\n") {
219            guard let m = line.firstMatch(of: #/(?i)^[ \t]*#\+INCLUDE:[ \t]+"([^"]+)"/#) else { continue }
220            let spec = String(m.1)
221            let url = includeURL(spec.range(of: "::").map { String(spec[..<$0.lowerBound]) } ?? spec, directory: directory)
222            guard let included = try? String(contentsOf: url, encoding: .utf8) else {
223                if !unreadable.contains(url.path) { unreadable.append(url.path) }
224                continue
225            }
226            for path in unreadableIncludes(included, directory: url.deletingLastPathComponent(), depth: depth + 1) where !unreadable.contains(path) {
227                unreadable.append(path)
228            }
229        }
230        return unreadable
231    }
232
233    /// `org-export--update-included-link`: the relative `file` links of a file in `directory`,
234    /// relative to `includer` instead. Links in descriptions too; `plain` for those, which
235    /// can only be plain or angle links.
236    static func rebasingLinks(_ text: String, from directory: URL, to includer: URL, plain: Bool = false) -> String {
237        guard plain || directory.resolvingSymlinksInPath().path != includer.resolvingSymlinksInPath().path else { return text }
238        let ns = text as NSString
239        var edits: [(range: Range<Int>, text: String)] = []
240        for node in OrgParser.parse(text).root.descendants() where node.kind == .link {
241            let whole = node.text
242            if whole.hasPrefix("[[") {
243                guard !plain else { continue }
244                if let description = node.firstChild(.linkDescription) {
245                    let rebased = rebasingLinks(description.text, from: directory, to: includer, plain: true)
246                    if rebased != description.text { edits.append((description.range, rebased)) }
247                }
248                if let path = node.tokens.first(where: { $0.kind == .linkPath }), let text = node.linkPath, let rebased = rebasedPath(text, from: directory, to: includer, bracket: true) {
249                    edits.append((path.range, rebased))
250                }
251            } else if whole.hasPrefix("<"), whole.hasSuffix(">") {
252                if let rebased = rebasedPath(String(whole.dropFirst().dropLast()), from: directory, to: includer, bracket: false) {
253                    edits.append((node.range, "<" + rebased + ">"))
254                }
255            } else if let rebased = rebasedPath(whole, from: directory, to: includer, bracket: false) {
256                edits.append((node.range, rebased))
257            }
258        }
259        guard !edits.isEmpty else { return text }
260        let out = NSMutableString(string: ns)
261        for edit in edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
262            out.replaceCharacters(in: NSRange(location: edit.range.lowerBound, length: edit.range.count), with: edit.text)
263        }
264        return out as String
265    }
266
267    /// A link's path rewritten as `org-element-link-interpreter` writes it back: the type only
268    /// when it was written. Nil when it isn't a relative file link.
269    static func rebasedPath(_ raw: String, from directory: URL, to includer: URL, bracket: Bool) -> String? {
270        var type = ""
271        var rest = raw
272        if let m = raw.firstMatch(of: /^(file(?:\+[^:]+)?|[^:\/]+\+file):/) {
273            type = String(m.0)
274            rest = String(raw[m.0.endIndex...])
275        } else if !(bracket && ["/", "./", "../", "~"].contains(where: raw.hasPrefix)) {
276            return nil
277        }
278        var path = rest
279        var search = ""
280        if let r = rest.range(of: "::") {
281            path = String(rest[..<r.lowerBound])
282            search = String(rest[r.lowerBound...])
283        }
284        guard !path.hasPrefix("/"), !path.hasPrefix("~") else { return nil }
285        // `file-relative-name` of `expand-file-name`.
286        func components(_ path: String) -> [String] {
287            var out: [String] = []
288            for part in path.split(separator: "/", omittingEmptySubsequences: true) {
289                if part == "." { continue }
290                if part == ".." { if !out.isEmpty { out.removeLast() } } else { out.append(String(part)) }
291            }
292            return out
293        }
294        let target = components(directory.path + "/" + path)
295        let base = components(includer.path)
296        var common = 0
297        while common < min(target.count, base.count), target[common] == base[common] { common += 1 }
298        let relative = (Array(repeating: "..", count: base.count - common) + target[common...]).joined(separator: "/")
299        return type + (relative.isEmpty ? "." : relative) + search
300    }
301
302    /// An include's file, relative to `directory`.
303    static func includeURL(_ file: String, directory: URL?) -> URL {
304        (file as NSString).isAbsolutePath || directory == nil
305            ? URL(fileURLWithPath: OrgPaths.expandingTilde(file))
306            : directory!.appendingPathComponent(file)
307    }
308
309    /// The subtree of `text` at `*Heading` or `#custom-id`.
310    static func subtree(_ text: String, _ target: String) -> String? {
311        let tree = OrgParser.parse(text)
312        let model = DocumentModel(tree: tree)
313        let found: Int?
314        if target.hasPrefix("#") {
315            let id = String(target.dropFirst())
316            found = model.headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
317        } else {
318            let title = target.hasPrefix("*") ? String(target.dropFirst()) : target
319            found = model.headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
320        }
321        guard let index = found else { return nil }
322        let start = model.headings[index].headingRange.lowerBound
323        let end = model.headings[(index + 1)...].first { $0.level <= model.headings[index].level }?.headingRange.lowerBound ?? (text as NSString).length
324        return (text as NSString).substring(with: NSRange(location: start, length: end - start))
325    }
326
327    /// Headings moved so the shallowest is at `level`.
328    static func shift(_ text: String, to level: Int) -> String {
329        let levels = text.matches(of: #/(?m)^(\*+) /#).map { $0.1.count }
330        guard let shallowest = levels.min() else { return text }
331        let delta = level - shallowest
332        guard delta != 0 else { return text }
333        return text.components(separatedBy: "\n").map { line in
334            guard let m = line.firstMatch(of: #/^(\*+) /#) else { return line }
335            return String(repeating: "*", count: max(1, m.1.count + delta)) + line[m.1.endIndex...]
336        }.joined(separator: "\n")
337    }
338
339    /// `{{{name(arg, …)}}}` replaced: `#+MACRO` definitions with `$1`… and the built-in title,
340    /// author, date, email, input-file, keyword, property, n and time macros. Others become
341    /// empty, as Lisp ones do here.
342    /// `setup` is the setup files' keyword lines, whose definitions count too.
343    public static func macros(_ text: String, path: String?, now: Date = Date(), setup: String = "") -> String {
344        guard text.contains("{{{") else { return text }
345        var definitions: [String: String] = [:]
346        var keywords: [String: String] = [:]
347        for m in (setup + text).matches(of: #/(?mi)^[ \t]*#\+([A-Z_]+):[ \t]*(.*?)[ \t]*$/#) {
348            let key = m.1.uppercased()
349            let value = String(m.2)
350            if key == "MACRO", let d = value.firstMatch(of: /^(\S+)[ \t]*(.*)$/) {
351                definitions[d.1.lowercased()] = String(d.2)
352            } else if keywords[key] == nil {
353                keywords[key] = value
354            }
355        }
356        var counters: [String: Int] = [:]
357        var model: DocumentModel?
358        /// `org-entry-get` with `selective` inheritance at the heading holding `location`, or
359        /// at the entry `search` finds (`*Title`, `#custom-id` or a title).
360        func property(_ name: String, _ search: String?, at location: Int) -> String {
361            if model == nil { model = DocumentModel(tree: OrgParser.parse(text)) }
362            let headings = model!.headings
363            let index: Int?
364            if let search, !search.isEmpty {
365                if search.hasPrefix("#") {
366                    let id = String(search.dropFirst())
367                    index = headings.firstIndex { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id } }
368                } else {
369                    let title = search.hasPrefix("*") ? String(search.dropFirst()) : search
370                    index = headings.firstIndex { Links.displayFormat($0.title).trimmingCharacters(in: .whitespaces) == title || $0.title == title }
371                }
372            } else {
373                index = headings.lastIndex { $0.headingRange.lowerBound <= location }
374            }
375            guard let index else { return "" }
376            if name.uppercased() == "ITEM" { return headings[index].title }
377            return model!.property(name, of: index)?.value ?? ""
378        }
379        let regex = try! NSRegularExpression(pattern: "\\{\\{\\{([-A-Za-z0-9_]+)(?:\\((.*?)\\))?\\}\\}\\}")
380        var out = ""
381        var at = 0
382        let ns = text as NSString
383        for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
384            out += ns.substring(with: NSRange(location: at, length: m.range.location - at))
385            at = NSMaxRange(m.range)
386            // Not on #+MACRO lines themselves.
387            let lineStart = ns.lineRange(for: NSRange(location: m.range.location, length: 0)).location
388            if ns.substring(from: lineStart).range(of: "^[ \\t]*#\\+MACRO:", options: [.regularExpression, .caseInsensitive]) != nil {
389                out += ns.substring(with: m.range)
390                continue
391            }
392            let name = ns.substring(with: m.range(at: 1)).lowercased()
393            // Inline results stay for the exporter, which shows them as `:exports` says.
394            if name == "results", definitions[name] == nil {
395                out += ns.substring(with: m.range)
396                continue
397            }
398            let args = m.range(at: 2).location == NSNotFound ? [] : arguments(ns.substring(with: m.range(at: 2)))
399            let location = m.range.location
400            out += expand(name, args, definitions: definitions, keywords: keywords, counters: &counters, path: path, now: now) {
401                property($0, $1, at: location)
402            }
403        }
404        out += ns.substring(from: at)
405        return out
406    }
407
408    /// Macro arguments: split on commas, `\,` for a literal one, blanks around trimmed.
409    static func arguments(_ s: String) -> [String] {
410        var args: [String] = []
411        var current = ""
412        var escaped = false
413        for c in s {
414            if escaped {
415                current.append(c == "," ? "," : "\\")
416                if c != "," { current.append(c) }
417                escaped = false
418            } else if c == "\\" {
419                escaped = true
420            } else if c == "," {
421                args.append(current)
422                current = ""
423            } else {
424                current.append(c)
425            }
426        }
427        if escaped { current.append("\\") }
428        args.append(current)
429        return args.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
430    }
431
432    static func expand(_ name: String, _ args: [String], definitions: [String: String], keywords: [String: String],
433                       counters: inout [String: Int], path: String?, now: Date, property: (String, String?) -> String) -> String {
434        if let template = definitions[name] {
435            guard !template.hasPrefix("(eval") else { return "" }
436            var result = template
437            for (i, arg) in args.enumerated().reversed() { result = result.replacingOccurrences(of: "$\(i + 1)", with: arg) }
438            return result.replacingOccurrences(of: "\\$[0-9]+", with: "", options: .regularExpression)
439        }
440        switch name {
441        case "title", "author", "date", "email": return keywords[name.uppercased()] ?? ""
442        case "keyword": return args.first.flatMap { keywords[$0.uppercased()] } ?? ""
443        case "input-file": return path.map { ($0 as NSString).lastPathComponent } ?? ""
444        case "property": return args.first.map { property($0, args.count > 1 ? args[1] : nil) } ?? ""
445        case "n":
446            let counter = args.first ?? ""
447            let action = args.count > 1 ? args[1] : ""
448            if action == "-" { return String(counters[counter] ?? 0) }
449            let value = Int(action) ?? ((counters[counter] ?? 0) + 1)
450            counters[counter] = value
451            return String(value)
452        case "time":
453            guard let format = args.first else { return "" }
454            return strftime(format, now)
455        default: return ""
456        }
457    }
458
459    /// `format-time-string` for the common directives.
460    static func strftime(_ format: String, _ date: Date) -> String {
461        var t = time_t(date.timeIntervalSince1970)
462        var tm = tm()
463        localtime_r(&t, &tm)
464        var buffer = [Int8](repeating: 0, count: 256)
465        let count = Foundation.strftime(&buffer, buffer.count, format, &tm)
466        return String(decoding: buffer.prefix(count).map { UInt8(bitPattern: $0) }, as: UTF8.self)
467    }
468}