Sources/OrgApp/AgendaViews.swift

3cf0c16fe4e67f7e48d03ff5cd2212f5a2bd15c1
orgstar/Sources/OrgApp/AgendaViews.swift

145 lines · 6091 bytes

  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
 15    /// The key `org-agenda-prefix-format` and `org-agenda-sorting-strategy` use for this kind
 16    /// of view.
 17    public var viewKey: String {
 18        switch self {
 19        case .agenda: "agenda"
 20        case .todo: "todo"
 21        case .match: "tags"
 22        case .search: "search"
 23        }
 24    }
 25}
 26
 27/// A view's own `org-agenda-prefix-format` and `org-agenda-sorting-strategy`, as an
 28/// `org-agenda-custom-commands` entry's settings give them.
 29public struct AgendaViewSettings: Hashable, Sendable {
 30    public var prefixFormat: String?
 31    public var sortingStrategy: [String]?
 32
 33    public init(prefixFormat: String? = nil, sortingStrategy: [String]? = nil) {
 34        self.prefixFormat = prefixFormat
 35        self.sortingStrategy = sortingStrategy
 36    }
 37
 38    public func apply(to options: AgendaOptions, view: String) -> AgendaOptions {
 39        var options = options
 40        if let prefixFormat { options.prefixFormat[view] = prefixFormat }
 41        if let sortingStrategy { options.sortingStrategy[view] = sortingStrategy }
 42        return options
 43    }
 44}
 45
 46/// A named view: the built-in ones and those in `views.toml`.
 47public struct AgendaViewDefinition: Hashable, Sendable, Identifiable {
 48    public let name: String
 49    public let mode: AgendaMode
 50    public var settings: AgendaViewSettings
 51    public var id: String { name }
 52
 53    public init(name: String, mode: AgendaMode, settings: AgendaViewSettings = AgendaViewSettings()) {
 54        self.name = name
 55        self.mode = mode
 56        self.settings = settings
 57    }
 58}
 59
 60/// Reads `views.toml`:
 61///
 62/// ```toml
 63/// [[view]]
 64/// name = "Work"
 65/// type = "match"        # agenda, todo, match, todo-match, search or todo-search
 66/// match = "+work-boss"
 67/// ```
 68///
 69/// `agenda` views take `span` and `start` (days from today), `todo` views `keywords`
 70/// (`WAIT|HOLD`); a `search` view's `match` is its search string. Any view can set
 71/// `prefix-format` and `sorting-strategy` (keys separated by spaces) for itself.
 72@MainActor
 73public enum AgendaViewLoader {
 74    public static var userFile: URL { UserConfig.file("views.toml") }
 75
 76    public static let builtIn = [
 77        AgendaViewDefinition(name: "Agenda", mode: .agenda(span: nil, startOffset: nil)),
 78        AgendaViewDefinition(name: "TODO List", mode: .todo(keywords: nil)),
 79    ]
 80
 81    /// The views' settings by mode; the first view with a mode wins.
 82    public static func settings(_ views: [AgendaViewDefinition]) -> [AgendaMode: AgendaViewSettings] {
 83        var settings: [AgendaMode: AgendaViewSettings] = [:]
 84        for view in views where settings[view.mode] == nil && view.settings != AgendaViewSettings() { settings[view.mode] = view.settings }
 85        return settings
 86    }
 87
 88    /// The built-in views followed by the user's, and the problems found in the file.
 89    public static func load(userFile: URL = userFile) -> (views: [AgendaViewDefinition], problems: [String]) {
 90        let interval = Perf.begin("views.load")
 91        defer { interval.end() }
 92        guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) }
 93        let tables: [TOML.Table]
 94        do {
 95            tables = try TOML.parse(text)
 96        } catch {
 97            return (builtIn, ["views.toml: \(error)"])
 98        }
 99        var views = builtIn
100        var problems: [String] = []
101        for table in tables where !(table.name.isEmpty && table.values.isEmpty) {
102            guard table.name == "view", table.isArrayElement else {
103                problems.append("views.toml line \(table.line): expected [[view]]")
104                continue
105            }
106            guard let name = table.values["name"]?.string else {
107                problems.append("views.toml line \(table.line): a view needs a name")
108                continue
109            }
110            let match = table.values["match"]?.string
111            let mode: AgendaMode
112            switch table.values["type"]?.string ?? "agenda" {
113            case "agenda":
114                mode = .agenda(span: table.values["span"]?.integer, startOffset: table.values["start"]?.integer)
115            case "todo":
116                mode = .todo(keywords: table.values["keywords"]?.string)
117            case "match", "todo-match":
118                guard let match else {
119                    problems.append("views.toml line \(table.line): \(name) needs a match")
120                    continue
121                }
122                mode = .match(match, todoOnly: table.values["type"]?.string == "todo-match")
123            case "search", "todo-search":
124                guard let match else {
125                    problems.append("views.toml line \(table.line): \(name) needs a match")
126                    continue
127                }
128                mode = .search(match, todoOnly: table.values["type"]?.string == "todo-search")
129            case let other:
130                problems.append("views.toml line \(table.line): unknown type \(other)")
131                continue
132            }
133            var settings = AgendaViewSettings(prefixFormat: table.values["prefix-format"]?.string)
134            if let strategy = table.values["sorting-strategy"]?.string {
135                let keys = strategy.split(whereSeparator: \.isWhitespace).map(String.init)
136                if let bad = keys.first(where: { !AgendaSort.keys.contains($0) }) {
137                    problems.append("views.toml line \(table.line): unknown sorting key \(bad)")
138                }
139                settings.sortingStrategy = keys.filter(AgendaSort.keys.contains)
140            }
141            views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings))
142        }
143        return (views, problems)
144    }
145}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form