Sources/OrgCore/Parser/SetupFile.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgCore/Parser/SetupFile.swift history · blame · raw

56 lines · 3283 bytes

 1import Foundation
 2
 3/// `#+SETUPFILE` (`org--collect-keywords-1`): each setup file's keywords count as if they were
 4/// in the file that names it, setup files named there included. Paths are relative to the
 5/// naming file's folder; URLs aren't fetched.
 6public enum SetupFile {
 7    /// The keyword lines the setup files `text` names bring, in order, as `#+KEY: value` lines.
 8    /// `read` gives a file's text, or nil when it can't be read.
 9    public static func keywordLines(in text: String, directory: String, read: (String) -> String?) -> String {
10        lines(in: text, directory: directory, read: read, own: false, seen: [])
11    }
12
13    private static func lines(in text: String, directory: String, read: (String) -> String?, own: Bool, seen: Set<String>) -> String {
14        guard own || text.range(of: "#+setupfile:", options: .caseInsensitive) != nil else { return "" }
15        var out = ""
16        for node in OrgParser.parse(text).root.descendants() where node.kind == .keyword {
17            let line = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
18            guard let colon = line.firstIndex(of: ":") else { continue }
19            let key = line[line.index(line.startIndex, offsetBy: 2)..<colon].uppercased()
20            guard key == "SETUPFILE" else {
21                if own { out += line + "\n" }
22                continue
23            }
24            var value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
25            if value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") { value = String(value.dropFirst().dropLast()) }
26            guard !value.isEmpty, value.range(of: "^[a-zA-Z][a-zA-Z0-9+.-]*://", options: .regularExpression) == nil else { continue }
27            let expanded = (value as NSString).expandingTildeInPath
28            let path = ((expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)) as NSString).standardizingPath
29            guard !seen.contains(path), let contents = read(path) else { continue }
30            out += lines(in: contents, directory: (path as NSString).deletingLastPathComponent, read: read, own: true, seen: seen.union([path]))
31        }
32        return out
33    }
34
35    /// `(key, value)` for each `#+KEY: value` line.
36    static func keywords(_ lines: String) -> [(key: String, value: Substring)] {
37        lines.split(separator: "\n").compactMap { line in
38            guard line.hasPrefix("#+"), let colon = line.firstIndex(of: ":") else { return nil }
39            return (line[line.index(line.startIndex, offsetBy: 2)..<colon].uppercased(), line[line.index(after: colon)...])
40        }
41    }
42}
43
44extension OrgSettings {
45    /// These settings with the keywords of the setup files `text` names, for a file at `path`.
46    public func resolvingSetupFiles(in text: String, path: String, read: (String) -> String?) -> OrgSettings {
47        var copy = self
48        copy.setupKeywords = SetupFile.keywordLines(in: text, directory: (path as NSString).deletingLastPathComponent, read: read)
49        return copy
50    }
51
52    /// A file's text readable as UTF-8, for `resolvingSetupFiles`.
53    public static func readFile(_ path: String) -> String? {
54        FileManager.default.contents(atPath: path).flatMap { String(data: $0, encoding: .utf8) }
55    }
56}