Sources/OrgCore/Export/ExportOptions.swift

2df4420ff51f7e97a9c06eacf814f64cdb5a4351
orgstar/Sources/OrgCore/Export/ExportOptions.swift

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