Sources/OrgConfig/AgendaViews.swift
300 lines · 14127 bytes
16 symbols in this file
1import Foundation
2import OrgCore
3
4/// What the agenda window shows.
5public enum AgendaMode: Hashable, Sendable {
6 /// `org-agenda-list`; nil span and start use the settings.
7 case agenda(span: Int?, startOffset: Int?)
8 /// `org-todo-list`, optionally for `KWD1|KWD2`.
9 case todo(keywords: String?)
10 /// `org-tags-view`.
11 case match(String, todoOnly: Bool)
12 /// `org-search-view`.
13 case search(String, todoOnly: Bool)
14 /// `org-agenda-list-stuck-projects`; nil uses the `org-stuck-projects` setting.
15 case stuck(StuckProjects?)
16 /// A block agenda: several views one after the other.
17 case blocks([AgendaBlock])
18
19 /// The key `org-agenda-prefix-format` and `org-agenda-sorting-strategy` use for this kind
20 /// of view.
21 public var viewKey: String {
22 switch self {
23 case .agenda: "agenda"
24 case .todo: "todo"
25 case .match, .stuck: "tags"
26 case .search: "search"
27 case .blocks: "agenda"
28 }
29 }
30}
31
32/// One view of a block agenda, with its own settings.
33public struct AgendaBlock: Hashable, Sendable {
34 public let mode: AgendaMode
35 public let settings: AgendaViewSettings
36
37 public init(mode: AgendaMode, settings: AgendaViewSettings = AgendaViewSettings()) {
38 self.mode = mode
39 self.settings = settings
40 }
41}
42
43/// A view's own settings, as an `org-agenda-custom-commands` entry's give them:
44/// `org-agenda-prefix-format`, `org-agenda-sorting-strategy`, `org-agenda-skip-function` (as
45/// `org-agenda-skip-entry-if` or `-subtree-if`) and `org-agenda-overriding-header`.
46public struct AgendaViewSettings: Hashable, Sendable {
47 public var prefixFormat: String?
48 public var sortingStrategy: [String]?
49 public var skip: AgendaSkip?
50 public var header: String?
51
52 public init(prefixFormat: String? = nil, sortingStrategy: [String]? = nil, skip: AgendaSkip? = nil, header: String? = nil) {
53 self.prefixFormat = prefixFormat
54 self.sortingStrategy = sortingStrategy
55 self.skip = skip
56 self.header = header
57 }
58
59 public func apply(to options: AgendaOptions, view: String) -> AgendaOptions {
60 var options = options
61 if let prefixFormat { options.prefixFormat[view] = prefixFormat }
62 if let sortingStrategy { options.sortingStrategy[view] = sortingStrategy }
63 if let skip { options.skip = skip }
64 return options
65 }
66
67 /// These settings with `block`'s over them, as a block's settings go over its command's.
68 public func merged(_ block: AgendaViewSettings) -> AgendaViewSettings {
69 AgendaViewSettings(prefixFormat: block.prefixFormat ?? prefixFormat, sortingStrategy: block.sortingStrategy ?? sortingStrategy,
70 skip: block.skip ?? skip, header: block.header)
71 }
72}
73
74extension AgendaMode {
75 /// The heading of a list or block: `TODO items: all`, `Week agenda`.
76 public var title: String {
77 switch self {
78 case .agenda(let span, _): Self.spanTitle(span)
79 case .todo(let keywords): "TODO items: \(keywords ?? "all")"
80 case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)"
81 case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)"
82 case .stuck: "Stuck projects"
83 case .blocks: "Block agenda"
84 }
85 }
86
87 /// `org-agenda-span-name`, as a title.
88 static func spanTitle(_ span: Int?) -> String {
89 switch span {
90 case 1?: "Day agenda"
91 case 7?: "Week agenda"
92 case 14?: "Fortnight agenda"
93 case 30?, 31?: "Month agenda"
94 case 365?: "Year agenda"
95 case let n?: "\(n)-day agenda"
96 case nil: "Agenda"
97 }
98 }
99}
100
101/// A named view: the built-in ones and those in `views.toml`.
102public struct AgendaViewDefinition: Hashable, Sendable, Identifiable {
103 public let name: String
104 public let mode: AgendaMode
105 public var settings: AgendaViewSettings
106 public var id: String { name }
107
108 public init(name: String, mode: AgendaMode, settings: AgendaViewSettings = AgendaViewSettings()) {
109 self.name = name
110 self.mode = mode
111 self.settings = settings
112 }
113}
114
115/// Reads `views.toml`:
116///
117/// ```toml
118/// [[view]]
119/// name = "Work"
120/// type = "match" # agenda, todo, match, todo-match, search or todo-search
121/// match = "+work-boss"
122/// ```
123///
124/// `agenda` views take `span` and `start` (days from today), `todo` views `keywords`
125/// (`WAIT|HOLD`); a `search` view's `match` is its search string. `stuck` views take
126/// `match`, `keywords`, `tags` and `regexp` as `[org-stuck-projects]` does, each defaulting
127/// to that setting. Any view can set
128/// `prefix-format` and `sorting-strategy` (keys separated by spaces) for itself.
129@MainActor
130public enum AgendaViewLoader {
131 public static var userFile: URL { UserConfig.file("views.toml") }
132
133 public static let builtIn = [
134 AgendaViewDefinition(name: "Agenda", mode: .agenda(span: nil, startOffset: nil)),
135 AgendaViewDefinition(name: "TODO List", mode: .todo(keywords: nil)),
136 AgendaViewDefinition(name: "Stuck Projects", mode: .stuck(nil)),
137 ]
138
139 /// The views' settings by mode; the first view with a mode wins.
140 public static func settings(_ views: [AgendaViewDefinition]) -> [AgendaMode: AgendaViewSettings] {
141 var settings: [AgendaMode: AgendaViewSettings] = [:]
142 for view in views where settings[view.mode] == nil && view.settings != AgendaViewSettings() { settings[view.mode] = view.settings }
143 return settings
144 }
145
146 /// The built-in views followed by the user's, and the problems found in the file. Stuck
147 /// views start from the `[org-stuck-projects]` settings in `defaults`.
148 public static func load(userFile: URL = userFile, defaults: UserDefaults = .standard) -> (views: [AgendaViewDefinition], problems: [String]) {
149 let interval = Perf.begin("views.load")
150 defer { interval.end() }
151 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) }
152 let tables: [TOML.Table]
153 do {
154 tables = try TOML.parse(text)
155 } catch {
156 return (builtIn, ["views.toml: \(error)"])
157 }
158 var problems: [String] = []
159 // Each [[view]] with the [[view.block]] tables after it.
160 var parsed: [(name: String, view: TOML.Table, blocks: [TOML.Table])] = []
161 for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
162 if table.name == "view.block", table.isArrayElement {
163 if parsed.isEmpty {
164 problems.append("views.toml line \(table.line): [[view.block]] before any [[view]]")
165 } else {
166 parsed[parsed.count - 1].blocks.append(table)
167 }
168 continue
169 }
170 guard table.name == "view", table.isArrayElement else {
171 problems.append("views.toml line \(table.line): expected [[view]]")
172 continue
173 }
174 guard let name = table.values["name"]?.string else {
175 problems.append("views.toml line \(table.line): a view needs a name")
176 continue
177 }
178 parsed.append((name, table, []))
179 }
180 var views = builtIn
181 for (name, table, blockTables) in parsed {
182 guard let settings = settings(table, &problems) else { continue }
183 if blockTables.isEmpty {
184 guard let mode = mode(table, name: name, defaults: defaults, &problems) else { continue }
185 views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings))
186 continue
187 }
188 var blocks: [AgendaBlock] = []
189 for block in blockTables {
190 guard var mode = mode(block, name: name, defaults: defaults, &problems), let own = Self.settings(block, &problems) else { continue }
191 // The view's span and start go to agenda blocks without their own.
192 if case .agenda(let span, let start) = mode {
193 mode = .agenda(span: span ?? table.values["span"]?.integer, startOffset: start ?? table.values["start"]?.integer)
194 }
195 blocks.append(AgendaBlock(mode: mode, settings: settings.merged(own)))
196 }
197 if !blocks.isEmpty { views.append(AgendaViewDefinition(name: name, mode: .blocks(blocks), settings: AgendaViewSettings(header: settings.header))) }
198 }
199 return (views, problems)
200 }
201
202 /// Why a view wasn't saved.
203 public struct SaveFailure: Error, Equatable, CustomStringConvertible {
204 public let description: String
205 }
206
207 /// The `[[view]]` table that makes `mode` a view named `name`; nil for a block agenda and a
208 /// stuck-projects view with its own definition, which one table can't hold.
209 static func table(name: String, mode: AgendaMode) -> String? {
210 func line(_ key: String, _ value: String?) -> String { value.map { "\(key) = \(UserConfig.format(.string($0)))\n" } ?? "" }
211 var toml = "[[view]]\n" + line("name", name)
212 switch mode {
213 case .agenda(let span, let start):
214 toml += line("type", "agenda") + (span.map { "span = \($0)\n" } ?? "") + (start.map { "start = \($0)\n" } ?? "")
215 case .todo(let keywords):
216 toml += line("type", "todo") + line("keywords", keywords)
217 case .match(let match, let todoOnly):
218 toml += line("type", todoOnly ? "todo-match" : "match") + line("match", match)
219 case .search(let string, let todoOnly):
220 toml += line("type", todoOnly ? "todo-search" : "search") + line("match", string)
221 case .stuck(nil):
222 toml += line("type", "stuck")
223 case .stuck, .blocks:
224 return nil
225 }
226 return toml
227 }
228
229 /// Adds a view of `mode` named `name` to the end of `views.toml`, making the file when it
230 /// isn't there. A name another view has, the built-in ones included, is refused.
231 public static func save(name: String, mode: AgendaMode, userFile: URL = userFile) throws(SaveFailure) {
232 let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
233 guard !name.isEmpty else { throw SaveFailure(description: String(localized: "A view needs a name.")) }
234 guard !load(userFile: userFile).views.contains(where: { $0.name == name }) else {
235 throw SaveFailure(description: String(localized: "There is already a view named \(name)."))
236 }
237 guard let table = table(name: name, mode: mode) else {
238 throw SaveFailure(description: String(localized: "This view can't be saved from here; write it in views.toml."))
239 }
240 do {
241 try FileManager.default.createDirectory(at: userFile.deletingLastPathComponent(), withIntermediateDirectories: true)
242 try UserFile.update(userFile) { text in
243 text + (text.isEmpty ? "" : text.hasSuffix("\n") ? "\n" : "\n\n") + table
244 }
245 } catch {
246 throw SaveFailure(description: error.localizedDescription)
247 }
248 }
249
250 /// The view a `[[view]]` or `[[view.block]]` table describes.
251 static func mode(_ table: TOML.Table, name: String, defaults: UserDefaults = .standard, _ problems: inout [String]) -> AgendaMode? {
252 let match = table.values["match"]?.string
253 let type = table.values["type"]?.string ?? "agenda"
254 switch type {
255 case "agenda":
256 return .agenda(span: table.values["span"]?.integer, startOffset: table.values["start"]?.integer)
257 case "todo":
258 return .todo(keywords: table.values["keywords"]?.string)
259 case "match", "todo-match", "search", "todo-search":
260 guard let match else {
261 problems.append("views.toml line \(table.line): \(name) needs a match")
262 return nil
263 }
264 return type.hasSuffix("match") ? .match(match, todoOnly: type == "todo-match") : .search(match, todoOnly: type == "todo-search")
265 case "stuck":
266 if ["match", "keywords", "tags", "regexp"].allSatisfy({ table.values[$0] == nil }) { return .stuck(nil) }
267 var definition = OrgPreferences.stuckProjects(defaults)
268 if let match { definition.match = match }
269 if let keywords = table.values["keywords"]?.string { definition.todo = OrgPreferences.words(keywords) }
270 if let tags = table.values["tags"]?.string { definition.tags = OrgPreferences.words(tags) }
271 if let regexp = table.values["regexp"]?.string { definition.regexp = regexp }
272 return .stuck(definition)
273 default:
274 problems.append("views.toml line \(table.line): unknown type \(type)")
275 return nil
276 }
277 }
278
279 /// The settings of a `[[view]]` or `[[view.block]]` table; nil when one can't be read.
280 static func settings(_ table: TOML.Table, _ problems: inout [String]) -> AgendaViewSettings? {
281 var settings = AgendaViewSettings(prefixFormat: table.values["prefix-format"]?.string, header: table.values["header"]?.string)
282 if let strategy = table.values["sorting-strategy"]?.string {
283 let keys = strategy.split(whereSeparator: \.isWhitespace).map(String.init)
284 if let bad = keys.first(where: { !AgendaSort.keys.contains($0) }) {
285 problems.append("views.toml line \(table.line): unknown sorting key \(bad)")
286 }
287 settings.sortingStrategy = keys.filter(AgendaSort.keys.contains)
288 }
289 for (key, subtree) in [("skip-entry-if", false), ("skip-subtree-if", true)] {
290 guard let text = table.values[key]?.string else { continue }
291 switch AgendaSkip.parse(text, subtree: subtree) {
292 case .success(let skip): settings.skip = skip
293 case .failure(.message(let message)):
294 problems.append("views.toml line \(table.line): \(key): \(message)")
295 return nil
296 }
297 }
298 return settings
299 }
300}