Agenda sorting strategy and per-view prefix format !263

merged merged by cmc on 2026-10-11 10:16 UTC · krz/orgstar:issue-13 into main

19 files changed, +531 −47

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +3 −1
@@ -35,6 +35,8 @@ public final class AgendaModel {
3535 /// Files below the top level of each folder are agenda files too.
3636 public var includeSubfolders = false
3737 public var options = AgendaOptions()
38 /// The settings of the views in `views.toml`, applied while `mode` is theirs.
39 public var viewSettings: [AgendaMode: AgendaViewSettings] = [:]
3840 public private(set) var isComputing = false
3941 /// Calendar events over the days shown, from `calendarEvents` (nil reads none) and the
4042 /// calendars in `calendarNames` (all when empty).
@@ -74,8 +76,8 @@ public final class AgendaModel {
7476 let today = Days.absolute(now, calendar: calendar)
7577 let clock = calendar.dateComponents([.hour, .minute], from: now)
7678 let (first, span) = shown(today: today)
77 let options = self.options
7879 let mode = self.mode
80 let options = viewSettings[mode]?.apply(to: self.options, view: mode.viewKey) ?? self.options
7981 let provider = calendarEvents
8082 let names = calendarNames
8183 let all = await sources(open: open)
Sources/OrgApp/AgendaViews.swift +51 −3
@@ -11,17 +11,49 @@ public enum AgendaMode: Hashable, Sendable {
1111 case match(String, todoOnly: Bool)
1212 /// `org-search-view`.
1313 case search(String, todoOnly: Bool)
14
15 /// The key `org-agenda-prefix-format` and `org-agenda-sorting-strategy` use for this kind
16 /// of view.
17 public var viewKey: String {
18 switch self {
19 case .agenda: "agenda"
20 case .todo: "todo"
21 case .match: "tags"
22 case .search: "search"
23 }
24 }
25}
26
27/// A view's own `org-agenda-prefix-format` and `org-agenda-sorting-strategy`, as an
28/// `org-agenda-custom-commands` entry's settings give them.
29public struct AgendaViewSettings: Hashable, Sendable {
30 public var prefixFormat: String?
31 public var sortingStrategy: [String]?
32
33 public init(prefixFormat: String? = nil, sortingStrategy: [String]? = nil) {
34 self.prefixFormat = prefixFormat
35 self.sortingStrategy = sortingStrategy
36 }
37
38 public func apply(to options: AgendaOptions, view: String) -> AgendaOptions {
39 var options = options
40 if let prefixFormat { options.prefixFormat[view] = prefixFormat }
41 if let sortingStrategy { options.sortingStrategy[view] = sortingStrategy }
42 return options
43 }
1444}
1545
1646/// A named view: the built-in ones and those in `views.toml`.
1747public struct AgendaViewDefinition: Hashable, Sendable, Identifiable {
1848 public let name: String
1949 public let mode: AgendaMode
50 public var settings: AgendaViewSettings
2051 public var id: String { name }
2152
22 public init(name: String, mode: AgendaMode) {
53 public init(name: String, mode: AgendaMode, settings: AgendaViewSettings = AgendaViewSettings()) {
2354 self.name = name
2455 self.mode = mode
56 self.settings = settings
2557 }
2658}
2759
@@ -35,7 +67,8 @@ public struct AgendaViewDefinition: Hashable, Sendable, Identifiable {
3567/// ```
3668///
3769/// `agenda` views take `span` and `start` (days from today), `todo` views `keywords`
38/// (`WAIT|HOLD`); a `search` view's `match` is its search string.
70/// (`WAIT|HOLD`); a `search` view's `match` is its search string. Any view can set
71/// `prefix-format` and `sorting-strategy` (keys separated by spaces) for itself.
3972@MainActor
4073public enum AgendaViewLoader {
4174 public static var userFile: URL { UserConfig.file("views.toml") }
@@ -45,6 +78,13 @@ public enum AgendaViewLoader {
4578 AgendaViewDefinition(name: "TODO List", mode: .todo(keywords: nil)),
4679 ]
4780
81 /// The views' settings by mode; the first view with a mode wins.
82 public static func settings(_ views: [AgendaViewDefinition]) -> [AgendaMode: AgendaViewSettings] {
83 var settings: [AgendaMode: AgendaViewSettings] = [:]
84 for view in views where settings[view.mode] == nil && view.settings != AgendaViewSettings() { settings[view.mode] = view.settings }
85 return settings
86 }
87
4888 /// The built-in views followed by the user's, and the problems found in the file.
4989 public static func load(userFile: URL = userFile) -> (views: [AgendaViewDefinition], problems: [String]) {
5090 let interval = Perf.begin("views.load")
@@ -90,7 +130,15 @@ public enum AgendaViewLoader {
90130 problems.append("views.toml line \(table.line): unknown type \(other)")
91131 continue
92132 }
93 views.append(AgendaViewDefinition(name: name, mode: mode))
133 var settings = AgendaViewSettings(prefixFormat: table.values["prefix-format"]?.string)
134 if let strategy = table.values["sorting-strategy"]?.string {
135 let keys = strategy.split(whereSeparator: \.isWhitespace).map(String.init)
136 if let bad = keys.first(where: { !AgendaSort.keys.contains($0) }) {
137 problems.append("views.toml line \(table.line): unknown sorting key \(bad)")
138 }
139 settings.sortingStrategy = keys.filter(AgendaSort.keys.contains)
140 }
141 views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings))
94142 }
95143 return (views, problems)
96144 }
Sources/OrgApp/EmacsImport.swift +21 −1
@@ -487,7 +487,8 @@ public struct EmacsImport: Sendable {
487487 "org-cycle-hide-drawer-startup", "org-cycle-hide-block-startup", "org-use-speed-commands", "org-startup-with-inline-images",
488488 "org-startup-indented", "org-hide-leading-stars", "org-startup-align-all-tables", "org-startup-truncated",
489489 "org-enforce-todo-dependencies", "org-enforce-todo-checkbox-dependencies",
490 "org-agenda-todo-ignore-with-date", "org-agenda-tags-todo-honor-ignore-options", "org-clock-out-remove-zero-time-clocks":
490 "org-agenda-todo-ignore-with-date", "org-agenda-tags-todo-honor-ignore-options", "org-clock-out-remove-zero-time-clocks",
491 "org-agenda-sort-notime-is-late", "org-agenda-sort-noeffort-is-high":
491492 add(name, .bool(truthy))
492493 case "org-archive-location":
493494 guard let location = value.string, location.contains("::") else { return note("not a file::heading location") }
@@ -523,6 +524,25 @@ public struct EmacsImport: Sendable {
523524 } else {
524525 add(name, .bool(truthy))
525526 }
527 case "org-agenda-sorting-strategy":
528 // `((agenda habit-down time-up) (todo urgency-down))`, or one list for every view.
529 func keys(_ items: [Sexp]) -> String? {
530 let names = items.compactMap(\.symbol)
531 guard names.count == items.count else { return nil }
532 if let bad = names.first(where: { !AgendaSort.keys.contains($0) }) { note("\(bad) isn't supported"); return nil }
533 return names.joined(separator: " ")
534 }
535 let entries = value.elements ?? []
536 if entries.allSatisfy({ $0.symbol != nil }) {
537 if let s = keys(entries) { for view in ["agenda", "todo", "tags", "search"] { add("org-agenda-sorting-strategy.\(view)", .string(s)) } }
538 } else {
539 for entry in entries {
540 var items = entry.elements
541 if case .dotted(let head, let tail) = entry { items = head + (tail.elements ?? [tail]) }
542 guard let items, let view = items.first?.symbol, ["agenda", "todo", "tags", "search"].contains(view) else { continue }
543 if let s = keys(Array(items.dropFirst())) { add("org-agenda-sorting-strategy.\(view)", .string(s)) }
544 }
545 }
526546 case "org-agenda-prefix-format":
527547 if let s = value.string {
528548 for view in ["agenda", "todo", "tags"] { add("org-agenda-prefix-format.\(view)", .string(s)) }
Sources/OrgApp/OrgPreferences.swift +9
@@ -101,8 +101,17 @@ public enum OrgPreferences {
101101 options.todoIgnoreDeadlines = AgendaOptions.TodoIgnore(string("agendaTodoIgnoreDeadlines", defaults), deadlines: true) ?? .off
102102 options.todoIgnoreTimestamp = AgendaOptions.TodoIgnore(string("agendaTodoIgnoreTimestamp", defaults)) ?? .off
103103 options.tagsTodoHonorIgnoreOptions = bool("agendaTagsTodoHonorIgnore", defaults)
104 for (view, key) in [("agenda", "agendaSortAgenda"), ("todo", "agendaSortTodo"), ("tags", "agendaSortTags"), ("search", "agendaSortSearch")] {
105 options.sortingStrategy[view] = sortingStrategy(string(key, defaults))
106 }
107 options.sortNotimeIsLate = bool("agendaSortNotimeIsLate", defaults)
108 options.sortNoeffortIsHigh = bool("agendaSortNoeffortIsHigh", defaults)
104109 return options
105110 }
111 /// An `org-agenda-sorting-strategy` entry, keys separated by spaces; unknown keys are left out.
112 public static func sortingStrategy(_ text: String) -> [String] {
113 text.split(whereSeparator: \.isWhitespace).map(String.init).filter(AgendaSort.keys.contains)
114 }
106115 /// `calendar-events`: Calendar's events show in the agenda.
107116 public static func calendarEvents(_ defaults: UserDefaults = .standard) -> Bool { bool("calendarEvents", defaults) }
108117 /// `calendar-event-calendars`: the calendars chosen, by title or identifier; empty for all.
Sources/OrgApp/UserConfig.swift +12
@@ -203,12 +203,24 @@ public enum UserConfig {
203203 comment: "t: marking the clocked entry done clocks out; nil: it doesn't; or keywords that clock out, separated by spaces", legacy: ""),
204204 Setting(section: "", key: "org-clock-history-length", defaultsKey: "clockHistoryLength", kind: .integer, fallback: .integer(5),
205205 comment: "recently clocked entries to remember", legacy: ""),
206 Setting(section: "", key: "org-agenda-sort-notime-is-late", defaultsKey: "agendaSortNotimeIsLate", kind: .bool, fallback: .bool(true),
207 comment: "lines without a time sort after timed ones for time-up, and without a date after dated ones", legacy: ""),
208 Setting(section: "", key: "org-agenda-sort-noeffort-is-high", defaultsKey: "agendaSortNoeffortIsHigh", kind: .bool, fallback: .bool(true),
209 comment: "entries without an effort sort as the longest for effort-up", legacy: ""),
206210 Setting(section: "org-agenda-prefix-format", key: "agenda", defaultsKey: "agendaPrefixAgenda", kind: .string, fallback: .string(PrefixFormat.defaults["agenda"]!),
207211 comment: "%c category, %t time, %s scheduled/deadline, %e effort, %l level, %b outline path; %-12 pads", legacy: ""),
208212 Setting(section: "org-agenda-prefix-format", key: "todo", defaultsKey: "agendaPrefixTodo", kind: .string, fallback: .string(PrefixFormat.defaults["todo"]!),
209213 comment: "the TODO list", legacy: ""),
210214 Setting(section: "org-agenda-prefix-format", key: "tags", defaultsKey: "agendaPrefixTags", kind: .string, fallback: .string(PrefixFormat.defaults["tags"]!),
211215 comment: "tag and property matches", legacy: ""),
216 Setting(section: "org-agenda-sorting-strategy", key: "agenda", defaultsKey: "agendaSortAgenda", kind: .string, fallback: .string(AgendaSort.defaults["agenda"]!.joined(separator: " ")),
217 comment: "how lines of a day are ordered: time-up, priority-down, category-keep, alpha-up, effort-up, tag-up, todo-state-up, …", legacy: ""),
218 Setting(section: "org-agenda-sorting-strategy", key: "todo", defaultsKey: "agendaSortTodo", kind: .string, fallback: .string(AgendaSort.defaults["todo"]!.joined(separator: " ")),
219 comment: "the TODO list", legacy: ""),
220 Setting(section: "org-agenda-sorting-strategy", key: "tags", defaultsKey: "agendaSortTags", kind: .string, fallback: .string(AgendaSort.defaults["tags"]!.joined(separator: " ")),
221 comment: "tag and property matches", legacy: ""),
222 Setting(section: "org-agenda-sorting-strategy", key: "search", defaultsKey: "agendaSortSearch", kind: .string, fallback: .string(AgendaSort.defaults["search"]!.joined(separator: " ")),
223 comment: "text search", legacy: ""),
212224 Setting(section: "theme", key: "font", defaultsKey: "themeFont", kind: .string, fallback: .string(""),
213225 comment: "a monospaced font family; \"\" for the system's", legacy: ""),
214226 Setting(section: "theme", key: "font-size", defaultsKey: "themeFontSize", kind: .integer, fallback: .integer(13),
Sources/OrgCore/Agenda/Agenda.swift +60 −20
@@ -47,6 +47,9 @@ public struct AgendaItem: Sendable, Equatable {
4747 public let line: String
4848 /// What `org-agenda-prefix-format` puts before the heading text.
4949 public var prefix = ""
50 /// The prefix without the category, time, leader and icon, which rows show in their own
51 /// places, trimmed; nil when nothing is left. `%e` and `%b` are what remain in practice.
52 public var prefixDetail: String?
5053 /// The entry's `Effort` property.
5154 public var effort: String?
5255 /// Deadlines and scheduled items: the day (as `Days` numbers it) of the timestamp the item
@@ -56,6 +59,16 @@ public struct AgendaItem: Sendable, Equatable {
5659 public var isBlocked = false
5760 /// The first done keyword of the sequence the entry's keyword belongs to.
5861 public var doneKeyword: String?
62 /// What `org-agenda-sorting-strategy` compares: Org's `priority`, `ts-date` and `type`
63 /// properties, the effort in minutes, the keyword's place from the end of the file's
64 /// keywords (negated), and the heading text for `alpha-up`.
65 public var priority = 0
66 public var tsDate: Int?
67 public var tsType = ""
68 public var effortMinutes: Double?
69 var todoRank = 0
70 var todoDone = false
71 var alpha: String?
5972 var blockedByCheckboxes = false
6073 var blockedByHierarchy = false
6174}
@@ -77,6 +90,11 @@ public struct AgendaOptions: Sendable, Equatable {
7790 public var currentTimeLine = "← now ───────────────────────────────────────────────"
7891 /// `org-agenda-prefix-format`, by view: `agenda`, `todo`, `tags`, `search`.
7992 public var prefixFormat = PrefixFormat.defaults
93 /// `org-agenda-sorting-strategy`, by view, and `org-agenda-sort-notime-is-late` and
94 /// `org-agenda-sort-noeffort-is-high`.
95 public var sortingStrategy = AgendaSort.defaults
96 public var sortNotimeIsLate = true
97 public var sortNoeffortIsHigh = true
8098 /// Log mode (`l`): closed entries and clocked time on each day.
8199 public var logMode = false
82100 /// `org-agenda-log-mode-items`.
@@ -140,6 +158,8 @@ public struct AgendaOptions: Sendable, Equatable {
140158
141159 public init() {}
142160
161 func strategy(_ view: String) -> [String] { sortingStrategy[view] ?? AgendaSort.defaults[view] ?? [] }
162
143163 func prefix(_ view: String) -> PrefixFormat {
144164 PrefixFormat(prefixFormat[view] ?? PrefixFormat.defaults[view]!)
145165 }
@@ -165,17 +185,24 @@ public enum Agenda {
165185 for source in sources { items += entries(source, day: day, today: today, options: options) }
166186 let isToday = day == today
167187 if (isToday || days == 1), items.contains(where: { $0.timeOfDay != nil }) {
168 items = grid(day: day, isToday: isToday, now: now, options: options) + items
188 let grid = grid(day: day, isToday: isToday, now: now, options: options)
189 items = options.strategy("agenda").contains("time-up") ? grid + items : items + grid
169190 }
170 return AgendaDay(day: day, isToday: isToday, header: header(day), items: sort(markBlocked(items, options: options)))
191 return AgendaDay(day: day, isToday: isToday, header: header(day), items: AgendaSort.sort(markBlocked(items, options: options), view: "agenda", options: options))
171192 }
172193 }
173194
174195 /// `org-agenda-get-day-entries` with the default entry types.
175196 static func entries(_ source: AgendaSource, day: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
176197 let deadlines = self.deadlines(source, day: day, today: today, options: options)
177 return (options.logMode ? progress(source, day: day, options: options) : []) + deadlines + scheduled(source, day: day, today: today, options: options) + blocks(source, day: day, options: options)
198 let items = (options.logMode ? progress(source, day: day, options: options) : []) + deadlines + scheduled(source, day: day, today: today, options: options) + blocks(source, day: day, options: options)
178199 + timestamps(source, day: day, today: today, options: options) + sexps(source, day: day, options: options)
200 // A timestamp's `ts-date` is the day shown.
201 return items.map { item in
202 var item = item
203 if item.kind == .timestamp { item.tsDate = day }
204 return item
205 }
179206 }
180207
181208 /// `org-time-string-to-absolute` for a planning timestamp's text: a diary sexp counts on
@@ -221,6 +248,7 @@ public enum Agenda {
221248 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), urgency: { (isToday ? -diff : 0) + $0 }
222249 )
223250 item.planningDay = current != deadline && current == repeat_ ? repeat_ : deadline
251 item.tsDate = deadline
224252 items.append(item)
225253 }
226254 return items
@@ -251,6 +279,7 @@ public enum Agenda {
251279 urgency: { habit?.urgency(today: today) ?? 99 + diff + $0 }
252280 )
253281 item.planningDay = current != schedule && current == repeat_ ? repeat_ : schedule
282 item.tsDate = schedule
254283 items.append(item)
255284 }
256285 return items
@@ -434,10 +463,15 @@ public enum Agenda {
434463 }
435464 }
436465 let category = heading.category
437 let prefix = prefixFormat.render([
438 "c": category, "t": timed.time, "s": habit == nil ? extra : "", "l": String(repeating: " ", count: heading.level),
439 "e": heading.properties["EFFORT"] ?? "", "b": breadcrumbs(source, heading), "T": tags.last?.name ?? "",
440 ])
466 var fields: [Character: String] = [
467 "l": String(repeating: " ", count: heading.level), "e": heading.properties["EFFORT"] ?? "", "b": breadcrumbs(source, heading),
468 "T": tags.last?.name ?? "",
469 ]
470 let detail = prefixFormat.render(fields).trimmingCharacters(in: .whitespaces)
471 fields["c"] = category
472 fields["t"] = timed.time
473 fields["s"] = habit == nil ? extra : ""
474 let prefix = prefixFormat.render(fields)
441475 txt = highlightTodo(txt, keywords: source.keywords)
442476 let priority = Self.priority(prefix + txt, source.priorities)
443477 var item = AgendaItem(
@@ -450,6 +484,21 @@ public enum Agenda {
450484 item.blockedByCheckboxes = heading.blockedByCheckboxes
451485 item.blockedByHierarchy = heading.blockedByHierarchy
452486 item.doneKeyword = heading.todo.flatMap { source.firstDone[$0] }
487 item.prefixDetail = detail.isEmpty ? nil : detail
488 switch kind {
489 case .search: item.priority = 1000
490 case .closed, .clock, .state: item.priority = 100_000
491 case .sexp: item.priority = 0
492 default: item.priority = priority
493 }
494 item.tsType = kind.rawValue
495 // Search and log lines carry no `todo-state`, and search lines no effort.
496 if kind != .search { item.effortMinutes = item.effort.flatMap(ColumnView.minutes) }
497 if ![.search, .closed, .clock, .state].contains(kind), let todo = heading.todo, let index = source.keywords.firstIndex(of: todo) {
498 item.todoRank = index - source.keywords.count
499 item.todoDone = heading.isDone
500 }
501 item.alpha = AgendaSort.alpha(txt, keywords: kind == .sexp ? [] : source.keywords)
453502 return item
454503 }
455504
@@ -590,11 +639,14 @@ public enum Agenda {
590639 func item(_ kind: AgendaItem.Kind, _ text: String, _ dotime: String) -> AgendaItem {
591640 var txt = text
592641 let timed = timeFields(&txt, tagString: "", dotime: .string(dotime), trailing: options.gridTrailing)
593 return AgendaItem(
642 var grid = AgendaItem(
594643 kind: kind, path: nil, headingOffset: nil, headingLine: nil, markerOffset: nil, category: "", timeOfDay: timed.timeOfDay,
595644 time: timed.time, extra: "", text: txt, tags: [], todo: nil, isDone: false, urgency: 0, warntime: nil, habit: nil,
596645 line: options.prefix("agenda").render(["t": timed.time]) + txt, prefix: options.prefix("agenda").render(["t": timed.time])
597646 )
647 grid.tsType = ""
648 grid.alpha = AgendaSort.alpha(txt, keywords: [])
649 return grid
598650 }
599651 var new = options.gridTimes.reversed().map { t in
600652 item(.timeGrid, options.gridLine, String(format: "%02d:%02d", t / 100, t % 100))
@@ -605,18 +657,6 @@ public enum Agenda {
605657 return new
606658 }
607659
608 /// `org-entries-lessp` with `(habit-down time-up urgency-down category-keep)`, stably.
609 static func sort(_ items: [AgendaItem]) -> [AgendaItem] {
610 items.enumerated().sorted { a, b in
611 if (a.element.habit == nil) != (b.element.habit == nil) { return a.element.habit == nil }
612 let ta = a.element.timeOfDay ?? 9901
613 let tb = b.element.timeOfDay ?? 9901
614 if ta != tb { return ta < tb }
615 if a.element.urgency != b.element.urgency { return a.element.urgency > b.element.urgency }
616 return a.offset < b.offset
617 }.map(\.element)
618 }
619
620660 static let dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
621661 static let monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
622662
Sources/OrgCore/Agenda/AgendaSearch.swift +13 −14
@@ -16,13 +16,16 @@ extension Agenda {
1616 continue
1717 }
1818 if ignoresTodo(source, index, options: options, today: today) { continue }
19 items.append(format(
19 var item = format(
2020 source, heading, kind: .todo, marker: heading.start, extra: "", dotime: .headline, removing: nil,
2121 trailing: "", prefix: options.prefix("todo"), urgency: { 1 + $0 }
22 ))
22 )
23 (item.tsDate, item.tsType) = AgendaSort.entryTimestamp(heading, strategy: options.strategy("todo"))
24 item.tsType = "todo" + item.tsType
25 items.append(item)
2326 }
2427 }
25 return sortByUrgency(markBlocked(items, options: options))
28 return AgendaSort.sort(markBlocked(items, options: options), view: "todo", options: options)
2629 }
2730
2831 /// `org-tags-view`: entries matching a tags/property/TODO match string. `todoOnly` keeps
@@ -39,13 +42,16 @@ extension Agenda {
3942 if matcher.todoOnly, heading.todo == nil { continue }
4043 guard matcher.matches(heading, in: source, now: now, calendar: calendar), !heading.skipped else { continue }
4144 if matcher.todoOnly, options.tagsTodoHonorIgnoreOptions, ignoresTodo(source, index, options: options, today: today) { continue }
42 items.append(format(
45 var item = format(
4346 source, heading, kind: .tagsMatch, marker: heading.start, extra: "", dotime: nil, removing: nil,
4447 trailing: "", prefix: options.prefix("tags"), urgency: { $0 }
45 ))
48 )
49 (item.tsDate, item.tsType) = AgendaSort.entryTimestamp(heading, strategy: options.strategy("tags"))
50 item.tsType = "tagsmatch" + item.tsType
51 items.append(item)
4652 }
4753 }
48 return sortByUrgency(markBlocked(items, options: options))
54 return AgendaSort.sort(markBlocked(items, options: options), view: "tags", options: options)
4955 }
5056
5157 /// `org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item` for the entry of heading
@@ -177,7 +183,7 @@ extension Agenda {
177183 }
178184 }
179185 }
180 return items
186 return AgendaSort.sort(items, view: "search", options: options)
181187 }
182188
183189 /// An `org-search-view` string read into regexps, in Emacs syntax and compiled.
@@ -284,13 +290,6 @@ extension Agenda {
284290 try? NSRegularExpression(pattern: EmacsRegex.translate(emacs, search: true), options: [.caseInsensitive, .anchorsMatchLines])
285291 }
286292 }
287
288 /// `(urgency-down category-keep)`, stably.
289 static func sortByUrgency(_ items: [AgendaItem]) -> [AgendaItem] {
290 items.enumerated().sorted { a, b in
291 a.element.urgency != b.element.urgency ? a.element.urgency > b.element.urgency : a.offset < b.offset
292 }.map(\.element)
293 }
294293}
295294
296295/// `org-make-tags-matcher`: `+work-boss|LEVEL>2+TODO="WAIT"/!NEXT`.
Sources/OrgCore/Agenda/AgendaSort.swift added +158
@@ -0,0 +1,158 @@
1import Foundation
2
3/// `org-agenda-sorting-strategy` and `org-entries-lessp` (Org 9.8.7).
4public enum AgendaSort {
5 /// The strategies `org-entries-lessp` knows, without the user-defined ones.
6 public static let keys: Set<String> = [
7 "time-up", "time-down", "timestamp-up", "timestamp-down", "scheduled-up", "scheduled-down", "deadline-up", "deadline-down",
8 "ts-up", "ts-down", "tsia-up", "tsia-down", "stats-up", "stats-down", "priority-up", "priority-down", "urgency-up", "urgency-down",
9 "effort-up", "effort-down", "category-up", "category-down", "category-keep", "tag-up", "tag-down", "todo-state-up",
10 "todo-state-down", "habit-up", "habit-down", "alpha-up", "alpha-down",
11 ]
12
13 public static let defaults: [String: [String]] = [
14 "agenda": ["habit-down", "time-up", "urgency-down", "category-keep"],
15 "todo": ["urgency-down", "category-keep"],
16 "tags": ["urgency-down", "category-keep"],
17 "search": ["category-keep"],
18 ]
19
20 /// `org-entries-lessp` for one strategy: -1, +1, or nil to try the next.
21 static func compare(_ key: String, _ a: AgendaItem, _ b: AgendaItem, _ options: AgendaOptions) -> Int? {
22 func values<T: Comparable>(_ x: T, _ y: T) -> Int? { x > y ? 1 : x < y ? -1 : nil }
23 func ts(_ x: AgendaItem, _ y: AgendaItem, _ type: String) -> Int? {
24 func date(_ item: AgendaItem) -> Int {
25 (type.isEmpty || item.tsType.contains(type) ? item.tsDate : nil) ?? (options.sortNotimeIsLate ? Int.max : -1)
26 }
27 return values(date(x), date(y))
28 }
29 func time(_ x: AgendaItem, _ y: AgendaItem) -> Int? {
30 let def = options.sortNotimeIsLate ? 9901 : -1
31 return values(x.timeOfDay ?? def, y.timeOfDay ?? def)
32 }
33 func effort(_ x: AgendaItem, _ y: AgendaItem) -> Int? {
34 let def = options.sortNoeffortIsHigh ? Double(Int.max) : -1
35 return values(x.effortMinutes ?? def, y.effortMinutes ?? def)
36 }
37 func category(_ x: AgendaItem, _ y: AgendaItem) -> Int? { values(x.category, y.category) }
38 func optional(_ x: String?, _ y: String?) -> Int? {
39 switch (x, y) {
40 case (nil, nil): return nil
41 case (nil, _): return 1
42 case (_, nil): return -1
43 case let (x?, y?): return values(x, y)
44 }
45 }
46 func todoState(_ x: AgendaItem, _ y: AgendaItem) -> Int? {
47 let doneX = x.todoDone, doneY = y.todoDone
48 if doneX, !doneY { return -1 }
49 if !doneX, doneY { return 1 }
50 return x.todoRank < y.todoRank ? -1 : y.todoRank < x.todoRank ? 1 : nil
51 }
52 func habit(_ x: AgendaItem, _ y: AgendaItem) -> Int? {
53 x.habit != nil && y.habit == nil ? -1 : x.habit == nil && y.habit != nil ? 1 : nil
54 }
55 switch key {
56 case "timestamp-up": return ts(a, b, "")
57 case "timestamp-down": return ts(b, a, "")
58 case "scheduled-up": return ts(a, b, "scheduled")
59 case "scheduled-down": return ts(b, a, "scheduled")
60 case "deadline-up": return ts(a, b, "deadline")
61 case "deadline-down": return ts(b, a, "deadline")
62 case "tsia-up": return ts(a, b, "timestamp_ia")
63 case "tsia-down": return ts(b, a, "timestamp_ia")
64 case "ts-up": return ts(a, b, "timestamp")
65 case "ts-down": return ts(b, a, "timestamp")
66 case "time-up": return time(a, b)
67 case "time-down": return time(b, a)
68 case "priority-up": return values(a.priority, b.priority)
69 case "priority-down": return values(b.priority, a.priority)
70 case "urgency-up": return values(a.urgency, b.urgency)
71 case "urgency-down": return values(b.urgency, a.urgency)
72 case "effort-up": return effort(a, b)
73 case "effort-down": return effort(b, a)
74 case "category-up": return category(a, b)
75 case "category-down": return category(b, a)
76 case "category-keep": return category(a, b).map { _ in 1 }
77 case "tag-up": return optional(a.tags.last, b.tags.last)
78 case "tag-down": return optional(b.tags.last, a.tags.last)
79 case "todo-state-up": return todoState(a, b)
80 case "todo-state-down": return todoState(b, a)
81 case "habit-up": return habit(a, b)
82 case "habit-down": return habit(b, a)
83 case "alpha-up": return optional(a.alpha, b.alpha)
84 case "alpha-down": return optional(b.alpha, a.alpha)
85 // `org-stats` is never set on agenda lines.
86 default: return nil
87 }
88 }
89
90 static func lessp(_ a: AgendaItem, _ b: AgendaItem, _ strategy: [String], _ options: AgendaOptions) -> Bool {
91 for key in strategy {
92 if let result = compare(key, a, b, options) { return result < 0 }
93 }
94 return false
95 }
96
97 /// `(sort list #'org-entries-lessp)` with the strategy for `view`. Emacs's sort is timsort,
98 /// which for lists this short takes the leading run and binary-inserts the rest; done the
99 /// same way, strategies that end comparisons early (`category-keep`) order as in Emacs.
100 static func sort(_ items: [AgendaItem], view: String, options: AgendaOptions) -> [AgendaItem] {
101 let strategy = options.sortingStrategy[view] ?? defaults[view] ?? []
102 guard items.count > 1, !strategy.isEmpty else { return items }
103 func lt(_ a: AgendaItem, _ b: AgendaItem) -> Bool { lessp(a, b, strategy, options) }
104 var list = items
105 // `count_run`: an ascending run, or a strictly descending one reversed.
106 var run = 2
107 if lt(list[1], list[0]) {
108 while run < list.count, lt(list[run], list[run - 1]) { run += 1 }
109 list[0..<run].reverse()
110 } else {
111 while run < list.count, !lt(list[run], list[run - 1]) { run += 1 }
112 }
113 // `binarysort`.
114 for start in run..<list.count {
115 let pivot = list[start]
116 var l = 0, r = start
117 while l < r {
118 let p = l + (r - l) / 2
119 if lt(pivot, list[p]) { r = p } else { l = p + 1 }
120 }
121 list.remove(at: start)
122 list.insert(pivot, at: l)
123 }
124 return list
125 }
126
127 /// `org-agenda-entry-get-agenda-timestamp`: the day of the timestamp the TODO and tags
128 /// views sort by, from the first ts strategy, and the type it adds.
129 static func entryTimestamp(_ heading: AgendaSource.Heading, strategy: [String]) -> (day: Int?, type: String) {
130 func has(_ a: String, _ b: String) -> Bool { strategy.contains(a) || strategy.contains(b) }
131 let ts: String?
132 let type: String
133 if has("scheduled-up", "scheduled-down") {
134 (ts, type) = (heading.scheduled?.raw, " scheduled")
135 } else if has("deadline-up", "deadline-down") {
136 (ts, type) = (heading.deadline?.raw, " deadline")
137 } else if has("ts-up", "ts-down") {
138 (ts, type) = (heading.firstActive, " timestamp")
139 } else if has("tsia-up", "tsia-down") {
140 (ts, type) = (heading.firstInactive, " timestamp_ia")
141 } else if has("timestamp-up", "timestamp-down") {
142 (ts, type) = (heading.scheduled?.raw ?? heading.deadline?.raw ?? heading.firstActive ?? heading.firstInactive, "")
143 } else {
144 (ts, type) = (nil, "")
145 }
146 return (ts.flatMap(Days.absolute(of:)), type)
147 }
148
149 /// The heading text `alpha-up` compares: from `org-heading` on, without the TODO keyword
150 /// and a `[x]` cookie, lower-cased. Sexp entries have no keyword regexp (`keywords` empty).
151 static func alpha(_ text: String, keywords: [String]) -> String {
152 var t = text
153 let todo = keywords.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
154 let pattern = "^[ \\t]*" + (todo.isEmpty ? "" : "(?:" + todo + ")") + "([ \\t]*\\[[a-zA-Z0-9]\\])? *"
155 if let r = t.range(of: pattern, options: .regularExpression) { t = String(t[r.upperBound...]) }
156 return t.lowercased()
157 }
158}
Sources/OrgPresentation/AgendaRows.swift +4
@@ -80,6 +80,8 @@ public struct AgendaRow: Sendable, Equatable, Identifiable {
8080 public let progress: String?
8181 /// Log mode: the time clocked (`1:30`) or the state set (`DONE`).
8282 public let detail: String?
83 /// What the view's prefix format adds, such as the effort or the outline path.
84 public let prefixDetail: String?
8385 /// `HHMM` of the start and the end, when timed.
8486 public let start: Int?
8587 public let end: Int?
@@ -152,6 +154,7 @@ public struct AgendaRow: Sendable, Equatable, Identifiable {
152154 self.priority = item.priorityLetter
153155 self.progress = item.progress
154156 self.detail = item.kind == .clock || item.kind == .state ? Self.logDetail(item.extra) : nil
157 self.prefixDetail = item.prefixDetail
155158 self.start = timed?.0
156159 self.end = timed?.1
157160 self.planningDay = planning
@@ -192,6 +195,7 @@ public struct AgendaRow: Sendable, Equatable, Identifiable {
192195 self.priority = nil
193196 self.progress = nil
194197 self.detail = nil
198 self.prefixDetail = nil
195199 self.start = start
196200 self.end = end
197201 self.planningDay = nil
Sources/Orgstar/AgendaRowView.swift +7
@@ -113,6 +113,13 @@ struct AgendaRowView: View {
113113 .font(.system(size: 11))
114114 .foregroundStyle(theme.color("agenda-category") ?? .secondary)
115115 .lineLimit(1)
116 if let detail = row.prefixDetail {
117 Text(detail)
118 .font(.system(size: 11))
119 .foregroundStyle(.secondary)
120 .lineLimit(1)
121 .truncationMode(.middle)
122 }
116123 }
117124 }
118125
Sources/Orgstar/AgendaView+Toolbar.swift +1
@@ -190,6 +190,7 @@ extension AgendaView {
190190 func loadViews() {
191191 let loaded = AgendaViewLoader.load()
192192 views = loaded.views
193 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
193194 message = loaded.problems.first
194195 }
195196
Sources/Orgstar/AgendaView.swift +7 −1
@@ -77,6 +77,10 @@ struct AgendaView: View {
7777 @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
7878 @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
7979 @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
80 @AppStorage("agendaSortAgenda") private var sortAgenda = ""
81 @AppStorage("agendaSortTodo") private var sortTodo = ""
82 @AppStorage("agendaSortTags") private var sortTags = ""
83 @AppStorage("agendaSortSearch") private var sortSearch = ""
8084 @Environment(\.openWindow) var openWindow
8185
8286 static let match = "Match…"
@@ -124,6 +128,7 @@ struct AgendaView: View {
124128 var startOnWeekday: String
125129 var includeSubfolders: Bool
126130 var prefix: [String]
131 var sorting: [String]
127132 var logMode: Bool
128133 var calendars: [String]
129134 var files: Int
@@ -137,7 +142,8 @@ struct AgendaView: View {
137142 /// they redraw only it.
138143 private var refreshKey: RefreshKey {
139144 RefreshKey(
140 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, startOnWeekday: startOnWeekday, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags], logMode: logMode,
145 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, startOnWeekday: startOnWeekday, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags],
146 sorting: [sortAgenda, sortTodo, sortTags, sortSearch], logMode: logMode,
141147 calendars: calendarEventsOn ? [calendarNames] : [], files: 0, changed: nil, edits: 0, path: nil, tick: tick
142148 )
143149 }
Sources/OrgstarMobile/AgendaScreen.swift +2
@@ -202,6 +202,7 @@ struct AgendaScreen: View, Equatable {
202202 .task {
203203 let loaded = AgendaViewLoader.load()
204204 views = loaded.views
205 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
205206 if let problem = loaded.problems.first { message = problem }
206207 }
207208 // The now line moves each minute; a new day refreshes the statuses.
@@ -644,6 +645,7 @@ struct AgendaRowView: View {
644645 Circle().fill(categoryColor).frame(width: 7, height: 7)
645646 Text(row.category).lineLimit(1).layoutPriority(1)
646647 }
648 if let detail = row.prefixDetail { Text(detail).lineLimit(1).truncationMode(.middle) }
647649 ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
648650 Text(progress).monospacedDigit()
649651 .padding(.horizontal, 5)
Tests/OrgAppTests/AppTests.swift +27
@@ -658,6 +658,33 @@ struct AgendaCommandTests {
658658 #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
659659 }
660660
661 @Test func viewsSortAndPrefixThemselves() async throws {
662 let notes = try Folder()
663 try notes.write("a.org", "* TODO b\n:PROPERTIES:\n:Effort: 0:30\n:END:\n* TODO [#A] c\n* TODO a\n")
664 let file = try notes.write("views.toml", """
665 [[view]]
666 name = "Alphabetical"
667 type = "todo"
668 sorting-strategy = "alpha-up bogus"
669 prefix-format = "%e"
670 """)
671 let loaded = AgendaViewLoader.load(userFile: file)
672 #expect(loaded.problems == ["views.toml line 1: unknown sorting key bogus"])
673 #expect(loaded.views[2].settings == AgendaViewSettings(prefixFormat: "%e", sortingStrategy: ["alpha-up"]))
674 let model = try WorkspaceModel(directory: nil)
675 try await model.addRoot(notes.url)
676 let agenda = AgendaModel(workspace: model)
677 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
678 agenda.mode = .todo(keywords: nil)
679 await agenda.refresh(open: [:])
680 // `alpha-up` keeps the priority cookie, as Org does.
681 #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO a", "TODO b"])
682 #expect(agenda.list.map(\.prefixDetail) == [nil, nil, "0:30"])
683 agenda.mode = .todo(keywords: "TODO")
684 await agenda.refresh(open: [:])
685 #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO b", "TODO a"])
686 }
687
661688 @Test func todoListMode() async throws {
662689 let notes = try Folder()
663690 try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
Tests/OrgAppTests/EmacsImportTests.swift +5 −1
@@ -20,6 +20,7 @@ struct EmacsImportTests {
2020 (setq org-tags-column 4)
2121 (setq org-log-done 'note org-log-into-drawer t org-log-reschedule 'time)
2222 (setq org-agenda-prefix-format '((agenda . " %i %-12:c%?-12t% s%b") (todo . " %-8:c")))
23 (setq org-agenda-sorting-strategy '((agenda time-up priority-down) (todo . (alpha-up))) org-agenda-sort-notime-is-late nil)
2324 (setq fill-column (+ 70 2))
2425 (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))
2526 (with-eval-after-load 'org (add-to-list 'org-structure-template-alist '("q" . "QUOTE")))
@@ -92,6 +93,9 @@ struct EmacsImportTests {
9293 #expect(s["org-log-into-drawer"] == .string("LOGBOOK"))
9394 #expect(s["org-agenda-prefix-format.agenda"] == .string(" %i %-12:c%?-12t% s%b"))
9495 #expect(s["org-agenda-prefix-format.todo"] == .string(" %-8:c"))
96 #expect(s["org-agenda-sorting-strategy.agenda"] == .string("time-up priority-down"))
97 #expect(s["org-agenda-sorting-strategy.todo"] == .string("alpha-up"))
98 #expect(s["org-agenda-sort-notime-is-late"] == .bool(false))
9599 // after! org runs after the top-level setq.
96100 #expect(s["org-tags-column"] == .integer(-80))
97101 #expect(s["org-agenda-span"] == .integer(10))
@@ -195,7 +199,7 @@ struct EmacsImportTests {
195199 let keymap = folder.appendingPathComponent("keymap.toml")
196200 #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty)
197201 #expect(KeymapLoader.load(.doom, userFile: keymap).keymap.keyLabels(for: "app.agenda", modes: ["normal"]).contains("C-c a"))
198 #expect(summary.hasPrefix("Imported 32 settings, 3 capture templates, 3 key bindings, 2 structure templates."), "\(summary)")
202 #expect(summary.hasPrefix("Imported 35 settings, 3 capture templates, 3 key bindings, 2 structure templates."), "\(summary)")
199203 #expect(UserConfig.structureTemplates(defaults) == [.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")])
200204 #expect(OrgPreferences.options(defaults).structureTemplates?.first { $0.key == "q" }?.type == "QUOTE")
201205 #expect(defaults.string(forKey: "themeFont") == "JetBrains Mono")
Tests/OrgCoreTests/AgendaSortTests.swift added +106
@@ -0,0 +1,106 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `org-agenda-sorting-strategy` against Emacs.
6struct AgendaSortTests {
7 static let today = Days.absolute(year: 2026, month: 10, day: 5)
8
9 static let files = [
10 ("a.org", """
11 #+CATEGORY: alpha
12 * TODO [#B] write report :work:
13 SCHEDULED: <2026-10-05 Mon 14:00>
14 :PROPERTIES:
15 :Effort: 1:30
16 :END:
17 * WAIT [#A] Call Bob :phone:
18 DEADLINE: <2026-10-07 Wed>
19 * TODO Buy milk :home:errand:
20 SCHEDULED: <2026-10-03 Sat>
21 :PROPERTIES:
22 :Effort: 0:10
23 :END:
24 * HOLD zebra notes
25 <2026-10-05 Mon 09:00>
26 [2026-09-01 Tue]
27 * TODO [#C] apples
28 DEADLINE: <2026-10-05 Mon 11:00>
29 :PROPERTIES:
30 :Effort: 2:00
31 :END:
32
33 """),
34 ("b.org", """
35 #+CATEGORY: beta
36 * IDEA Mango :work:
37 SCHEDULED: <2026-10-05 Mon>
38 * TODO [#A] banana
39 <2026-10-06 Tue 08:00>
40 [2026-08-15 Sat]
41 * STRT Kiwi :home:
42 DEADLINE: <2026-10-04 Sun>
43 :PROPERTIES:
44 :Effort: 0:45
45 :END:
46 * DONE cherry
47 SCHEDULED: <2026-10-05 Mon 10:00>
48
49 """),
50 ]
51
52 static func lisp(_ strategy: [String]) -> String { "(" + strategy.joined(separator: " ") + ")" }
53
54 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
55 func agendaSortsLikeOrg() throws {
56 let strategies: [[String]] = [
57 ["time-down", "priority-up", "category-keep"], ["category-up", "alpha-up"], ["category-down", "alpha-down"],
58 ["effort-up", "tag-up"], ["effort-down", "tag-down"], ["todo-state-up", "alpha-up"], ["todo-state-down", "alpha-up"],
59 ["deadline-up", "scheduled-down", "alpha-up"], ["timestamp-up", "alpha-up"], ["ts-down", "urgency-up"],
60 ["category-keep", "alpha-up"], ["habit-up", "priority-down"],
61 ]
62 for strategy in strategies {
63 for late in [true, false] {
64 let form = "(let ((org-agenda-sorting-strategy '((agenda . \(Self.lisp(strategy))))) (org-agenda-sort-notime-is-late \(late ? "t" : "nil")) (org-agenda-sort-noeffort-is-high \(late ? "t" : "nil"))) (org-agenda-list nil \"2026-10-04\" 3))"
65 let emacs = try AgendaOracle.run(files: Self.files, form: form, today: Self.today, hour: 9, minute: 30)
66 let defaults = OrgSettings.default.withTodoKeywords(AgendaOracle.keywords)!
67 let sources = Self.files.map { AgendaSource(path: $0.0, text: $0.1, defaults: defaults) }
68 var options = AgendaOptions.terminal
69 options.sortingStrategy["agenda"] = strategy
70 options.sortNotimeIsLate = late
71 options.sortNoeffortIsHigh = late
72 let ours = Agenda.list(sources, start: Self.today - 1, days: 3, today: Self.today, now: (9, 30), options: options)
73 #expect(ours.count == emacs.count)
74 for (o, e) in zip(ours, emacs) {
75 #expect(AgendaOracle.describe(o.items, today: Self.today) == AgendaOracle.describe(e.items), "\(strategy) \(late) \(e.header)")
76 }
77 }
78 }
79 }
80
81 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
82 func listsSortLikeOrg() throws {
83 let strategies: [[String]] = [
84 ["priority-down", "alpha-up"], ["scheduled-up", "alpha-up"], ["deadline-down", "alpha-up"], ["timestamp-up", "alpha-up"],
85 ["tsia-up", "alpha-down"], ["ts-up", "alpha-up"], ["todo-state-down", "effort-up"], ["category-keep", "alpha-up"],
86 ["tag-down", "category-down"], ["effort-down", "alpha-up"],
87 ]
88 var utc = Calendar(identifier: .gregorian)
89 utc.timeZone = TimeZone(identifier: "UTC")!
90 let now = Date(timeIntervalSince1970: Double((Self.today - 719163) * 86400 + 9 * 3600 + 30 * 60))
91 for strategy in strategies {
92 var options = AgendaOptions()
93 for view in ["todo", "tags", "search"] { options.sortingStrategy[view] = strategy }
94 let alist = "'((todo . \(Self.lisp(strategy))) (tags . \(Self.lisp(strategy))) (search . \(Self.lisp(strategy))))"
95 try AgendaOracle.compareList(files: Self.files, form: "(let ((org-agenda-sorting-strategy \(alist))) (org-todo-list nil))", today: Self.today) {
96 Agenda.todoList($0, options: options, today: Self.today)
97 }
98 try AgendaOracle.compareList(files: Self.files, form: "(let ((org-agenda-sorting-strategy \(alist))) (org-tags-view nil \"work|home\"))", today: Self.today) {
99 Agenda.tagsMatch($0, match: "work|home", now: now, calendar: utc, options: options)
100 }
101 try AgendaOracle.compareList(files: Self.files, form: "(let ((org-agenda-sorting-strategy \(alist))) (org-search-view nil \"a\"))", today: Self.today) {
102 Agenda.textSearch($0, string: "a", options: options)
103 }
104 }
105 }
106}
Tests/OrgCoreTests/AgendaTests.swift +1 −1
@@ -151,7 +151,7 @@ enum AgendaOracle {
151151 let line = item.habit.map { Habit.insertGraph($0.graph(today: today), into: item.line) } ?? item.line
152152 let type: String = switch item.kind {
153153 case .timeGrid, .currentTime: "-"
154 default: item.kind.rawValue
154 default: item.tsType
155155 }
156156 return "\(normalize(line)) | \(type) \(item.category) \(item.timeOfDay.map(String.init) ?? "-") [\(item.extra)] \(item.urgency) \(item.headingOffset == nil ? "-" : item.path ?? "-")@\(item.headingOffset.map(String.init) ?? "-")"
157157 }
docs/manual/guide/07-agenda.org +26 −3
@@ -118,7 +118,26 @@ On today, a line marked with the current time sits between the timed entries: be
118118
119119** Sorting
120120
121Days are sorted as =org-agenda-sorting-strategy= sorts them by default for the agenda: =(habit-down time-up urgency-down category-keep)=. Habits go last; timed entries come first, earliest first; the rest by urgency, which combines priority with how overdue an entry is; ties keep file order. Calendar events go among them as described in [[*Calendar events][Calendar events]]. The TODO list and match views sort by urgency, then file order. The sorting is not configurable.
121Lines are sorted by =org-agenda-sorting-strategy=, set per kind of view in the =[org-agenda-sorting-strategy]= table of =config.toml= (see [[file:13-configuration.org][Configuration]]) or for one view in =views.toml=. The defaults are Org's: =habit-down time-up urgency-down category-keep= for days, =urgency-down category-keep= for the TODO list and matches, and =category-keep= for text search. With those, habits go last; timed entries come first, earliest first; the rest by urgency, which combines priority with how overdue an entry is; ties keep file order. Calendar events go among them as described in [[*Calendar events][Calendar events]].
122
123Each key compares two lines, and the next key is tried when they tie:
124
125| Key | Sorts by |
126|--------------------------------------+-----------------------------------------------------------------------------|
127| =time-up=, =time-down= | Time of day; lines without one go last (=org-agenda-sort-notime-is-late=) |
128| =timestamp-up=, =timestamp-down= | The date of the line's timestamp, of any kind |
129| =scheduled-up=, =deadline-up=, =ts-up=, =tsia-up= and their =-down= forms | The date of a =SCHEDULED=, =DEADLINE=, active or inactive timestamp only |
130| =priority-up=, =priority-down= | Priority |
131| =urgency-up=, =urgency-down= | Urgency: priority adjusted for how close or overdue the date is |
132| =effort-up=, =effort-down= | =Effort=; entries without one count as longest (=org-agenda-sort-noeffort-is-high=) |
133| =category-up=, =category-down= | Category name |
134| =category-keep= | Stops comparing lines of different categories, so they keep their order |
135| =tag-up=, =tag-down= | The last tag |
136| =todo-state-up=, =todo-state-down= | Done keywords first, then keywords in the order your sequences list them |
137| =habit-up=, =habit-down= | Habits first or last |
138| =alpha-up=, =alpha-down= | The title, ignoring case and the TODO keyword |
139
140In the TODO list and matches, the date keys use the first one in the strategy: with =scheduled-up= every line sorts by its =SCHEDULED= date, as in Org. Org's =user-defined-up= and =user-defined-down= are not supported.
122141
123142** Log mode
124143
@@ -415,10 +434,12 @@ match = "+invoice -paid"
415434| =start= | =agenda= | First day as an integer number of days from today (=-3=, =0=); the setting when omitted |
416435| =keywords= | =todo= | Keywords separated by the vertical bar; all open TODOs when omitted |
417436| =match= | =match=, =todo-match=, =search=, =todo-search=, required | A match string as in [[*Tag and property matches][Tag and property matches]], or for =search= a search string as in [[*Text search][Text search]]; the =todo-= types keep only open TODO entries |
437| =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 |
438| =prefix-format= | all | The view's =org-agenda-prefix-format=, in place of the one in =config.toml= for its kind |
418439
419440Note that =start= is a plain integer here, while =org-agenda-start-day= in =config.toml= is a string such as ="-3d"=.
420441
421Not supported: block agendas (several views in one), per-view settings such as =org-agenda-skip-function= or a different prefix format, and =stuck= projects. 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.
442Not supported: block agendas (several views in one), =org-agenda-skip-function=, and =stuck= projects. 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.
422443
423444* Filters
424445
@@ -456,7 +477,9 @@ The =\= prompt reads every word as a tag, whether or not a line has it; there, =
456477
457478* Prefix format and colors
458479
459The rows look the same whatever =org-agenda-prefix-format= says. orgstar reads the =[org-agenda-prefix-format]= table in =config.toml= (see [[file:13-configuration.org][Configuration]]), but the only effect is on times written in heading text: when the =agenda= format contains =%t=, as the default =" %i %-12:c%?-12t% s"= does, a time such as =9:30am= in =Call Ada 9:30am= moves out of the title into the left column, as =org-agenda-remove-times-when-in-prefix= does. Without =%t=, the title keeps it.
480orgstar reads =org-agenda-prefix-format= from the =[org-agenda-prefix-format]= table in =config.toml= (see [[file:13-configuration.org][Configuration]]) or a view's =prefix-format=. Rows already show the category, the time and the scheduled or deadline leader in their own places, so =%c=, =%t=, =%s= and =%i= add nothing there. What the format adds besides them shows after the category: =%e= the effort, =%b= the outline path (=Project->Phase->=), =%T= the last tag, and any literal text. =%l= (the level as spaces) and =%(…)= Lisp forms show nothing. Widths, =?= and punctuation work as in Org.
481
482Times written in heading text depend on =%t=: when the =agenda= format contains it, as the default =" %i %-12:c%?-12t% s"= does, a time such as =9:30am= in =Call Ada 9:30am= moves out of the title into the left column, as =org-agenda-remove-times-when-in-prefix= does. Without =%t=, the title keeps it.
460483
461484The agenda's colors come from these theme keys (see [[file:13-configuration.org][Configuration]]):
462485
docs/manual/guide/13-configuration.org +18 −2
@@ -169,11 +169,12 @@ These settings have no control in the Settings window. Some are in the View menu
169169| =org-agenda-search-view-always-boolean= | |
170170| =org-agenda-search-view-force-full-words= | |
171171| =[org-agenda-prefix-format]= | |
172| =[org-agenda-sorting-strategy]=, =org-agenda-sort-notime-is-late=, =org-agenda-sort-noeffort-is-high= | |
172173| =theme-file= | |
173174
174175* config.toml reference
175176
176Settings that mirror an Emacs variable sit at the top of the file under that variable's name. The agenda prefix formats are in =[org-agenda-prefix-format]=, type and theme in =[theme]=, and the settings Emacs has no variable for in =[orgstar]=.
177Settings that mirror an Emacs variable sit at the top of the file under that variable's name. The agenda prefix formats are in =[org-agenda-prefix-format]=, the sorting strategies in =[org-agenda-sorting-strategy]=, type and theme in =[theme]=, and the settings Emacs has no variable for in =[orgstar]=.
177178
178179A key you remove from the file goes back to its default. A key that isn't in the table below is reported as unknown.
179180
@@ -226,6 +227,8 @@ A key you remove from the file goes back to its default. A key that isn't in the
226227| =org-agenda-tags-todo-honor-ignore-options= | boolean | =false= | The four settings above apply to TODO-only matches (=M=) too. Mirrors =org-agenda-tags-todo-honor-ignore-options=. |
227228| =org-agenda-search-view-always-boolean= | boolean | =false= | The agenda's text search reads every string as =+word -word {regexp}= snippets, never as a phrase. Mirrors =org-agenda-search-view-always-boolean=. |
228229| =org-agenda-search-view-force-full-words= | boolean | =false= | Text search snippets match whole words only, as a leading =:= does. Mirrors =org-agenda-search-view-force-full-words=. |
230| =org-agenda-sort-notime-is-late= | boolean | =true= | Lines without a time sort after timed ones for =time-up=, and lines without a date after dated ones for the date keys. Mirrors =org-agenda-sort-notime-is-late=. |
231| =org-agenda-sort-noeffort-is-high= | boolean | =true= | Entries without an =Effort= sort as the longest for =effort-up=. Mirrors =org-agenda-sort-noeffort-is-high=. |
229232| =org-agenda-dim-blocked-tasks= | string | ="t"= | =t= dims entries the two enforce settings block, =invisible= hides them (entries blocked only by checkboxes are still dimmed), =nil= shows them as usual. Mirrors =org-agenda-dim-blocked-tasks=. |
230233| =appt-message-warning-time= | integer | =12= | Minutes of warning before timed entries. An entry's =APPT_WARNTIME= property overrides it. Mirrors =appt-message-warning-time=. |
231234| =org-clock-idle-time= | integer | =0= | Minutes without keyboard or mouse input, with a clock running, before orgstar asks what to do with the idle time. =0= never asks (Emacs's =nil=). Mac only. Mirrors =org-clock-idle-time=. |
@@ -252,7 +255,18 @@ The startup settings (=org-startup-*=, =org-hide-leading-stars=, =org-cycle-hide
252255| =todo= | string | =" %i %-12:c"= | Prefix of lines in the TODO list |
253256| =tags= | string | =" %i %-12:c"= | Prefix of tag and property matches |
254257
255These mirror the entries of =org-agenda-prefix-format=. The agenda's rows don't show a prefix, so the formats don't change how the agenda looks. The one effect left is that a time written in heading text leaves the title when the =agenda= format contains =%t=. See [[file:07-agenda.org][The agenda]].
258These mirror the entries of =org-agenda-prefix-format=. Rows show the category, time and leader in their own places; the rest of the format, such as =%e= or =%b=, shows after the category. A time written in heading text leaves the title when the =agenda= format contains =%t=. A view in =views.toml= can set its own with =prefix-format=. See [[file:07-agenda.org][The agenda]].
259
260** [org-agenda-sorting-strategy]
261
262| Key | Type | Default | Effect |
263|----------+--------+-------------------------------------------------+--------------------------------|
264| =agenda= | string | ="habit-down time-up urgency-down category-keep"= | Order of lines within a day |
265| =todo= | string | ="urgency-down category-keep"= | Order of the TODO list |
266| =tags= | string | ="urgency-down category-keep"= | Order of tag and property matches |
267| =search= | string | ="category-keep"= | Order of text search results |
268
269These mirror the entries of =org-agenda-sorting-strategy=, keys separated by spaces. Unknown keys are ignored. A view in =views.toml= can set its own with =sorting-strategy=. The keys are listed in [[file:07-agenda.org][The agenda]].
256270
257271** [org-structure-template-alist]
258272
@@ -476,6 +490,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
476490| =org-hide-drawer-startup=, =org-hide-block-startup= | =org-cycle-hide-drawer-startup=, =org-cycle-hide-block-startup= |
477491| =org-M-RET-may-split-line= | =org-M-RET-may-split-line=, from the =default= entry of an alist; other per-context entries aren't supported |
478492| =org-agenda-prefix-format= | =[org-agenda-prefix-format]=: a string sets all three views; an alist sets =agenda=, =todo= and =tags= |
493| =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 |
494| =org-agenda-sort-notime-is-late=, =org-agenda-sort-noeffort-is-high= | The same key, as booleans |
479495| =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= |
480496| =org-log-into-drawer= | A string as given; =t= becomes ="LOGBOOK"=; =nil= becomes =""= |
481497| =display-line-numbers-type= | =true= unless =nil=; =relative= and =visual= become absolute numbers |