Sources/Orgstar/AgendaView+Actions.swift
cmc Agenda prompts, Week of titles and notification status through the catalog
e633d6bf48 19 hours ago285 lines · 12367 bytes
1import AppKit
2import OrgApp
3import OrgDocument
4import OrgCore
5import OrgPresentation
6import SwiftUI
7
8extension AgendaView {
9 // MARK: - Commands
10
11 func handle(_ press: KeyPress) -> KeyPress.Result {
12 let control = press.modifiers.contains(.control)
13 // `C-x` and friends arrive as control characters or as letters with control.
14 func isControl(_ letter: String, _ code: String) -> Bool { control && (press.characters == letter || press.characters == code) }
15 if let pending = prefix {
16 prefix = nil
17 if pending == "v" {
18 switch press.characters {
19 case "d" where isAgenda: setSpan(.day)
20 case "w" where isAgenda: setSpan(.week)
21 case "m" where isAgenda: setSpan(.month)
22 default: message = "v \(press.characters) is undefined"
23 }
24 if message == "v-" { message = nil }
25 return .handled
26 }
27 if pending == "C-c C-x" {
28 if isControl("s", "\u{13}") { archive() } else { message = "C-c C-x \(press.characters) is undefined" }
29 return .handled
30 }
31 if isControl("s", "\u{13}") {
32 run(SetPlanning(deadline: false))
33 } else if isControl("d", "\u{04}") {
34 run(SetPlanning(deadline: true))
35 } else if isControl("q", "\u{11}") {
36 run(SetTags())
37 } else if isControl("t", "\u{14}") {
38 run(TodoCycle())
39 } else if isControl("w", "\u{17}") {
40 refile(marked: false)
41 } else if isControl("x", "\u{18}") {
42 prefix = "C-c C-x"
43 message = "C-c C-x-"
44 } else if press.characters == "$" {
45 archive()
46 } else {
47 message = "C-c \(press.characters) is undefined"
48 }
49 return .handled
50 }
51 if isControl("c", "\u{03}") {
52 prefix = "C-c"
53 message = "C-c-"
54 return .handled
55 }
56 if isControl("n", "\u{0e}") || (press.key == .downArrow && press.modifiers.isEmpty) {
57 step(1)
58 return .handled
59 }
60 if isControl("p", "\u{10}") || (press.key == .upArrow && press.modifiers.isEmpty) {
61 step(-1)
62 return .handled
63 }
64 if press.key == .return || press.key == .tab, let selection, let line = line(selection) {
65 open(line)
66 return .handled
67 }
68 if press.key == .space, let selection {
69 jump(selection, focus: false)
70 return .handled
71 }
72 if press.modifiers == .shift, press.key == .rightArrow || press.key == .leftArrow {
73 run(ShiftTimestampDay(later: press.key == .rightArrow), atMarker: true)
74 return .handled
75 }
76 guard press.modifiers.subtracting(.shift).isEmpty else { return .ignored }
77 switch press.characters {
78 case "n": step(1)
79 case "p": step(-1)
80 case "f" where isAgenda: move(forward: true)
81 case "b" where isAgenda: move(forward: false)
82 case "." where isAgenda: goToday()
83 case "j" where isAgenda:
84 pickedDate = Self.date(anchorDay)
85 showingDatePicker = true
86 case "v" where isAgenda:
87 prefix = "v"
88 message = "v-"
89 case "d" where isAgenda: setSpan(.day)
90 case "w" where isAgenda: setSpan(.week)
91 case "k" where isAgenda: capture(on: anchorDay)
92 case "s":
93 commands.run("app.save-all")
94 message = "Saved"
95 case "/", "\\", "=", "_": askFilter(press.characters.first!)
96 case "<": toggleCategoryFilter()
97 case "|":
98 filter = AgendaFilter()
99 message = "Filters removed"
100 case "l" where isAgenda:
101 logMode.toggle()
102 message = logMode ? "Log mode on" : "Log mode off"
103 case "g", "r":
104 loadViews()
105 tick += 1
106 case "I": clockIn()
107 case "O": message = clock.clockOut(session)
108 case "X": message = clock.clockOut(session, cancel: true)
109 case "$": archive()
110 case "m": mark(true)
111 case "u": mark(false)
112 case "U":
113 marked = []
114 message = "No entries marked"
115 case "B": askBulk()
116 case "t": run(TodoCycle())
117 case "+": run(PriorityUp())
118 case "-": run(PriorityDown())
119 case ",": run(SetPriority())
120 case ":": run(SetTags())
121 default: return .ignored
122 }
123 return .handled
124 }
125
126 // MARK: - Clock, refile, archive, bulk
127
128 private var selectedEntry: EntryRef? { selection.flatMap(item).flatMap(EntryRef.init) }
129
130 func clockIn() {
131 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
132 message = "No entry selected"
133 return
134 }
135 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
136 Task {
137 let outcome = await clock.clockIn(session, target: .entry(path: entry.path, offset: offset), paths: paths, ask: commands.askClock)
138 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
139 message = outcome.messages.last { !$0.isEmpty }
140 tick += 1
141 }
142 }
143
144 func archive() {
145 guard let entry = selectedEntry, let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
146 message = "No entry selected"
147 return
148 }
149 #if APPSTORE
150 guard commands.reach(session.archiveFile(from: (entry.path, offset)).map { [$0] } ?? []) else { return }
151 #endif
152 message = session.archive(from: (entry.path, offset))
153 tick += 1
154 }
155
156 /// Refiles the selected entry, or with `marked` the marked ones, to a target chosen from a
157 /// searchable list.
158 private func refile(marked bulk: Bool) {
159 let entries = bulk ? marked : selectedEntry.map { [$0] } ?? []
160 guard !entries.isEmpty else {
161 message = "No entry selected"
162 return
163 }
164 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
165 ask(Prompt(key: "refile", message: String(localized: "Refile to:"), choices: targets.map(\.label))) { answer in
166 guard targets.contains(where: { $0.label == answer }) else { return }
167 message = eachEntry(entries) { entry, offset in
168 // Targets in the entry's own file from its text now, as earlier moves shift them.
169 let document = session.openDocuments.first { $0.path == entry.path }?.document
170 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
171 guard let target = workspace.refileTargets(openPath: entry.path, document: document).first(where: { $0.label == answer }) else {
172 return "Can't find \(answer) any more."
173 }
174 return session.refile(to: target, from: (entry.path, offset))
175 }
176 if bulk { marked = [] }
177 tick += 1
178 }
179 }
180
181 /// Runs `action` on each entry, finding it again first: later entries in a file first, so
182 /// earlier ones keep their place. Returns the last message.
183 private func eachEntry(_ entries: [EntryRef], _ action: (EntryRef, Int) -> String?) -> String? {
184 var last: String?
185 var failed = 0
186 for entry in entries.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
187 guard let offset = session.locateHeading(path: entry.path, line: entry.line, near: entry.offset) else {
188 failed += 1
189 continue
190 }
191 last = action(entry, offset)
192 }
193 return failed > 0 ? String(localized: "\(failed) marked entries changed and were skipped") : last
194 }
195
196 func mark(_ on: Bool) {
197 guard let entry = selectedEntry else {
198 message = "No entry selected"
199 return
200 }
201 if on {
202 if !marked.contains(entry) { marked.append(entry) }
203 } else {
204 marked.removeAll { $0 == entry }
205 }
206 message = "\(marked.count) marked"
207 }
208
209 /// `B`: an action for every marked entry.
210 private func askBulk() {
211 guard !marked.isEmpty else {
212 message = "No entries are marked"
213 return
214 }
215 ask(Prompt(key: "action", message: String(localized: "Bulk action on \(marked.count): [$] archive [r] refile [t] TODO state [+] tag [-] untag [s] schedule [d] deadline"))) { answer in
216 switch answer.trimmingCharacters(in: .whitespaces) {
217 case "$": bulk { session.archive(from: ($0.path, $1)) }
218 case "r": refile(marked: true)
219 case "t":
220 ask(Prompt(key: "todo", message: String(localized: "TODO state (empty for none):"))) { keyword in
221 let word = keyword.trimmingCharacters(in: .whitespaces)
222 bulk { performAt($0, $1, SetTodo(keyword: word.isEmpty ? nil : word)) }
223 }
224 case "+", "-":
225 let on = answer.trimmingCharacters(in: .whitespaces) == "+"
226 ask(Prompt(key: "tag", message: on ? String(localized: "Tag to add:") : String(localized: "Tag to remove:"))) { tag in
227 let tag = tag.trimmingCharacters(in: .whitespaces)
228 guard !tag.isEmpty else { return }
229 bulk { performAt($0, $1, ToggleTag(tag: tag, on: on)) }
230 }
231 case "s", "d":
232 let deadline = answer.trimmingCharacters(in: .whitespaces) == "d"
233 ask(Prompt(key: "date", message: deadline ? String(localized: "Deadline (+2d, fri, 2026-10-12):") : String(localized: "Schedule (+2d, fri, 2026-10-12):"))) { date in
234 bulk { performAt($0, $1, SetPlanning(deadline: deadline), answers: ["date": date]) }
235 }
236 default:
237 message = "No bulk action \(answer)"
238 }
239 }
240 }
241
242 func bulk(_ action: (EntryRef, Int) -> String?) {
243 message = eachEntry(marked, action) ?? "Done with \(marked.count) entries"
244 marked = []
245 tick += 1
246 }
247
248 /// Runs `command` at the heading at `offset`, as `run` does for the selection.
249 private func performAt(_ entry: EntryRef, _ offset: Int, _ command: any OrgCommand, answers: [String: String] = [:]) -> String? {
250 switch session.perform(command, path: entry.path, at: offset, expect: (offset, entry.line), answers: answers) {
251 case .failed(let text): text
252 case .prompt: String(localized: "\(CommandTitle.localized(command.title)) needs an answer; run it on the entry itself", comment: "A command run from the agenda that asks a question")
253 default: nil
254 }
255 }
256
257 /// Runs `command` on the selected entry, at its heading or, with `atMarker`, at the
258 /// timestamp the entry is listed for.
259 func run(_ command: any OrgCommand, atMarker: Bool = false, answers: [String: String] = [:], itemID: String? = nil) {
260 guard let id = itemID ?? selection, let item = item(id), let path = item.path, let start = item.headingOffset else {
261 message = "No entry selected"
262 return
263 }
264 if atMarker, ![.deadline, .upcomingDeadline, .scheduled, .pastScheduled, .timestamp].contains(item.kind) {
265 message = "Only dated entries can move"
266 return
267 }
268 let offset = atMarker ? (item.markerOffset ?? start) : start
269 let step = session.perform(command, path: path, at: offset, expect: item.headingLine.map { (start, $0) }, answers: answers)
270 switch step {
271 case .prompt(let request):
272 ask(request) { answer in
273 run(command, atMarker: atMarker, answers: answers.merging([request.key: answer]) { $1 }, itemID: id)
274 }
275 case .failed(let text):
276 message = text
277 tick += 1
278 case .external:
279 message = "Not available from the agenda"
280 case .commit:
281 message = nil
282 tick += 1
283 }
284 }
285}