Sources/OrgCore/Commands/ClockTable.swift

734 lines · 40928 bytes

  1import Foundation
  2
  3// Clock tables (org-clock.el, Org 9.8.7): the `clocktable` dynamic block written by
  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.
 10
 11enum ClockTable {
 12    struct Params {
 13        var values: [String: Sexp] = [:]
 14
 15        func symbol(_ key: String) -> String? { values[key]?.symbol ?? values[key]?.string }
 16        func flag(_ key: String) -> Bool { values[key].map { $0.symbol != "nil" } ?? false }
 17        func int(_ key: String) -> Int? { values[key]?.integer }
 18
 19        /// `org-clocktable-defaults` under the block's own.
 20        static let defaults: [String: Sexp] = [
 21            ":maxlevel": .integer(2), ":scope": .symbol("file"), ":wstart": .integer(1), ":mstart": .integer(1),
 22            ":narrow": .symbol("40!"), ":indent": .symbol("t"), ":lang": .string("en"),
 23        ]
 24
 25        init(_ line: String, defaults: [String: Sexp] = Self.defaults) throws {
 26            values = defaults
 27            let forms = try LispReader.read("(" + line + ")")
 28            let items = forms.first?.sexp.elements ?? []
 29            var i = 0
 30            while i + 1 < items.count {
 31                if let key = items[i].symbol, key.hasPrefix(":") { values[key] = items[i + 1] }
 32                i += 2
 33            }
 34        }
 35    }
 36
 37    struct Row {
 38        let level: Int
 39        let headline: String
 40        let tags: [String]
 41        let minutes: Int
 42        let properties: [String: String]
 43    }
 44
 45    /// `org-duration-from-minutes` with the default format: `H:MM`, days as `Nd ` before it.
 46    static func duration(_ minutes: Int) -> String {
 47        let days = minutes / 1440
 48        let rest = minutes % 1440
 49        let hm = String(format: "%d:%02d", rest / 60, rest % 60)
 50        return days > 0 ? "\(days)d " + hm : hm
 51    }
 52
 53    /// `org-clock-special-range` for `:block`: the start and end in seconds, and the caption's
 54    /// text.
 55    static func range(_ block: String, now: Date, calendar: Calendar, wstart: Int, mstart: Int) throws -> (Double, Double, String) {
 56        let c = calendar.dateComponents([.year, .month, .day, .weekday], from: now)
 57        var key = block
 58        var shift = 0
 59        var y = c.year!, month = c.month!, d = c.day!
 60        // `decode-time`'s day of week: Sunday 0.
 61        var dow = c.weekday! - 1
 62        if let m = block.wholeMatch(of: /([0-9]+)/) {
 63            y = Int(m.1)!; month = 1; d = 1; key = "year"
 64        } else if let m = block.wholeMatch(of: /([0-9]+)-([0-9]{1,2})/) {
 65            y = Int(m.1)!; month = Int(m.2)!; d = 1; key = "month"
 66        } else if let m = block.wholeMatch(of: /([0-9]+)-[wW]([0-9]{1,2})/) {
 67            var iso = Calendar(identifier: .iso8601)
 68            iso.timeZone = calendar.timeZone
 69            let date = iso.date(from: DateComponents(weekday: 2, weekOfYear: Int(m.2)!, yearForWeekOfYear: Int(m.1)!))!
 70            let g = calendar.dateComponents([.year, .month, .day], from: date)
 71            y = g.year!; month = g.month!; d = g.day!; dow = 1; key = "week"
 72        } else if let m = block.wholeMatch(of: /([0-9]+)-([0-9]{1,2})-([0-9]{1,2})/) {
 73            y = Int(m.1)!; month = Int(m.2)!; d = Int(m.3)!; key = "day"
 74        } else if let m = block.firstMatch(of: /([-+][0-9]+)$/) {
 75            shift = Int(m.1.replacingOccurrences(of: "+", with: ""))!
 76            key = String(block[..<m.range.lowerBound])
 77        }
 78        if shift == 0 {
 79            switch key {
 80            case "yesterday": key = "today"; shift = -1
 81            case "lastweek": key = "week"; shift = -1
 82            case "lastmonth": key = "month"; shift = -1
 83            case "lastyear": key = "year"; shift = -1
 84            default: break
 85            }
 86        }
 87        var start = DateComponents(year: y, month: month, day: d, hour: 0, minute: 0)
 88        var end = start
 89        let text: String
 90        let formatter = DateFormatter()
 91        formatter.locale = Locale(identifier: "en_US_POSIX")
 92        formatter.timeZone = calendar.timeZone
 93        switch key {
 94        case "day", "today":
 95            start.day = d + shift
 96            end = start
 97            end.hour = 24
 98            formatter.dateFormat = "EEEE, MMMM dd, yyyy"
 99            text = formatter.string(from: calendar.date(from: start)!)
100        case "week", "thisweek":
101            let diff = -7 * shift + ((dow + 7 - wstart) % 7 + 7) % 7
102            start.day = d - diff
103            end = start
104            end.day = start.day! + 7
105            var iso = Calendar(identifier: .iso8601)
106            iso.timeZone = calendar.timeZone
107            let s = calendar.date(from: start)!
108            text = String(format: "week %04d-W%02d", iso.component(.yearForWeekOfYear, from: s), iso.component(.weekOfYear, from: s))
109        case "month", "thismonth":
110            start.day = mstart
111            start.month = month + shift
112            end = start
113            end.month = start.month! + 1
114            formatter.dateFormat = "MMMM yyyy"
115            text = formatter.string(from: calendar.date(from: start)!)
116        case "year", "thisyear":
117            start.day = 1
118            start.month = 1
119            start.year = y + shift
120            end = start
121            end.year = start.year! + 1
122            text = "the year \(start.year!)"
123        default:
124            throw EmacsBuffer.UserError(message: "No such time block \(block)")
125        }
126        return (calendar.date(from: start)!.timeIntervalSince1970, calendar.date(from: end)!.timeIntervalSince1970, text)
127    }
128
129    static let clockRange = try! NSRegularExpression(pattern:
130        "^[ \\t]*CLOCK:[ \\t]*\\[([0-9]{4})-([0-9]{2})-([0-9]{2})[^\\]\\n]*? ([0-9]{1,2}):([0-9]{2})\\]-+\\[([0-9]{4})-([0-9]{2})-([0-9]{2})[^\\]\\n]*? ([0-9]{1,2}):([0-9]{2})\\]",
131        options: .anchorsMatchLines)
132    static let nakedClock = try! NSRegularExpression(pattern: "^[ \\t]*CLOCK:[ \\t]*=>[ \\t]+([0-9]+):([0-9]+)", options: .anchorsMatchLines)
133
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) {
139        let ns = text as NSString
140        let range = NSRange(region)
141        func seconds(_ m: NSTextCheckingResult, _ first: Int) -> Double {
142            let parts = (first..<(first + 5)).map { Int(ns.substring(with: m.range(at: $0)))! }
143            return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4]))!.timeIntervalSince1970
144        }
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))) }
149        for m in clockRange.matches(in: text, range: range) {
150            let ts = seconds(m, 1)
151            let te = seconds(m, 6)
152            let dt = (tend.map { min(te, $0) } ?? te) - (tstart.map { max(ts, $0) } ?? ts)
153            marks.append((m.range.location, .clock(dt > 0 ? Int(floor(dt / 60)) : 0)))
154        }
155        for m in nakedClock.matches(in: text, range: range) {
156            marks.append((m.range.location, .clock(Int(ns.substring(with: m.range(at: 1)))! * 60 + Int(ns.substring(with: m.range(at: 2)))!)))
157        }
158        marks.sort { $0.offset > $1.offset }
159        var ltimes = [Int](repeating: 0, count: 30)
160        var t1 = 0
161        var forced: Set<Int> = []
162        var rows: [(Int, Int, Int)] = []
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                }
189            }
190        }
191        return (rows.reversed().map { (start: $0.0, level: $0.1, minutes: $0.2) }, ltimes[0])
192    }
193
194    static let headingLine = try! NSRegularExpression(pattern: "^(\\*+)[ \\t]", options: .anchorsMatchLines)
195
196    /// `org-shorten-string`.
197    static func shorten(_ s: String, _ max: Int) -> String {
198        guard s.count > max else { return s }
199        let n = Swift.max(max - 4, 1)
200        if let m = s.firstMatch(of: try! Regex("^(.{1,\(n)}[^ ])( |$)")) {
201            return String(m.output[1].substring!) + "..."
202        }
203        return String(s.prefix(Swift.max(max - 3, 0))) + "..."
204    }
205
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 {
216        let maxlevel = params.int(":maxlevel") ?? 3
217        let link = params.flag(":link")
218        let showTags = params.flag(":tags")
219        let properties = params.values[":properties"]?.elements?.compactMap(\.string) ?? []
220        let text = buffer.string
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)
231        var rows: [Row] = []
232        for entry in summed.rows where entry.minutes > 0 && entry.level <= maxlevel {
233            buffer.point = entry.start
234            guard let match = buffer.lookingAt(buffer.complexHeadingPattern) else { continue }
235            var title = match[4].map { buffer.substring($0.lowerBound, $0.upperBound) } ?? ""
236            if title == "COMMENT" { title = "" } else if title.hasPrefix("COMMENT ") { title = String(title.dropFirst(8)) }
237            var headline = title
238            if link {
239                let search = "*" + Links.normalize(title, context: false)
240                let description = Links.displayFormat(title.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: "", options: .regularExpression)).trimmingCharacters(in: .whitespaces)
241                headline = Links.makeString(path.map { "file:\($0)::" + search } ?? search, description)
242            }
243            // `org-get-tags`: inherited ones first.
244            let own = buffer.tags()
245            let tags = showTags ? own.inherited + own.local : []
246            var props: [String: String] = [:]
247            for name in properties {
248                if let line = buffer.saveExcursion({ () -> [Range<Int>?]? in
249                    let end = buffer.saveExcursion { () -> Int in Capture.nextHeading(buffer); return buffer.point }
250                    return buffer.searchForward("^[ \\t]*:" + NSRegularExpression.escapedPattern(for: name) + ":[ \\t]+(.*?)[ \\t]*$", bound: end, caseInsensitive: true)
251                }), let value = line[1] {
252                    props[name] = buffer.substring(value.lowerBound, value.upperBound)
253                }
254            }
255            rows.append(Row(level: entry.level, headline: headline, tags: tags, minutes: entry.minutes, properties: props))
256        }
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 }
292
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        let lang = params.symbol(":lang") ?? "en"
298        func tr(_ term: String) -> String { ExportDictionary.clockTable(term, language: lang) }
299
300        var out: String
301        if let header = params.values[":header"]?.string {
302            out = header
303        } else {
304            let stamp = buffer.formatTimestamp(buffer.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: buffer.now), withTime: true, inactive: true)
305            out = "#+CAPTION: \(tr("Clock summary at")) \(stamp)\(rangeText.map { ", for \($0)." } ?? "")\n"
306        }
307        if let narrow, !narrowCut {
308            out += "|" + file + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) + "<\(narrow)>| |\n"
309        }
310        out += "|" + (multifile ? tr("File") + "|" : "") + (showLevel ? tr("L") + "|" : "") + (showTags ? "Tags |" : "") + properties.map { $0 + "|" }.joined()
311            + tr("Headline") + "|" + tr("Time") + "|" + String(repeating: "|", count: max(0, columns - 1)) + (percent ? "%|\n" : "\n")
312        out += "|-\n|" + (multifile ? "| \(tr("ALL")) " : "") + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count)
313            + "*\(tr("Total time"))*| *\(duration(total))*|" + String(repeating: "|", count: max(0, columns - 1))
314            + (percent ? (total == 0 ? "0.0|" : "100.0|") : "") + "\n"
315        if total > 0 {
316            for table in tables where table.total > 0 || !params.flag(":fileskip0") {
317                out += "|-\n"
318                if multifile {
319                    let name = table.path.map { path in
320                        (params.flag(":filetitle") ? Self.title(path) : nil) ?? (path as NSString).lastPathComponent
321                    } ?? ""
322                    out += "| \(name) " + (showLevel ? "| " : "") + "| " + (showTags ? "| " : "") + String(repeating: "|", count: properties.count)
323                        + "*\(tr("File time"))* | *\(duration(table.total))*|" + String(repeating: "|", count: max(0, columns - 1))
324                        + (percent ? String(format: " %.1f |", 100 * Double(table.total) / Double(total)) : "") + "\n"
325                }
326                guard maxlevel > 0 else { continue }
327                for row in table.rows {
328                    var headline = row.headline
329                    if narrowCut, let narrow {
330                        if let m = headline.wholeMatch(of: /\[\[(.+?)\]\[(.+)\]\]/) {
331                            headline = "[[\(m.1)][\(shorten(String(m.2), narrow))]]"
332                        } else {
333                            headline = shorten(headline, narrow)
334                        }
335                    }
336                    func field(_ f: String) -> String {
337                        guard emph else { return f + " |" }
338                        return row.level == 1 ? "*\(f)* |" : row.level == 2 ? "/\(f)/ |" : f + " |"
339                    }
340                    out += "|" + file + (showLevel ? "\(row.level)|" : "") + (showTags ? row.tags.joined(separator: ", ") + "|" : "")
341                        + properties.map { (row.properties[$0] ?? "") + "|" }.joined()
342                        + (indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) : "")
343                        + field(headline) + String(repeating: "|", count: max(0, min(columns, row.level) - 1))
344                        + field(duration(row.minutes)) + String(repeating: "|", count: max(0, columns - row.level))
345                        + (percent ? String(format: "%.1f |", 100 * Double(row.minutes) / Double(total)) : "") + "\n"
346                }
347            }
348        }
349        out.removeLast()
350        if !percent, params.values[":formula"].map({ $0.symbol != "nil" }) ?? false {
351            if let formula = params.values[":formula"]?.string { out += "\n#+TBLFM: " + formula }
352        } else if let tblfm = content.range(of: "(?m)^[ \\t]*#\\+tblfm:.*", options: [.regularExpression, .caseInsensitive]) {
353            out += "\n" + content[tblfm]
354        }
355        return out
356    }
357
358    /// `org-get-title` of the file at `path`.
359    static func title(_ path: String) -> String? {
360        guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { return nil }
361        let titles = text.components(separatedBy: "\n").compactMap { line -> String? in
362            guard let r = line.range(of: "^#\\+(?i:title):[ \\t]*", options: .regularExpression) else { return nil }
363            return String(line[r.upperBound...]).trimmingCharacters(in: .whitespaces)
364        }
365        return titles.isEmpty ? nil : titles.joined(separator: " ")
366    }
367}
368
369extension EmacsBuffer {
370    /// `org-dblock-start-re` on point's line.
371    static let dblockStart = "^[ \\t]*#\\+(?:BEGIN|begin):[ \\t]+(\\S+)([ \\t]+(.*))?"
372
373    /// The dynamic block whose lines hold point: its #+BEGIN line's start.
374    func dynamicBlockStart() -> Int? {
375        saveExcursion {
376            let origin = point
377            point = lineEnd(point)
378            guard let begin = searchBackward(Self.dblockStart, caseInsensitive: false)?[0]?.lowerBound else { return nil }
379            point = lineEnd(begin)
380            guard let end = searchForward("^[ \\t]*#\\+(?:END|end):?", caseInsensitive: false)?[0] else { return nil }
381            return origin <= lineEnd(end.lowerBound) ? begin : nil
382        }
383    }
384
385    /// `org-update-dblock` for a clock table at `begin`.
386    func updateDynamicBlock(at begin: Int) throws {
387        point = begin
388        guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") }
389        let name = start[1].map { substring($0.lowerBound, $0.upperBound) } ?? ""
390        let paramText = start[3].map { substring($0.lowerBound, $0.upperBound) } ?? ""
391        let deleteFrom = start[0]!.upperBound + 1
392        point = start[0]!.upperBound
393        guard let end = searchForward("^[ \\t]*#\\+(?:END|end):?", caseInsensitive: false)?[0] else { throw UserError(message: "Dynamic block not terminated") }
394        let content = substring(min(deleteFrom, end.lowerBound), end.lowerBound)
395        if name == "columnview" {
396            let params = try ClockTable.Params(paramText, defaults: [:])
397            let mark = marker(begin)
398            defer { release(mark) }
399            let table = try writeColumnView(params, at: begin, content: content, tree: OrgParser.parse(string))
400            try replaceDynamicBlockContent(at: mark.position, with: table, recalculate: table.range(of: "(?mi)^[ \\t]*#\\+TBLFM:", options: .regularExpression) != nil)
401            return
402        }
403        if DenoteBlocks.names.contains(name) {
404            try replaceDynamicBlockContent(at: begin, with: denoteBlock(name, paramText: paramText))
405            return
406        }
407        guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") }
408        var defaults = ClockTable.Params.defaults
409        defaults[":lang"] = .string(options.exportLanguage)
410        let params = try ClockTable.Params(paramText, defaults: defaults)
411        let range = try ClockTable.timeRange(params, now: now, calendar: calendar)
412        if let step = params.symbol(":step"), step != "nil" {
413            let table = try clockTableSteps(step, params: params, begin: begin, range: range, content: content)
414            try replaceDynamicBlockContent(at: begin, with: table, alignAll: true)
415            return
416        }
417        let tables = try clockTables(params, begin: begin, tstart: range.start, tend: range.end)
418        let table = try ClockTable.write(self, params: params, tables: tables.tables, multifile: tables.multifile, rangeText: range.text, content: content)
419        try replaceDynamicBlockContent(at: begin, with: table)
420    }
421
422    /// The files `:scope` names and each one's table data, and whether the table gets a File
423    /// column, as `org-dblock-write:clocktable` works them out.
424    func clockTables(_ params: ClockTable.Params, begin: Int, tstart: Double?, tend: Double?) throws -> (tables: [ClockTable.FileTable], multifile: Bool) {
425        let path = options.filePath
426        func read(_ file: String) -> String? {
427            file == path ? string : (try? String(contentsOfFile: file, encoding: .utf8))
428        }
429        let files: [String]?
430        let scopeValue = params.values[":scope"] ?? .symbol("file")
431        let scope = scopeValue.symbol ?? scopeValue.string ?? ""
432        if let list = scopeValue.elements, scopeValue.symbol == nil {
433            // A list of files; folders give their org files, as agenda entries do.
434            let base = path.map { ($0 as NSString).deletingLastPathComponent }
435            var expanded: [String] = []
436            for item in list {
437                guard let name = item.string else { throw UserError(message: "Unknown scope: \(scopeValue.description)") }
438                var file = OrgPaths.expandingTilde(name)
439                if !file.hasPrefix("/"), let base { file = (base as NSString).appendingPathComponent(file) }
440                file = (file as NSString).standardizingPath
441                var isDirectory: ObjCBool = false
442                if FileManager.default.fileExists(atPath: file, isDirectory: &isDirectory), isDirectory.boolValue {
443                    let names = (try? FileManager.default.contentsOfDirectory(atPath: file)) ?? []
444                    expanded += names.sorted().filter { !$0.hasPrefix(".") && $0.hasSuffix(".org") }.map { (file as NSString).appendingPathComponent($0) }
445                } else {
446                    expanded.append(file)
447                }
448            }
449            files = expanded
450        } else {
451            switch scope {
452            case "agenda": files = options.agendaFiles ?? []
453            case "agenda-with-archives": files = Archive.addArchiveFiles(options.agendaFiles ?? [], options: options, read: read)
454            case "file-with-archives": files = path.map { Archive.addArchiveFiles([$0], options: options, read: read) }
455            case "nil", "file", "subtree", "tree": files = nil
456            case let s where s.wholeMatch(of: /tree[0-9]+/) != nil: files = nil
457            default: throw UserError(message: "Unknown scope: \(scopeValue.description)")
458            }
459        }
460        if let files, scope != "file-with-archives" || path != nil {
461            var tables: [ClockTable.FileTable] = []
462            for file in files {
463                guard let text = read(file) else { continue }
464                let buffer = file == path ? self : EmacsBuffer(text, point: 0, settings: OrgParser.parse(text).settings, options: options)
465                buffer.now = now
466                buffer.calendar = calendar
467                let saved = point
468                tables.append(ClockTable.tableData(buffer, path: file, params: params, region: 0..<buffer.length, tstart: tstart, tend: tend))
469                point = saved
470            }
471            // `file-with-archives` counts as one extended file.
472            return (tables, !params.flag(":hidefiles") && scope != "file-with-archives")
473        }
474        // The scope's text in this buffer.
475        point = begin
476        let region: Range<Int>
477        switch scope {
478        case "subtree":
479            guard !beforeFirstHeading, let r = try? subtreeRange() else { throw UserError(message: "Before first headline") }
480            region = r
481        case let scope where scope.hasPrefix("tree"):
482            guard !beforeFirstHeading else { throw UserError(message: "Before first headline") }
483            try backToHeading()
484            let limit = Int(scope.dropFirst(4))
485            while let level = currentLevel, level > (limit ?? 1), upHeadingSafe() != nil {
486                if let limit, outlineLevel <= limit { break }
487            }
488            region = try subtreeRange()
489        default:
490            region = 0..<length
491        }
492        return ([ClockTable.tableData(self, path: path, params: params, region: region, tstart: tstart, tend: tend)], false)
493    }
494
495    /// `org-clocktable-steps`: a table per day, week, semimonth, month, quarter or year of the
496    /// range, each after a line naming its start; with `:stepskip0`, only those with time.
497    func clockTableSteps(_ step: String, params: ClockTable.Params, begin: Int, range: (start: Double?, end: Double?, text: String?), content: String) throws -> String {
498        let headers = ["day": "Daily report: ", "week": "Weekly report starting on: ", "semimonth": "Semimonthly report starting on: ",
499                       "month": "Monthly report starting on: ", "year": "Annual report starting on: ", "quarter": "Quarterly report starting on: "]
500        guard let stepHeader = headers[step] else { throw UserError(message: "Unknown `:step' specification: \(step)") }
501        guard let start = range.start, let end = range.end else {
502            throw UserError(message: "Clocktable `:step' can only be used with `:block' or `:tstart', `:tend'")
503        }
504        let weekStart = params.int(":wstart") ?? 1
505        let monthStart = params.int(":mstart") ?? 1
506        var stepParams = params
507        stepParams.values[":header"] = .string("")
508        stepParams.values[":step"] = nil
509        stepParams.values[":block"] = nil
510        // The block's contents as `org-clocktable-steps` builds them after `org-prepare-dblock`'s
511        // `open-line`, with point at `p`; `out` ends where the #+END line starts.
512        var out = "\n"
513        var p = 0
514        var at = Date(timeIntervalSince1970: start)
515        let stop = Date(timeIntervalSince1970: end)
516        while at < stop {
517            let c = calendar.dateComponents([.year, .month, .day, .weekday], from: at)
518            let (y, m, d, dow) = (c.year!, c.month!, c.day!, c.weekday! - 1)
519            func date(_ year: Int, _ month: Int, _ day: Int) -> Date {
520                calendar.date(from: DateComponents(year: year, month: month, day: day))!
521            }
522            let next: Date = switch step {
523            case "day": date(y, m, d + 1)
524            case "week": date(y, m, d + (dow == weekStart ? 7 : ((weekStart - dow) % 7 + 7) % 7))
525            case "semimonth": d < 16 ? date(y, m, 16) : date(y, m + 1, 1)
526            case "month": date(y, m + 1, monthStart)
527            case "quarter": date(y, m + 3, monthStart)
528            default: date(y + 1, 1, 1)
529            }
530            let tables = try clockTables(stepParams, begin: begin, tstart: at.timeIntervalSince1970, tend: min(next, stop).timeIntervalSince1970)
531            let total = tables.tables.reduce(0) { $0 + $1.total }
532            let stamp = formatTimestamp(calendar.dateComponents([.year, .month, .day], from: at), withTime: false, inactive: true)
533            let table = try ClockTable.write(self, params: stepParams, tables: tables.tables, multifile: tables.multifile, rangeText: nil, content: content)
534            if p > 0, (out as NSString).character(at: p - 1) != 10 {
535                out = (out as NSString).replacingCharacters(in: NSRange(location: p, length: 0), with: "\n")
536                p += 1
537            }
538            let tableBegin = p + 1
539            out = (out as NSString).replacingCharacters(in: NSRange(location: p, length: 0), with: "\n" + stepHeader + stamp + "\n" + table)
540            // An empty table goes, from its header line to the #+END line.
541            if params.flag(":stepskip0"), total == 0 {
542                out = (out as NSString).substring(to: tableBegin)
543            }
544            // `(end-of-line 0)` from the #+END line.
545            p = max(0, (out as NSString).length - 1)
546            at = next
547        }
548        return String(out.dropLast())
549    }
550
551    /// Puts `table` between the #+BEGIN and #+END lines of the block at `begin`, indented like
552    /// the #+BEGIN line as `org-update-dblock` does, and aligns it.
553    func replaceDynamicBlockContent(at begin: Int, with table: String, recalculate: Bool = false, alignAll: Bool = false) throws {
554        point = begin
555        guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") }
556        let indentation = currentIndentation
557        let deleteFrom = start[0]!.upperBound + 1
558        point = start[0]!.upperBound
559        guard let end = searchForward("^[ \\t]*#\\+(?:END|end):?", caseInsensitive: false)?[0] else { throw UserError(message: "Dynamic block not terminated") }
560        // Replace the old contents.
561        let contentEnd = end.lowerBound
562        deleteRegion(min(deleteFrom, contentEnd), contentEnd)
563        point = min(deleteFrom, length)
564        insert(table + "\n")
565        // Indent like the #+BEGIN line, as `org-update-dblock` does.
566        if indentation > 0 {
567            let pad = String(repeating: " ", count: indentation)
568            point = deleteFrom
569            while lookingAt("^[ \\t]*#\\+(?:END|end):?") == nil {
570                insert(pad)
571                if forwardLine(1) != 0 { break }
572            }
573            if let blank = lookingAt("[ \\t]+") { deleteRegion(blank[0]!.lowerBound, blank[0]!.upperBound) }
574            insert(pad)
575        }
576        point = deleteFrom
577        let endMark = marker(deleteFrom + (table as NSString).length + 1)
578        defer { release(endMark) }
579        while let bar = searchForward("^[ \\t]*\\|", bound: endMark.position, caseInsensitive: false) {
580            point = bar[0]!.upperBound
581            // A table kept with formulas is recalculated, as the column view writer does.
582            if recalculate {
583                do {
584                    try tableRecalculate(all: true)
585                } catch let error as Calc.Unsupported {
586                    throw UserError(message: TableRecalculate.emacsMessage + error.reason)
587                }
588            }
589            tableAlign()
590            // `:step` writes a table per step, each aligned.
591            guard alignAll else { break }
592            point = lineStart(point)
593            while lookingAt("^[ \\t]*\\|") != nil, forwardLine(1) == 0 {}
594        }
595        point = begin
596    }
597}
598
599/// C-c C-x C-u, and C-c C-c on a dynamic block's #+BEGIN line: `org-update-dblock` (clock
600/// tables).
601public struct UpdateDynamicBlock: OrgCommand {
602    public init() {}
603    public var id: String { "org.dblock.update" }
604    public var title: String { "Update Dynamic Block" }
605    public func applies(in context: EditContext) -> Bool {
606        EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).dynamicBlockStart() != nil
607    }
608    public func run(in context: EditContext) -> CommandStep {
609        guard let begin = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).dynamicBlockStart() else {
610            return .failed("Not at a dynamic block")
611        }
612        return commitBuffer(context) { buffer in
613            try buffer.updateDynamicBlock(at: begin)
614            buffer.point = begin
615        }
616    }
617}
618
619/// C-c C-x C-r: `org-clock-report`. Updates the clock table at point, or inserts one for the
620/// subtree (the file before the first heading).
621public struct ClockReportTable: OrgCommand {
622    public init() {}
623    public var id: String { "org.clock.report" }
624    public var title: String { "Insert or Update Clock Table" }
625    public func applies(in context: EditContext) -> Bool { true }
626    public func run(in context: EditContext) -> CommandStep {
627        commitBuffer(context) { buffer in
628            if let begin = buffer.dynamicBlockStart(), buffer.saveExcursion({ buffer.point = begin; return buffer.lookingAt("^[ \\t]*#\\+(?:BEGIN|begin):[ \\t]+clocktable") != nil }) {
629                try buffer.updateDynamicBlock(at: begin)
630                buffer.point = begin
631                return
632            }
633            let scope = buffer.beforeFirstHeading ? "file" : "subtree"
634            let begin = buffer.createDynamicBlock("clocktable :scope \(scope) :maxlevel 2")
635            try buffer.updateDynamicBlock(at: begin)
636            buffer.point = begin
637        }
638    }
639}
640
641extension EmacsBuffer {
642    /// `org-create-dblock`: an empty block named by `header` on a line of its own at point.
643    func createDynamicBlock(_ header: String) -> Int {
644        if substring(lineStart(point), lineEnd(point)).contains(where: { !$0.isWhitespace }) {
645            point = lineEnd(point)
646            insert("\n")
647        }
648        let column = currentColumn
649        let begin = lineStart(point)
650        insert("#+BEGIN: \(header)\n\n" + String(repeating: " ", count: column) + "#+END:\n")
651        return begin
652    }
653}
654
655/// C-c C-x i: `org-columns-insert-dblock`, asking what to capture (this subtree, the file, or an
656/// entry by ID).
657public struct InsertColumnView: OrgCommand {
658    public init() {}
659    public var id: String { "org.columns.insert-dblock" }
660    public var title: String { "Insert Column View Table" }
661    public func applies(in context: EditContext) -> Bool { true }
662    public func run(in context: EditContext) -> CommandStep {
663        guard let answer = context.answers["capture"] else {
664            let ids = SparseTreeCommand.propertyValues("ID", in: context.text)
665            return .prompt(Prompt(key: "capture", message: "Capture columns (local, global, entry with :ID: property) [local]:",
666                                  choices: ["global", "local"] + ids, requireMatch: false))
667        }
668        let id = answer.isEmpty || answer == "local" ? "local" : answer == "global" ? "global" : answer
669        return commitBuffer(context) { buffer in
670            let begin = buffer.createDynamicBlock("columnview :hlines 1 :id \(id)")
671            try buffer.updateDynamicBlock(at: begin)
672            buffer.point = begin
673        }
674    }
675}
676
677/// C-c C-x C-c: `org-columns`, shown read-only: the entries from the column view's top level
678/// with their values and summaries.
679public struct ShowColumnView: OrgCommand {
680    let global: Bool
681    public init(global: Bool = false) { self.global = global }
682    public var id: String { global ? "org.columns.global" : "org.columns" }
683    public var title: String { global ? "Column View of File" : "Column View" }
684    public func applies(in context: EditContext) -> Bool { true }
685    public func run(in context: EditContext) -> CommandStep {
686        var view: ColumnView.View
687        do {
688            view = try ColumnView.capture(text: context.text, tree: context.tree, at: context.caret, global: global, now: context.now, calendar: context.calendar).view
689            view.global = global
690        } catch let error as EmacsBuffer.UserError {
691            return .failed(error.message)
692        } catch {
693            return .failed("\(error)")
694        }
695        guard !view.rows.isEmpty else { return .failed("No entries for column view") }
696        return .external(.columnView(view))
697    }
698}
699
700/// C-c C-x e: `org-set-effort`. Offers the entry's `Effort_ALL` values; sets `Effort`.
701public struct SetEffort: OrgCommand {
702    public init() {}
703    public var id: String { "org.effort.set" }
704    public var title: String { "Set Effort" }
705    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
706    public func run(in context: EditContext) -> CommandStep {
707        guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
708        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
709        guard let answer = context.answers["effort"] else {
710            let current = buffer.saveExcursion { () -> String in
711                _ = try? buffer.backToHeading()
712                let end = buffer.saveExcursion { () -> Int in Capture.nextHeading(buffer); return buffer.point }
713                guard let line = buffer.searchForward("^[ \\t]*:Effort:[ \\t]+(.*?)[ \\t]*$", bound: end, caseInsensitive: true), let value = line[1] else { return "" }
714                return buffer.substring(value.lowerBound, value.upperBound)
715            }
716            let allowed = (buffer.inheritedProperty("Effort_ALL")?.value ?? Self.fileProperty(context.text, "Effort_ALL") ?? "")
717                .split(whereSeparator: \.isWhitespace).map(String.init)
718            return .prompt(Prompt(key: "effort", message: "Effort:", initial: current, choices: allowed, requireMatch: false))
719        }
720        let value = answer.trimmingCharacters(in: .whitespaces)
721        return commitBuffer(context) { buffer in
722            buffer.saveExcursion {
723                _ = try? buffer.backToHeading()
724                buffer.entryPut("Effort", value)
725            }
726        }
727    }
728
729    /// `#+PROPERTY: NAME value`.
730    static func fileProperty(_ text: String, _ name: String) -> String? {
731        text.firstMatch(of: try! Regex("(?im)^[ \\t]*#\\+PROPERTY:[ \\t]+" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]+(.*?)[ \\t]*$"))
732            .map { String($0.output[1].substring!) }
733    }
734}