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