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