Commit 4b342a9cb3
Verified · cmc
Layout: unified · split
Sources/OrgApp/AgendaModel.swift +50 −24
| @@ -23,6 +23,8 @@ public final class AgendaModel { | |||
| 23 | public private(set) var days: [AgendaDay] = [] | 23 | public private(set) var days: [AgendaDay] = [] |
| 24 | /// The entries of a TODO list, match or search view. | 24 | /// The entries of a TODO list, match or search view. |
| 25 | public private(set) var list: [AgendaItem] = [] | 25 | public private(set) var list: [AgendaItem] = [] |
| 26 | /// A block agenda's views, in order. | ||
| 27 | public private(set) var blocks: [AgendaBlockResult] = [] | ||
| 26 | public var mode: AgendaMode = .agenda(span: nil, startOffset: nil) | 28 | public var mode: AgendaMode = .agenda(span: nil, startOffset: nil) |
| 27 | /// The first day shown, as `Days` numbers it; nil follows today. | 29 | /// The first day shown, as `Days` numbers it; nil follows today. |
| 28 | public var start: Int? | 30 | public var start: Int? |
| @@ -75,39 +77,55 @@ public final class AgendaModel { | |||
| 75 | isComputing = true | 77 | isComputing = true |
| 76 | let today = Days.absolute(now, calendar: calendar) | 78 | let today = Days.absolute(now, calendar: calendar) |
| 77 | let clock = calendar.dateComponents([.hour, .minute], from: now) | 79 | let clock = calendar.dateComponents([.hour, .minute], from: now) |
| 78 | let (first, span) = shown(today: today) | ||
| 79 | let mode = self.mode | 80 | let mode = self.mode |
| 80 | let options = viewSettings[mode]?.apply(to: self.options, view: mode.viewKey) ?? self.options | 81 | let options = viewSettings[mode]?.apply(to: self.options, view: mode.viewKey) ?? self.options |
| 82 | // What each view computes: the mode, its options, and for days the first and the span. | ||
| 83 | var jobs: [(mode: AgendaMode, options: AgendaOptions, first: Int, span: Int, header: String)] = [] | ||
| 84 | if case .blocks(let blocks) = mode { | ||
| 85 | for block in blocks { | ||
| 86 | let (first, span) = shown(today: today, mode: block.mode, start: nil) | ||
| 87 | jobs.append((block.mode, block.settings.apply(to: self.options, view: block.mode.viewKey), first, span, block.settings.header ?? block.mode.title)) | ||
| 88 | } | ||
| 89 | } else { | ||
| 90 | let (first, span) = shown(today: today) | ||
| 91 | jobs.append((mode, options, first, span, "")) | ||
| 92 | } | ||
| 81 | let provider = calendarEvents | 93 | let provider = calendarEvents |
| 82 | let names = calendarNames | 94 | let names = calendarNames |
| 83 | let all = await sources(open: open) | 95 | let all = await sources(open: open) |
| 84 | let result = await Task.detached { | 96 | let results = await Task.detached { |
| 85 | var days: [AgendaDay] = [] | 97 | jobs.map { job in |
| 86 | var list: [AgendaItem] = [] | 98 | var result = AgendaBlockResult(header: job.header, mode: job.mode) |
| 87 | var events: [AgendaEvent] = [] | 99 | switch job.mode { |
| 88 | switch mode { | 100 | case .agenda: |
| 89 | case .agenda: | 101 | result.days = Agenda.list(all, start: job.first, days: job.span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: job.options) |
| 90 | days = Agenda.list(all, start: first, days: span, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: options) | 102 | if let provider { |
| 91 | if let provider { | 103 | let from = Self.date(job.first, calendar: calendar) |
| 92 | let from = Self.date(first, calendar: calendar) | 104 | result.events = provider.events(from: from, to: Self.date(job.first + job.span, calendar: calendar), chosen: names) |
| 93 | events = provider.events(from: from, to: Self.date(first + span, calendar: calendar), chosen: names) | 105 | } |
| 106 | case .todo(let keywords): | ||
| 107 | result.list = Agenda.todoList(all, keywords: keywords, options: job.options, today: today) | ||
| 108 | case .match(let match, let todoOnly): | ||
| 109 | result.list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: job.options) | ||
| 110 | case .search(let string, let todoOnly): | ||
| 111 | result.list = Agenda.textSearch(all, string: string, todoOnly: todoOnly, options: job.options) | ||
| 112 | case .stuck(let definition): | ||
| 113 | result.list = Agenda.stuckProjects(all, definition ?? job.options.stuckProjects, now: now, calendar: calendar, options: job.options) | ||
| 114 | case .blocks: | ||
| 115 | break | ||
| 94 | } | 116 | } |
| 95 | case .todo(let keywords): | 117 | return result |
| 96 | list = Agenda.todoList(all, keywords: keywords, options: options, today: today) | ||
| 97 | case .match(let match, let todoOnly): | ||
| 98 | list = Agenda.tagsMatch(all, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: options) | ||
| 99 | case .search(let string, let todoOnly): | ||
| 100 | list = Agenda.textSearch(all, string: string, todoOnly: todoOnly, options: options) | ||
| 101 | case .stuck(let definition): | ||
| 102 | list = Agenda.stuckProjects(all, definition ?? options.stuckProjects, now: now, calendar: calendar, options: options) | ||
| 103 | } | 118 | } |
| 104 | return (days, list, events) | ||
| 105 | }.value | 119 | }.value |
| 106 | guard id == generation else { return } | 120 | guard id == generation else { return } |
| 107 | // Unchanged results leave the views alone: a new value redraws the whole list. | 121 | // Unchanged results leave the views alone: a new value redraws the whole list. |
| 108 | if days != result.0 { days = result.0 } | 122 | let isBlocks = { if case .blocks = mode { true } else { false } }() |
| 109 | if list != result.1 { list = result.1 } | 123 | let single = isBlocks ? AgendaBlockResult(header: "", mode: mode) : results[0] |
| 110 | if events != result.2 { events = result.2 } | 124 | let blocks = isBlocks ? results : [] |
| 125 | if days != single.days { days = single.days } | ||
| 126 | if list != single.list { list = single.list } | ||
| 127 | if events != single.events { events = single.events } | ||
| 128 | if self.blocks != blocks { self.blocks = blocks } | ||
| 111 | if self.today != today { self.today = today } | 129 | if self.today != today { self.today = today } |
| 112 | if self.calendar != calendar { self.calendar = calendar } | 130 | if self.calendar != calendar { self.calendar = calendar } |
| 113 | isComputing = false | 131 | isComputing = false |
| @@ -192,6 +210,11 @@ public final class AgendaModel { | |||
| 192 | AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep) | 210 | AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep) |
| 193 | } | 211 | } |
| 194 | 212 | ||
| 213 | /// A block's days as rows, as `groups` does for the view's. | ||
| 214 | public func groups(_ block: AgendaBlockResult, showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] { | ||
| 215 | AgendaRows.groups(block.days, events: block.events, today: today, showAllDates: showAllDates, calendar: calendar, keep: filter.keeps) | ||
| 216 | } | ||
| 217 | |||
| 195 | /// `groups` with `filter`, kept while the days, events and arguments are the same, as | 218 | /// `groups` with `filter`, kept while the days, events and arguments are the same, as |
| 196 | /// views ask on every redraw. | 219 | /// views ask on every redraw. |
| 197 | public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] { | 220 | public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] { |
| @@ -222,7 +245,10 @@ public final class AgendaModel { | |||
| 222 | /// The first day the agenda shows and how many, as `org-agenda-list` works them out: the | 245 | /// The first day the agenda shows and how many, as `org-agenda-list` works them out: the |
| 223 | /// view's span and start, or the settings', with 7- and 14-day spans moved back to | 246 | /// view's span and start, or the settings', with 7- and 14-day spans moved back to |
| 224 | /// `startOnWeekday`. | 247 | /// `startOnWeekday`. |
| 225 | public func shown(today: Int) -> (first: Int, span: Int) { | 248 | public func shown(today: Int) -> (first: Int, span: Int) { shown(today: today, mode: mode, start: start) } |
| 249 | |||
| 250 | /// `shown(today:)` for `mode`, from `start` when it isn't nil. | ||
| 251 | func shown(today: Int, mode: AgendaMode, start: Int?) -> (first: Int, span: Int) { | ||
| 226 | var span = self.span | 252 | var span = self.span |
| 227 | var startOffset = self.startOffset | 253 | var startOffset = self.startOffset |
| 228 | if case .agenda(let viewSpan, let viewStart) = mode { | 254 | if case .agenda(let viewSpan, let viewStart) = mode { |
Sources/OrgApp/AgendaViews.swift +148 −43
| @@ -1,5 +1,6 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import OrgCore | 2 | import OrgCore |
| 3 | import OrgPresentation | ||
| 3 | 4 | ||
| 4 | /// What the agenda window shows. | 5 | /// What the agenda window shows. |
| 5 | public enum AgendaMode: Hashable, Sendable { | 6 | public enum AgendaMode: Hashable, Sendable { |
| @@ -13,6 +14,8 @@ public enum AgendaMode: Hashable, Sendable { | |||
| 13 | case search(String, todoOnly: Bool) | 14 | case search(String, todoOnly: Bool) |
| 14 | /// `org-agenda-list-stuck-projects`; nil uses the `org-stuck-projects` setting. | 15 | /// `org-agenda-list-stuck-projects`; nil uses the `org-stuck-projects` setting. |
| 15 | case stuck(StuckProjects?) | 16 | case stuck(StuckProjects?) |
| 17 | /// A block agenda: several views one after the other. | ||
| 18 | case blocks([AgendaBlock]) | ||
| 16 | 19 | ||
| 17 | /// The key `org-agenda-prefix-format` and `org-agenda-sorting-strategy` use for this kind | 20 | /// The key `org-agenda-prefix-format` and `org-agenda-sorting-strategy` use for this kind |
| 18 | /// of view. | 21 | /// of view. |
| @@ -22,27 +25,92 @@ public enum AgendaMode: Hashable, Sendable { | |||
| 22 | case .todo: "todo" | 25 | case .todo: "todo" |
| 23 | case .match, .stuck: "tags" | 26 | case .match, .stuck: "tags" |
| 24 | case .search: "search" | 27 | case .search: "search" |
| 28 | case .blocks: "agenda" | ||
| 25 | } | 29 | } |
| 26 | } | 30 | } |
| 27 | } | 31 | } |
| 28 | 32 | ||
| 29 | /// A view's own `org-agenda-prefix-format` and `org-agenda-sorting-strategy`, as an | 33 | /// What one view of a block agenda shows. |
| 30 | /// `org-agenda-custom-commands` entry's settings give them. | 34 | public 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. | ||
| 48 | public 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`. | ||
| 31 | public struct AgendaViewSettings: Hashable, Sendable { | 61 | public struct AgendaViewSettings: Hashable, Sendable { |
| 32 | public var prefixFormat: String? | 62 | public var prefixFormat: String? |
| 33 | public var sortingStrategy: [String]? | 63 | public var sortingStrategy: [String]? |
| 64 | public var skip: AgendaSkip? | ||
| 65 | public var header: String? | ||
| 34 | 66 | ||
| 35 | public init(prefixFormat: String? = nil, sortingStrategy: [String]? = nil) { | 67 | public init(prefixFormat: String? = nil, sortingStrategy: [String]? = nil, skip: AgendaSkip? = nil, header: String? = nil) { |
| 36 | self.prefixFormat = prefixFormat | 68 | self.prefixFormat = prefixFormat |
| 37 | self.sortingStrategy = sortingStrategy | 69 | self.sortingStrategy = sortingStrategy |
| 70 | self.skip = skip | ||
| 71 | self.header = header | ||
| 38 | } | 72 | } |
| 39 | 73 | ||
| 40 | public func apply(to options: AgendaOptions, view: String) -> AgendaOptions { | 74 | public func apply(to options: AgendaOptions, view: String) -> AgendaOptions { |
| 41 | var options = options | 75 | var options = options |
| 42 | if let prefixFormat { options.prefixFormat[view] = prefixFormat } | 76 | if let prefixFormat { options.prefixFormat[view] = prefixFormat } |
| 43 | if let sortingStrategy { options.sortingStrategy[view] = sortingStrategy } | 77 | if let sortingStrategy { options.sortingStrategy[view] = sortingStrategy } |
| 78 | if let skip { options.skip = skip } | ||
| 44 | return options | 79 | return options |
| 45 | } | 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 | |||
| 89 | extension 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 | } | ||
| 46 | } | 114 | } |
| 47 | 115 | ||
| 48 | /// A named view: the built-in ones and those in `views.toml`. | 116 | /// A named view: the built-in ones and those in `views.toml`. |
| @@ -101,9 +169,18 @@ public enum AgendaViewLoader { | |||
| 101 | } catch { | 169 | } catch { |
| 102 | return (builtIn, ["views.toml: \(error)"]) | 170 | return (builtIn, ["views.toml: \(error)"]) |
| 103 | } | 171 | } |
| 104 | var views = builtIn | ||
| 105 | var problems: [String] = [] | 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])] = [] | ||
| 106 | for table in tables where !(table.name.isEmpty && table.values.isEmpty) { | 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 | } | ||
| 107 | guard table.name == "view", table.isArrayElement else { | 184 | guard table.name == "view", table.isArrayElement else { |
| 108 | problems.append("views.toml line \(table.line): expected [[view]]") | 185 | problems.append("views.toml line \(table.line): expected [[view]]") |
| 109 | continue | 186 | continue |
| @@ -112,50 +189,78 @@ public enum AgendaViewLoader { | |||
| 112 | problems.append("views.toml line \(table.line): a view needs a name") | 189 | problems.append("views.toml line \(table.line): a view needs a name") |
| 113 | continue | 190 | continue |
| 114 | } | 191 | } |
| 115 | let match = table.values["match"]?.string | 192 | parsed.append((name, table, [])) |
| 116 | let mode: AgendaMode | 193 | } |
| 117 | switch table.values["type"]?.string ?? "agenda" { | 194 | var views = builtIn |
| 118 | case "agenda": | 195 | for (name, table, blockTables) in parsed { |
| 119 | mode = .agenda(span: table.values["span"]?.integer, startOffset: table.values["start"]?.integer) | 196 | guard let settings = settings(table, &problems) else { continue } |
| 120 | case "todo": | 197 | if blockTables.isEmpty { |
| 121 | mode = .todo(keywords: table.values["keywords"]?.string) | 198 | guard let mode = mode(table, name: name, &problems) else { continue } |
| 122 | case "match", "todo-match": | 199 | views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings)) |
| 123 | guard let match else { | ||
| 124 | problems.append("views.toml line \(table.line): \(name) needs a match") | ||
| 125 | continue | ||
| 126 | } | ||
| 127 | mode = .match(match, todoOnly: table.values["type"]?.string == "todo-match") | ||
| 128 | case "search", "todo-search": | ||
| 129 | guard let match else { | ||
| 130 | problems.append("views.toml line \(table.line): \(name) needs a match") | ||
| 131 | continue | ||
| 132 | } | ||
| 133 | mode = .search(match, todoOnly: table.values["type"]?.string == "todo-search") | ||
| 134 | case "stuck": | ||
| 135 | if ["match", "keywords", "tags", "regexp"].allSatisfy({ table.values[$0] == nil }) { | ||
| 136 | mode = .stuck(nil) | ||
| 137 | } else { | ||
| 138 | var definition = OrgPreferences.stuckProjects() | ||
| 139 | if let match { definition.match = match } | ||
| 140 | if let keywords = table.values["keywords"]?.string { definition.todo = OrgPreferences.words(keywords) } | ||
| 141 | if let tags = table.values["tags"]?.string { definition.tags = OrgPreferences.words(tags) } | ||
| 142 | if let regexp = table.values["regexp"]?.string { definition.regexp = regexp } | ||
| 143 | mode = .stuck(definition) | ||
| 144 | } | ||
| 145 | case let other: | ||
| 146 | problems.append("views.toml line \(table.line): unknown type \(other)") | ||
| 147 | continue | 200 | continue |
| 148 | } | 201 | } |
| 149 | var settings = AgendaViewSettings(prefixFormat: table.values["prefix-format"]?.string) | 202 | var blocks: [AgendaBlock] = [] |
| 150 | if let strategy = table.values["sorting-strategy"]?.string { | 203 | for block in blockTables { |
| 151 | let keys = strategy.split(whereSeparator: \.isWhitespace).map(String.init) | 204 | guard var mode = mode(block, name: name, &problems), let own = Self.settings(block, &problems) else { continue } |
| 152 | if let bad = keys.first(where: { !AgendaSort.keys.contains($0) }) { | 205 | // The view's span and start go to agenda blocks without their own. |
| 153 | problems.append("views.toml line \(table.line): unknown sorting key \(bad)") | 206 | if case .agenda(let span, let start) = mode { |
| 207 | mode = .agenda(span: span ?? table.values["span"]?.integer, startOffset: start ?? table.values["start"]?.integer) | ||
| 154 | } | 208 | } |
| 155 | settings.sortingStrategy = keys.filter(AgendaSort.keys.contains) | 209 | blocks.append(AgendaBlock(mode: mode, settings: settings.merged(own))) |
| 156 | } | 210 | } |
| 157 | views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings)) | 211 | if !blocks.isEmpty { views.append(AgendaViewDefinition(name: name, mode: .blocks(blocks), settings: AgendaViewSettings(header: settings.header))) } |
| 158 | } | 212 | } |
| 159 | return (views, problems) | 213 | return (views, problems) |
| 160 | } | 214 | } |
| 215 | |||
| 216 | /// The view a `[[view]]` or `[[view.block]]` table describes. | ||
| 217 | static func mode(_ table: TOML.Table, name: String, _ problems: inout [String]) -> AgendaMode? { | ||
| 218 | let match = table.values["match"]?.string | ||
| 219 | let type = table.values["type"]?.string ?? "agenda" | ||
| 220 | switch type { | ||
| 221 | case "agenda": | ||
| 222 | return .agenda(span: table.values["span"]?.integer, startOffset: table.values["start"]?.integer) | ||
| 223 | case "todo": | ||
| 224 | return .todo(keywords: table.values["keywords"]?.string) | ||
| 225 | case "match", "todo-match", "search", "todo-search": | ||
| 226 | guard let match else { | ||
| 227 | problems.append("views.toml line \(table.line): \(name) needs a match") | ||
| 228 | return nil | ||
| 229 | } | ||
| 230 | return type.hasSuffix("match") ? .match(match, todoOnly: type == "todo-match") : .search(match, todoOnly: type == "todo-search") | ||
| 231 | case "stuck": | ||
| 232 | if ["match", "keywords", "tags", "regexp"].allSatisfy({ table.values[$0] == nil }) { return .stuck(nil) } | ||
| 233 | var definition = OrgPreferences.stuckProjects() | ||
| 234 | if let match { definition.match = match } | ||
| 235 | if let keywords = table.values["keywords"]?.string { definition.todo = OrgPreferences.words(keywords) } | ||
| 236 | if let tags = table.values["tags"]?.string { definition.tags = OrgPreferences.words(tags) } | ||
| 237 | if let regexp = table.values["regexp"]?.string { definition.regexp = regexp } | ||
| 238 | return .stuck(definition) | ||
| 239 | default: | ||
| 240 | problems.append("views.toml line \(table.line): unknown type \(type)") | ||
| 241 | return nil | ||
| 242 | } | ||
| 243 | } | ||
| 244 | |||
| 245 | /// The settings of a `[[view]]` or `[[view.block]]` table; nil when one can't be read. | ||
| 246 | static func settings(_ table: TOML.Table, _ problems: inout [String]) -> AgendaViewSettings? { | ||
| 247 | var settings = AgendaViewSettings(prefixFormat: table.values["prefix-format"]?.string, header: table.values["header"]?.string) | ||
| 248 | if let strategy = table.values["sorting-strategy"]?.string { | ||
| 249 | let keys = strategy.split(whereSeparator: \.isWhitespace).map(String.init) | ||
| 250 | if let bad = keys.first(where: { !AgendaSort.keys.contains($0) }) { | ||
| 251 | problems.append("views.toml line \(table.line): unknown sorting key \(bad)") | ||
| 252 | } | ||
| 253 | settings.sortingStrategy = keys.filter(AgendaSort.keys.contains) | ||
| 254 | } | ||
| 255 | for (key, subtree) in [("skip-entry-if", false), ("skip-subtree-if", true)] { | ||
| 256 | guard let text = table.values[key]?.string else { continue } | ||
| 257 | switch AgendaSkip.parse(text, subtree: subtree) { | ||
| 258 | case .success(let skip): settings.skip = skip | ||
| 259 | case .failure(.message(let message)): | ||
| 260 | problems.append("views.toml line \(table.line): \(key): \(message)") | ||
| 261 | return nil | ||
| 262 | } | ||
| 263 | } | ||
| 264 | return settings | ||
| 265 | } | ||
| 161 | } | 266 | } |
Sources/OrgApp/EmacsImport.swift +118 −2
| @@ -17,6 +17,8 @@ public struct EmacsImport: Sendable { | |||
| 17 | case binding(keys: String, command: String, mode: String?) | 17 | case binding(keys: String, command: String, mode: String?) |
| 18 | /// An `[org-structure-template-alist]` entry for config.toml. | 18 | /// An `[org-structure-template-alist]` entry for config.toml. |
| 19 | case structureTemplate(key: String, type: String) | 19 | case structureTemplate(key: String, type: String) |
| 20 | /// A `[[view]]` table, with its blocks, for views.toml. | ||
| 21 | case view(name: String, toml: String) | ||
| 20 | } | 22 | } |
| 21 | 23 | ||
| 22 | public struct Item: Sendable, Identifiable { | 24 | public struct Item: Sendable, Identifiable { |
| @@ -150,6 +152,8 @@ public struct EmacsImport: Sendable { | |||
| 150 | var bindings: [Binding] = [] | 152 | var bindings: [Binding] = [] |
| 151 | /// `(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))` entries. | 153 | /// `(add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))` entries. |
| 152 | var addedTemplates: [(entry: Sexp, source: String)] = [] | 154 | var addedTemplates: [(entry: Sexp, source: String)] = [] |
| 155 | /// `(add-to-list 'org-agenda-custom-commands '("w" "Work" tags "work"))` entries. | ||
| 156 | var addedCommands: [(entry: Sexp, source: String)] = [] | ||
| 153 | var usesEvil = false | 157 | var usesEvil = false |
| 154 | var order = 0 | 158 | var order = 0 |
| 155 | 159 | ||
| @@ -174,6 +178,9 @@ public struct EmacsImport: Sendable { | |||
| 174 | if args.count >= 2, unquote(args[0])?.symbol == "org-structure-template-alist", let entry = unquote(args[1]) { | 178 | if args.count >= 2, unquote(args[0])?.symbol == "org-structure-template-alist", let entry = unquote(args[1]) { |
| 175 | addedTemplates.append((entry, source)) | 179 | addedTemplates.append((entry, source)) |
| 176 | } | 180 | } |
| 181 | if args.count >= 2, unquote(args[0])?.symbol == "org-agenda-custom-commands", let entry = unquote(args[1]) { | ||
| 182 | addedCommands.append((entry, source)) | ||
| 183 | } | ||
| 177 | case "defvar", "defcustom": | 184 | case "defvar", "defcustom": |
| 178 | // Only sets a variable nothing set, so under every assignment. | 185 | // Only sets a variable nothing set, so under every assignment. |
| 179 | if args.count >= 2, let name = args[0].symbol { assign(name, args[1], source, priority: -1, deferred: false) } | 186 | if args.count >= 2, let name = args[0].symbol { assign(name, args[1], source, priority: -1, deferred: false) } |
| @@ -445,6 +452,7 @@ public struct EmacsImport: Sendable { | |||
| 445 | } | 452 | } |
| 446 | } | 453 | } |
| 447 | for (entry, source) in scanner.addedTemplates { structureTemplates([entry], source: source, id: id) } | 454 | for (entry, source) in scanner.addedTemplates { structureTemplates([entry], source: source, id: id) } |
| 455 | for (entry, source) in scanner.addedCommands { agendaCommand(entry, source: source, id: id) } | ||
| 448 | // One item per folder. | 456 | // One item per folder. |
| 449 | var folders: Set<String> = [] | 457 | var folders: Set<String> = [] |
| 450 | items.removeAll { item in | 458 | items.removeAll { item in |
| @@ -626,6 +634,8 @@ public struct EmacsImport: Sendable { | |||
| 626 | } | 634 | } |
| 627 | case "org-capture-templates": | 635 | case "org-capture-templates": |
| 628 | for entry in value.elements ?? [] { captureTemplate(entry, source: source, env: env, id: id) } | 636 | for entry in value.elements ?? [] { captureTemplate(entry, source: source, env: env, id: id) } |
| 637 | case "org-agenda-custom-commands": | ||
| 638 | for entry in value.elements ?? [] { agendaCommand(entry, source: source, id: id) } | ||
| 629 | case "doom-font": | 639 | case "doom-font": |
| 630 | note("not a font-spec orgstar can read") | 640 | note("not a font-spec orgstar can read") |
| 631 | case "doom-variable-pitch-font": | 641 | case "doom-variable-pitch-font": |
| @@ -685,6 +695,99 @@ public struct EmacsImport: Sendable { | |||
| 685 | } | 695 | } |
| 686 | } | 696 | } |
| 687 | 697 | ||
| 698 | /// An `org-agenda-custom-commands` entry as a `[[view]]` table: `("w" "Work" tags "+work" | ||
| 699 | /// ((settings)))`, or with a list of blocks in place of the type and match. | ||
| 700 | mutating func agendaCommand(_ entry: Sexp, source: String, id: () -> Int) { | ||
| 701 | guard var parts = entry.elements, let key = parts.first?.string else { return } | ||
| 702 | parts.removeFirst() | ||
| 703 | let name = parts.first?.string ?? key | ||
| 704 | if parts.first?.string != nil { parts.removeFirst() } | ||
| 705 | // A key and a description only: a prefix for other commands. | ||
| 706 | guard let first = parts.first else { return } | ||
| 707 | func note(_ reason: String) { unsupported.append(Note(id: id(), name: "agenda command \"\(key)\"", reason: reason, source: source)) } | ||
| 708 | func quoted(_ s: String) -> String { UserConfig.format(.string(s)) } | ||
| 709 | func unquote(_ s: Sexp) -> Sexp { | ||
| 710 | if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" || items[0].symbol == "function" { return items[1] } | ||
| 711 | return s | ||
| 712 | } | ||
| 713 | /// `(type match settings)` as TOML lines, or nil with a note. | ||
| 714 | func view(_ type: String, _ match: Sexp?, _ settings: Sexp?) -> String? { | ||
| 715 | var toml = "" | ||
| 716 | let matchString = match.flatMap { unquote($0).string }.flatMap { $0.isEmpty ? nil : $0 } | ||
| 717 | switch type { | ||
| 718 | case "agenda": toml += "type = \"agenda\"\n" | ||
| 719 | case "alltodo": toml += "type = \"todo\"\n" | ||
| 720 | case "todo": | ||
| 721 | toml += "type = \"todo\"\n" | ||
| 722 | if let matchString { toml += "keywords = \(quoted(matchString))\n" } | ||
| 723 | case "tags", "tags-todo", "search": | ||
| 724 | guard let matchString else { note("\(type) needs a match"); return nil } | ||
| 725 | let kind = ["tags": "match", "tags-todo": "todo-match", "search": "search"][type]! | ||
| 726 | toml += "type = \"\(kind)\"\nmatch = \(quoted(matchString))\n" | ||
| 727 | case "stuck": toml += "type = \"stuck\"\n" | ||
| 728 | default: note("\(type) views aren't supported"); return nil | ||
| 729 | } | ||
| 730 | guard let settings = settings.map(unquote), let pairs = settings.elements else { return toml } | ||
| 731 | for pair in pairs { | ||
| 732 | guard let items = pair.elements, items.count == 2, let variable = items[0].symbol else { continue } | ||
| 733 | let value = unquote(items[1]) | ||
| 734 | switch variable { | ||
| 735 | case "org-agenda-span" where type == "agenda": | ||
| 736 | let spans = ["day": 1, "week": 7, "fortnight": 14, "month": 30, "year": 365] | ||
| 737 | if let n = value.integer ?? value.symbol.flatMap({ spans[$0] }) { toml += "span = \(n)\n" } else { note("org-agenda-span \(value.description)") } | ||
| 738 | case "org-agenda-start-day" where type == "agenda": | ||
| 739 | if let s = value.string, let n = Int(s.replacingOccurrences(of: "d", with: "").replacingOccurrences(of: "+", with: "")) { | ||
| 740 | toml += "start = \(n)\n" | ||
| 741 | } else { note("org-agenda-start-day \(value.description)") } | ||
| 742 | case "org-agenda-overriding-header": | ||
| 743 | if let s = value.string { toml += "header = \(quoted(s))\n" } | ||
| 744 | case "org-agenda-sorting-strategy": | ||
| 745 | let keys = (value.elements ?? []).compactMap(\.symbol) | ||
| 746 | if !keys.isEmpty, keys.allSatisfy(AgendaSort.keys.contains) { toml += "sorting-strategy = \(quoted(keys.joined(separator: " ")))\n" } else { note("org-agenda-sorting-strategy \(value.description)") } | ||
| 747 | case "org-agenda-prefix-format": | ||
| 748 | if let s = value.string { toml += "prefix-format = \(quoted(s))\n" } else { note("org-agenda-prefix-format as an alist") } | ||
| 749 | case "org-agenda-skip-function": | ||
| 750 | guard let form = value.elements, let head = form.first?.symbol, ["org-agenda-skip-entry-if", "org-agenda-skip-subtree-if"].contains(head) else { | ||
| 751 | note("org-agenda-skip-function \(value.description)") | ||
| 752 | continue | ||
| 753 | } | ||
| 754 | let subtree = head == "org-agenda-skip-subtree-if" | ||
| 755 | switch AgendaSkip.parse(form.dropFirst().map(\.description).joined(separator: " "), subtree: subtree) { | ||
| 756 | case .success(let skip): toml += "\(subtree ? "skip-subtree-if" : "skip-entry-if") = \(quoted(skip.lisp))\n" | ||
| 757 | case .failure(.message(let message)): note("org-agenda-skip-function: \(message)") | ||
| 758 | } | ||
| 759 | default: | ||
| 760 | note("\(variable) in a view isn't supported") | ||
| 761 | } | ||
| 762 | } | ||
| 763 | return toml | ||
| 764 | } | ||
| 765 | var toml = "[[view]]\nname = \(quoted(name))\n" | ||
| 766 | if let type = first.symbol { | ||
| 767 | if type == "agenda*" { note("agenda* views aren't supported"); return } | ||
| 768 | guard let body = view(type, parts.count > 1 ? parts[1] : nil, parts.count > 2 ? parts[2] : nil) else { return } | ||
| 769 | toml += body | ||
| 770 | if parts.count > 3 { note("files for a view are ignored") } | ||
| 771 | } else if let blocks = first.elements { | ||
| 772 | // Settings for all the blocks come after them. | ||
| 773 | var common = view("agenda", nil, parts.count > 1 ? parts[1] : nil) ?? "" | ||
| 774 | common = common.replacingOccurrences(of: "type = \"agenda\"\n", with: "") | ||
| 775 | toml += common | ||
| 776 | var count = 0 | ||
| 777 | for block in blocks { | ||
| 778 | guard let items = block.elements, let type = items.first?.symbol, | ||
| 779 | let body = view(type, items.count > 1 ? items[1] : nil, items.count > 2 ? items[2] : nil) else { continue } | ||
| 780 | toml += "[[view.block]]\n" + body | ||
| 781 | count += 1 | ||
| 782 | } | ||
| 783 | guard count > 0 else { return } | ||
| 784 | if parts.count > 2 { note("files for a view are ignored") } | ||
| 785 | } else { | ||
| 786 | return note("not a view orgstar can read") | ||
| 787 | } | ||
| 788 | items.append(Item(id: id(), name: "org-agenda-custom-commands \"\(key)\"", summary: "views.toml view \(name)", source: source, change: .view(name: name, toml: toml))) | ||
| 789 | } | ||
| 790 | |||
| 688 | mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) { | 791 | mutating func captureTemplate(_ entry: Sexp, source: String, env: [String: Sexp] = [:], id: () -> Int) { |
| 689 | guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return } | 792 | guard let parts = entry.elements, parts.count >= 2, let key = parts[0].string else { return } |
| 690 | let name = parts[1].string ?? key | 793 | let name = parts[1].string ?? key |
| @@ -798,7 +901,7 @@ extension EmacsImport { | |||
| 798 | public static func apply( | 901 | public static func apply( |
| 799 | _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory | 902 | _ items: [Item], defaults: UserDefaults = .standard, workspace: WorkspaceModel?, directory: URL = UserConfig.directory |
| 800 | ) async -> String { | 903 | ) async -> String { |
| 801 | var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0 | 904 | var settings = 0, folders = 0, templates = 0, bindings = 0, blocks = 0, views = 0 |
| 802 | var problems: [String] = [] | 905 | var problems: [String] = [] |
| 803 | for item in items { | 906 | for item in items { |
| 804 | guard case .setting(let key, let value) = item.change, | 907 | guard case .setting(let key, let value) = item.change, |
| @@ -834,6 +937,19 @@ extension EmacsImport { | |||
| 834 | capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture | 937 | capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture |
| 835 | try? capture.write(to: captureFile, atomically: true, encoding: .utf8) | 938 | try? capture.write(to: captureFile, atomically: true, encoding: .utf8) |
| 836 | } | 939 | } |
| 940 | let viewsFile = directory.appendingPathComponent("views.toml") | ||
| 941 | var viewsText = (try? String(contentsOf: viewsFile, encoding: .utf8)) ?? "" | ||
| 942 | var viewNames = Set((try? TOML.parse(viewsText))?.filter { $0.name == "view" }.compactMap { $0.values["name"]?.string } ?? []) | ||
| 943 | var addedViews = "" | ||
| 944 | for item in items { | ||
| 945 | guard case .view(let name, let toml) = item.change, viewNames.insert(name).inserted else { continue } | ||
| 946 | addedViews += "\n" + toml | ||
| 947 | views += 1 | ||
| 948 | } | ||
| 949 | if !addedViews.isEmpty { | ||
| 950 | viewsText += (viewsText.isEmpty ? "# Agenda views. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedViews | ||
| 951 | try? viewsText.write(to: viewsFile, atomically: true, encoding: .utf8) | ||
| 952 | } | ||
| 837 | let keymapFile = directory.appendingPathComponent("keymap.toml") | 953 | let keymapFile = directory.appendingPathComponent("keymap.toml") |
| 838 | var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? "" | 954 | var keymap = (try? String(contentsOf: keymapFile, encoding: .utf8)) ?? "" |
| 839 | func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") } | 955 | func binding(_ keys: String?, _ command: String?, _ mode: String?) -> String { [keys ?? "", command ?? "", mode ?? ""].joined(separator: "\u{0}") } |
| @@ -862,7 +978,7 @@ extension EmacsImport { | |||
| 862 | if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) } | 978 | if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) } |
| 863 | func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } | 979 | func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } |
| 864 | let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), | 980 | let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), |
| 865 | count(blocks, "structure template")].compactMap { $0 } | 981 | count(blocks, "structure template"), count(views, "agenda view")].compactMap { $0 } |
| 866 | var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "." | 982 | var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "." |
| 867 | if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." } | 983 | if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." } |
| 868 | return summary | 984 | return summary |
Sources/OrgCore/Agenda/Agenda.swift +22 −4
| @@ -93,6 +93,8 @@ public struct AgendaOptions: Sendable, Equatable { | |||
| 93 | public var showCurrentTimeInGrid = true | 93 | public var showCurrentTimeInGrid = true |
| 94 | /// `org-stuck-projects`, for views that don't give their own. | 94 | /// `org-stuck-projects`, for views that don't give their own. |
| 95 | public var stuckProjects = StuckProjects() | 95 | public var stuckProjects = StuckProjects() |
| 96 | /// `org-agenda-skip-function`, as `org-agenda-skip-entry-if` or `-subtree-if`. | ||
| 97 | public var skip: AgendaSkip? | ||
| 96 | public var gridTrailing = " ┄┄┄┄┄ " | 98 | public var gridTrailing = " ┄┄┄┄┄ " |
| 97 | public var gridLine = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" | 99 | public var gridLine = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" |
| 98 | public var currentTimeLine = "← now ───────────────────────────────────────────────" | 100 | public var currentTimeLine = "← now ───────────────────────────────────────────────" |
| @@ -226,8 +228,11 @@ public enum Agenda { | |||
| 226 | static func deadlines(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] { | 228 | static func deadlines(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] { |
| 227 | let isToday = current == today | 229 | let isToday = current == today |
| 228 | var items: [AgendaItem] = [] | 230 | var items: [AgendaItem] = [] |
| 229 | for heading in source.headings { | 231 | var skipper = Skipper(options.skip, source) |
| 230 | guard !heading.skipped, let (s, offset) = heading.deadline, let (deadline, sexp) = planningDay(s, current: current) else { continue } | 232 | for (index, heading) in source.headings.enumerated() { |
| 233 | guard !heading.skipped, let (s, offset) = heading.deadline else { continue } | ||
| 234 | if skipper.skips(heading.start, heading: index) { continue } | ||
| 235 | guard let (deadline, sexp) = planningDay(s, current: current) else { continue } | ||
| 231 | let repeat_ = sexp || current <= today ? deadline : (Days.closest(s, to: current, prefer: .future) ?? deadline) | 236 | let repeat_ = sexp || current <= today ? deadline : (Days.closest(s, to: current, prefer: .future) ?? deadline) |
| 232 | let diff = deadline - current | 237 | let diff = deadline - current |
| 233 | let warningDays = Days.warningDays(s, delay: false, defaultDays: options.deadlineWarningDays) | 238 | let warningDays = Days.warningDays(s, delay: false, defaultDays: options.deadlineWarningDays) |
| @@ -264,8 +269,11 @@ public enum Agenda { | |||
| 264 | static func scheduled(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] { | 269 | static func scheduled(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] { |
| 265 | let isToday = current == today | 270 | let isToday = current == today |
| 266 | var items: [AgendaItem] = [] | 271 | var items: [AgendaItem] = [] |
| 267 | for heading in source.headings { | 272 | var skipper = Skipper(options.skip, source) |
| 268 | guard !heading.skipped, let (s, offset) = heading.scheduled, let (schedule, sexp) = planningDay(s, current: current) else { continue } | 273 | for (index, heading) in source.headings.enumerated() { |
| 274 | guard !heading.skipped, let (s, offset) = heading.scheduled else { continue } | ||
| 275 | if skipper.skips(heading.start, heading: index) { continue } | ||
| 276 | guard let (schedule, sexp) = planningDay(s, current: current) else { continue } | ||
| 269 | let repeat_ = sexp || current <= today ? schedule : (Days.closest(s, to: current, prefer: .future) ?? schedule) | 277 | let repeat_ = sexp || current <= today ? schedule : (Days.closest(s, to: current, prefer: .future) ?? schedule) |
| 270 | let diff = current - schedule | 278 | let diff = current - schedule |
| 271 | let past = schedule < today | 279 | let past = schedule < today |
| @@ -294,7 +302,9 @@ public enum Agenda { | |||
| 294 | 302 | ||
| 295 | static func blocks(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] { | 303 | static func blocks(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] { |
| 296 | var items: [AgendaItem] = [] | 304 | var items: [AgendaItem] = [] |
| 305 | var skipper = Skipper(options.skip, source) | ||
| 297 | for block in source.blocks { | 306 | for block in source.blocks { |
| 307 | if skipper.skips(block.marker, heading: block.heading) { continue } | ||
| 298 | guard let startDay = Days.absolute(of: block.start), let endDay = Days.absolute(of: block.end), | 308 | guard let startDay = Days.absolute(of: block.start), let endDay = Days.absolute(of: block.end), |
| 299 | current >= startDay, endDay >= current else { continue } | 309 | current >= startDay, endDay >= current else { continue } |
| 300 | let heading = source.headings[block.heading] | 310 | let heading = source.headings[block.heading] |
| @@ -319,7 +329,9 @@ public enum Agenda { | |||
| 319 | let date = Days.date(current) | 329 | let date = Days.date(current) |
| 320 | let literal = String(format: "%04d-%02d-%02d", date.year, date.month, date.day) | 330 | let literal = String(format: "%04d-%02d-%02d", date.year, date.month, date.day) |
| 321 | var items: [AgendaItem] = [] | 331 | var items: [AgendaItem] = [] |
| 332 | var skipper = Skipper(options.skip, source) | ||
| 322 | for entry in source.progress where entry.date == literal { | 333 | for entry in source.progress where entry.date == literal { |
| 334 | if skipper.skips(entry.offset, heading: entry.heading) { continue } | ||
| 323 | let kind: AgendaItem.Kind | 335 | let kind: AgendaItem.Kind |
| 324 | let extra: String | 336 | let extra: String |
| 325 | switch entry.kind { | 337 | switch entry.kind { |
| @@ -362,9 +374,13 @@ public enum Agenda { | |||
| 362 | let date = Days.date(current) | 374 | let date = Days.date(current) |
| 363 | let literal = String(format: "<%04d-%02d-%02d", date.year, date.month, date.day) | 375 | let literal = String(format: "<%04d-%02d-%02d", date.year, date.month, date.day) |
| 364 | var items: [AgendaItem] = [] | 376 | var items: [AgendaItem] = [] |
| 377 | var skipper = Skipper(options.skip, source) | ||
| 365 | for stamp in source.stamps { | 378 | for stamp in source.stamps { |
| 366 | let rest = stamp.rest as NSString | 379 | let rest = stamp.rest as NSString |
| 367 | let all = NSRange(location: 0, length: rest.length) | 380 | let all = NSRange(location: 0, length: rest.length) |
| 381 | // The stamps the day's regexp finds: of the day, with a repeater, or a diary sexp. | ||
| 382 | if options.skip != nil, stamp.rest.hasPrefix(literal) || diaryStamp.firstMatch(in: stamp.rest, range: all) != nil | ||
| 383 | || repeating.firstMatch(in: stamp.rest, range: all) != nil, skipper.skips(stamp.offset, heading: stamp.heading) { continue } | ||
| 368 | let timestamp: String | 384 | let timestamp: String |
| 369 | if stamp.rest.hasPrefix(literal) { | 385 | if stamp.rest.hasPrefix(literal) { |
| 370 | guard let m = stampBoth.firstMatch(in: stamp.rest, range: all) else { continue } | 386 | guard let m = stampBoth.firstMatch(in: stamp.rest, range: all) else { continue } |
| @@ -394,8 +410,10 @@ public enum Agenda { | |||
| 394 | /// `org-agenda-get-sexps`. | 410 | /// `org-agenda-get-sexps`. |
| 395 | static func sexps(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] { | 411 | static func sexps(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] { |
| 396 | var items: [AgendaItem] = [] | 412 | var items: [AgendaItem] = [] |
| 413 | var skipper = Skipper(options.skip, source) | ||
| 397 | for line in source.sexps { | 414 | for line in source.sexps { |
| 398 | guard let results = DiarySexp.entries(line.sexp, entry: line.entry, day: current) else { continue } | 415 | guard let results = DiarySexp.entries(line.sexp, entry: line.entry, day: current) else { continue } |
| 416 | if skipper.skips(line.offset, heading: line.heading) { continue } | ||
| 399 | let heading = source.headings[line.heading] | 417 | let heading = source.headings[line.heading] |
| 400 | for result in results { | 418 | for result in results { |
| 401 | let txt = result.contains(where: { !$0.isWhitespace }) ? result : "SEXP entry returned empty string" | 419 | let txt = result.contains(where: { !$0.isWhitespace }) ? result : "SEXP entry returned empty string" |
Sources/OrgCore/Agenda/AgendaSearch.swift +9
| @@ -8,6 +8,7 @@ extension Agenda { | |||
| 8 | let selected = keywords.map { $0.split(separator: "|").map(String.init) } | 8 | let selected = keywords.map { $0.split(separator: "|").map(String.init) } |
| 9 | var items: [AgendaItem] = [] | 9 | var items: [AgendaItem] = [] |
| 10 | for source in sources { | 10 | for source in sources { |
| 11 | var skipper = Skipper(options.skip, source) | ||
| 11 | for (index, heading) in source.headings.enumerated() where !heading.skipped { | 12 | for (index, heading) in source.headings.enumerated() where !heading.skipped { |
| 12 | guard let todo = heading.todo else { continue } | 13 | guard let todo = heading.todo else { continue } |
| 13 | if let selected { | 14 | if let selected { |
| @@ -15,6 +16,7 @@ extension Agenda { | |||
| 15 | } else if heading.isDone { | 16 | } else if heading.isDone { |
| 16 | continue | 17 | continue |
| 17 | } | 18 | } |
| 19 | if skipper.skips(heading.start, heading: index) { continue } | ||
| 18 | if ignoresTodo(source, index, options: options, today: today) { continue } | 20 | if ignoresTodo(source, index, options: options, today: today) { continue } |
| 19 | var item = format( | 21 | var item = format( |
| 20 | source, heading, kind: .todo, marker: heading.start, extra: "", dotime: .headline, removing: nil, | 22 | source, heading, kind: .todo, marker: heading.start, extra: "", dotime: .headline, removing: nil, |
| @@ -38,10 +40,12 @@ extension Agenda { | |||
| 38 | let today = Days.absolute(now, calendar: calendar) | 40 | let today = Days.absolute(now, calendar: calendar) |
| 39 | var items: [AgendaItem] = [] | 41 | var items: [AgendaItem] = [] |
| 40 | for source in sources { | 42 | for source in sources { |
| 43 | var skipper = Skipper(skip == nil ? options.skip : nil, source, caseFold: true) | ||
| 41 | for (index, heading) in source.headings.enumerated() { | 44 | for (index, heading) in source.headings.enumerated() { |
| 42 | if matcher.todoOnly, heading.todo == nil { continue } | 45 | if matcher.todoOnly, heading.todo == nil { continue } |
| 43 | guard matcher.matches(heading, in: source, now: now, calendar: calendar), !heading.skipped else { continue } | 46 | guard matcher.matches(heading, in: source, now: now, calendar: calendar), !heading.skipped else { continue } |
| 44 | if let skip, skip(source, index) { continue } | 47 | if let skip, skip(source, index) { continue } |
| 48 | if skipper.skips(heading.start, heading: index) { continue } | ||
| 45 | if matcher.todoOnly, options.tagsTodoHonorIgnoreOptions, ignoresTodo(source, index, options: options, today: today) { continue } | 49 | if matcher.todoOnly, options.tagsTodoHonorIgnoreOptions, ignoresTodo(source, index, options: options, today: today) { continue } |
| 46 | var item = format( | 50 | var item = format( |
| 47 | source, heading, kind: .tagsMatch, marker: heading.start, extra: "", dotime: nil, removing: nil, | 51 | source, heading, kind: .tagsMatch, marker: heading.start, extra: "", dotime: nil, removing: nil, |
| @@ -135,6 +139,7 @@ extension Agenda { | |||
| 135 | let starts = headingLine.matches(in: text, range: NSRange(location: 0, length: length)).map(\.range.location) | 139 | let starts = headingLine.matches(in: text, range: NSRange(location: 0, length: length)).map(\.range.location) |
| 136 | guard let firstHeading = starts.first else { continue } | 140 | guard let firstHeading = starts.first else { continue } |
| 137 | let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a }) | 141 | let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a }) |
| 142 | let indexByStart = Dictionary(source.headings.enumerated().map { ($0.element.start, $0.offset) }, uniquingKeysWith: { a, _ in a }) | ||
| 138 | var required = patterns | 143 | var required = patterns |
| 139 | if query.todoOnly { | 144 | if query.todoOnly { |
| 140 | guard !source.notDoneKeywords.isEmpty else { continue } | 145 | guard !source.notDoneKeywords.isEmpty else { continue } |
| @@ -167,6 +172,10 @@ extension Agenda { | |||
| 167 | at = max(stop, at + 1) | 172 | at = max(stop, at + 1) |
| 168 | continue | 173 | continue |
| 169 | } | 174 | } |
| 175 | if let skip = options.skip, let headingIndex = indexByStart[beg], let skipTo = skip.skipEnd(source, heading: headingIndex, caseFold: true) { | ||
| 176 | at = max(skipTo, at + 1) | ||
| 177 | continue | ||
| 178 | } | ||
| 170 | let lineEnd = ns.range(of: "\n", range: NSRange(location: beg, length: length - beg)).location | 179 | let lineEnd = ns.range(of: "\n", range: NSRange(location: beg, length: length - beg)).location |
| 171 | let stop = query.headlinesOnly && lineEnd != NSNotFound ? lineEnd : end | 180 | let stop = query.headlinesOnly && lineEnd != NSNotFound ? lineEnd : end |
| 172 | let entryText = ns.substring(with: NSRange(location: beg, length: stop - beg)) | 181 | let entryText = ns.substring(with: NSRange(location: beg, length: stop - beg)) |
Sources/OrgCore/Agenda/AgendaSkip.swift added +214
| @@ -0,0 +1,214 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// `org-agenda-skip-entry-if` and `org-agenda-skip-subtree-if` (Org 9.8.7) as | ||
| 4 | /// `org-agenda-skip-function`: an entry, or a whole subtree, is left out of a view when any | ||
| 5 | /// of the conditions holds. | ||
| 6 | public struct AgendaSkip: Sendable, Hashable { | ||
| 7 | public enum Condition: Sendable, Hashable { | ||
| 8 | case scheduled, notScheduled, deadline, notDeadline, timestamp, notTimestamp | ||
| 9 | /// Emacs regexps. | ||
| 10 | case regexp(String), notRegexp(String) | ||
| 11 | case todo(Keywords), notTodo(Keywords) | ||
| 12 | } | ||
| 13 | |||
| 14 | /// What `todo` and `nottodo` take: keywords (`*` for any), or the class `todo`, `done` | ||
| 15 | /// or `any`. | ||
| 16 | public enum Keywords: Sendable, Hashable { | ||
| 17 | case list([String]) | ||
| 18 | case open, done, any | ||
| 19 | } | ||
| 20 | |||
| 21 | public enum Failure: Error, Equatable { | ||
| 22 | case message(String) | ||
| 23 | } | ||
| 24 | |||
| 25 | public var subtree: Bool | ||
| 26 | public var conditions: [Condition] | ||
| 27 | |||
| 28 | public init(subtree: Bool, conditions: [Condition]) { | ||
| 29 | self.subtree = subtree | ||
| 30 | self.conditions = conditions | ||
| 31 | } | ||
| 32 | |||
| 33 | /// The arguments as Lisp writes them: `'scheduled 'regexp "\\<IGNORE\\>" 'todo '("DONE")`, | ||
| 34 | /// the quotes optional. Nil, with the reason, for what `org-agenda-skip-if` doesn't take. | ||
| 35 | public static func parse(_ text: String, subtree: Bool) -> Result<AgendaSkip, Failure> { | ||
| 36 | let forms: [Sexp] | ||
| 37 | do { | ||
| 38 | forms = try LispReader.read("(" + text + ")").first?.sexp.elements ?? [] | ||
| 39 | } catch { | ||
| 40 | return .failure(.message("can't read \(text)")) | ||
| 41 | } | ||
| 42 | func unquote(_ s: Sexp) -> Sexp { | ||
| 43 | if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" { return items[1] } | ||
| 44 | return s | ||
| 45 | } | ||
| 46 | let args = forms.map(unquote) | ||
| 47 | var conditions: [Condition] = [] | ||
| 48 | var i = 0 | ||
| 49 | while i < args.count { | ||
| 50 | guard let name = args[i].symbol else { return .failure(.message("\(args[i].description) isn't a condition")) } | ||
| 51 | i += 1 | ||
| 52 | func next() -> Sexp? { | ||
| 53 | defer { i += 1 } | ||
| 54 | return i < args.count ? args[i] : nil | ||
| 55 | } | ||
| 56 | switch name { | ||
| 57 | case "scheduled": conditions.append(.scheduled) | ||
| 58 | case "notscheduled": conditions.append(.notScheduled) | ||
| 59 | case "deadline": conditions.append(.deadline) | ||
| 60 | case "notdeadline": conditions.append(.notDeadline) | ||
| 61 | case "timestamp": conditions.append(.timestamp) | ||
| 62 | case "nottimestamp": conditions.append(.notTimestamp) | ||
| 63 | case "regexp", "notregexp": | ||
| 64 | guard let re = next()?.string else { return .failure(.message("\(name) needs a string")) } | ||
| 65 | conditions.append(name == "regexp" ? .regexp(re) : .notRegexp(re)) | ||
| 66 | case "todo", "nottodo": | ||
| 67 | let keywords: Keywords | ||
| 68 | switch next() { | ||
| 69 | case .symbol("todo")?: keywords = .open | ||
| 70 | case .symbol("done")?: keywords = .done | ||
| 71 | case .symbol("any")?: keywords = .any | ||
| 72 | case let arg?: | ||
| 73 | guard let items = arg.elements, items.allSatisfy({ $0.string != nil }) else { return .failure(.message("\(name) needs keywords or todo, done or any")) } | ||
| 74 | keywords = .list(items.compactMap(\.string)) | ||
| 75 | case nil: return .failure(.message("\(name) needs keywords or todo, done or any")) | ||
| 76 | } | ||
| 77 | conditions.append(name == "todo" ? .todo(keywords) : .notTodo(keywords)) | ||
| 78 | default: | ||
| 79 | return .failure(.message("\(name) isn't supported")) | ||
| 80 | } | ||
| 81 | } | ||
| 82 | return .success(AgendaSkip(subtree: subtree, conditions: conditions)) | ||
| 83 | } | ||
| 84 | |||
| 85 | /// The conditions as `parse` reads them. | ||
| 86 | public var lisp: String { | ||
| 87 | conditions.map { condition in | ||
| 88 | func keywords(_ k: Keywords) -> String { | ||
| 89 | switch k { | ||
| 90 | case .list(let words): "(" + words.map { "\"\($0)\"" }.joined(separator: " ") + ")" | ||
| 91 | case .open: "todo" | ||
| 92 | case .done: "done" | ||
| 93 | case .any: "any" | ||
| 94 | } | ||
| 95 | } | ||
| 96 | func quoted(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" } | ||
| 97 | return switch condition { | ||
| 98 | case .scheduled: "scheduled" | ||
| 99 | case .notScheduled: "notscheduled" | ||
| 100 | case .deadline: "deadline" | ||
| 101 | case .notDeadline: "notdeadline" | ||
| 102 | case .timestamp: "timestamp" | ||
| 103 | case .notTimestamp: "nottimestamp" | ||
| 104 | case .regexp(let re): "regexp " + quoted(re) | ||
| 105 | case .notRegexp(let re): "notregexp " + quoted(re) | ||
| 106 | case .todo(let k): "todo " + keywords(k) | ||
| 107 | case .notTodo(let k): "nottodo " + keywords(k) | ||
| 108 | } | ||
| 109 | }.joined(separator: " ") | ||
| 110 | } | ||
| 111 | |||
| 112 | |||
| 113 | /// `org-agenda-skip-if` at the heading `index`: where the scan continues when it is skipped | ||
| 114 | /// (the next heading, or the end of the subtree), else nil. `caseFold` is the scan's | ||
| 115 | /// `case-fold-search`: nil for the day and TODO scans, t for tags and search. | ||
| 116 | func skipEnd(_ source: AgendaSource, heading index: Int, caseFold: Bool = false) -> Int? { | ||
| 117 | let heading = source.headings[index] | ||
| 118 | let ns = source.text as NSString | ||
| 119 | let begin = heading.start | ||
| 120 | let end: Int | ||
| 121 | if subtree { | ||
| 122 | // `org-end-of-subtree`: before the line break and blank lines ending it. | ||
| 123 | var e = source.headings[(index + 1)...].first { $0.level <= heading.level }?.start ?? ns.length | ||
| 124 | if e > begin, ns.character(at: e - 1) == 10 { | ||
| 125 | e -= 1 | ||
| 126 | while e > begin, [10, 13, 9, 32].contains(ns.character(at: e - 1)) { e -= 1 } | ||
| 127 | } | ||
| 128 | end = e | ||
| 129 | } else { | ||
| 130 | end = index + 1 < source.headings.count ? source.headings[index + 1].start : ns.length | ||
| 131 | } | ||
| 132 | // The planning line is the one after the heading. | ||
| 133 | var planningEnd = end | ||
| 134 | if !subtree { | ||
| 135 | let first = NSMaxRange(ns.lineRange(for: NSRange(location: begin, length: 0))) | ||
| 136 | let second = first < ns.length ? ns.lineRange(for: NSRange(location: first, length: 0)) : NSRange(location: first, length: 0) | ||
| 137 | var lineEnd = NSMaxRange(second) | ||
| 138 | if lineEnd > second.location, ns.character(at: lineEnd - 1) == 10 { lineEnd -= 1 } | ||
| 139 | planningEnd = min(max(first, lineEnd), ns.length) | ||
| 140 | } | ||
| 141 | let fold: NSRegularExpression.Options = caseFold ? [.caseInsensitive, .anchorsMatchLines] : .anchorsMatchLines | ||
| 142 | let scheduledRegex = try? NSRegularExpression(pattern: "\\bSCHEDULED: *<([^>]+)>", options: fold) | ||
| 143 | let deadlineRegex = try? NSRegularExpression(pattern: "\\bDEADLINE: *<([^>]+)>", options: fold) | ||
| 144 | let timestampRegex = try? NSRegularExpression(pattern: "<(\(AgendaSource.tsInternal))>", options: fold) | ||
| 145 | func found(_ regex: NSRegularExpression?, _ limit: Int) -> Bool { | ||
| 146 | guard let regex, limit > begin else { return false } | ||
| 147 | return regex.firstMatch(in: source.text, range: NSRange(location: begin, length: limit - begin)) != nil | ||
| 148 | } | ||
| 149 | func todoRegex(_ keywords: Keywords) -> NSRegularExpression? { | ||
| 150 | let done = source.keywords.filter { !source.notDoneKeywords.contains($0) } | ||
| 151 | let words: [String] = switch keywords { | ||
| 152 | case .open: source.notDoneKeywords | ||
| 153 | case .done: done | ||
| 154 | case .any: source.keywords | ||
| 155 | case .list(let list): list.contains("*") ? source.keywords : list | ||
| 156 | } | ||
| 157 | guard !words.isEmpty else { return nil } | ||
| 158 | let alternatives = words.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") | ||
| 159 | return try? NSRegularExpression(pattern: "^\\*+[ \\t]+\\b(?:" + alternatives + ")\\b", options: .anchorsMatchLines) | ||
| 160 | } | ||
| 161 | func regex(_ emacs: String) -> NSRegularExpression? { | ||
| 162 | try? NSRegularExpression(pattern: EmacsRegex.translate(emacs), options: fold) | ||
| 163 | } | ||
| 164 | // `org-agenda-skip-if` tests in this order, whatever order the conditions are in. | ||
| 165 | let c = conditions | ||
| 166 | let first: (Condition) -> String? = { if case .regexp(let re) = $0 { re } else { nil } } | ||
| 167 | let firstNot: (Condition) -> String? = { if case .notRegexp(let re) = $0 { re } else { nil } } | ||
| 168 | let todoArgument = c.first { if case .notTodo = $0 { true } else if case .todo = $0 { true } else { false } } | ||
| 169 | let notTodo = c.first { if case .notTodo = $0 { true } else { false } } | ||
| 170 | var holds = (c.contains(.scheduled) && found(scheduledRegex, planningEnd)) | ||
| 171 | || (c.contains(.notScheduled) && !found(scheduledRegex, planningEnd)) | ||
| 172 | || (c.contains(.deadline) && found(deadlineRegex, planningEnd)) | ||
| 173 | || (c.contains(.notDeadline) && !found(deadlineRegex, planningEnd)) | ||
| 174 | || (c.contains(.timestamp) && found(timestampRegex, end)) | ||
| 175 | || (c.contains(.notTimestamp) && !found(timestampRegex, end)) | ||
| 176 | if !holds, let re = c.lazy.compactMap(first).first { holds = found(regex(re), end) } | ||
| 177 | if !holds, let re = c.lazy.compactMap(firstNot).first { holds = !found(regex(re), end) } | ||
| 178 | // `nottodo` is looked for before `todo`. | ||
| 179 | if !holds, let condition = notTodo ?? todoArgument { | ||
| 180 | switch condition { | ||
| 181 | case .todo(let k): holds = found(todoRegex(k), end) | ||
| 182 | case .notTodo(let k): holds = !found(todoRegex(k), end) | ||
| 183 | default: break | ||
| 184 | } | ||
| 185 | } | ||
| 186 | return holds ? end : nil | ||
| 187 | } | ||
| 188 | } | ||
| 189 | |||
| 190 | /// `org-agenda-skip` for one scan of one file: candidates come in buffer order, and a skip | ||
| 191 | /// moves the scan past the entry or subtree, leaving out the candidates there too. | ||
| 192 | struct Skipper { | ||
| 193 | let skip: AgendaSkip? | ||
| 194 | let source: AgendaSource | ||
| 195 | let caseFold: Bool | ||
| 196 | var until = 0 | ||
| 197 | |||
| 198 | init(_ skip: AgendaSkip?, _ source: AgendaSource, caseFold: Bool = false) { | ||
| 199 | self.skip = skip | ||
| 200 | self.source = source | ||
| 201 | self.caseFold = caseFold | ||
| 202 | } | ||
| 203 | |||
| 204 | /// Whether the candidate at `position`, in the heading `index`, is skipped. | ||
| 205 | mutating func skips(_ position: Int, heading index: Int) -> Bool { | ||
| 206 | guard let skip else { return false } | ||
| 207 | if position < until { return true } | ||
| 208 | if let end = skip.skipEnd(source, heading: index, caseFold: caseFold) { | ||
| 209 | until = end | ||
| 210 | return true | ||
| 211 | } | ||
| 212 | return false | ||
| 213 | } | ||
| 214 | } | ||
Sources/Orgstar/AgendaView+Toolbar.swift +4 −8
| @@ -179,13 +179,8 @@ extension AgendaView { | |||
| 179 | } | 179 | } |
| 180 | 180 | ||
| 181 | var listTitle: String { | 181 | var listTitle: String { |
| 182 | switch agenda.mode { | 182 | if case .agenda = agenda.mode { return "" } |
| 183 | case .todo(let keywords): "TODO items: \(keywords ?? "all")" | 183 | return agenda.viewSettings[agenda.mode]?.header ?? agenda.mode.title |
| 184 | case .match(let match, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " matching \(match)" | ||
| 185 | case .search(let string, let todoOnly): (todoOnly ? "TODO entries" : "Entries") + " containing \(string)" | ||
| 186 | case .stuck: "Stuck projects" | ||
| 187 | case .agenda: "" | ||
| 188 | } | ||
| 189 | } | 184 | } |
| 190 | 185 | ||
| 191 | func loadViews() { | 186 | func loadViews() { |
| @@ -231,7 +226,8 @@ extension AgendaView { | |||
| 231 | 226 | ||
| 232 | /// The tags and categories on the view's lines, which filter words are read against. | 227 | /// The tags and categories on the view's lines, which filter words are read against. |
| 233 | var shown: (tags: Set<String>, categories: Set<String>) { | 228 | var shown: (tags: Set<String>, categories: Set<String>) { |
| 234 | let items = (isAgenda ? agenda.days.flatMap(\.items) : agenda.list).filter { $0.path != nil } | 229 | let shown = isBlocks ? agenda.blocks.flatMap { $0.days.flatMap(\.items) + $0.list } : isAgenda ? agenda.days.flatMap(\.items) : agenda.list |
| 230 | let items = shown.filter { $0.path != nil } | ||
| 235 | return (Set(items.flatMap(\.tags)), Set(items.map(\.category))) | 231 | return (Set(items.flatMap(\.tags)), Set(items.map(\.category))) |
| 236 | } | 232 | } |
| 237 | 233 | ||
Sources/Orgstar/AgendaView.swift +44 −10
| @@ -166,7 +166,7 @@ struct AgendaView: View { | |||
| 166 | agenda.options.logMode = logMode | 166 | agenda.options.logMode = logMode |
| 167 | agenda.options = OrgPreferences.agendaOptions(agenda.options) | 167 | agenda.options = OrgPreferences.agendaOptions(agenda.options) |
| 168 | agenda.calendarNames = OrgPreferences.calendarEventCalendars() | 168 | agenda.calendarNames = OrgPreferences.calendarEventCalendars() |
| 169 | if calendarEventsOn, isAgenda { | 169 | if calendarEventsOn, isAgenda || isBlocks { |
| 170 | agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil | 170 | agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil |
| 171 | } else { | 171 | } else { |
| 172 | agenda.calendarEvents = nil | 172 | agenda.calendarEvents = nil |
| @@ -204,6 +204,11 @@ struct AgendaView: View { | |||
| 204 | return false | 204 | return false |
| 205 | } | 205 | } |
| 206 | 206 | ||
| 207 | var isBlocks: Bool { | ||
| 208 | if case .blocks = agenda.mode { return true } | ||
| 209 | return false | ||
| 210 | } | ||
| 211 | |||
| 207 | var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch } | 212 | var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch } |
| 208 | var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch } | 213 | var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch } |
| 209 | 214 | ||
| @@ -222,16 +227,28 @@ struct AgendaView: View { | |||
| 222 | isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : [] | 227 | isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : [] |
| 223 | } | 228 | } |
| 224 | 229 | ||
| 225 | private var listRows: [AgendaRow] { | 230 | private var listRows: [AgendaRow] { rows(agenda.list) } |
| 226 | isAgenda ? [] : agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) } | 231 | |
| 232 | private func rows(_ list: [AgendaItem]) -> [AgendaRow] { | ||
| 233 | list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) } | ||
| 227 | } | 234 | } |
| 228 | 235 | ||
| 229 | /// The lines in order, as up and down move through them. | 236 | /// The lines in order, as up and down move through them. |
| 230 | func lines(_ groups: [AgendaDayGroup]) -> [Line] { | 237 | func lines(_ groups: [AgendaDayGroup]) -> [Line] { |
| 238 | if isBlocks { | ||
| 239 | return agenda.blocks.enumerated().flatMap { k, block in | ||
| 240 | block.isAgenda ? dayLines(agenda.groups(block, showAllDates: showAllDates, filter: filter), prefix: "b\(k):") | ||
| 241 | : rows(block.list).enumerated().map { Line(id: "b\(k):list:\($0.offset)", row: $0.element, day: agenda.today) } | ||
| 242 | } | ||
| 243 | } | ||
| 231 | guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } } | 244 | guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } } |
| 232 | return groups.flatMap { group in | 245 | return dayLines(groups, prefix: "") |
| 233 | (overdueShown ? group.overdue.enumerated().map { Line(id: "\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : []) | 246 | } |
| 234 | + group.rows.enumerated().map { Line(id: "\(group.day):\($0.offset)", row: $0.element, day: group.day) } | 247 | |
| 248 | private func dayLines(_ groups: [AgendaDayGroup], prefix: String) -> [Line] { | ||
| 249 | groups.flatMap { group in | ||
| 250 | (overdueShown ? group.overdue.enumerated().map { Line(id: "\(prefix)\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : []) | ||
| 251 | + group.rows.enumerated().map { Line(id: "\(prefix)\(group.day):\($0.offset)", row: $0.element, day: group.day) } | ||
| 235 | } | 252 | } |
| 236 | } | 253 | } |
| 237 | 254 | ||
| @@ -243,7 +260,24 @@ struct AgendaView: View { | |||
| 243 | return ScrollViewReader { proxy in | 260 | return ScrollViewReader { proxy in |
| 244 | ScrollView { | 261 | ScrollView { |
| 245 | LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) { | 262 | LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) { |
| 246 | if isAgenda { | 263 | if isBlocks { |
| 264 | ForEach(Array(agenda.blocks.enumerated()), id: \.offset) { k, block in | ||
| 265 | Section { | ||
| 266 | if block.isAgenda { | ||
| 267 | ForEach(agenda.groups(block, showAllDates: showAllDates, filter: filter)) { group in | ||
| 268 | dayHeader(group) | ||
| 269 | dayRows(group, prefix: "b\(k):") | ||
| 270 | } | ||
| 271 | } else { | ||
| 272 | ForEach(Array(rows(block.list).enumerated()), id: \.offset) { index, row in | ||
| 273 | rowView(Line(id: "b\(k):list:\(index)", row: row, day: agenda.today), showsGutter: false) | ||
| 274 | } | ||
| 275 | } | ||
| 276 | } header: { | ||
| 277 | header { Text(block.header).font(.system(size: 13, weight: .semibold)) } | ||
| 278 | } | ||
| 279 | } | ||
| 280 | } else if isAgenda { | ||
| 247 | ForEach(groups) { group in | 281 | ForEach(groups) { group in |
| 248 | Section { | 282 | Section { |
| 249 | dayRows(group) | 283 | dayRows(group) |
| @@ -360,12 +394,12 @@ struct AgendaView: View { | |||
| 360 | private var todayColor: Color { theme.color("agenda-today") ?? .accentColor } | 394 | private var todayColor: Color { theme.color("agenda-today") ?? .accentColor } |
| 361 | 395 | ||
| 362 | @ViewBuilder | 396 | @ViewBuilder |
| 363 | private func dayRows(_ group: AgendaDayGroup) -> some View { | 397 | private func dayRows(_ group: AgendaDayGroup, prefix: String = "") -> some View { |
| 364 | if group.isToday, !group.overdue.isEmpty { | 398 | if group.isToday, !group.overdue.isEmpty { |
| 365 | overdueHeader(count: group.overdue.count) | 399 | overdueHeader(count: group.overdue.count) |
| 366 | if overdueShown { | 400 | if overdueShown { |
| 367 | ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in | 401 | ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in |
| 368 | rowView(Line(id: "\(group.day):o\(index)", row: row, day: group.day)) | 402 | rowView(Line(id: "\(prefix)\(group.day):o\(index)", row: row, day: group.day)) |
| 369 | } | 403 | } |
| 370 | Divider().padding(.leading, 16).padding(.vertical, 4) | 404 | Divider().padding(.leading, 16).padding(.vertical, 4) |
| 371 | } | 405 | } |
| @@ -379,7 +413,7 @@ struct AgendaView: View { | |||
| 379 | } | 413 | } |
| 380 | ForEach(Array(group.lines(now: Self.hhmm(now)).enumerated()), id: \.offset) { _, line in | 414 | ForEach(Array(group.lines(now: Self.hhmm(now)).enumerated()), id: \.offset) { _, line in |
| 381 | switch line { | 415 | switch line { |
| 382 | case .row(let index): rowView(Line(id: "\(group.day):\(index)", row: group.rows[index], day: group.day)) | 416 | case .row(let index): rowView(Line(id: "\(prefix)\(group.day):\(index)", row: group.rows[index], day: group.day)) |
| 383 | case .grid(let time): gridLine(time) | 417 | case .grid(let time): gridLine(time) |
| 384 | case .now: nowLine | 418 | case .now: nowLine |
| 385 | } | 419 | } |
Sources/Orgstar/EmacsImportView.swift +1
| @@ -71,6 +71,7 @@ struct EmacsImportView: View { | |||
| 71 | ("Capture templates", result.items.filter { if case .capture = $0.change { true } else { false } }), | 71 | ("Capture templates", result.items.filter { if case .capture = $0.change { true } else { false } }), |
| 72 | ("Key bindings", result.items.filter { if case .binding = $0.change { true } else { false } }), | 72 | ("Key bindings", result.items.filter { if case .binding = $0.change { true } else { false } }), |
| 73 | ("Structure templates", result.items.filter { if case .structureTemplate = $0.change { true } else { false } }), | 73 | ("Structure templates", result.items.filter { if case .structureTemplate = $0.change { true } else { false } }), |
| 74 | ("Agenda views", result.items.filter { if case .view = $0.change { true } else { false } }), | ||
| 74 | ] | 75 | ] |
| 75 | return List { | 76 | return List { |
| 76 | ForEach(groups.filter { !$0.1.isEmpty }, id: \.0) { title, items in | 77 | ForEach(groups.filter { !$0.1.isEmpty }, id: \.0) { title, items in |
Sources/OrgstarMobile/AgendaScreen.swift +23
| @@ -89,6 +89,28 @@ struct AgendaScreen: View, Equatable { | |||
| 89 | header(group) | 89 | header(group) |
| 90 | } | 90 | } |
| 91 | } | 91 | } |
| 92 | } else if case .blocks = agenda.mode { | ||
| 93 | // A block's title over its days, or over its entries. | ||
| 94 | ForEach(Array(agenda.blocks.enumerated()), id: \.offset) { _, block in | ||
| 95 | if block.isAgenda { | ||
| 96 | Section { } header: { Text(block.header).font(.headline) } | ||
| 97 | ForEach(agenda.groups(block, showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter)) { group in | ||
| 98 | Section { | ||
| 99 | day(group) | ||
| 100 | } header: { | ||
| 101 | header(group) | ||
| 102 | } | ||
| 103 | } | ||
| 104 | } else { | ||
| 105 | Section { | ||
| 106 | let rows = block.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) } | ||
| 107 | if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) } | ||
| 108 | ForEach(rows) { item in Deferred { row(item, day: agenda.today) } } | ||
| 109 | } header: { | ||
| 110 | Text(block.header).font(.headline) | ||
| 111 | } | ||
| 112 | } | ||
| 113 | } | ||
| 92 | } else { | 114 | } else { |
| 93 | let rows = agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) } | 115 | let rows = agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) } |
| 94 | if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) } | 116 | if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) } |
| @@ -248,6 +270,7 @@ struct AgendaScreen: View, Equatable { | |||
| 248 | 270 | ||
| 249 | private var shownItems: [AgendaItem] { | 271 | private var shownItems: [AgendaItem] { |
| 250 | if case .agenda = agenda.mode { return agenda.days.flatMap(\.items).filter(\.isEntry) } | 272 | if case .agenda = agenda.mode { return agenda.days.flatMap(\.items).filter(\.isEntry) } |
| 273 | if case .blocks = agenda.mode { return agenda.blocks.flatMap { $0.days.flatMap(\.items).filter(\.isEntry) + $0.list } } | ||
| 251 | return agenda.list | 274 | return agenda.list |
| 252 | } | 275 | } |
| 253 | 276 | ||
Tests/OrgAppTests/AppTests.swift +43
| @@ -713,6 +713,49 @@ struct AgendaCommandTests { | |||
| 713 | #expect(agenda.list.isEmpty) | 713 | #expect(agenda.list.isEmpty) |
| 714 | } | 714 | } |
| 715 | 715 | ||
| 716 | @Test func blockViews() async throws { | ||
| 717 | let notes = try Folder() | ||
| 718 | let today = Days.date(Days.absolute(Date(), calendar: .current)) | ||
| 719 | let stamp = String(format: "%04d-%02d-%02d", today.year, today.month, today.day) | ||
| 720 | try notes.write("a.org", "#+TODO: TODO NEXT WAIT | DONE\n* TODO Call\nSCHEDULED: <\(stamp)>\n* NEXT Write\n* WAIT Hear back\n* TODO Later :someday:\n") | ||
| 721 | let file = try notes.write("views.toml", """ | ||
| 722 | [[view]] | ||
| 723 | name = "Daily" | ||
| 724 | span = 1 | ||
| 725 | sorting-strategy = "alpha-up" | ||
| 726 | [[view.block]] | ||
| 727 | type = "agenda" | ||
| 728 | header = "Today" | ||
| 729 | [[view.block]] | ||
| 730 | type = "todo" | ||
| 731 | skip-entry-if = "'scheduled 'regexp \\"someday\\"" | ||
| 732 | [[view.block]] | ||
| 733 | type = "match" | ||
| 734 | match = "TODO=\\"WAIT\\"" | ||
| 735 | [[view]] | ||
| 736 | name = "Broken skip" | ||
| 737 | type = "todo" | ||
| 738 | skip-entry-if = "'level 2" | ||
| 739 | """) | ||
| 740 | let loaded = AgendaViewLoader.load(userFile: file) | ||
| 741 | #expect(loaded.problems == ["views.toml line 14: skip-entry-if: level isn't supported"]) | ||
| 742 | guard case .blocks(let blocks) = loaded.views.last!.mode else { Issue.record("no blocks"); return } | ||
| 743 | #expect(blocks.map(\.mode) == [.agenda(span: 1, startOffset: nil), .todo(keywords: nil), .match("TODO=\"WAIT\"", todoOnly: false)]) | ||
| 744 | #expect(blocks.map(\.settings.header) == ["Today", nil, nil]) | ||
| 745 | #expect(blocks.allSatisfy { $0.settings.sortingStrategy == ["alpha-up"] }) | ||
| 746 | #expect(blocks[1].settings.skip == AgendaSkip(subtree: false, conditions: [.scheduled, .regexp("someday")])) | ||
| 747 | let model = try WorkspaceModel(directory: nil) | ||
| 748 | try await model.addRoot(notes.url) | ||
| 749 | let agenda = AgendaModel(workspace: model) | ||
| 750 | agenda.mode = loaded.views.last!.mode | ||
| 751 | await agenda.refresh(open: [:]) | ||
| 752 | #expect(agenda.blocks.map(\.header) == ["Today", "TODO items: all", "Entries matching TODO=\"WAIT\""]) | ||
| 753 | #expect(agenda.blocks[0].days.count == 1 && agenda.blocks[0].days[0].items.contains { $0.text == "TODO Call" }) | ||
| 754 | #expect(agenda.blocks[1].list.map(\.text) == ["WAIT Hear back", "NEXT Write"]) | ||
| 755 | #expect(agenda.blocks[2].list.map(\.text) == ["WAIT Hear back"]) | ||
| 756 | #expect(agenda.list.isEmpty && agenda.days.isEmpty) | ||
| 757 | } | ||
| 758 | |||
| 716 | @Test func todoListMode() async throws { | 759 | @Test func todoListMode() async throws { |
| 717 | let notes = try Folder() | 760 | let notes = try Folder() |
| 718 | try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n") | 761 | try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n") |
Tests/OrgAppTests/EmacsImportTests.swift +26 −3
| @@ -23,6 +23,15 @@ struct EmacsImportTests { | |||
| 23 | (setq org-agenda-sorting-strategy '((agenda time-up priority-down) (todo . (alpha-up))) org-agenda-sort-notime-is-late nil) | 23 | (setq org-agenda-sorting-strategy '((agenda time-up priority-down) (todo . (alpha-up))) org-agenda-sort-notime-is-late nil) |
| 24 | (setq org-agenda-time-grid '((daily today) (800 1300) "......" "----") org-agenda-use-time-grid nil) | 24 | (setq org-agenda-time-grid '((daily today) (800 1300) "......" "----") org-agenda-use-time-grid nil) |
| 25 | (setq org-stuck-projects '("+project/-DONE" ("NEXT" "TODO") ("errand") "\\<IGNORE\\>")) | 25 | (setq org-stuck-projects '("+project/-DONE" ("NEXT" "TODO") ("errand") "\\<IGNORE\\>")) |
| 26 | (setq org-agenda-custom-commands | ||
| 27 | '(("d" "Daily" ((agenda "" ((org-agenda-span 'day) (org-agenda-overriding-header "Today"))) | ||
| 28 | (todo "NEXT" ((org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled 'deadline)))) | ||
| 29 | (tags-todo "+work" ((org-agenda-sorting-strategy '(priority-down alpha-up))))) | ||
| 30 | ((org-agenda-prefix-format " %e "))) | ||
| 31 | ("w" "Work" tags "+work-boss" ((org-agenda-skip-function '(org-agenda-skip-subtree-if 'regexp "IGNORE")))) | ||
| 32 | ("x" "Prefix") | ||
| 33 | ("f" "Function" my-agenda-function))) | ||
| 34 | (add-to-list 'org-agenda-custom-commands '("s" "Stuck" stuck "")) | ||
| 26 | (setq fill-column (+ 70 2)) | 35 | (setq fill-column (+ 70 2)) |
| 27 | (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp")) | 36 | (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp")) |
| 28 | (with-eval-after-load 'org (add-to-list 'org-structure-template-alist '("q" . "QUOTE"))) | 37 | (with-eval-after-load 'org (add-to-list 'org-structure-template-alist '("q" . "QUOTE"))) |
| @@ -128,7 +137,7 @@ struct EmacsImportTests { | |||
| 128 | #expect(folders == ["~/notes/", "~/work"]) | 137 | #expect(folders == ["~/notes/", "~/work"]) |
| 129 | #expect(result.unreadable.map(\.name) == ["fill-column"]) | 138 | #expect(result.unreadable.map(\.name) == ["fill-column"]) |
| 130 | #expect(Set(result.unsupported.map(\.name)) == ["org-support-shift-select", "doom-theme", "org-roam-directory", | 139 | #expect(Set(result.unsupported.map(\.name)) == ["org-support-shift-select", "doom-theme", "org-roam-directory", |
| 131 | "capture \"j\"", "capture \"x\"", "SPC z t → tr/report", "C-c l"]) | 140 | "capture \"j\"", "capture \"x\"", "SPC z t → tr/report", "C-c l", "agenda command \"f\""]) |
| 132 | #expect(result.skipped == 1) | 141 | #expect(result.skipped == 1) |
| 133 | #expect(result.doomDefaultsLeftOut == 1) | 142 | #expect(result.doomDefaultsLeftOut == 1) |
| 134 | } | 143 | } |
| @@ -208,7 +217,21 @@ struct EmacsImportTests { | |||
| 208 | let keymap = folder.appendingPathComponent("keymap.toml") | 217 | let keymap = folder.appendingPathComponent("keymap.toml") |
| 209 | #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty) | 218 | #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty) |
| 210 | #expect(KeymapLoader.load(.doom, userFile: keymap).keymap.keyLabels(for: "app.agenda", modes: ["normal"]).contains("C-c a")) | 219 | #expect(KeymapLoader.load(.doom, userFile: keymap).keymap.keyLabels(for: "app.agenda", modes: ["normal"]).contains("C-c a")) |
| 211 | #expect(summary.hasPrefix("Imported 42 settings, 3 capture templates, 3 key bindings, 2 structure templates."), "\(summary)") | 220 | #expect(summary.hasPrefix("Imported 42 settings, 3 capture templates, 3 key bindings, 2 structure templates, 3 agenda views."), "\(summary)") |
| 221 | let views = AgendaViewLoader.load(userFile: folder.appendingPathComponent("views.toml")) | ||
| 222 | #expect(views.problems.isEmpty, "\(views.problems)") | ||
| 223 | #expect(views.views.dropFirst(3).map(\.name) == ["Daily", "Work", "Stuck"]) | ||
| 224 | if case .blocks(let blocks) = views.views[3].mode { | ||
| 225 | #expect(blocks.map(\.mode) == [.agenda(span: 1, startOffset: nil), .todo(keywords: "NEXT"), .match("+work", todoOnly: true)]) | ||
| 226 | #expect(blocks[0].settings.header == "Today" && blocks.allSatisfy { $0.settings.prefixFormat == " %e " }) | ||
| 227 | #expect(blocks[1].settings.skip == AgendaSkip(subtree: false, conditions: [.scheduled, .deadline])) | ||
| 228 | #expect(blocks[2].settings.sortingStrategy == ["priority-down", "alpha-up"]) | ||
| 229 | } else { | ||
| 230 | Issue.record("Daily isn't a block view") | ||
| 231 | } | ||
| 232 | #expect(views.views[4].mode == .match("+work-boss", todoOnly: false)) | ||
| 233 | #expect(views.views[4].settings.skip == AgendaSkip(subtree: true, conditions: [.regexp("IGNORE")])) | ||
| 234 | #expect(views.views[5].mode == .stuck(nil)) | ||
| 212 | #expect(UserConfig.structureTemplates(defaults) == [.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")]) | 235 | #expect(UserConfig.structureTemplates(defaults) == [.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")]) |
| 213 | #expect(OrgPreferences.options(defaults).structureTemplates?.first { $0.key == "q" }?.type == "QUOTE") | 236 | #expect(OrgPreferences.options(defaults).structureTemplates?.first { $0.key == "q" }?.type == "QUOTE") |
| 214 | #expect(defaults.string(forKey: "themeFont") == "JetBrains Mono") | 237 | #expect(defaults.string(forKey: "themeFont") == "JetBrains Mono") |
| @@ -218,6 +241,6 @@ struct EmacsImportTests { | |||
| 218 | let before = try String(contentsOf: keymap, encoding: .utf8) | 241 | let before = try String(contentsOf: keymap, encoding: .utf8) |
| 219 | let again = await EmacsImport.apply(result.items, defaults: defaults, workspace: nil, directory: folder) | 242 | let again = await EmacsImport.apply(result.items, defaults: defaults, workspace: nil, directory: folder) |
| 220 | #expect(try String(contentsOf: keymap, encoding: .utf8) == before) | 243 | #expect(try String(contentsOf: keymap, encoding: .utf8) == before) |
| 221 | #expect(!again.contains("key binding") && !again.contains("capture template"), "\(again)") | 244 | #expect(!again.contains("key binding") && !again.contains("capture template") && !again.contains("agenda view"), "\(again)") |
| 222 | } | 245 | } |
| 223 | } | 246 | } |
Tests/OrgCoreTests/AgendaSkipTests.swift added +81
| @@ -0,0 +1,81 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import OrgCore | ||
| 4 | |||
| 5 | /// `org-agenda-skip-entry-if` and `org-agenda-skip-subtree-if` against Emacs. | ||
| 6 | struct AgendaSkipTests { | ||
| 7 | static let today = Days.absolute(year: 2026, month: 10, day: 5) | ||
| 8 | static let file = """ | ||
| 9 | * TODO Parent :work: | ||
| 10 | SCHEDULED: <2026-10-05 Mon> | ||
| 11 | ** TODO Child one | ||
| 12 | DEADLINE: <2026-10-06 Tue> | ||
| 13 | ** WAIT Child two | ||
| 14 | <2026-10-05 Mon 10:00> | ||
| 15 | Mentions IGNORE here. | ||
| 16 | *** NEXT Grandchild | ||
| 17 | SCHEDULED: <2026-10-04 Sun> | ||
| 18 | * DONE Finished | ||
| 19 | CLOSED: [2026-10-05 Mon 09:00] | ||
| 20 | <2026-10-05 Mon 12:00> | ||
| 21 | * HOLD Plain :home: | ||
| 22 | Some text with a <2026-10-07 Wed> timestamp. | ||
| 23 | * IDEA Range | ||
| 24 | <2026-10-04 Sun>--<2026-10-06 Tue> | ||
| 25 | * TODO Waiting for IGNORE | ||
| 26 | DEADLINE: <2026-10-05 Mon> | ||
| 27 | ** TODO Under ignore | ||
| 28 | SCHEDULED: <2026-10-05 Mon 15:00> | ||
| 29 | * Sexp | ||
| 30 | <%%(diary-float t 1 1)> | ||
| 31 | |||
| 32 | """ | ||
| 33 | |||
| 34 | static let conditions = [ | ||
| 35 | "'scheduled", "'notscheduled", "'deadline", "'notdeadline", "'timestamp", "'nottimestamp", | ||
| 36 | "'regexp \"IGNORE\"", "'notregexp \"IGNORE\"", "'todo '(\"WAIT\" \"NEXT\")", "'nottodo '(\"TODO\")", | ||
| 37 | "'todo 'done", "'nottodo 'todo", "'todo 'any", "'todo '(\"*\")", "'scheduled 'deadline", | ||
| 38 | ] | ||
| 39 | |||
| 40 | @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) | ||
| 41 | func skipsLikeOrg() throws { | ||
| 42 | var utc = Calendar(identifier: .gregorian) | ||
| 43 | utc.timeZone = TimeZone(identifier: "UTC")! | ||
| 44 | let now = Date(timeIntervalSince1970: Double((Self.today - 719163) * 86400 + 9 * 3600 + 30 * 60)) | ||
| 45 | let defaults = OrgSettings.default.withTodoKeywords(AgendaOracle.keywords)! | ||
| 46 | let files = [("s.org", Self.file)] | ||
| 47 | for subtree in [false, true] { | ||
| 48 | for condition in Self.conditions { | ||
| 49 | let skip = try AgendaSkip.parse(condition, subtree: subtree).get() | ||
| 50 | let fn = "'(org-agenda-skip-\(subtree ? "subtree" : "entry")-if \(condition))" | ||
| 51 | var options = AgendaOptions() | ||
| 52 | options.skip = skip | ||
| 53 | for (form, ours) in [ | ||
| 54 | ("(org-todo-list nil)", { (s: [AgendaSource]) in Agenda.todoList(s, options: options, today: Self.today) }), | ||
| 55 | ("(org-tags-view nil \"LEVEL>0\")", { Agenda.tagsMatch($0, match: "LEVEL>0", now: now, calendar: utc, options: options) }), | ||
| 56 | ("(org-search-view nil \"e\")", { Agenda.textSearch($0, string: "e", options: options) }), | ||
| 57 | ] { | ||
| 58 | try AgendaOracle.compareList(files: files, form: "(let ((org-agenda-skip-function \(fn))) \(form))", today: Self.today, ours) | ||
| 59 | } | ||
| 60 | let form = "(let ((org-agenda-skip-function \(fn)) (org-agenda-start-with-log-mode t)) (org-agenda-list nil \"2026-10-04\" 3))" | ||
| 61 | let emacs = try AgendaOracle.run(files: files, form: form, today: Self.today, hour: 9, minute: 30) | ||
| 62 | var dayOptions = AgendaOptions.terminal | ||
| 63 | dayOptions.skip = skip | ||
| 64 | dayOptions.logMode = true | ||
| 65 | let days = Agenda.list([AgendaSource(path: "s.org", text: Self.file, defaults: defaults)], start: Self.today - 1, days: 3, | ||
| 66 | today: Self.today, now: (9, 30), options: dayOptions) | ||
| 67 | #expect(days.count == emacs.count) | ||
| 68 | for (o, e) in zip(days, emacs) { | ||
| 69 | #expect(AgendaOracle.describe(o.items, today: Self.today) == AgendaOracle.describe(e.items), "\(fn) \(e.header)") | ||
| 70 | } | ||
| 71 | } | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | @Test func parsesAndWrites() throws { | ||
| 76 | let skip = try AgendaSkip.parse("'scheduled 'regexp \"\\\\<A\\\"B\" 'nottodo '(\"DONE\" \"KILL\") 'todo done", subtree: true).get() | ||
| 77 | #expect(skip.conditions == [.scheduled, .regexp("\\<A\"B"), .notTodo(.list(["DONE", "KILL"])), .todo(.done)]) | ||
| 78 | #expect(try AgendaSkip.parse(skip.lisp, subtree: true).get() == skip) | ||
| 79 | #expect(throws: AgendaSkip.Failure.self) { try AgendaSkip.parse("'level 2", subtree: false).get() } | ||
| 80 | } | ||
| 81 | } | ||
docs/manual/guide/07-agenda.org +41 −1
| @@ -450,10 +450,49 @@ match = "+invoice -paid" | |||
| 450 | | =keywords=, =tags=, =regexp= | =stuck= | The =todo=, =tags= (separated by spaces) and =regexp= of =[org-stuck-projects]=; with =match= they replace the setting's values for this view, and the ones left out keep them | | 450 | | =keywords=, =tags=, =regexp= | =stuck= | The =todo=, =tags= (separated by spaces) and =regexp= of =[org-stuck-projects]=; with =match= they replace the setting's values for this view, and the ones left out keep them | |
| 451 | | =sorting-strategy= | all | The view's =org-agenda-sorting-strategy=, keys separated by spaces, in place of the one in =config.toml= for its kind | | 451 | | =sorting-strategy= | all | The view's =org-agenda-sorting-strategy=, keys separated by spaces, in place of the one in =config.toml= for its kind | |
| 452 | | =prefix-format= | all | The view's =org-agenda-prefix-format=, in place of the one in =config.toml= for its kind | | 452 | | =prefix-format= | all | The view's =org-agenda-prefix-format=, in place of the one in =config.toml= for its kind | |
| 453 | | =header= | all | The title over a list or block, as =org-agenda-overriding-header= | | ||
| 454 | | =skip-entry-if=, =skip-subtree-if= | all | Entries to leave out, as =org-agenda-skip-function= set to =org-agenda-skip-entry-if= or =org-agenda-skip-subtree-if=; see below | | ||
| 453 | 455 | ||
| 454 | Note that =start= is a plain integer here, while =org-agenda-start-day= in =config.toml= is a string such as ="-3d"=. | 456 | Note that =start= is a plain integer here, while =org-agenda-start-day= in =config.toml= is a string such as ="-3d"=. |
| 455 | 457 | ||
| 456 | Not supported: block agendas (several views in one) and =org-agenda-skip-function=. The views load when the window opens and again on =g= or =r=. A problem in the file, such as a missing =name= or an unknown =type=, shows in the status line at the bottom of the window, and the remaining views still load. | 458 | ** Skipping entries |
| 459 | |||
| 460 | =skip-entry-if= takes the arguments of =org-agenda-skip-entry-if= as Lisp writes them, the quotes optional: | ||
| 461 | |||
| 462 | #+BEGIN_SRC toml | ||
| 463 | [[view]] | ||
| 464 | name = "Unplanned" | ||
| 465 | type = "todo" | ||
| 466 | skip-entry-if = "'scheduled 'deadline" | ||
| 467 | #+END_SRC | ||
| 468 | |||
| 469 | An entry is left out when any condition holds: =scheduled=, =notscheduled=, =deadline= and =notdeadline= look at the planning line; =timestamp= and =nottimestamp= at active timestamps in the entry; =regexp "RE"= and =notregexp "RE"= at its text, with an Emacs regular expression; =todo= and =nottodo= at its keyword, given as a list (='("WAIT" "HOLD")=, ="*"= for any) or a class (=todo=, =done= or =any=). =skip-subtree-if= takes the same conditions, looks at the whole subtree, and leaves out the subtree when one holds. As in Org, the day and TODO views match the regexps case-sensitively, and tag matches and search ignore case. Org's =todo-unblocked= and =nottodo-unblocked=, and skip functions of your own, are not supported. | ||
| 470 | |||
| 471 | ** Block agendas | ||
| 472 | |||
| 473 | A view with =[[view.block]]= tables after it shows several views one after the other, as an =org-agenda-custom-commands= entry with a list of blocks does. Each block takes the keys of a view except =name=; the view's =sorting-strategy=, =prefix-format= and skip settings, and for =agenda= blocks its =span= and =start=, apply to blocks that don't set their own: | ||
| 474 | |||
| 475 | #+BEGIN_SRC toml | ||
| 476 | [[view]] | ||
| 477 | name = "Daily" | ||
| 478 | span = 1 | ||
| 479 | |||
| 480 | [[view.block]] | ||
| 481 | type = "agenda" | ||
| 482 | header = "Today" | ||
| 483 | |||
| 484 | [[view.block]] | ||
| 485 | type = "todo" | ||
| 486 | keywords = "NEXT" | ||
| 487 | skip-entry-if = "'scheduled 'deadline" | ||
| 488 | |||
| 489 | [[view.block]] | ||
| 490 | type = "stuck" | ||
| 491 | #+END_SRC | ||
| 492 | |||
| 493 | Each block has its title over it: its =header=, or one for its kind such as =Day agenda= or =TODO items: NEXT=. Agenda blocks start from their own =start= (or the setting), so the arrows that move through days don't apply to them. | ||
| 494 | |||
| 495 | The views load when the window opens and again on =g= or =r=. A problem in the file, such as a missing =name= or an unknown =type=, shows in the status line at the bottom of the window, and the remaining views still load. | ||
| 457 | 496 | ||
| 458 | * Filters | 497 | * Filters |
| 459 | 498 | ||
| @@ -606,6 +645,7 @@ The Agenda tab shows the same views from the same files, using the settings in t | |||
| 606 | - The Views menu, at the top left, lists the built-in views, your saved views, Tags and Properties…, which asks for a match string, and Search…, which asks for a search string. There is no TODO-only match or search from the menu; use =/!= in the match, =!= at the start of the search string, or a =todo-match= or =todo-search= view. | 645 | - The Views menu, at the top left, lists the built-in views, your saved views, Tags and Properties…, which asks for a match string, and Search…, which asks for a search string. There is no TODO-only match or search from the menu; use =/!= in the match, =!= at the start of the search string, or a =todo-match= or =todo-search= view. |
| 607 | - A bar floats at the bottom of the screen with Earlier, Filter, Today, Go to Date, the span and Later. The span menu switches between Day, Week, Month and the configured span (=10 Days= by default); Day, Week and Month are around today when today is shown, else around the first day shown. Weeks start on =org-agenda-start-on-weekday=, as on the Mac. In the TODO list and match views the bar has Filter and Agenda, which returns to the day view. Messages show above the bar; tap one to dismiss it. | 646 | - A bar floats at the bottom of the screen with Earlier, Filter, Today, Go to Date, the span and Later. The span menu switches between Day, Week, Month and the configured span (=10 Days= by default); Day, Week and Month are around today when today is shown, else around the first day shown. Weeks start on =org-agenda-start-on-weekday=, as on the Mac. In the TODO list and match views the bar has Filter and Agenda, which returns to the day view. Messages show above the bar; tap one to dismiss it. |
| 608 | - The title names the days shown: =Thu 8 Oct=, =Week of 5 Oct=, =October 2026=, or =5 Oct – 14 Oct=. | 647 | - The title names the days shown: =Thu 8 Oct=, =Week of 5 Oct=, =October 2026=, or =5 Oct – 14 Oct=. |
| 648 | - A block view lists its blocks one after the other, each under its title; an agenda block's days follow its title. | ||
| 609 | - Day headers read =Today · Thu 8 Oct=, =Tomorrow · Fri 9 Oct= or =Mon 12 Oct=, with a + that captures onto that day. Days before today are grey. | 649 | - Day headers read =Today · Thu 8 Oct=, =Tomorrow · Fri 9 Oct= or =Mon 12 Oct=, with a + that captures onto that day. Days before today are grey. |
| 610 | - Pull down to refresh. | 650 | - Pull down to refresh. |
| 611 | - The Filter button opens a sheet: type a filter as for =/=, or tap a tag or category to cycle between Keep, Leave out and no filter. | 651 | - The Filter button opens a sheet: type a filter as for =/=, or tap a tag or category to cycle between Keep, Leave out and no filter. |
docs/manual/guide/13-configuration.org +4 −2
| @@ -455,14 +455,14 @@ Keywords from setup files count for TODO keywords, priorities, =#+STARTUP=, =#+T | |||
| 455 | 455 | ||
| 456 | * Import from Emacs | 456 | * Import from Emacs |
| 457 | 457 | ||
| 458 | Import from Emacs reads your Emacs or Doom Emacs configuration and offers to carry its org settings, folders, capture templates and key bindings over. Nothing changes until you choose Import. | 458 | Import from Emacs reads your Emacs or Doom Emacs configuration and offers to carry its org settings, folders, capture templates, key bindings and agenda views over. Nothing changes until you choose Import. |
| 459 | 459 | ||
| 460 | ** Running it | 460 | ** Running it |
| 461 | 461 | ||
| 462 | 1. Open Settings ▸ General and click Import from Emacs…, or run Import from Emacs… from the command palette (=⇧⌘P=). | 462 | 1. Open Settings ▸ General and click Import from Emacs…, or run Import from Emacs… from the command palette (=⇧⌘P=). |
| 463 | 2. orgstar looks for a configuration in these places, in order, and reads the first it finds: =$DOOMDIR=, =~/.config/doom=, =~/.doom.d=, =~/.config/emacs=, =~/.emacs.d=, =~/.emacs=. A folder counts when it holds =init.el=, =config.el= or =custom.el=. Doom's own installation folder (one with =lisp/doom.el=) is skipped. | 463 | 2. orgstar looks for a configuration in these places, in order, and reads the first it finds: =$DOOMDIR=, =~/.config/doom=, =~/.doom.d=, =~/.config/emacs=, =~/.emacs.d=, =~/.emacs=. A folder counts when it holds =init.el=, =config.el= or =custom.el=. Doom's own installation folder (one with =lisp/doom.el=) is skipped. |
| 464 | 3. To read another configuration, click Choose… and pick a file or a folder. For a folder, orgstar reads =init.el=, =config.el= and =custom.el= in it. | 464 | 3. To read another configuration, click Choose… and pick a file or a folder. For a folder, orgstar reads =init.el=, =config.el= and =custom.el= in it. |
| 465 | 4. The sheet lists what it found under Settings, Folders, Capture templates and Key bindings, each with the line it came from (=config.el:27=, or =Doom default=). Everything is selected; clear what you don't want. | 465 | 4. The sheet lists what it found under Settings, Folders, Capture templates, Key bindings, Structure templates and Agenda views, each with the line it came from (=config.el:27=, or =Doom default=). Everything is selected; clear what you don't want. |
| 466 | 5. Click Import. The sheet then summarizes what was imported and any problems. | 466 | 5. Click Import. The sheet then summarizes what was imported and any problems. |
| 467 | 467 | ||
| 468 | What Import does with each kind of item: | 468 | What Import does with each kind of item: |
| @@ -471,6 +471,7 @@ What Import does with each kind of item: | |||
| 471 | - Folders are added to the sidebar if they exist and aren't there already. | 471 | - Folders are added to the sidebar if they exist and aren't there already. |
| 472 | - Capture templates are appended to =capture.toml=, except those whose key is already in the file. | 472 | - Capture templates are appended to =capture.toml=, except those whose key is already in the file. |
| 473 | - Key bindings are appended to =keymap.toml=, except those already in the file with the same keys, command and state. Running the import again adds no duplicates. | 473 | - Key bindings are appended to =keymap.toml=, except those already in the file with the same keys, command and state. Running the import again adds no duplicates. |
| 474 | - Agenda views are appended to =views.toml=, except those whose name is already in the file. | ||
| 474 | 475 | ||
| 475 | The Not imported section lists what orgstar read but can't use, with the reason: settings it has no equivalent for, values it can't work out without running Emacs, bindings to code rather than a command, and files it couldn't read. The footer counts variables that aren't about org, which are left alone. | 476 | The Not imported section lists what orgstar read but can't use, with the reason: settings it has no equivalent for, values it can't work out without running Emacs, bindings to code rather than a command, and files it couldn't read. The footer counts variables that aren't about org, which are left alone. |
| 476 | 477 | ||
| @@ -516,6 +517,7 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, = | |||
| 516 | | =org-agenda-prefix-format= | =[org-agenda-prefix-format]=: a string sets all three views; an alist sets =agenda=, =todo= and =tags= | | 517 | | =org-agenda-prefix-format= | =[org-agenda-prefix-format]=: a string sets all three views; an alist sets =agenda=, =todo= and =tags= | |
| 517 | | =org-agenda-sorting-strategy= | =[org-agenda-sorting-strategy]=: a list sets all four views; an alist sets =agenda=, =todo=, =tags= and =search=. A list with =user-defined-up= or =user-defined-down= isn't imported | | 518 | | =org-agenda-sorting-strategy= | =[org-agenda-sorting-strategy]=: a list sets all four views; an alist sets =agenda=, =todo=, =tags= and =search=. A list with =user-defined-up= or =user-defined-down= isn't imported | |
| 518 | | =org-agenda-sort-notime-is-late=, =org-agenda-sort-noeffort-is-high=, =org-agenda-use-time-grid=, =org-agenda-show-current-time-in-grid= | The same key, as booleans | | 519 | | =org-agenda-sort-notime-is-late=, =org-agenda-sort-noeffort-is-high=, =org-agenda-use-time-grid=, =org-agenda-show-current-time-in-grid= | The same key, as booleans | |
| 520 | | =org-agenda-custom-commands= | A =views.toml= view per command, named by its description, and per block a =[[view.block]]=. Types =agenda=, =alltodo=, =todo=, =tags=, =tags-todo=, =search= and =stuck=; settings =org-agenda-span=, =org-agenda-start-day=, =org-agenda-overriding-header=, =org-agenda-sorting-strategy=, =org-agenda-prefix-format= (a string) and =org-agenda-skip-function= as =org-agenda-skip-entry-if= or =org-agenda-skip-subtree-if=. Entries from =(add-to-list 'org-agenda-custom-commands …)= too. Other types, other settings and file lists aren't imported | | ||
| 519 | | =org-stuck-projects= | =[org-stuck-projects]=: =match=, =todo=, =tags= and =regexp= from the four elements | | 521 | | =org-stuck-projects= | =[org-stuck-projects]=: =match=, =todo=, =tags= and =regexp= from the four elements | |
| 520 | | =org-agenda-time-grid= | =[org-agenda-time-grid]=: =when= from the first element, =times= from the second; the strings are left out | | 522 | | =org-agenda-time-grid= | =[org-agenda-time-grid]=: =when= from the first element, =times= from the second; the strings are left out | |
| 521 | | =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= | | 523 | | =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= | |