Sources/OrgCore/Parser/Settings.swift

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

153 lines · 6508 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
 51    public init(todoSequences: [TodoSequence], priorities: Priorities, radioTargets: [String] = []) {
 52        self.todoSequences = todoSequences
 53        self.priorities = priorities
 54        self.radioTargets = radioTargets
 55    }
 56
 57    public static let `default` = OrgSettings(
 58        todoSequences: [TodoSequence(kind: .sequence, active: [TodoKeyword(name: "TODO")], done: [TodoKeyword(name: "DONE")])],
 59        priorities: Priorities(highest: "A", lowest: "C", default: "B")
 60    )
 61
 62    public var todoKeywordNames: Set<String> {
 63        Set(todoSequences.flatMap { ($0.active + $0.done).map(\.name) })
 64    }
 65
 66    /// These settings with TODO keywords from `#+TODO:` syntax (`TODO NEXT | DONE`), one
 67    /// sequence per line; nil when there are no keywords.
 68    public func withTodoKeywords(_ lines: String) -> OrgSettings? {
 69        let sequences = lines.split(separator: "\n").compactMap { SettingsScanner.todoSequence($0, kind: .sequence) }
 70        guard !sequences.isEmpty else { return nil }
 71        var copy = self
 72        copy.todoSequences = sequences
 73        return copy
 74    }
 75
 76    public func isDone(_ name: String) -> Bool {
 77        todoSequences.contains { $0.done.contains { $0.name == name } }
 78    }
 79}
 80
 81enum SettingsScanner {
 82    /// Reads `#+TODO`, `#+SEQ_TODO`, `#+TYP_TODO` and `#+PRIORITIES` outside blocks. Any TODO
 83    /// line replaces the default sequences, as in org.
 84    static func scan(lines: [RawLine], info: [ClassifiedLine], blockEnds: [Int: Int], defaults: OrgSettings) -> OrgSettings {
 85        var sequences: [TodoSequence] = []
 86        var priorities = defaults.priorities
 87        var k = 0
 88        while k < lines.count {
 89            switch info[k].cls {
 90            case .blockBegin, .dynamicBegin:
 91                if let end = blockEnds[k] { k = end }
 92            case .keyword(let key):
 93                let value = keywordValue(lines[k].content)
 94                switch key {
 95                case "TODO", "SEQ_TODO":
 96                    if let s = todoSequence(value, kind: .sequence) { sequences.append(s) }
 97                case "TYP_TODO":
 98                    if let s = todoSequence(value, kind: .type) { sequences.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            default:
108                break
109            }
110            k += 1
111        }
112        var radio: [String] = []
113        for line in lines where line.content.contains("<<<") {
114            for m in String(line.content).matches(of: /<<<([^<>\n\r \t](?:[^<>\n\r]*[^<>\n\r \t])?)>>>/) where !radio.contains(String(m.1)) {
115                radio.append(String(m.1))
116            }
117        }
118        var settings = OrgSettings(todoSequences: sequences.isEmpty ? defaults.todoSequences : sequences, priorities: priorities,
119                                   radioTargets: radio.sorted { $0.count > $1.count })
120        settings.listAllowAlphabetical = defaults.listAllowAlphabetical
121        return settings
122    }
123
124    static func keywordValue(_ line: Substring) -> Substring {
125        guard let colon = line.firstIndex(of: ":") else { return "" }
126        return line[line.index(after: colon)...]
127    }
128
129    static func todoSequence(_ value: Substring, kind: TodoSequence.Kind) -> TodoSequence? {
130        let words = value.split(whereSeparator: \.isWhitespace)
131        guard !words.isEmpty else { return nil }
132        if let bar = words.firstIndex(of: "|") {
133            return TodoSequence(kind: kind, active: words[..<bar].map(todoKeyword), done: words[(bar + 1)...].map(todoKeyword))
134        }
135        return TodoSequence(kind: kind, active: words.dropLast().map(todoKeyword), done: [todoKeyword(words.last!)])
136    }
137
138    /// `NAME`, or `NAME(spec)` where spec is an optional fast key followed by `enter/leave`
139    /// logging flags.
140    static func todoKeyword(_ word: Substring) -> TodoKeyword {
141        guard let open = word.firstIndex(of: "("), word.last == ")" else { return TodoKeyword(name: String(word)) }
142        var spec = word[word.index(after: open)..<word.index(before: word.endIndex)]
143        var fastKey: Character?
144        if let first = spec.first, first != "!", first != "@", first != "/" {
145            fastKey = first
146            spec = spec.dropFirst()
147        }
148        let parts = spec.split(separator: "/", omittingEmptySubsequences: false)
149        let enter = parts.first.flatMap { $0.isEmpty ? nil : String($0) }
150        let leave = parts.count > 1 && !parts[1].isEmpty ? String(parts[1]) : nil
151        return TodoKeyword(name: String(word[..<open]), fastKey: fastKey, logOnEnter: enter, logOnLeave: leave)
152    }
153}