Commit 28d8fe3d25

28d8fe3d2501e91a1294d65c28e5deceb36a5930

parent: ac467cbd60

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 11:31 UTC

Clock tables over other files, :match and :step

Ports org-clock-sum with its headline filter for :match, org-clock-get-table-data per file, the multi-file parts of org-clocktable-write-default (File column, ALL and File time rows, :hidefiles, :filetitle, :fileskip0, :header), org-clocktable-steps (:step day through year, :stepskip0), and the agenda, agenda-with-archives, file-with-archives and file-list scopes (folders allowed). The editors pass the buffer's file and the agenda files in EditingOptions.

Closes #23

Layout: unified · split

Sources/OrgApp/AgendaFiles.swift +14
@@ -41,3 +41,17 @@ public enum AgendaFiles {
4141 return out
4242 }
4343}
44
45extension WorkspaceModel {
46 /// `(org-agenda-files)`: `list` resolved, or when it is empty the org files at the top of
47 /// each folder (or below it, with `includeSubfolders`), by path, as Emacs lists a
48 /// directory.
49 public func agendaFilePaths(list: [String] = OrgPreferences.agendaFiles(), includeSubfolders: Bool = OrgPreferences.agendaSubfolders()) -> [String] {
50 if !list.isEmpty { return AgendaFiles.resolve(list, base: rootPaths.first) }
51 return files
52 // Dotfiles stay out, as `org-agenda-file-regexp` leaves them out.
53 .filter { $0.kind == .org && !$0.name.hasPrefix(".") && (includeSubfolders || !$0.relativePath.contains("/")) }
54 .map(\.path)
55 .sorted()
56 }
57}
Sources/OrgApp/AgendaModel.swift +1 −8
@@ -62,14 +62,7 @@ public final class AgendaModel {
6262
6363 /// Org files directly in each folder (or below it, with `includeSubfolders`), by path, as
6464 /// Emacs lists a directory in `org-agenda-files`.
65 public var files: [String] {
66 if !agendaFiles.isEmpty { return AgendaFiles.resolve(agendaFiles, base: workspace.rootPaths.first) }
67 return workspace.files
68 // Dotfiles stay out, as `org-agenda-file-regexp` leaves them out.
69 .filter { $0.kind == .org && !$0.name.hasPrefix(".") && (includeSubfolders || !$0.relativePath.contains("/")) }
70 .map(\.path)
71 .sorted()
72 }
65 public var files: [String] { workspace.agendaFilePaths(list: agendaFiles, includeSubfolders: includeSubfolders) }
7366
7467 /// Recomputes the days. `open` is the open buffers' text by path.
7568 public func refresh(open: [String: String], now: Date = Date(), calendar: Calendar = .current) async {
Sources/OrgCore/Commands/Archive.swift +38
@@ -207,6 +207,44 @@ public enum Archive {
207207 return .success(Destination(path: (path as NSString).standardizingPath, heading: heading.isEmpty ? nil : heading, isSameFile: path == sourcePath))
208208 }
209209
210 /// The file part of an archive location for a file at `sourcePath`; the file itself when
211 /// the location names none.
212 static func archiveFile(_ spec: String, sourcePath: String) -> String? {
213 guard let separator = spec.range(of: "::") else { return nil }
214 let fileFormat = String(spec[..<separator.lowerBound])
215 guard fileFormat.contains(where: { !$0.isWhitespace }) else { return sourcePath }
216 let file = fileFormat.replacingOccurrences(of: "%s", with: (sourcePath as NSString).lastPathComponent)
217 let directory = (sourcePath as NSString).deletingLastPathComponent
218 let path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: NSHomeDirectory(), options: .anchored)
219 return (path as NSString).standardizingPath
220 }
221
222 /// `org-all-archive-files`: the archive files of `text`, the file at `path`, that exist:
223 /// its `#+ARCHIVE:` or `org-archive-location`, then each `:ARCHIVE:` property's.
224 public static func allArchiveFiles(_ text: String, path: String, options: EditingOptions, fileManager: FileManager = .default) -> [String] {
225 let buffer = EmacsBuffer(text, point: 0, settings: OrgParser.parse(text).settings)
226 var specs = [buffer.keyword("ARCHIVE") ?? options.archiveLocation ?? "%s_archive::"]
227 let property = try! NSRegularExpression(pattern: "^[ \\t]*:ARCHIVE:[ \\t]+(.*?)[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
228 let ns = text as NSString
229 for m in property.matches(in: text, range: NSRange(location: 0, length: ns.length)) { specs.append(ns.substring(with: m.range(at: 1))) }
230 var files: [String] = []
231 for spec in specs {
232 guard let file = archiveFile(spec, sourcePath: path), !files.contains(file) else { continue }
233 files.append(file)
234 }
235 return files.filter { fileManager.fileExists(atPath: $0) }
236 }
237
238 /// `org-add-archive-files`: each existing file followed by its archive files, without repeats.
239 public static func addArchiveFiles(_ paths: [String], options: EditingOptions, read: (String) -> String?) -> [String] {
240 var out: [String] = []
241 for path in paths {
242 guard let text = read(path) else { continue }
243 for file in [path] + allArchiveFiles(text, path: path, options: options) where !out.contains(file) { out.append(file) }
244 }
245 return out
246 }
247
210248 public enum ArchiveError: Error, Equatable {
211249 case message(String)
212250 }
Sources/OrgCore/Commands/ClockTable.swift +277 −77
@@ -1,12 +1,12 @@
11import Foundation
22
33// Clock tables (org-clock.el, Org 9.8.7): the `clocktable` dynamic block written by
4// `org-clocktable-write-default` from `org-clock-sum`, updated by `org-update-dblock` (C-c C-c
5// on its #+BEGIN line, C-c C-x C-u) and inserted by `org-clock-report` (C-c C-x C-r), with
6// `org-clocktable-defaults` and `org-duration-format` ((\"d\" . nil) (special . h:mm)).
7// Scopes within the file (file, subtree, tree, treeN); `:link` links within the file, as
8// Emacs does in a buffer without a file. `:match`, `:step`, `:formatter` and scopes over
9// other files aren't supported.
4// `org-clocktable-write-default` from `org-clock-get-table-data` and `org-clock-sum`, updated
5// by `org-update-dblock` (C-c C-c on its #+BEGIN line, C-c C-x C-u) and inserted by
6// `org-clock-report` (C-c C-x C-r), with `org-clocktable-defaults` and `org-duration-format`
7// ((\"d\" . nil) (special . h:mm)). Scopes within the file (file, subtree, tree, treeN), the
8// agenda files, archives and lists of files, `:match`, and `:step`. Other files are read from
9// disk. `:formatter` and scopes given as functions aren't supported.
1010
1111enum ClockTable {
1212 struct Params {
@@ -131,42 +131,68 @@ enum ClockTable {
131131 options: .anchorsMatchLines)
132132 static let nakedClock = try! NSRegularExpression(pattern: "^[ \\t]*CLOCK:[ \\t]*=>[ \\t]+([0-9]+):([0-9]+)", options: .anchorsMatchLines)
133133
134 /// `org-clock-sum` over `region`: each heading's minutes with its subtree's, and the total.
135 static func sum(_ text: String, region: Range<Int>, tstart: Double?, tend: Double?, calendar: Calendar) -> (rows: [(start: Int, level: Int, minutes: Int)], total: Int) {
134 /// `org-clock-sum` over `region`: the minutes of each heading with its subtree's, and the
135 /// total. With `include`, headings it rejects add none of their own time, though their
136 /// ancestors still show the time of included descendants.
137 static func sum(_ text: String, region: Range<Int>, tstart: Double?, tend: Double?, calendar: Calendar,
138 include: ((Int) -> Bool)? = nil) -> (rows: [(start: Int, level: Int, minutes: Int)], total: Int) {
136139 let ns = text as NSString
137140 let range = NSRange(region)
138 var own: [Int: Int] = [:] // heading start → minutes
139 let headings = (try! NSRegularExpression(pattern: "^(\\*+)[ \\t]", options: .anchorsMatchLines)).matches(in: text, range: range)
140 .map { (start: $0.range.location, level: $0.range(at: 1).length) }
141 func owner(_ offset: Int) -> Int? { headings.last { $0.start <= offset }?.start }
142141 func seconds(_ m: NSTextCheckingResult, _ first: Int) -> Double {
143142 let parts = (first..<(first + 5)).map { Int(ns.substring(with: m.range(at: $0)))! }
144143 return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4]))!.timeIntervalSince1970
145144 }
145 // Clock lines and headings, scanned from the end as Org does.
146 enum Mark { case heading(level: Int), clock(Int) }
147 var marks: [(offset: Int, mark: Mark)] = []
148 for m in headingLine.matches(in: text, range: range) { marks.append((m.range.location, .heading(level: m.range(at: 1).length))) }
146149 for m in clockRange.matches(in: text, range: range) {
147 guard let head = owner(m.range.location) else { continue }
148150 let ts = seconds(m, 1)
149151 let te = seconds(m, 6)
150152 let dt = (tend.map { min(te, $0) } ?? te) - (tstart.map { max(ts, $0) } ?? ts)
151 if dt > 0 { own[head, default: 0] += Int(floor(dt / 60)) }
153 marks.append((m.range.location, .clock(dt > 0 ? Int(floor(dt / 60)) : 0)))
152154 }
153155 for m in nakedClock.matches(in: text, range: range) {
154 guard let head = owner(m.range.location) else { continue }
155 own[head, default: 0] += Int(ns.substring(with: m.range(at: 1)))! * 60 + Int(ns.substring(with: m.range(at: 2)))!
156 marks.append((m.range.location, .clock(Int(ns.substring(with: m.range(at: 1)))! * 60 + Int(ns.substring(with: m.range(at: 2)))!)))
156157 }
158 marks.sort { $0.offset > $1.offset }
159 var ltimes = [Int](repeating: 0, count: 30)
160 var t1 = 0
161 var forced: Set<Int> = []
157162 var rows: [(Int, Int, Int)] = []
158 for (i, heading) in headings.enumerated() {
159 var minutes = own[heading.start] ?? 0
160 for later in headings[(i + 1)...] {
161 if later.level <= heading.level { break }
162 minutes += own[later.start] ?? 0
163 let ordered: [(start: Int, level: Int)] = marks.reversed().compactMap { mark in
164 if case .heading(let level) = mark.mark { return (mark.offset, level) }
165 return nil
166 }
167 for (offset, mark) in marks {
168 switch mark {
169 case .clock(let minutes): t1 += minutes
170 case .heading(let level):
171 while level >= ltimes.count { ltimes += [Int](repeating: 0, count: ltimes.count) }
172 let included = include?(offset) ?? true
173 if t1 > 0 || ltimes[level] > 0 {
174 if included || forced.contains(offset) {
175 if included { for l in 0...level { ltimes[l] += t1 } }
176 rows.append((offset, level, ltimes[level]))
177 if include != nil {
178 // `org-clock-force-headline-inclusion` on the ancestors.
179 var current = level
180 for heading in ordered.reversed() where heading.start < offset && heading.level < current {
181 forced.insert(heading.start)
182 current = heading.level
183 }
184 }
185 }
186 t1 = 0
187 for l in level..<ltimes.count { ltimes[l] = 0 }
188 }
163189 }
164 if minutes > 0 { rows.append((heading.start, heading.level, minutes)) }
165190 }
166 let total = own.values.reduce(0, +)
167 return (rows.map { (start: $0.0, level: $0.1, minutes: $0.2) }, total)
191 return (rows.reversed().map { (start: $0.0, level: $0.1, minutes: $0.2) }, ltimes[0])
168192 }
169193
194 static let headingLine = try! NSRegularExpression(pattern: "^(\\*+)[ \\t]", options: .anchorsMatchLines)
195
170196 /// `org-shorten-string`.
171197 static func shorten(_ s: String, _ max: Int) -> String {
172198 guard s.count > max else { return s }
@@ -177,43 +203,33 @@ enum ClockTable {
177203 return String(s.prefix(Swift.max(max - 3, 0))) + "..."
178204 }
179205
180 /// The table `org-clocktable-write-default` writes, without its final newline.
181 static func write(_ buffer: EmacsBuffer, params: Params, region: Range<Int>, content: String) throws -> String {
206 /// What `org-clock-get-table-data` gives for one file: its name, its total and its rows.
207 struct FileTable {
208 let path: String?
209 let total: Int
210 let rows: [Row]
211 }
212
213 /// `org-clock-get-table-data` over `region` of `buffer`, the file at `path`, between
214 /// `tstart` and `tend` (seconds).
215 static func tableData(_ buffer: EmacsBuffer, path: String?, params: Params, region: Range<Int>, tstart: Double?, tend: Double?) -> FileTable {
182216 let maxlevel = params.int(":maxlevel") ?? 3
183 let emph = params.flag(":emphasize")
184217 let link = params.flag(":link")
185 let compact = params.flag(":compact")
186 let showLevel = !compact && params.flag(":level")
187218 let showTags = params.flag(":tags")
188 let indent = compact || params.flag(":indent")
189 let percent = params.values[":formula"]?.symbol == "%"
190219 let properties = params.values[":properties"]?.elements?.compactMap(\.string) ?? []
191 if params.values[":match"].map({ $0.symbol != "nil" }) ?? false { throw EmacsBuffer.UserError(message: "Clock tables with :match aren't supported yet") }
192 if params.values[":step"].map({ $0.symbol != "nil" }) ?? false { throw EmacsBuffer.UserError(message: "Clock tables with :step aren't supported yet") }
193 var narrow: Int?
194 var narrowCut = false
195 if let value = params.values[":narrow"] {
196 if let n = value.integer { narrow = n }
197 else if let s = value.symbol, let m = s.wholeMatch(of: /([0-9]+)!/) { narrow = Int(m.1); narrowCut = true }
198 else if value.symbol != "nil" { throw EmacsBuffer.UserError(message: "Invalid value \(value.description) of :narrow property in clock table") }
199 }
200 if compact, narrow == nil { narrow = 40; narrowCut = true }
201 if let n = narrow, !narrowCut, link { narrow = n; narrowCut = true }
202
203 var tstart: Double?
204 var tend: Double?
205 var rangeText: String?
206 if let block = params.symbol(":block") ?? params.values[":block"]?.integer.map(String.init), block != "nil" {
207 let r = try range(block, now: buffer.now, calendar: buffer.calendar, wstart: params.int(":wstart") ?? 1, mstart: params.int(":mstart") ?? 1)
208 (tstart, tend, rangeText) = (r.0, r.1, r.2)
209 } else {
210 if let s = params.values[":tstart"]?.string { tstart = TagsMatcher.matcherTime(s, now: buffer.now, calendar: buffer.calendar) }
211 if let s = params.values[":tend"]?.string { tend = TagsMatcher.matcherTime(s, now: buffer.now, calendar: buffer.calendar) }
212 }
213220 let text = buffer.string
214 let summed = sum(text, region: region, tstart: tstart, tend: tend, calendar: buffer.calendar)
221 // `:match`: a tags/property/TODO match each heading's own time must pass.
222 var include: ((Int) -> Bool)?
223 if let match = params.values[":match"]?.string {
224 let matcher = TagsMatcher(match)
225 let source = AgendaSource(path: path ?? "", text: text, defaults: buffer.settings, checksBlocking: false)
226 let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a })
227 let now = buffer.now, calendar = buffer.calendar
228 include = { start in byStart[start].map { matcher.matches($0, in: source, now: now, calendar: calendar) } ?? false }
229 }
230 let summed = sum(text, region: region, tstart: tstart, tend: tend, calendar: buffer.calendar, include: include)
215231 var rows: [Row] = []
216 for entry in summed.rows where entry.level <= maxlevel {
232 for entry in summed.rows where entry.minutes > 0 && entry.level <= maxlevel {
217233 buffer.point = entry.start
218234 guard let match = buffer.lookingAt(buffer.complexHeadingPattern) else { continue }
219235 var title = match[4].map { buffer.substring($0.lowerBound, $0.upperBound) } ?? ""
@@ -222,7 +238,7 @@ enum ClockTable {
222238 if link {
223239 let search = "*" + Links.normalize(title, context: false)
224240 let description = Links.displayFormat(title.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: "", options: .regularExpression)).trimmingCharacters(in: .whitespaces)
225 headline = Links.makeString(search, description)
241 headline = Links.makeString(path.map { "file:\($0)::" + search } ?? search, description)
226242 }
227243 // `org-get-tags`: inherited ones first.
228244 let own = buffer.tags()
@@ -238,23 +254,75 @@ enum ClockTable {
238254 }
239255 rows.append(Row(level: entry.level, headline: headline, tags: tags, minutes: entry.minutes, properties: props))
240256 }
241 let total = summed.total
242 let columns = compact || maxlevel < 2 ? 1 : min(maxlevel, params.int(":tcolumns") ?? 100, rows.map(\.level).max() ?? 1)
257 return FileTable(path: path, total: summed.total, rows: rows)
258 }
259
260 /// The `:block`, or `:tstart` and `:tend`, as seconds, with the block's caption text.
261 static func timeRange(_ params: Params, now: Date, calendar: Calendar) throws -> (start: Double?, end: Double?, text: String?) {
262 if let block = params.symbol(":block") ?? params.values[":block"]?.integer.map(String.init), block != "nil" {
263 let r = try range(block, now: now, calendar: calendar, wstart: params.int(":wstart") ?? 1, mstart: params.int(":mstart") ?? 1)
264 return (r.0, r.1, r.2)
265 }
266 let start = params.values[":tstart"]?.string.map { TagsMatcher.matcherTime($0, now: now, calendar: calendar) }
267 let end = params.values[":tend"]?.string.map { TagsMatcher.matcherTime($0, now: now, calendar: calendar) }
268 return (start, end, nil)
269 }
270
271 /// The table `org-clocktable-write-default` writes for `tables`, without its final
272 /// newline. `multifile` adds the File column and a row per file.
273 static func write(_ buffer: EmacsBuffer, params: Params, tables: [FileTable], multifile: Bool, rangeText: String?, content: String) throws -> String {
274 let maxlevel = params.int(":maxlevel") ?? 3
275 let emph = params.flag(":emphasize")
276 let link = params.flag(":link")
277 let compact = params.flag(":compact")
278 let showLevel = !compact && params.flag(":level")
279 let showTags = params.flag(":tags")
280 let indent = compact || params.flag(":indent")
281 let percent = params.values[":formula"]?.symbol == "%"
282 let properties = params.values[":properties"]?.elements?.compactMap(\.string) ?? []
283 var narrow: Int?
284 var narrowCut = false
285 if let value = params.values[":narrow"] {
286 if let n = value.integer { narrow = n }
287 else if let s = value.symbol, let m = s.wholeMatch(of: /([0-9]+)!/) { narrow = Int(m.1); narrowCut = true }
288 else if value.symbol != "nil" { throw EmacsBuffer.UserError(message: "Invalid value \(value.description) of :narrow property in clock table") }
289 }
290 if compact, narrow == nil { narrow = 40; narrowCut = true }
291 if let n = narrow, !narrowCut, link { narrow = n; narrowCut = true }
243292
244 let stamp = buffer.formatTimestamp(buffer.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: buffer.now), withTime: true, inactive: true)
245 var out = "#+CAPTION: Clock summary at \(stamp)\(rangeText.map { ", for \($0)." } ?? "")\n"
293 let total = tables.reduce(0) { $0 + $1.total }
294 let levels = tables.filter { $0.total != 0 }.flatMap { $0.rows.map(\.level) }
295 let columns = compact || maxlevel < 2 ? 1 : min(maxlevel, params.int(":tcolumns") ?? 100, levels.max() ?? 1)
296 let file = multifile ? "|" : ""
297
298 var out: String
299 if let header = params.values[":header"]?.string {
300 out = header
301 } else {
302 let stamp = buffer.formatTimestamp(buffer.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: buffer.now), withTime: true, inactive: true)
303 out = "#+CAPTION: Clock summary at \(stamp)\(rangeText.map { ", for \($0)." } ?? "")\n"
304 }
246305 if let narrow, !narrowCut {
247 out += "|" + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) + "<\(narrow)>| |\n"
306 out += "|" + file + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) + "<\(narrow)>| |\n"
248307 }
249 out += "|" + (showLevel ? "L|" : "") + (showTags ? "Tags |" : "") + properties.map { $0 + "|" }.joined()
308 out += "|" + (multifile ? "File|" : "") + (showLevel ? "L|" : "") + (showTags ? "Tags |" : "") + properties.map { $0 + "|" }.joined()
250309 + "Headline|Time|" + String(repeating: "|", count: max(0, columns - 1)) + (percent ? "%|\n" : "\n")
251 out += "|-\n|" + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count)
310 out += "|-\n|" + (multifile ? "| ALL " : "") + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count)
252311 + "*Total time*| *\(duration(total))*|" + String(repeating: "|", count: max(0, columns - 1))
253312 + (percent ? (total == 0 ? "0.0|" : "100.0|") : "") + "\n"
254313 if total > 0 {
255 if total > 0 || !params.flag(":fileskip0") { out += "|-\n" }
256 if maxlevel > 0 {
257 for row in rows {
314 for table in tables where table.total > 0 || !params.flag(":fileskip0") {
315 out += "|-\n"
316 if multifile {
317 let name = table.path.map { path in
318 (params.flag(":filetitle") ? Self.title(path) : nil) ?? (path as NSString).lastPathComponent
319 } ?? ""
320 out += "| \(name) " + (showLevel ? "| " : "") + "| " + (showTags ? "| " : "") + String(repeating: "|", count: properties.count)
321 + "*File time* | *\(duration(table.total))*|" + String(repeating: "|", count: max(0, columns - 1))
322 + (percent ? String(format: " %.1f |", 100 * Double(table.total) / Double(total)) : "") + "\n"
323 }
324 guard maxlevel > 0 else { continue }
325 for row in table.rows {
258326 var headline = row.headline
259327 if narrowCut, let narrow {
260328 if let m = headline.wholeMatch(of: /\[\[(.+?)\]\[(.+)\]\]/) {
@@ -267,7 +335,7 @@ enum ClockTable {
267335 guard emph else { return f + " |" }
268336 return row.level == 1 ? "*\(f)* |" : row.level == 2 ? "/\(f)/ |" : f + " |"
269337 }
270 out += "|" + (showLevel ? "\(row.level)|" : "") + (showTags ? row.tags.joined(separator: ", ") + "|" : "")
338 out += "|" + file + (showLevel ? "\(row.level)|" : "") + (showTags ? row.tags.joined(separator: ", ") + "|" : "")
271339 + properties.map { (row.properties[$0] ?? "") + "|" }.joined()
272340 + (indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) : "")
273341 + field(headline) + String(repeating: "|", count: max(0, min(columns, row.level) - 1))
@@ -284,6 +352,16 @@ enum ClockTable {
284352 }
285353 return out
286354 }
355
356 /// `org-get-title` of the file at `path`.
357 static func title(_ path: String) -> String? {
358 guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { return nil }
359 let titles = text.components(separatedBy: "\n").compactMap { line -> String? in
360 guard let r = line.range(of: "^#\\+(?i:title):[ \\t]*", options: .regularExpression) else { return nil }
361 return String(line[r.upperBound...]).trimmingCharacters(in: .whitespaces)
362 }
363 return titles.isEmpty ? nil : titles.joined(separator: " ")
364 }
287365}
288366
289367extension EmacsBuffer {
@@ -322,12 +400,73 @@ extension EmacsBuffer {
322400 }
323401 guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") }
324402 let params = try ClockTable.Params(paramText)
325 // The scope's text.
403 let range = try ClockTable.timeRange(params, now: now, calendar: calendar)
404 if let step = params.symbol(":step"), step != "nil" {
405 let table = try clockTableSteps(step, params: params, begin: begin, range: range, content: content)
406 try replaceDynamicBlockContent(at: begin, with: table, alignAll: true)
407 return
408 }
409 let tables = try clockTables(params, begin: begin, tstart: range.start, tend: range.end)
410 let table = try ClockTable.write(self, params: params, tables: tables.tables, multifile: tables.multifile, rangeText: range.text, content: content)
411 try replaceDynamicBlockContent(at: begin, with: table)
412 }
413
414 /// The files `:scope` names and each one's table data, and whether the table gets a File
415 /// column, as `org-dblock-write:clocktable` works them out.
416 func clockTables(_ params: ClockTable.Params, begin: Int, tstart: Double?, tend: Double?) throws -> (tables: [ClockTable.FileTable], multifile: Bool) {
417 let path = options.filePath
418 func read(_ file: String) -> String? {
419 file == path ? string : (try? String(contentsOfFile: file, encoding: .utf8))
420 }
421 let files: [String]?
422 let scopeValue = params.values[":scope"] ?? .symbol("file")
423 let scope = scopeValue.symbol ?? scopeValue.string ?? ""
424 if let list = scopeValue.elements, scopeValue.symbol == nil {
425 // A list of files; folders give their org files, as agenda entries do.
426 let base = path.map { ($0 as NSString).deletingLastPathComponent }
427 var expanded: [String] = []
428 for item in list {
429 guard let name = item.string else { throw UserError(message: "Unknown scope: \(scopeValue.description)") }
430 var file = (name as NSString).expandingTildeInPath
431 if !file.hasPrefix("/"), let base { file = (base as NSString).appendingPathComponent(file) }
432 file = (file as NSString).standardizingPath
433 var isDirectory: ObjCBool = false
434 if FileManager.default.fileExists(atPath: file, isDirectory: &isDirectory), isDirectory.boolValue {
435 let names = (try? FileManager.default.contentsOfDirectory(atPath: file)) ?? []
436 expanded += names.sorted().filter { !$0.hasPrefix(".") && $0.hasSuffix(".org") }.map { (file as NSString).appendingPathComponent($0) }
437 } else {
438 expanded.append(file)
439 }
440 }
441 files = expanded
442 } else {
443 switch scope {
444 case "agenda": files = options.agendaFiles ?? []
445 case "agenda-with-archives": files = Archive.addArchiveFiles(options.agendaFiles ?? [], options: options, read: read)
446 case "file-with-archives": files = path.map { Archive.addArchiveFiles([$0], options: options, read: read) }
447 case "nil", "file", "subtree", "tree": files = nil
448 case let s where s.wholeMatch(of: /tree[0-9]+/) != nil: files = nil
449 default: throw UserError(message: "Unknown scope: \(scopeValue.description)")
450 }
451 }
452 if let files, scope != "file-with-archives" || path != nil {
453 var tables: [ClockTable.FileTable] = []
454 for file in files {
455 guard let text = read(file) else { continue }
456 let buffer = file == path ? self : EmacsBuffer(text, point: 0, settings: OrgParser.parse(text).settings, options: options)
457 buffer.now = now
458 buffer.calendar = calendar
459 let saved = point
460 tables.append(ClockTable.tableData(buffer, path: file, params: params, region: 0..<buffer.length, tstart: tstart, tend: tend))
461 point = saved
462 }
463 // `file-with-archives` counts as one extended file.
464 return (tables, !params.flag(":hidefiles") && scope != "file-with-archives")
465 }
466 // The scope's text in this buffer.
326467 point = begin
327468 let region: Range<Int>
328 switch params.symbol(":scope") ?? "file" {
329 case "nil", "file":
330 region = 0..<length
469 switch scope {
331470 case "subtree":
332471 guard !beforeFirstHeading, let r = try? subtreeRange() else { throw UserError(message: "Before first headline") }
333472 region = r
@@ -339,16 +478,71 @@ extension EmacsBuffer {
339478 if let limit, outlineLevel <= limit { break }
340479 }
341480 region = try subtreeRange()
342 case let scope:
343 throw UserError(message: "Clock tables over \(scope) aren't supported yet")
481 default:
482 region = 0..<length
344483 }
345 let table = try ClockTable.write(self, params: params, region: region, content: content)
346 try replaceDynamicBlockContent(at: begin, with: table)
484 return ([ClockTable.tableData(self, path: path, params: params, region: region, tstart: tstart, tend: tend)], false)
485 }
486
487 /// `org-clocktable-steps`: a table per day, week, semimonth, month, quarter or year of the
488 /// range, each after a line naming its start; with `:stepskip0`, only those with time.
489 func clockTableSteps(_ step: String, params: ClockTable.Params, begin: Int, range: (start: Double?, end: Double?, text: String?), content: String) throws -> String {
490 let headers = ["day": "Daily report: ", "week": "Weekly report starting on: ", "semimonth": "Semimonthly report starting on: ",
491 "month": "Monthly report starting on: ", "year": "Annual report starting on: ", "quarter": "Quarterly report starting on: "]
492 guard let stepHeader = headers[step] else { throw UserError(message: "Unknown `:step' specification: \(step)") }
493 guard let start = range.start, let end = range.end else {
494 throw UserError(message: "Clocktable `:step' can only be used with `:block' or `:tstart', `:tend'")
495 }
496 let weekStart = params.int(":wstart") ?? 1
497 let monthStart = params.int(":mstart") ?? 1
498 var stepParams = params
499 stepParams.values[":header"] = .string("")
500 stepParams.values[":step"] = nil
501 stepParams.values[":block"] = nil
502 // The block's contents as `org-clocktable-steps` builds them after `org-prepare-dblock`'s
503 // `open-line`, with point at `p`; `out` ends where the #+END line starts.
504 var out = "\n"
505 var p = 0
506 var at = Date(timeIntervalSince1970: start)
507 let stop = Date(timeIntervalSince1970: end)
508 while at < stop {
509 let c = calendar.dateComponents([.year, .month, .day, .weekday], from: at)
510 let (y, m, d, dow) = (c.year!, c.month!, c.day!, c.weekday! - 1)
511 func date(_ year: Int, _ month: Int, _ day: Int) -> Date {
512 calendar.date(from: DateComponents(year: year, month: month, day: day))!
513 }
514 let next: Date = switch step {
515 case "day": date(y, m, d + 1)
516 case "week": date(y, m, d + (dow == weekStart ? 7 : ((weekStart - dow) % 7 + 7) % 7))
517 case "semimonth": d < 16 ? date(y, m, 16) : date(y, m + 1, 1)
518 case "month": date(y, m + 1, monthStart)
519 case "quarter": date(y, m + 3, monthStart)
520 default: date(y + 1, 1, 1)
521 }
522 let tables = try clockTables(stepParams, begin: begin, tstart: at.timeIntervalSince1970, tend: min(next, stop).timeIntervalSince1970)
523 let total = tables.tables.reduce(0) { $0 + $1.total }
524 let stamp = formatTimestamp(calendar.dateComponents([.year, .month, .day], from: at), withTime: false, inactive: true)
525 let table = try ClockTable.write(self, params: stepParams, tables: tables.tables, multifile: tables.multifile, rangeText: nil, content: content)
526 if p > 0, (out as NSString).character(at: p - 1) != 10 {
527 out = (out as NSString).replacingCharacters(in: NSRange(location: p, length: 0), with: "\n")
528 p += 1
529 }
530 let tableBegin = p + 1
531 out = (out as NSString).replacingCharacters(in: NSRange(location: p, length: 0), with: "\n" + stepHeader + stamp + "\n" + table)
532 // An empty table goes, from its header line to the #+END line.
533 if params.flag(":stepskip0"), total == 0 {
534 out = (out as NSString).substring(to: tableBegin)
535 }
536 // `(end-of-line 0)` from the #+END line.
537 p = max(0, (out as NSString).length - 1)
538 at = next
539 }
540 return String(out.dropLast())
347541 }
348542
349543 /// Puts `table` between the #+BEGIN and #+END lines of the block at `begin`, indented like
350544 /// the #+BEGIN line as `org-update-dblock` does, and aligns it.
351 func replaceDynamicBlockContent(at begin: Int, with table: String, recalculate: Bool = false) throws {
545 func replaceDynamicBlockContent(at begin: Int, with table: String, recalculate: Bool = false, alignAll: Bool = false) throws {
352546 point = begin
353547 guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") }
354548 let indentation = currentIndentation
@@ -372,7 +566,9 @@ extension EmacsBuffer {
372566 insert(pad)
373567 }
374568 point = deleteFrom
375 if let bar = searchForward("^[ \\t]*\\|", caseInsensitive: false) {
569 let endMark = marker(deleteFrom + (table as NSString).length + 1)
570 defer { release(endMark) }
571 while let bar = searchForward("^[ \\t]*\\|", bound: endMark.position, caseInsensitive: false) {
376572 point = bar[0]!.upperBound
377573 // A table kept with formulas is recalculated, as the column view writer does.
378574 if recalculate {
@@ -383,6 +579,10 @@ extension EmacsBuffer {
383579 }
384580 }
385581 tableAlign()
582 // `:step` writes a table per step, each aligned.
583 guard alignAll else { break }
584 point = lineStart(point)
585 while lookingAt("^[ \\t]*\\|") != nil, forwardLine(1) == 0 {}
386586 }
387587 point = begin
388588 }
Sources/OrgCore/Commands/Command.swift +4
@@ -44,6 +44,10 @@ public struct EditingOptions: Sendable, Equatable, Codable {
4444 /// `org-archive-location`, for entries without an `ARCHIVE` property or `#+ARCHIVE:`; nil
4545 /// for Org's default, `%s_archive::`.
4646 public var archiveLocation: String?
47 /// The agenda files (`(org-agenda-files)`), for clock tables over `agenda` scopes; nil for none.
48 public var agendaFiles: [String]?
49 /// The file the buffer visits (`buffer-file-name`); nil for a buffer without one.
50 public var filePath: String?
4751 /// `org-track-ordered-property-with-tag`: the tag toggling `ORDERED` toggles too; nil for none.
4852 public var trackOrderedPropertyWithTag: String?
4953 /// `org-use-speed-commands`: single keys at the start of a heading line run commands.
Sources/Orgstar/ContentView.swift +4 −1
@@ -56,7 +56,7 @@ struct ContentView: View {
5656 @State private var defaultsChanges = 0
5757 private var options: EditingOptions {
5858 _ = defaultsChanges
59 return Preferences.options(
59 var options = Preferences.options(
6060 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
6161 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
6262 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
@@ -65,6 +65,9 @@ struct ContentView: View {
6565 startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
6666 enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
6767 )
68 // The agenda files, for clock tables over `agenda` scopes.
69 options.agendaFiles = workspace.agendaFilePaths()
70 return options
6871 }
6972 /// A block being edited apart (`org-edit-special`).
7073 @State private var blockEdit: BlockEditRequest?
Sources/Orgstar/PaneView.swift +4 −1
@@ -63,7 +63,10 @@ struct PaneView: NSViewRepresentable {
6363 if editor.keymap != settings.keymap { editor.keymap = settings.keymap }
6464 editor.modal = settings.modal
6565 editor.optionAsMeta = settings.optionAsMeta
66 editor.options = settings.options
66 // `buffer-file-name`, for clock tables.
67 var options = settings.options
68 options.filePath = path
69 if editor.options != options { editor.options = options }
6770 editor.showMarkup = settings.showMarkup
6871 editor.showLineNumbers = settings.showLineNumbers
6972 editor.themeSpec = settings.theme
Sources/OrgstarMobile/EditorScreen.swift +10 −2
@@ -24,6 +24,14 @@ struct EditorScreen: View {
2424 @Environment(MobileModel.self) private var model
2525 @Environment(\.openURL) private var openURL
2626
27 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
28 private var editorOptions: EditingOptions {
29 var options = session.options
30 options.filePath = path
31 options.agendaFiles = workspace.agendaFilePaths()
32 return options
33 }
34
2735 struct PromptRequest: Identifiable {
2836 let id = UUID()
2937 let prompt: Prompt
@@ -145,7 +153,7 @@ struct EditorScreen: View {
145153 if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
146154 }
147155 .onChange(of: model.settingsVersion) {
148 editor?.options = session.options
156 editor?.options = editorOptions
149157 editor?.themeSpec = model.theme
150158 editor?.keymap = model.keymap
151159 editor?.modal = model.modalKeys
@@ -196,7 +204,7 @@ struct EditorScreen: View {
196204 if session.path != path { session.open(path) }
197205 if editor == nil, let document = session.document {
198206 let editor = MobileEditor(
199 document: document, editable: document.isEditable, options: session.options, theme: model.theme,
207 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
200208 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
201209 )
202210 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
Tests/OrgCoreTests/ClockTableTests.swift +95
@@ -32,6 +32,10 @@ struct ClockTableTests {
3232 ":link t :maxlevel 3", ":narrow 20! :maxlevel 3", ":tags t :level t :maxlevel 3", ":properties (\"Effort\") :formula %",
3333 ":indent nil :maxlevel 3", ":block yesterday", ":block 2026-W36 :maxlevel 3", ":fileskip0 t :block 2025",
3434 ":maxlevel nil",
35 ":match \"work\" :maxlevel 3", ":match \"-work\" :maxlevel 3", ":match \"TODO=\\\"TODO\\\"\" :maxlevel 3",
36 ":match \"LEVEL=2\" :maxlevel 3", ":block 2026-09 :step week", ":block 2026-09 :step day :stepskip0 t",
37 ":tstart \"<2026-08-25>\" :tend \"<2026-09-15>\" :step week :wstart 0", ":block 2026 :step month :stepskip0 t",
38 ":block 2026 :step quarter", ":block 2026-09 :step semimonth :stepskip0 t",
3539 ]
3640
3741 static func ours(_ text: String, caret: Int, command: any OrgCommand, answers: [String: String] = [:]) -> String {
@@ -87,3 +91,94 @@ struct ClockTableTests {
8791 #expect(ClockTable.duration(0) == "0:00" && ClockTable.duration(95) == "1:35" && ClockTable.duration(1560) == "1d 2:00")
8892 }
8993}
94
95/// Clock tables over several files, against Emacs visiting the same files.
96struct ClockTableScopeTests {
97 static let files: [(String, String)] = [
98 ("a.org", """
99 #+BEGIN: clocktable
100 #+END:
101 * Alpha :work:
102 CLOCK: [2026-09-07 Mon 09:00]--[2026-09-07 Mon 10:00] => 1:00
103 ** Alpha child
104 CLOCK: [2026-09-08 Tue 09:00]--[2026-09-08 Tue 09:30] => 0:30
105 * Beta
106 :PROPERTIES:
107 :ARCHIVE: old.org::
108 :END:
109
110 """),
111 ("a.org_archive", "* Archived :work:\nCLOCK: [2026-09-02 Wed 09:00]--[2026-09-02 Wed 11:00] => 2:00\n"),
112 ("old.org", "* Old entry\nCLOCK: [2026-09-03 Thu 09:00]--[2026-09-03 Thu 09:15] => 0:15\n"),
113 ("b.org", "#+TITLE: Bee file\n* Bee :work:\nCLOCK: [2026-09-09 Wed 13:00]--[2026-09-09 Wed 15:00] => 2:00\n* Idle\n"),
114 ("sub/c.org", "* Sea\nCLOCK: [2026-08-01 Sat 13:00]--[2026-08-01 Sat 14:00] => 1:00\n"),
115 ]
116
117 static let params = [
118 ":scope agenda", ":scope agenda-with-archives", ":scope file-with-archives", ":scope (\"b.org\" \"sub/c.org\")",
119 ":scope agenda :hidefiles t", ":scope agenda :block 2026-09 :fileskip0 t", ":scope (\"b.org\" \"sub/c.org\") :block 2026-09 :fileskip0 t",
120 ":scope agenda :link t", ":scope agenda :filetitle t :formula %", ":scope agenda :level t :tags t",
121 ":scope agenda :block 2026-09 :step week :stepskip0 t", ":scope agenda :match \"work\"",
122 ]
123
124 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
125 func scopesLikeOrg() throws {
126 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-clocktable-\(UUID().uuidString)").standardizedFileURL
127 defer { try? FileManager.default.removeItem(at: folder) }
128 var utc = Calendar(identifier: .gregorian)
129 utc.timeZone = TimeZone(identifier: "UTC")!
130 for param in Self.params {
131 for (name, text) in Self.files {
132 let url = folder.appendingPathComponent(name)
133 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
134 try (name == "a.org" ? text.replacingOccurrences(of: "#+BEGIN: clocktable\n", with: "#+BEGIN: clocktable \(param)\n") : text)
135 .write(to: url, atomically: true, encoding: .utf8)
136 }
137 let a = folder.appendingPathComponent("a.org").path
138 let b = folder.appendingPathComponent("b.org").path
139 let form = """
140 (progn
141 (require 'org) (require 'org-clock)
142 (add-to-list 'auto-mode-alist '("\\\\.org_archive\\\\'" . org-mode))
143 (setq org-agenda-files (list "\(a)" "\(b)"))
144 (find-file "\(a)")
145 (goto-char (point-min))
146 \(frozenClock(1_789_000_000, "(org-update-dblock)"))
147 (princ (buffer-string)))
148 """
149 let emacs = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
150 let text = try String(contentsOfFile: a, encoding: .utf8)
151 var options = EditingOptions.org
152 options.filePath = a
153 options.agendaFiles = [a, b]
154 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<0],
155 now: Date(timeIntervalSince1970: 1_789_000_000), calendar: utc, options: options)
156 var ours = text
157 if case .commit(let result) = UpdateDynamicBlock().run(in: context) {
158 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
159 } else {
160 ours = "failed"
161 }
162 #expect(emacs.hasSuffix(ours), "\(param)\nours:\n\(ours)\nemacs:\n\(emacs)")
163 }
164 }
165}
166
167extension ClockTableScopeTests {
168 /// A folder in a `:scope` list gives its org files; Emacs takes only files there.
169 @Test func folderScopes() throws {
170 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-clocktable-\(UUID().uuidString)").standardizedFileURL
171 defer { try? FileManager.default.removeItem(at: folder) }
172 try FileManager.default.createDirectory(at: folder.appendingPathComponent("sub"), withIntermediateDirectories: true)
173 try "* Sea\nCLOCK: [2026-08-01 Sat 13:00]--[2026-08-01 Sat 14:00] => 1:00\n".write(to: folder.appendingPathComponent("sub/c.org"), atomically: true, encoding: .utf8)
174 try "* Dee\nCLOCK: [2026-08-02 Sun 13:00]--[2026-08-02 Sun 13:30] => 0:30\n".write(to: folder.appendingPathComponent("sub/d.org"), atomically: true, encoding: .utf8)
175 let text = "#+BEGIN: clocktable :scope (\"sub\")\n#+END:\n"
176 var options = EditingOptions.org
177 options.filePath = folder.appendingPathComponent("a.org").path
178 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<0], options: options)
179 guard case .commit(let result) = UpdateDynamicBlock().run(in: context) else { Issue.record("no table"); return }
180 let table = result.edits[0].apply(to: text).replacingOccurrences(of: " +", with: " ", options: .regularExpression)
181 #expect(table.contains("| c.org | *File time* | *1:00*") && table.contains("| d.org | *File time* | *0:30*"), "\(table)")
182 #expect(table.contains("*1:30*"))
183 }
184}
docs/manual/guide/06-dates-and-clocking.org +31 −3
@@ -423,7 +423,7 @@ Times are written as =H:MM=, with a day count such as =2d= before them for a day
423423
424424| Parameter | Values | Default |
425425|-------------------+------------------------------------------------+-----------|
426| =:scope= | =file= (or =nil=), =subtree=, =tree=, =treeN= | =file= |
426| =:scope= | =file= (or =nil=), =subtree=, =tree=, =treeN=, =agenda=, =agenda-with-archives=, =file-with-archives=, or a list of files such as =("work.org" "~/notes/")= | =file= |
427427| =:maxlevel= | Deepest heading level listed | =2= |
428428| =:block= | A time block (see below) | none |
429429| =:tstart=, =:tend= | Start and end, such as ="<2026-09-01>"=, ="<today>"=, ="<-1w>"= | none |
@@ -439,7 +439,13 @@ Times are written as =H:MM=, with a day count such as =2d= before them for a day
439439| =:properties= | A list of property names, such as =("Effort")=, one column each | none |
440440| =:tcolumns= | Number of time columns | up to =:maxlevel= |
441441| =:formula= | =%= adds a percentage column; a string becomes the table's =#+TBLFM= | none |
442| =:fileskip0= | Accepted; has no effect within one file | =nil= |
442| =:match= | A tag and property match, as for the agenda; only matching headings' own time counts | none |
443| =:step= | =day=, =week=, =semimonth=, =month=, =quarter= or =year=: a table per step of =:block= or =:tstart= to =:tend= | none |
444| =:stepskip0= | =t=: leave out steps without time | =nil= |
445| =:fileskip0= | =t=: leave out files without time | =nil= |
446| =:hidefiles= | =t=: no File column over several files | =nil= |
447| =:filetitle= | =t=: name files by their =#+TITLE= | =nil= |
448| =:header= | Text written in place of the =#+CAPTION= line | none |
443449
444450=:scope tree= covers the top-level tree around the block; =tree2= the tree from its level-2 ancestor, and so on. =:block= takes precedence over =:tstart= and =:tend=. Clocks that cross the start or end of the range count only the part inside it.
445451
@@ -457,7 +463,29 @@ Times are written as =H:MM=, with a day count such as =2d= before them for a day
457463
458464A =#+TBLFM= line already under the table is kept when the table is updated, unless =:formula= gives one.
459465
460Not supported: scopes over other files (=agenda=, file lists, =file-with-archives=), =:match= and =:step=, which stop the update with a message, and =:formatter=, which is ignored along with other unknown parameters. Labels are in English only.
466** Other files
467
468=:scope agenda= sums the agenda files (see [[file:07-agenda.org][The agenda]]), and =agenda-with-archives= adds each one's archive files: the one its =#+ARCHIVE:= or =org-archive-location= names, and those its =ARCHIVE= properties name, where they exist. =file-with-archives= is this file with its archives, summed as one file. A list names files, relative to this file's folder; a folder in the list gives its =.org= files, which Org doesn't do. Over several files the table gets a File column and a row with each file's total before its headings:
469
470#+BEGIN_SRC org
471| File | Headline | Time | |
472|----------+------------------+--------+------|
473| | ALL *Total time* | *3:30* | |
474|----------+------------------+--------+------|
475| work.org | *File time* | *1:30* | |
476| | Project Alpha | 1:30 | |
477| | \_ Design | | 0:30 |
478#+END_SRC
479
480Other files are read from disk, so unsaved edits in another open file don't count; this file's buffer does. With =:link t=, headlines link to =file:PATH::*Heading=.
481
482** Steps
483
484=:step= writes a table for each day, week (from =:wstart=), half month, month (from =:mstart=), quarter or year of the range, each after a line such as =Daily report: [2026-10-05 Mon]= or =Weekly report starting on: [2026-10-05 Mon]=, without captions. It needs =:block=, or both =:tstart= and =:tend=.
485
486=:match= takes a match such as ="work"=, ="-home"= or ~"TODO=\"DONE\""~. Headings that don't match add none of their own time, but the headings above a matching one are still listed with its time.
487
488Not supported: =:formatter=, which is ignored along with other unknown parameters, and scopes given as functions. Labels are in English only.
461489
462490* Habits
463491