Sources/OrgCore/Export/ExportOptions.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Sources/OrgCore/Export/ExportOptions.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form