Sources/OrgCore/Parser/Settings.swift

0e58e1b1ae285390762ec1b8bf93c882ecc94a02
orgstar/Sources/OrgCore/Parser/Settings.swift history · blame · raw

164 lines · 7094 bytes

  1public struct TodoKeyword: Sendable, Hashable {
  2    public var name: String
  3    public var fastKey: Character?
  4    /// Logging flag when entering the state (`!` or `@`), from `NAME(k!/@)`.
  5    public var logOnEnter: String?
  6    /// Logging flag when leaving the state.
  7    public var logOnLeave: String?
  8
  9    public init(name: String, fastKey: Character? = nil, logOnEnter: String? = nil, logOnLeave: String? = nil) {
 10        self.name = name
 11        self.fastKey = fastKey
 12        self.logOnEnter = logOnEnter
 13        self.logOnLeave = logOnLeave
 14    }
 15}
 16
 17public struct TodoSequence: Sendable, Equatable {
 18    public enum Kind: Sendable, Equatable { case sequence, type }
 19
 20    public var kind: Kind
 21    public var active: [TodoKeyword]
 22    public var done: [TodoKeyword]
 23
 24    public init(kind: Kind, active: [TodoKeyword], done: [TodoKeyword]) {
 25        self.kind = kind
 26        self.active = active
 27        self.done = done
 28    }
 29}
 30
 31public struct Priorities: Sendable, Equatable {
 32    public var highest: String
 33    public var lowest: String
 34    public var `default`: String
 35
 36    public init(highest: String, lowest: String, default: String) {
 37        self.highest = highest
 38        self.lowest = lowest
 39        self.default = `default`
 40    }
 41}
 42
 43public struct OrgSettings: Sendable, Equatable {
 44    public var todoSequences: [TodoSequence]
 45    public var priorities: Priorities
 46    /// `<<<radio target>>>` texts in the file, longest first: their words elsewhere are links.
 47    public var radioTargets: [String] = []
 48    /// `org-list-allow-alphabetical`: `a.` and `A)` are bullets.
 49    public var listAllowAlphabetical = false
 50    /// Keyword lines from the file's `#+SETUPFILE`s, as `#+KEY: value` lines: they count as
 51    /// the file's own, before them.
 52    public var setupKeywords = ""
 53
 54    public init(todoSequences: [TodoSequence], priorities: Priorities, radioTargets: [String] = []) {
 55        self.todoSequences = todoSequences
 56        self.priorities = priorities
 57        self.radioTargets = radioTargets
 58    }
 59
 60    public static let `default` = OrgSettings(
 61        todoSequences: [TodoSequence(kind: .sequence, active: [TodoKeyword(name: "TODO")], done: [TodoKeyword(name: "DONE")])],
 62        priorities: Priorities(highest: "A", lowest: "C", default: "B")
 63    )
 64
 65    public var todoKeywordNames: Set<String> {
 66        Set(todoSequences.flatMap { ($0.active + $0.done).map(\.name) })
 67    }
 68
 69    /// These settings with TODO keywords from `#+TODO:` syntax (`TODO NEXT | DONE`), one
 70    /// sequence per line; nil when there are no keywords.
 71    public func withTodoKeywords(_ lines: String) -> OrgSettings? {
 72        let sequences = lines.split(separator: "\n").compactMap { SettingsScanner.todoSequence($0, kind: .sequence) }
 73        guard !sequences.isEmpty else { return nil }
 74        var copy = self
 75        copy.todoSequences = sequences
 76        return copy
 77    }
 78
 79    public func isDone(_ name: String) -> Bool {
 80        todoSequences.contains { $0.done.contains { $0.name == name } }
 81    }
 82}
 83
 84enum SettingsScanner {
 85    /// Reads `#+TODO`, `#+SEQ_TODO`, `#+TYP_TODO` and `#+PRIORITIES` outside blocks. Any TODO
 86    /// line replaces the default sequences; as in org, `TYP_TODO` sequences come first, then
 87    /// `TODO`, then `SEQ_TODO`.
 88    static func scan(lines: [RawLine], info: [ClassifiedLine], blockEnds: [Int: Int], defaults: OrgSettings) -> OrgSettings {
 89        var types: [TodoSequence] = [], todos: [TodoSequence] = [], seqs: [TodoSequence] = []
 90        var priorities = defaults.priorities
 91        func apply(_ key: String, _ value: Substring) {
 92            switch key {
 93            case "TODO":
 94                if let s = todoSequence(value, kind: .sequence) { todos.append(s) }
 95            case "SEQ_TODO":
 96                if let s = todoSequence(value, kind: .sequence) { seqs.append(s) }
 97            case "TYP_TODO":
 98                if let s = todoSequence(value, kind: .type) { types.append(s) }
 99            case "PRIORITIES":
100                let words = value.split(whereSeparator: \.isWhitespace)
101                if words.count == 3 {
102                    priorities = Priorities(highest: String(words[0]), lowest: String(words[1]), default: String(words[2]))
103                }
104            default:
105                break
106            }
107        }
108        for (key, value) in SetupFile.keywords(defaults.setupKeywords) { apply(key, value) }
109        var k = 0
110        while k < lines.count {
111            switch info[k].cls {
112            case .blockBegin, .dynamicBegin:
113                if let end = blockEnds[k] { k = end }
114            case .keyword(let key):
115                apply(key, keywordValue(lines[k].content))
116            default:
117                break
118            }
119            k += 1
120        }
121        let sequences = types + todos + seqs
122        var radio: [String] = []
123        for line in lines where line.content.contains("<<<") {
124            for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) {
125                radio.append(String(m.1))
126            }
127        }
128        var settings = OrgSettings(todoSequences: sequences.isEmpty ? defaults.todoSequences : sequences, priorities: priorities,
129                                   radioTargets: radio.sorted { $0.count > $1.count })
130        settings.listAllowAlphabetical = defaults.listAllowAlphabetical
131        settings.setupKeywords = defaults.setupKeywords
132        return settings
133    }
134
135    static func keywordValue(_ line: Substring) -> Substring {
136        guard let colon = line.firstIndex(of: ":") else { return "" }
137        return line[line.index(after: colon)...]
138    }
139
140    static func todoSequence(_ value: Substring, kind: TodoSequence.Kind) -> TodoSequence? {
141        let words = value.split(whereSeparator: \.isWhitespace)
142        guard !words.isEmpty else { return nil }
143        if let bar = words.firstIndex(of: "|") {
144            return TodoSequence(kind: kind, active: words[..<bar].map(todoKeyword), done: words[(bar + 1)...].map(todoKeyword))
145        }
146        return TodoSequence(kind: kind, active: words.dropLast().map(todoKeyword), done: [todoKeyword(words.last!)])
147    }
148
149    /// `NAME`, or `NAME(spec)` where spec is an optional fast key followed by `enter/leave`
150    /// logging flags.
151    static func todoKeyword(_ word: Substring) -> TodoKeyword {
152        guard let open = word.firstIndex(of: "("), word.last == ")" else { return TodoKeyword(name: String(word)) }
153        var spec = word[word.index(after: open)..<word.index(before: word.endIndex)]
154        var fastKey: Character?
155        if let first = spec.first, first != "!", first != "@", first != "/" {
156            fastKey = first
157            spec = spec.dropFirst()
158        }
159        let parts = spec.split(separator: "/", omittingEmptySubsequences: false)
160        let enter = parts.first.flatMap { $0.isEmpty ? nil : String($0) }
161        let leave = parts.count > 1 && !parts[1].isEmpty ? String(parts[1]) : nil
162        return TodoKeyword(name: String(word[..<open]), fastKey: fastKey, logOnEnter: enter, logOnLeave: leave)
163    }
164}