Clock options: rounding, switch state, clock out when done, effort !256

merged merged by cmc on 2026-10-11 09:05 UTC · krz/orgstar:clock-options into main

18 files changed, +321 −34

Layout: unified · split

Sources/OrgApp/ClockModel.swift +111 −1
@@ -48,6 +48,11 @@ public final class ClockModel {
4848 public private(set) var leftover: Date?
4949 /// A clock question is open (`org-clock-resolving-clocks`).
5050 public private(set) var isResolving = false
51 /// Where the effort reminder goes (`org-clock-notify-once-if-expired`); nil sets none.
52 @ObservationIgnored public var notifications: ReminderCenter?
53 /// The clocked entry's heading line as last seen, and its keyword, for
54 /// `org-clock-out-when-done`.
55 @ObservationIgnored private var watched: (line: String, keyword: String?)?
5156 private let file: URL
5257 private let defaults: UserDefaults
5358
@@ -110,6 +115,8 @@ public final class ClockModel {
110115 running = Running(path: path, start: start, heading: entry.title, startedAt: now)
111116 if let task = ClockTask.at(heading, in: updated, path: path) { push(task, session) }
112117 save()
118 watched = clockedHeading(path, session)
119 remindAtEffort(session, now: now)
113120 return "Clock starts at [\(start)]"
114121 case .failed(let message):
115122 return message
@@ -121,13 +128,16 @@ public final class ClockModel {
121128 /// `org-clock-out`, or `org-clock-cancel` with `cancel`.
122129 public func clockOut(_ session: DocumentSession, cancel: Bool = false, now: Date = Date()) -> String {
123130 guard let clock = running else { return "No active clock" }
131 notifications?.remove([Self.effortReminderID])
124132 switch session.perform(ClockOut(start: clock.start, cancel: cancel), path: clock.path, at: 0, expect: nil, now: now) {
125133 case .commit:
126134 running = nil
135 watched = nil
127136 save()
128137 if cancel { return "Clock canceled" }
129138 let minutes = Int(now.timeIntervalSince(clock.startedAt) / 60)
130 return String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60)
139 let removed = Self.text(clock.path, session).map { !$0.contains("CLOCK: [\(clock.start)]") } ?? false
140 return String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60) + (removed ? " => LINE REMOVED" : "")
131141 case .failed(let message):
132142 if message == "Clock start time is gone" || message == "No active clock" {
133143 running = nil
@@ -160,6 +170,104 @@ public final class ClockModel {
160170 return outcome
161171 }
162172
173 // MARK: - Done and effort
174
175 /// The heading line above the running clock's line in `text`.
176 private func clockedHeadingLine(_ text: String) -> String? {
177 guard let clock = running else { return nil }
178 let ns = text as NSString
179 var end = ns.range(of: "CLOCK: [\(clock.start)]").location
180 guard end != NSNotFound else { return nil }
181 while end > 0 {
182 let newline = ns.range(of: "\n", options: .backwards, range: NSRange(location: 0, length: end)).location
183 let start = newline == NSNotFound ? 0 : newline + 1
184 let line = ns.substring(with: ns.lineRange(for: NSRange(location: start, length: 0))).trimmingCharacters(in: .newlines)
185 if line.range(of: "^\\*+ ", options: .regularExpression) != nil { return line }
186 guard newline != NSNotFound else { return nil }
187 end = newline
188 }
189 return nil
190 }
191
192 /// The clocked entry's heading line and keyword.
193 private func clockedHeading(_ path: String, _ session: DocumentSession) -> (line: String, keyword: String?)? {
194 guard let text = Self.text(path, session), let heading = clockedHeadingLine(text) else { return nil }
195 let settings = OrgParser.parse(text, defaults: session.defaults).settings
196 let word = String(heading.drop { $0 == "*" }.drop { $0 == " " }.prefix { !$0.isWhitespace })
197 let keywords = settings.todoSequences.flatMap { $0.active + $0.done }.map(\.name)
198 return (heading, keywords.contains(word) ? word : nil)
199 }
200
201 /// `org-clock-out-if-current`: clocks out when the clocked entry's keyword became one of
202 /// `org-clock-out-when-done`'s (any done keyword for `t`). Returns the message.
203 public func textChanged(_ path: String, _ session: DocumentSession, now: Date = Date()) -> String? {
204 guard let clock = running, clock.path == path, let states = OrgPreferences.clockOutWhenDone(defaults),
205 let text = Self.text(path, session), let line = clockedHeadingLine(text), line != watched?.line,
206 let current = clockedHeading(path, session) else { return nil }
207 let before = watched
208 watched = current
209 guard let before else { return nil }
210 let settings = OrgParser.parse(text, defaults: session.defaults).settings
211 func stops(_ keyword: String?) -> Bool {
212 guard let keyword else { return false }
213 return states.isEmpty ? settings.isDone(keyword) : states.contains(keyword)
214 }
215 guard stops(current.keyword), !stops(before.keyword) else { return nil }
216 return clockOut(session, now: now)
217 }
218
219 static let effortReminderID = "orgstar-effort"
220
221 /// The running clock's entry: its Effort in minutes, and the minutes clocked on it before
222 /// this clock (`org-clock-sum-current-item` from `org-clock-get-sum-start`).
223 public func effort(_ session: DocumentSession, now: Date = Date(), calendar: Calendar = .current) -> (effort: Int, clocked: Int, value: String)? {
224 guard let clock = running, let text = Self.text(clock.path, session) else { return nil }
225 let line = (text as NSString).range(of: "CLOCK: [\(clock.start)]")
226 guard line.location != NSNotFound else { return nil }
227 let model = DocumentModel(tree: OrgParser.parse(text, defaults: session.defaults))
228 guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= line.location }),
229 let value = model.headings[index].properties.last(where: { $0.key.uppercased() == "EFFORT" })?.value,
230 let effort = ColumnView.minutes(value), effort > 0 else { return nil }
231 let own = { (key: String) in model.headings[index].properties.last { $0.key.uppercased() == key }?.value }
232 func day(_ p: Timestamp.Point) -> Date? { calendar.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour ?? 0, minute: p.minute ?? 0)) }
233 let since: Date? = switch own("CLOCK_MODELINE_TOTAL") ?? "auto" {
234 case "current": .distantFuture
235 case "today": calendar.startOfDay(for: now)
236 case "all": nil
237 default: own("LAST_REPEAT").flatMap { stamp in Timestamp.parse(stamp).flatMap { day($0.start) } }
238 }
239 let level = model.headings[index].level
240 var subtree = [index]
241 for i in (index + 1)..<model.headings.count {
242 guard model.headings[i].level > level else { break }
243 subtree.append(i)
244 }
245 let clocked = subtree.flatMap { model.headings[$0].clocks }.filter { clock in
246 guard clock.end != nil else { return false }
247 guard let since else { return true }
248 return day(clock.start).map { $0 >= since } ?? false
249 }.compactMap(\.minutes).reduce(0, +)
250 return (Int(effort), clocked, value)
251 }
252
253 /// A notification when the running clock passes the entry's Effort, as
254 /// `org-clock-notify-once-if-expired` shows: "Task `…' should be finished by now. (1:00)".
255 public func remindAtEffort(_ session: DocumentSession, now: Date = Date()) {
256 guard let notifications else { return }
257 notifications.remove([Self.effortReminderID])
258 guard let clock = running, let status = effort(session, now: now) else { return }
259 let due = clock.startedAt.addingTimeInterval(Double((status.effort - status.clocked) * 60))
260 let fire = max(due, now.addingTimeInterval(1))
261 let location = location(session)
262 let reminder = Reminder(id: Self.effortReminderID, fireDate: fire, eventDate: fire, title: "Effort used up",
263 body: "Task `\(clock.heading)' should be finished by now. (\(status.value))",
264 path: clock.path, offset: location?.offset ?? 0)
265 Task {
266 guard await notifications.authorize() else { return }
267 try? await notifications.add(reminder)
268 }
269 }
270
163271 static func text(_ path: String, _ session: DocumentSession) -> String? {
164272 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
165273 }
@@ -510,6 +618,8 @@ public final class ClockModel {
510618 running = Running(path: clock.path, start: clock.start, heading: clock.heading, startedAt: clock.startedAt)
511619 if let task { push(task, session) }
512620 save()
621 watched = clockedHeading(clock.path, session)
622 remindAtEffort(session)
513623 messages.append("Clock starts at [\(clock.start)]")
514624 }
515625 }
Sources/OrgApp/DocumentSession.swift +4
@@ -80,6 +80,8 @@ public final class DocumentSession {
8080 public var autosaveDelay: Duration = .seconds(1)
8181 /// Org options for commands the session runs (refile, archive).
8282 public var options: EditingOptions = .org
83 /// Called with a file's path after its text changed through the session, typed or not.
84 @ObservationIgnored public var textChanged: ((String) -> Void)?
8385 /// TODO keywords and priorities for files without their own settings.
8486 public var defaults: OrgSettings = .default
8587
@@ -345,6 +347,7 @@ public final class DocumentSession {
345347 }
346348 scheduleAutosave(entry)
347349 refreshLists()
350 textChanged?(entry.path)
348351 }
349352
350353 /// `pane`'s view of its buffer, from the buffer's state.
@@ -757,6 +760,7 @@ public final class DocumentSession {
757760 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
758761 return .failed("\(name) changed on disk; nothing was changed.")
759762 }
763 if case .commit = step { textChanged?(path) }
760764 return step
761765 } catch {
762766 return .failed("Can't change \(name): \(error.localizedDescription)")
Sources/OrgApp/EmacsImport.swift +14 −1
@@ -487,7 +487,7 @@ 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":
490 "org-agenda-todo-ignore-with-date", "org-agenda-tags-todo-honor-ignore-options", "org-clock-out-remove-zero-time-clocks":
491491 add(name, .bool(truthy))
492492 case "org-archive-location":
493493 guard let location = value.string, location.contains("::") else { return note("not a file::heading location") }
@@ -543,6 +543,19 @@ public struct EmacsImport: Sendable {
543543 case "org-clock-idle-time":
544544 // nil is never; a number is minutes.
545545 if value.symbol == "nil" { add(name, .integer(0)) } else if let minutes = value.integer, minutes > 0 { add(name, .integer(minutes)) } else { note("not a number of minutes") }
546 case "org-clock-rounding-minutes":
547 guard let n = value.integer, n >= 0 else { return note("not a number of minutes") }
548 add(name, .integer(n))
549 case "org-clock-in-switch-to-state":
550 if let state = value.string { add(name, .string(state)) } else if value.symbol == "nil" { add(name, .string("")) } else { note("a function isn't supported; use a keyword") }
551 case "org-clock-out-when-done":
552 if let states = value.elements, !states.isEmpty {
553 let names = states.compactMap(\.string)
554 guard names.count == states.count else { return note("not a list of keywords") }
555 add(name, .string(names.joined(separator: " ")))
556 } else {
557 add(name, .string(truthy ? "t" : "nil"))
558 }
546559 case "org-clock-into-drawer":
547560 if let drawer = value.string { add(name, .string(drawer)) } else if let n = value.integer { add(name, .string("\(n)")) } else { add(name, .string(truthy ? "t" : "nil")) }
548561 case "org-clock-history-length":
Sources/OrgApp/OrgPreferences.swift +10
@@ -37,6 +37,9 @@ public enum OrgPreferences {
3737 options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults)
3838 options.archiveLocation = string("archiveLocation", defaults).nonEmpty
3939 options.clockIntoDrawer = string("clockIntoDrawer", defaults).nonEmpty
40 options.clockRoundingMinutes = integer("clockRoundingMinutes", defaults)
41 options.clockOutRemoveZeroTimeClocks = bool("clockRemoveZeroTime", defaults)
42 options.clockInSwitchToState = string("clockInSwitchToState", defaults).nonEmpty
4043 let templates = UserConfig.structureTemplates(defaults)
4144 options.structureTemplates = templates.isEmpty ? nil : StructureTemplate.merged(templates)
4245 options.trackOrderedPropertyWithTag = switch string("trackOrderedTag", defaults) {
@@ -64,6 +67,13 @@ public enum OrgPreferences {
6467 public static func agendaStartOffset(_ defaults: UserDefaults = .standard) -> Int { integer("agendaStartOffset", defaults) }
6568 /// `org-agenda-start-on-weekday`: 0 is Sunday; nil for `nil`.
6669 public static func agendaStartOnWeekday(_ defaults: UserDefaults = .standard) -> Int? { Int(string("agendaStartOnWeekday", defaults)) }
70 /// `org-clock-out-when-done`: nil when marking an entry done doesn't clock out, an empty
71 /// set for any done keyword, else the keywords that do.
72 public static func clockOutWhenDone(_ defaults: UserDefaults = .standard) -> Set<String>? {
73 let words = string("clockOutWhenDone", defaults).split(whereSeparator: \.isWhitespace).map(String.init)
74 if words == ["nil"] { return nil }
75 return words == ["t"] || words.isEmpty ? [] : Set(words)
76 }
6777 public static func agendaSubfolders(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaSubfolders", defaults) }
6878 /// `org-agenda-show-all-dates`: days without entries show.
6979 public static func agendaShowAllDates(_ defaults: UserDefaults = .standard) -> Bool { bool("agendaShowAllDates", defaults) }
Sources/OrgApp/UserConfig.swift +8
@@ -187,6 +187,14 @@ public enum UserConfig {
187187 comment: "minutes idle with a clock running before asking what to do with the time; 0 never (nil)", legacy: ""),
188188 Setting(section: "", key: "org-clock-into-drawer", defaultsKey: "clockIntoDrawer", kind: .string, fallback: .string("t"),
189189 comment: "t: clock lines go in the log drawer (LOGBOOK); nil: none; a number: once there are that many; or a drawer name", legacy: ""),
190 Setting(section: "", key: "org-clock-rounding-minutes", defaultsKey: "clockRoundingMinutes", kind: .integer, fallback: .integer(0),
191 comment: "clocks start and end on multiples of this many minutes; 0 doesn't round", legacy: ""),
192 Setting(section: "", key: "org-clock-out-remove-zero-time-clocks", defaultsKey: "clockRemoveZeroTime", kind: .bool, fallback: .bool(false),
193 comment: "clocking out removes a clock line of 0:00", legacy: ""),
194 Setting(section: "", key: "org-clock-in-switch-to-state", defaultsKey: "clockInSwitchToState", kind: .string, fallback: .string(""),
195 comment: "the TODO keyword an entry takes when you clock in; \"\" leaves it", legacy: ""),
196 Setting(section: "", key: "org-clock-out-when-done", defaultsKey: "clockOutWhenDone", kind: .string, fallback: .string("t"),
197 comment: "t: marking the clocked entry done clocks out; nil: it doesn't; or keywords that clock out, separated by spaces", legacy: ""),
190198 Setting(section: "", key: "org-clock-history-length", defaultsKey: "clockHistoryLength", kind: .integer, fallback: .integer(5),
191199 comment: "recently clocked entries to remember", legacy: ""),
192200 Setting(section: "org-agenda-prefix-format", key: "agenda", defaultsKey: "agendaPrefixAgenda", kind: .string, fallback: .string(PrefixFormat.defaults["agenda"]!),
Sources/OrgCore/Commands/Clock.swift +40 −6
@@ -1,8 +1,9 @@
11import Foundation
22
33// Clocking (org-clock.el, Org 9.8.7) with `org-clock-into-drawer` and the CLOCK_INTO_DRAWER
4// property, `org-log-states-order-reversed` t (newest first), no rounding, no resume, and
5// zero-time clocks kept.
4// property, `org-clock-rounding-minutes`, `org-clock-out-remove-zero-time-clocks`,
5// `org-clock-in-switch-to-state`, `org-log-states-order-reversed` t (newest first) and no
6// resume.
67
78extension EmacsBuffer {
89 /// What `org-clock-into-drawer` comes to for an entry.
@@ -118,9 +119,38 @@ extension EmacsBuffer {
118119 forwardLine(1)
119120 }
120121
122 /// `org-current-time` with `org-clock-rounding-minutes`: the minute rounded to a multiple,
123 /// with `past` one not after now.
124 func clockTime(past: Bool) -> Date {
125 let r = options.clockRoundingMinutes
126 guard r >= 1 else { return now }
127 var c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: now)
128 c.minute = r * Int((Double(c.minute!) / Double(r)).rounded(.toNearestOrEven))
129 c.second = 0
130 guard let rounded = calendar.date(from: c) else { return now }
131 return !past || rounded < now ? rounded : rounded.addingTimeInterval(-Double(r * 60))
132 }
133
134 /// `org-clock-in-switch-to-state` on the heading at point, unless it has that keyword.
135 func switchToClockInState(answers: [String: String]) throws {
136 guard let state = options.clockInSwitchToState, !state.isEmpty else { return }
137 try saveExcursion {
138 try backToHeading()
139 let previous = todoKeyword
140 guard previous != state else { return }
141 guard keywordsInOrder.contains(state) else { throw UserError(message: "State `\(state)' not valid in this file") }
142 // `org-todo` stops at a blocker, and clocking in goes on.
143 guard (try? checkTodoBlocking(from: previous, to: state)) != nil else { return }
144 setTodoKeyword(state)
145 var answers = answers
146 if answers["note"] == nil { answers["note"] = "" }
147 try afterTodoChange(previous: previous, answers: answers)
148 }
149 }
150
121151 /// `org-clock-in` on the heading at point. Returns the clock's start stamp.
122152 @discardableResult
123 func clockIn() throws -> String {
153 func clockIn(answers: [String: String] = [:]) throws -> String {
124154 let start = point
125155 let pointMarker = marker(start)
126156 defer {
@@ -128,6 +158,7 @@ extension EmacsBuffer {
128158 release(pointMarker)
129159 }
130160 if eobp, !atHeadingLine { point = lineStart(max(0, lineStart(point) - 1)) }
161 try switchToClockInState(answers: answers)
131162 try clockFindPosition()
132163 insertBeforeMarkers("\n")
133164 point -= 1
@@ -140,7 +171,7 @@ extension EmacsBuffer {
140171 indentLineTo(max(0, current - 2))
141172 }
142173 insert("CLOCK: ")
143 let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: now)
174 let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: clockTime(past: true))
144175 let stamp = insertTimestamp(components, withTime: true, inactive: true)
145176 // `org-indent-line` puts lines in a drawer at column 0 without adapted indentation.
146177 let lineText = substring(lineStart(point), lineEnd(point))
@@ -168,7 +199,7 @@ extension EmacsBuffer {
168199 point = match[0]!.upperBound
169200 deleteRegion(point, lineEnd(point))
170201 insert("--")
171 let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: now)
202 let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: clockTime(past: false))
172203 let end = insertTimestamp(components, withTime: true, inactive: true)
173204 guard let startTime = Self.parseTimeString(start), let endTime = Self.parseTimeString(String(end.dropFirst().dropLast())),
174205 let a = calendar.date(from: startTime), let b = calendar.date(from: endTime) else { throw UserError(message: "Clock start time is gone") }
@@ -176,6 +207,9 @@ extension EmacsBuffer {
176207 let hours = Int((Double(seconds) / 3600).rounded(.down))
177208 let minutes = Int((Double(seconds - hours * 3600) / 60).rounded(.down))
178209 insert(" => " + String(format: "%2d:%02d", hours, minutes))
210 if options.clockOutRemoveZeroTimeClocks, hours == 0, minutes == 0 {
211 deleteRegion(lineStart(point), min(length, lineEnd(point) + 1))
212 }
179213 removeEmptyClockDrawer()
180214 }
181215
@@ -226,7 +260,7 @@ public struct ClockIn: OrgCommand {
226260 public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
227261 public func run(in context: EditContext) -> CommandStep {
228262 guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
229 return commitBuffer(context) { try $0.clockIn() }
263 return commitBuffer(context) { try $0.clockIn(answers: context.answers) }
230264 }
231265
232266 /// The start of the clock `ClockIn` left running in the entry at `offset`.
Sources/OrgCore/Commands/ColumnView.swift +1 −1
@@ -90,7 +90,7 @@ public enum ColumnView {
9090 static let unitMinutes: [(String, Double)] = [("min", 1), ("h", 60), ("d", 1440), ("w", 10080), ("m", 43200), ("y", 525960)]
9191
9292 /// `org-duration-to-minutes`.
93 static func minutes(_ duration: String) -> Double? {
93 public static func minutes(_ duration: String) -> Double? {
9494 let s = duration.trimmingCharacters(in: .whitespaces)
9595 if s.isEmpty { return 0 }
9696 if s.wholeMatch(of: /[0-9]+(?::[0-9]{2}){1,2}/) != nil {
Sources/OrgCore/Commands/Command.swift +6
@@ -27,6 +27,12 @@ public struct EditingOptions: Sendable, Equatable, Codable {
2727 public var enforceTodoDependencies = false
2828 /// `org-enforce-todo-checkbox-dependencies`: an entry can't become done with unchecked boxes.
2929 public var enforceTodoCheckboxDependencies = false
30 /// `org-clock-rounding-minutes`: clocks start and end on multiples of this many minutes.
31 public var clockRoundingMinutes = 0
32 /// `org-clock-out-remove-zero-time-clocks`.
33 public var clockOutRemoveZeroTimeClocks = false
34 /// `org-clock-in-switch-to-state`: the keyword an entry takes when clocked in.
35 public var clockInSwitchToState: String?
3036 /// `org-clock-into-drawer` as `config.toml` writes it: `nil`, `t`, a number of clock lines,
3137 /// or a drawer name; nil for Org's default, `t`.
3238 public var clockIntoDrawer: String?
Sources/Orgstar/ContentView.swift +12 −1
@@ -52,8 +52,11 @@ struct ContentView: View {
5252 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
5353 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
5454
55 /// Bumped when user defaults change, so settings only config.toml has reach `options`.
56 @State private var defaultsChanges = 0
5557 private var options: EditingOptions {
56 Preferences.options(
58 _ = defaultsChanges
59 return Preferences.options(
5760 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
5861 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
5962 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
@@ -284,6 +287,13 @@ struct ContentView: View {
284287 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
285288 .onAppear {
286289 commands.externalHandler = runExternal
290 // `org-clock-out-when-done`, and the notification when the Effort runs out.
291 clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
292 session.textChanged = { [weak session, weak clock, weak commands] path in
293 guard let session, let clock, let message = clock.textChanged(path, session) else { return }
294 commands?.show(message)
295 }
296 clock.remindAtEffort(session)
287297 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
288298 commands.mainWindowOpen = true
289299 if let stale = window { commands.store.windows.removeAll { $0 === stale } }
@@ -311,6 +321,7 @@ struct ContentView: View {
311321 }
312322 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
313323 .onChange(of: options, initial: true) { _, options in session.options = options }
324 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
314325 .onChange(of: preset, initial: true) { loadKeymap() }
315326 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
316327 .sheet(item: $panel) { panel in
Sources/Orgstar/Preferences.swift +23 −11
@@ -21,17 +21,29 @@ enum Preferences {
2121 startupIndented: Bool, hideLeadingStars: Bool, startupAlignAllTables: Bool, startupTruncated: Bool, spellCheck: Bool, electricPair: Bool,
2222 enforceTodoDependencies: Bool, enforceTodoCheckboxDependencies: Bool
2323 ) -> EditingOptions {
24 var options = EditingOptions(
25 tagsColumn: tagsColumn, insertHeadingRespectContent: headingAfterSubtree,
26 metaReturnMaySplitLine: splitLine, listAllowAlphabetical: alphabeticalLists, fillColumn: fillColumn,
27 hideEmphasisMarkers: hiddenMarkers, prettyEntities: prettyEntities, subSuperscriptsNeedBraces: true,
28 logDone: LogHow(rawValue: logDone), logIntoDrawer: logIntoDrawer.isEmpty ? nil : logIntoDrawer,
29 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup,
30 logReschedule: LogHow(rawValue: logReschedule), logRedeadline: LogHow(rawValue: logRedeadline),
31 useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
32 startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
33 startupTruncated: startupTruncated, spellCheck: spellCheck
34 )
24 // The settings only config.toml has, under those the Settings window binds.
25 var options = OrgPreferences.options()
26 options.tagsColumn = tagsColumn
27 options.insertHeadingRespectContent = headingAfterSubtree
28 options.metaReturnMaySplitLine = splitLine
29 options.listAllowAlphabetical = alphabeticalLists
30 options.fillColumn = fillColumn
31 options.hideEmphasisMarkers = hiddenMarkers
32 options.prettyEntities = prettyEntities
33 options.subSuperscriptsNeedBraces = true
34 options.logDone = LogHow(rawValue: logDone)
35 options.logIntoDrawer = logIntoDrawer.isEmpty ? nil : logIntoDrawer
36 options.hideDrawerStartup = hideDrawerStartup
37 options.hideBlockStartup = hideBlockStartup
38 options.logReschedule = LogHow(rawValue: logReschedule)
39 options.logRedeadline = LogHow(rawValue: logRedeadline)
40 options.useSpeedCommands = useSpeedCommands
41 options.startupWithInlineImages = startupWithInlineImages
42 options.startupIndented = startupIndented
43 options.hideLeadingStars = hideLeadingStars
44 options.startupAlignAllTables = startupAlignAllTables
45 options.startupTruncated = startupTruncated
46 options.spellCheck = spellCheck
3547 options.electricPair = electricPair
3648 options.enforceTodoDependencies = enforceTodoDependencies
3749 options.enforceTodoCheckboxDependencies = enforceTodoCheckboxDependencies
Sources/OrgstarMobile/MobileModel.swift +7
@@ -82,6 +82,13 @@ final class MobileModel {
8282 applySettings(colors)
8383 shareTemplates()
8484 watchConfig()
85 // `org-clock-out-when-done`, and the reminder when the Effort runs out.
86 clock.notifications = SystemReminderCenter()
87 session.textChanged = { [weak self] path in
88 guard let self else { return }
89 _ = self.clock.textChanged(path, self.session)
90 }
91 clock.remindAtEffort(session)
8592 // A new Dynamic Type size restyles editors and the reader.
8693 sizeObserver = NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] _ in
8794 MainActor.assumeIsolated { self?.settingsVersion += 1 }
Tests/OrgAppTests/AppTests.swift +33
@@ -1006,6 +1006,39 @@ struct ClockModelTests {
10061006 let text = try String(contentsOf: work, encoding: .utf8)
10071007 #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=> 1:35\n:END:\nBody\n"), "\(text)")
10081008 }
1009
1010 /// `org-clock-out-when-done`, through the session's text-changed hook, and the Effort
1011 /// notification.
1012 @Test func clocksOutWhenDoneAndRemindsAtEffort() async throws {
1013 let notes = try Folder()
1014 let work = try notes.write("work.org", "* TODO Task\n:PROPERTIES:\n:Effort: 1:00\n:END:\n:LOGBOOK:\nCLOCK: [2026-09-01 Tue 09:00]--[2026-09-01 Tue 09:20] => 0:20\n:END:\n** Sub\n:LOGBOOK:\nCLOCK: [2026-09-02 Wed 09:00]--[2026-09-02 Wed 09:10] => 0:10\n:END:\n")
1015 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1016 let defaults = try #require(UserDefaults(suiteName: "orgstar-clock-done-\(UUID().uuidString)"))
1017 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"), defaults: defaults)
1018 let center = FakeReminderCenter()
1019 clock.notifications = center
1020 var messages: [String] = []
1021 session.textChanged = { path in if let message = clock.textChanged(path, session) { messages.append(message) } }
1022 let start = Date(timeIntervalSince1970: 1_789_000_000)
1023 _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1024 #expect(clock.running != nil)
1025 // An hour of effort, half an hour clocked in the subtree before.
1026 #expect(clock.effort(session, now: start).map { [$0.effort, $0.clocked] } == [60, 30])
1027 for _ in 0..<200 where center.added.isEmpty { try await Task.sleep(for: .milliseconds(10)) }
1028 #expect(center.added == ["orgstar-effort"])
1029 // Marking it done from an unopened file's command clocks out.
1030 _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1031 #expect(clock.running == nil && messages.count == 1)
1032 let text = try String(contentsOf: work, encoding: .utf8)
1033 #expect(!text.contains(#/CLOCK: \[[^\]]+\]\n/#), "\(text)")
1034
1035 // nil keeps it running.
1036 UserConfig.apply("org-clock-out-when-done = \"nil\"\n", to: defaults)
1037 _ = session.perform(SetTodo(keyword: "TODO"), path: work.path, at: 2, expect: nil)
1038 _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1039 _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1040 #expect(clock.running != nil)
1041 }
10091042}
10101043
10111044@MainActor
Tests/OrgAppTests/EmacsImportTests.swift +4 −1
@@ -49,6 +49,8 @@ struct EmacsImportTests {
4949 org-agenda-todo-ignore-deadlines 7
5050 org-agenda-log-mode-items '(closed clock state)
5151 org-clock-into-drawer "CLOCKS"
52 org-clock-rounding-minutes 5
53 org-clock-out-when-done '("DONE" "KILL")
5254 org-agenda-start-day "-3d"
5355 org-clock-idle-time 15
5456 org-clock-history-length 10
@@ -95,6 +97,7 @@ struct EmacsImportTests {
9597 #expect(s["org-track-ordered-property-with-tag"] == .string("t"))
9698 #expect(s["org-archive-location"] == .string("archive/%s::"))
9799 #expect(s["org-agenda-log-mode-items"] == .string("closed clock state") && s["org-clock-into-drawer"] == .string("CLOCKS"))
100 #expect(s["org-clock-rounding-minutes"] == .integer(5) && s["org-clock-out-when-done"] == .string("DONE KILL"))
98101 #expect(s["org-agenda-todo-ignore-scheduled"] == .string("future") && s["org-agenda-todo-ignore-deadlines"] == .string("7"))
99102 #expect(s["org-agenda-start-day"] == .string("-3d"))
100103 #expect(s["org-clock-idle-time"] == .integer(15))
@@ -187,7 +190,7 @@ struct EmacsImportTests {
187190 let keymap = folder.appendingPathComponent("keymap.toml")
188191 #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty)
189192 #expect(KeymapLoader.load(.doom, userFile: keymap).keymap.keyLabels(for: "app.agenda", modes: ["normal"]).contains("C-c a"))
190 #expect(summary.hasPrefix("Imported 27 settings, 3 capture templates, 3 key bindings, 2 structure templates."), "\(summary)")
193 #expect(summary.hasPrefix("Imported 29 settings, 3 capture templates, 3 key bindings, 2 structure templates."), "\(summary)")
191194 #expect(UserConfig.structureTemplates(defaults) == [.init(key: "el", type: "src emacs-lisp"), .init(key: "q", type: "QUOTE")])
192195 #expect(OrgPreferences.options(defaults).structureTemplates?.first { $0.key == "q" }?.type == "QUOTE")
193196 #expect(defaults.string(forKey: "themeFont") == "JetBrains Mono")
Tests/OrgAppTests/OrgPreferencesTests.swift +6
@@ -13,6 +13,7 @@ struct OrgPreferencesTests {
1313 #expect(OrgPreferences.agendaSpan(defaults) == 10 && OrgPreferences.agendaStartOffset(defaults) == 0)
1414 #expect(OrgPreferences.orgSettings(defaults).deadlineWarningDays == 14)
1515 #expect(OrgPreferences.agendaStartOnWeekday(defaults) == 1)
16 #expect(OrgPreferences.clockOutWhenDone(defaults) == [] && OrgPreferences.options(defaults).clockRoundingMinutes == 0)
1617 #expect(OrgPreferences.options(defaults).trackOrderedPropertyWithTag == nil)
1718 #expect(OrgPreferences.options(defaults).archiveLocation == "%s_archive::")
1819 #expect(OrgPreferences.agendaOptions(AgendaOptions(), defaults).deadlineWarningDays == 14)
@@ -36,6 +37,9 @@ struct OrgPreferencesTests {
3637 org-agenda-todo-ignore-scheduled = "-2"
3738 org-agenda-log-mode-items = "closed state"
3839 org-clock-into-drawer = "3"
40 org-clock-rounding-minutes = 5
41 org-clock-in-switch-to-state = "STRT"
42 org-clock-out-when-done = "DONE KILL"
3943 org-M-RET-may-split-line = true
4044 org-hide-emphasis-markers = false
4145 org-pretty-entities = false
@@ -54,6 +58,8 @@ struct OrgPreferencesTests {
5458 #expect(OrgPreferences.options(defaults).archiveLocation == "~/org/archive.org::* %s")
5559 let ignoring = OrgPreferences.agendaOptions(AgendaOptions(), defaults)
5660 #expect(ignoring.logItems == ["closed", "state"] && OrgPreferences.options(defaults).clockIntoDrawer == "3")
61 #expect(OrgPreferences.options(defaults).clockRoundingMinutes == 5 && OrgPreferences.options(defaults).clockInSwitchToState == "STRT")
62 #expect(OrgPreferences.clockOutWhenDone(defaults) == ["DONE", "KILL"])
5763 #expect(ignoring.todoIgnoreDeadlines == .near && ignoring.todoIgnoreScheduled == .days(-2) && ignoring.todoIgnoreTimestamp == .off)
5864 #expect(OrgPreferences.agendaOptions(AgendaOptions(), defaults).deadlineWarningDays == 5)
5965 #expect(!OrgPreferences.reminders(defaults) && OrgPreferences.reminderLead(defaults) == 30)
Tests/OrgCoreTests/ClockTests.swift +27 −9
@@ -57,9 +57,27 @@ struct ClockTests {
5757 }
5858 }
5959
60 func compare(_ texts: [String], lisp: String = "t", log: String = "nil", options: EditingOptions = .org) throws {
60 /// `org-clock-rounding-minutes`, `org-clock-out-remove-zero-time-clocks` and
61 /// `org-clock-in-switch-to-state`.
62 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
63 func optionsMatchEmacs() throws {
64 let texts = Self.texts + ["#+TODO: TODO NEXT | DONE\n* TODO Task\n", "#+TODO: TODO NEXT | DONE\n* NEXT Task\nBody\n"]
65 var rounding = EditingOptions.org
66 rounding.clockRoundingMinutes = 5
67 try compare(texts, extra: "org-clock-rounding-minutes 5", options: rounding)
68 try compare(texts, extra: "org-clock-rounding-minutes 15", options: { var o = EditingOptions.org; o.clockRoundingMinutes = 15; return o }(), length: 7 * 60)
69 var zero = EditingOptions.org
70 zero.clockOutRemoveZeroTimeClocks = true
71 try compare(texts, extra: "org-clock-out-remove-zero-time-clocks t", options: zero, length: 20)
72 var state = EditingOptions.org
73 state.clockInSwitchToState = "NEXT"
74 try compare(texts, extra: "org-clock-in-switch-to-state \"NEXT\"", options: state)
75 }
76
77 func compare(_ texts: [String], lisp: String = "t", log: String = "nil", extra: String = "", options: EditingOptions = .org,
78 length: Int = 3 * 3600 + 17 * 60 + 42) throws {
6179 let t1 = 1_789_000_000 // Thu 2026-09-10 00:26
62 let t2 = t1 + 3 * 3600 + 17 * 60 + 42
80 let t2 = t1 + length
6381 var cases: [EmacsOracle.Case] = []
6482 var ours: [(String, String)] = []
6583 for text in texts {
@@ -67,18 +85,18 @@ struct ClockTests {
6785 for mode in ["out", "cancel"] {
6886 // Clock in at t1, then out (or cancel) at t2.
6987 let first = run(ClockIn(), text, caret: caret, at: t1, options: options)
70 guard let start = ClockIn.runningStart(in: first.text, near: caret) else {
71 ours.append(("no running clock: \(first.failure ?? "")", text))
72 cases.append(EmacsOracle.Case(text: text, point: 1, form: "nil"))
73 continue
88 // Clocking in failed: the text stays, as Emacs's does when it signals.
89 if let start = ClockIn.runningStart(in: first.text, near: caret) {
90 let second = run(ClockOut(start: start, cancel: mode == "cancel"), first.text, caret: first.caret, at: t2, options: options)
91 ours.append((second.text, first.text))
92 } else {
93 ours.append((first.text, first.failure ?? ""))
7494 }
75 let second = run(ClockOut(start: start, cancel: mode == "cancel"), first.text, caret: first.caret, at: t2, options: options)
76 ours.append((second.text, first.text))
7795 let out = mode == "cancel" ? "(org-clock-cancel)" : "(org-clock-out)"
7896 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
7997 (progn
8098 (require 'org-clock)
81 (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer \(lisp) org-log-into-drawer \(log))
99 (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer \(lisp) org-log-into-drawer \(log) \(extra))
82100 \(frozenClock(t1, "(org-clock-in)"))
83101 (setq orgstar-after-in (buffer-substring-no-properties (point-min) (point-max)))
84102 \(frozenClock(t2, out)))
docs/manual/guide/06-dates-and-clocking.org +6 −2
@@ -239,7 +239,11 @@ CLOCK: [2026-10-06 Tue 14:00]--[2026-10-06 Tue 15:30] => 1:30
239239- Only one clock runs at a time. Clocking in while another clock runs clocks that one out first, and remembers it as the interrupted task (=i= in the selection below).
240240- Clocking in on the entry whose clock is running changes nothing and says =Clock continues in "Write the report"=.
241241- =CLOCK:= lines outside a drawer move into the new drawer the first time you clock in on that entry.
242- Clock Out completes the line with the end time and the duration in hours and minutes. Clocks of zero minutes are kept.
242- With =org-clock-in-switch-to-state= set to a keyword in =config.toml=, Clock In gives the entry that keyword first (unless it has it), logging and checking dependencies as =C-c C-t= does. A file without the keyword can't be clocked in, as in Org: "State `NEXT' not valid in this file".
243- Clock Out completes the line with the end time and the duration in hours and minutes. Clocks of zero minutes are kept, unless =org-clock-out-remove-zero-time-clocks= is =true=; then the line goes and the message ends with "LINE REMOVED".
244- With =org-clock-rounding-minutes= set to N, the clock starts at the multiple of N minutes nearest now that isn't later, and stops at the nearest multiple; with 5, clocking in at 14:47 starts at 14:45.
245- Marking the clocked entry done clocks out (=org-clock-out-when-done=, on by default as in Org; set it to ="nil"= to keep the clock running, or to keywords that clock out). orgstar watches the entry's heading line, so typing a done keyword yourself clocks out too.
246- When the entry has an =Effort=, a notification says "Task `…' should be finished by now. (1:00)" once the time clocked on it and its subtree passes it, counting earlier clocks as =org-clock-mode-line-total= =auto= does (since =LAST_REPEAT= for a repeating task) or as its =CLOCK_MODELINE_TOTAL= says.
243247- Cancel Clock removes the running clock's line, and the drawer if it is left empty.
244248- Go to Clocked Entry opens the file and moves the caret to the running clock's line. With no clock running, it goes to the most recently clocked entry and says "No running clock, this is the most recently clocked task".
245249
@@ -250,7 +254,7 @@ orgstar remembers the running clock and the clock history across restarts, in =c
250254These parts of Org's clocking are not implemented:
251255
252256- sharing the running clock with Emacs: orgstar does not read or write Emacs's =org-clock-persist= file, so a clock started in one is not known to the other, although both see the open =CLOCK:= line;
253- rounding, changing the TODO state on clock-in (=org-clock-in-switch-to-state=), and clocking out when the entry is marked done (=org-clock-out-when-done=): the clock keeps running.
257- =org-clock-in-switch-to-state= and =org-clock-out-switch-to-state= as functions, and =org-clock-sound=: the notification uses the system's sound.
254258
255259** The clock drawer
256260
docs/manual/guide/13-configuration.org +8
@@ -163,6 +163,7 @@ These settings have no control in the Settings window. Some are in the View menu
163163| =org-agenda-skip-deadline-if-done= | |
164164| =org-agenda-log-mode-items= | |
165165| =org-clock-into-drawer= | |
166| =org-clock-rounding-minutes=, =org-clock-out-remove-zero-time-clocks=, =org-clock-in-switch-to-state=, =org-clock-out-when-done= | |
166167| =org-agenda-todo-ignore-with-date=, =org-agenda-todo-ignore-scheduled=, =org-agenda-todo-ignore-deadlines=, =org-agenda-todo-ignore-timestamp=, =org-agenda-tags-todo-honor-ignore-options= | |
167168| =org-agenda-search-view-always-boolean= | |
168169| =org-agenda-search-view-force-full-words= | |
@@ -225,6 +226,10 @@ A key you remove from the file goes back to its default. A key that isn't in the
225226| =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=. |
226227| =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=. |
227228| =org-clock-into-drawer= | string | ="t"= | Where clock lines go: ="t"= the log drawer (=LOGBOOK=), ="nil"= no drawer, ="N"= a drawer once there are N clock lines, or a drawer's name. An entry's =CLOCK_INTO_DRAWER= property overrides it. Mirrors =org-clock-into-drawer=. |
229| =org-clock-rounding-minutes= | integer | =0= | Clocks start and end on multiples of this many minutes; =0= doesn't round. Mirrors =org-clock-rounding-minutes=. |
230| =org-clock-out-remove-zero-time-clocks= | boolean | =false= | Clocking out removes a clock line of =0:00=. Mirrors =org-clock-out-remove-zero-time-clocks=. |
231| =org-clock-in-switch-to-state= | string | =""= | The keyword an entry takes when you clock in; =""= leaves it. Mirrors =org-clock-in-switch-to-state=. |
232| =org-clock-out-when-done= | string | ="t"= | ="t"=: marking the clocked entry done clocks out; ="nil"=: it doesn't; or the keywords that clock out, separated by spaces. Mirrors =org-clock-out-when-done=. |
228233| =org-clock-history-length= | integer | =5= | How many recently clocked entries orgstar remembers. Mirrors =org-clock-history-length=. |
229234
230235The default =org-todo-keywords= is the first sequence of Doom Emacs's default:
@@ -474,6 +479,9 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
474479| =org-clock-idle-time= | Minutes; =nil= becomes =0= (never) |
475480| =org-clock-history-length= | The same key, when the value is a positive number |
476481| =org-clock-into-drawer= | A drawer name as given, a number as a string, =t= or =nil= |
482| =org-clock-rounding-minutes=, =org-clock-out-remove-zero-time-clocks= | The same key |
483| =org-clock-in-switch-to-state= | A keyword string; a function isn't supported |
484| =org-clock-out-when-done= | =t=, =nil=, or a list of keywords as a string separated by spaces |
477485| =org-agenda-start-day= | A day offset such as ="-3d"=; =nil= becomes ="+0d"=. Other forms aren't supported. |
478486| =org-agenda-start-on-weekday= | ="0"= to ="6"=, or ="nil"= |
479487| =org-agenda-log-mode-items= | The symbols =closed=, =clock= and =state= of the list, separated by spaces |
docs/manual/guide/14-ios.org +1 −1
@@ -354,7 +354,7 @@ These settings from =config.toml= apply on iOS:
354354- =org-agenda-span=, =org-agenda-start-day=, =org-agenda-start-on-weekday=, =org-deadline-warning-days=, =agenda-include-subfolders=, =org-agenda-show-all-dates=, =org-agenda-skip-scheduled-if-done=, =org-agenda-skip-deadline-if-done=, =org-agenda-search-view-always-boolean=, =org-agenda-search-view-force-full-words=, =org-agenda-log-mode-items=, the =org-agenda-todo-ignore-= settings, =org-agenda-tags-todo-honor-ignore-options=
355355- =calendar-events=, =calendar-event-calendars=
356356- =reminders=, =appt-message-warning-time=
357- =org-clock-history-length=, =org-clock-into-drawer=
357- =org-clock-history-length=, =org-clock-into-drawer=, =org-clock-rounding-minutes=, =org-clock-out-remove-zero-time-clocks=, =org-clock-in-switch-to-state=, =org-clock-out-when-done=
358358
359359=capture.toml= and =views.toml= in the folder apply too. Other settings, including =keymap=, =save= and =org-clock-idle-time=, don't apply on iOS. See [[file:13-configuration.org][Configuration]].
360360