Sources/OrgCore/Commands/ClockTable.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgCore/Commands/ClockTable.swift history · blame · raw

725 lines · 40375 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
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        }
305        if let narrow, !narrowCut {
306            out += "|" + file + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count) + "<\(narrow)>| |\n"
307        }
308        out += "|" + (multifile ? "File|" : "") + (showLevel ? "L|" : "") + (showTags ? "Tags |" : "") + properties.map { $0 + "|" }.joined()
309            + "Headline|Time|" + String(repeating: "|", count: max(0, columns - 1)) + (percent ? "%|\n" : "\n")
310        out += "|-\n|" + (multifile ? "| ALL " : "") + (showLevel ? "|" : "") + (showTags ? "|" : "") + String(repeating: "|", count: properties.count)
311            + "*Total time*| *\(duration(total))*|" + String(repeating: "|", count: max(0, columns - 1))
312            + (percent ? (total == 0 ? "0.0|" : "100.0|") : "") + "\n"
313        if total > 0 {
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 {
326                    var headline = row.headline
327                    if narrowCut, let narrow {
328                        if let m = headline.wholeMatch(of: /\[\[(.+?)\]\[(.+)\]\]/) {
329                            headline = "[[\(m.1)][\(shorten(String(m.2), narrow))]]"
330                        } else {
331                            headline = shorten(headline, narrow)
332                        }
333                    }
334                    func field(_ f: String) -> String {
335                        guard emph else { return f + " |" }
336                        return row.level == 1 ? "*\(f)* |" : row.level == 2 ? "/\(f)/ |" : f + " |"
337                    }
338                    out += "|" + file + (showLevel ? "\(row.level)|" : "") + (showTags ? row.tags.joined(separator: ", ") + "|" : "")
339                        + properties.map { (row.properties[$0] ?? "") + "|" }.joined()
340                        + (indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) : "")
341                        + field(headline) + String(repeating: "|", count: max(0, min(columns, row.level) - 1))
342                        + field(duration(row.minutes)) + String(repeating: "|", count: max(0, columns - row.level))
343                        + (percent ? String(format: "%.1f |", 100 * Double(row.minutes) / Double(total)) : "") + "\n"
344                }
345            }
346        }
347        out.removeLast()
348        if !percent, params.values[":formula"].map({ $0.symbol != "nil" }) ?? false {
349            if let formula = params.values[":formula"]?.string { out += "\n#+TBLFM: " + formula }
350        } else if let tblfm = content.range(of: "(?m)^[ \\t]*#\\+tblfm:.*", options: [.regularExpression, .caseInsensitive]) {
351            out += "\n" + content[tblfm]
352        }
353        return out
354    }
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    }
365}
366
367extension EmacsBuffer {
368    /// `org-dblock-start-re` on point's line.
369    static let dblockStart = "^[ \\t]*#\\+(?:BEGIN|begin):[ \\t]+(\\S+)([ \\t]+(.*))?"
370
371    /// The dynamic block whose lines hold point: its #+BEGIN line's start.
372    func dynamicBlockStart() -> Int? {
373        saveExcursion {
374            let origin = point
375            point = lineEnd(point)
376            guard let begin = searchBackward(Self.dblockStart, caseInsensitive: false)?[0]?.lowerBound else { return nil }
377            point = lineEnd(begin)
378            guard let end = searchForward("^[ \\t]*#\\+(?:END|end):?", caseInsensitive: false)?[0] else { return nil }
379            return origin <= lineEnd(end.lowerBound) ? begin : nil
380        }
381    }
382
383    /// `org-update-dblock` for a clock table at `begin`.
384    func updateDynamicBlock(at begin: Int) throws {
385        point = begin
386        guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") }
387        let name = start[1].map { substring($0.lowerBound, $0.upperBound) } ?? ""
388        let paramText = start[3].map { substring($0.lowerBound, $0.upperBound) } ?? ""
389        let deleteFrom = start[0]!.upperBound + 1
390        point = start[0]!.upperBound
391        guard let end = searchForward("^[ \\t]*#\\+(?:END|end):?", caseInsensitive: false)?[0] else { throw UserError(message: "Dynamic block not terminated") }
392        let content = substring(min(deleteFrom, end.lowerBound), end.lowerBound)
393        if name == "columnview" {
394            let params = try ClockTable.Params(paramText, defaults: [:])
395            let mark = marker(begin)
396            defer { release(mark) }
397            let table = try writeColumnView(params, at: begin, content: content, tree: OrgParser.parse(string))
398            try replaceDynamicBlockContent(at: mark.position, with: table, recalculate: table.range(of: "(?mi)^[ \\t]*#\\+TBLFM:", options: .regularExpression) != nil)
399            return
400        }
401        guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") }
402        let params = try ClockTable.Params(paramText)
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.
467        point = begin
468        let region: Range<Int>
469        switch scope {
470        case "subtree":
471            guard !beforeFirstHeading, let r = try? subtreeRange() else { throw UserError(message: "Before first headline") }
472            region = r
473        case let scope where scope.hasPrefix("tree"):
474            guard !beforeFirstHeading else { throw UserError(message: "Before first headline") }
475            try backToHeading()
476            let limit = Int(scope.dropFirst(4))
477            while let level = currentLevel, level > (limit ?? 1), upHeadingSafe() != nil {
478                if let limit, outlineLevel <= limit { break }
479            }
480            region = try subtreeRange()
481        default:
482            region = 0..<length
483        }
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())
541    }
542
543    /// Puts `table` between the #+BEGIN and #+END lines of the block at `begin`, indented like
544    /// the #+BEGIN line as `org-update-dblock` does, and aligns it.
545    func replaceDynamicBlockContent(at begin: Int, with table: String, recalculate: Bool = false, alignAll: Bool = false) throws {
546        point = begin
547        guard let start = lookingAt(Self.dblockStart) else { throw UserError(message: "Not at a dynamic block") }
548        let indentation = currentIndentation
549        let deleteFrom = start[0]!.upperBound + 1
550        point = start[0]!.upperBound
551        guard let end = searchForward("^[ \\t]*#\\+(?:END|end):?", caseInsensitive: false)?[0] else { throw UserError(message: "Dynamic block not terminated") }
552        // Replace the old contents.
553        let contentEnd = end.lowerBound
554        deleteRegion(min(deleteFrom, contentEnd), contentEnd)
555        point = min(deleteFrom, length)
556        insert(table + "\n")
557        // Indent like the #+BEGIN line, as `org-update-dblock` does.
558        if indentation > 0 {
559            let pad = String(repeating: " ", count: indentation)
560            point = deleteFrom
561            while lookingAt("^[ \\t]*#\\+(?:END|end):?") == nil {
562                insert(pad)
563                if forwardLine(1) != 0 { break }
564            }
565            if let blank = lookingAt("[ \\t]+") { deleteRegion(blank[0]!.lowerBound, blank[0]!.upperBound) }
566            insert(pad)
567        }
568        point = deleteFrom
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) {
572            point = bar[0]!.upperBound
573            // A table kept with formulas is recalculated, as the column view writer does.
574            if recalculate {
575                do {
576                    try tableRecalculate(all: true)
577                } catch let error as Calc.Unsupported {
578                    throw UserError(message: TableRecalculate.emacsMessage + error.reason)
579                }
580            }
581            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 {}
586        }
587        point = begin
588    }
589}
590
591/// C-c C-x C-u, and C-c C-c on a dynamic block's #+BEGIN line: `org-update-dblock` (clock
592/// tables).
593public struct UpdateDynamicBlock: OrgCommand {
594    public init() {}
595    public var id: String { "org.dblock.update" }
596    public var title: String { "Update Dynamic Block" }
597    public func applies(in context: EditContext) -> Bool {
598        EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).dynamicBlockStart() != nil
599    }
600    public func run(in context: EditContext) -> CommandStep {
601        guard let begin = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).dynamicBlockStart() else {
602            return .failed("Not at a dynamic block")
603        }
604        return commitBuffer(context) { buffer in
605            try buffer.updateDynamicBlock(at: begin)
606            buffer.point = begin
607        }
608    }
609}
610
611/// C-c C-x C-r: `org-clock-report`. Updates the clock table at point, or inserts one for the
612/// subtree (the file before the first heading).
613public struct ClockReportTable: OrgCommand {
614    public init() {}
615    public var id: String { "org.clock.report" }
616    public var title: String { "Insert or Update Clock Table" }
617    public func applies(in context: EditContext) -> Bool { true }
618    public func run(in context: EditContext) -> CommandStep {
619        commitBuffer(context) { buffer in
620            if let begin = buffer.dynamicBlockStart(), buffer.saveExcursion({ buffer.point = begin; return buffer.lookingAt("^[ \\t]*#\\+(?:BEGIN|begin):[ \\t]+clocktable") != nil }) {
621                try buffer.updateDynamicBlock(at: begin)
622                buffer.point = begin
623                return
624            }
625            let scope = buffer.beforeFirstHeading ? "file" : "subtree"
626            let begin = buffer.createDynamicBlock("clocktable :scope \(scope) :maxlevel 2")
627            try buffer.updateDynamicBlock(at: begin)
628            buffer.point = begin
629        }
630    }
631}
632
633extension EmacsBuffer {
634    /// `org-create-dblock`: an empty block named by `header` on a line of its own at point.
635    func createDynamicBlock(_ header: String) -> Int {
636        if substring(lineStart(point), lineEnd(point)).contains(where: { !$0.isWhitespace }) {
637            point = lineEnd(point)
638            insert("\n")
639        }
640        let column = currentColumn
641        let begin = lineStart(point)
642        insert("#+BEGIN: \(header)\n\n" + String(repeating: " ", count: column) + "#+END:\n")
643        return begin
644    }
645}
646
647/// C-c C-x i: `org-columns-insert-dblock`, asking what to capture (this subtree, the file, or an
648/// entry by ID).
649public struct InsertColumnView: OrgCommand {
650    public init() {}
651    public var id: String { "org.columns.insert-dblock" }
652    public var title: String { "Insert Column View Table" }
653    public func applies(in context: EditContext) -> Bool { true }
654    public func run(in context: EditContext) -> CommandStep {
655        guard let answer = context.answers["capture"] else {
656            let ids = SparseTreeCommand.propertyValues("ID", in: context.text)
657            return .prompt(Prompt(key: "capture", message: "Capture columns (local, global, entry with :ID: property) [local]:",
658                                  choices: ["global", "local"] + ids, requireMatch: false))
659        }
660        let id = answer.isEmpty || answer == "local" ? "local" : answer == "global" ? "global" : answer
661        return commitBuffer(context) { buffer in
662            let begin = buffer.createDynamicBlock("columnview :hlines 1 :id \(id)")
663            try buffer.updateDynamicBlock(at: begin)
664            buffer.point = begin
665        }
666    }
667}
668
669/// C-c C-x C-c: `org-columns`, shown read-only: the entries from the column view's top level
670/// with their values and summaries.
671public struct ShowColumnView: OrgCommand {
672    let global: Bool
673    public init(global: Bool = false) { self.global = global }
674    public var id: String { global ? "org.columns.global" : "org.columns" }
675    public var title: String { global ? "Column View of File" : "Column View" }
676    public func applies(in context: EditContext) -> Bool { true }
677    public func run(in context: EditContext) -> CommandStep {
678        let view: ColumnView.View
679        do {
680            view = try ColumnView.capture(text: context.text, tree: context.tree, at: context.caret, global: global, now: context.now, calendar: context.calendar).view
681        } catch let error as EmacsBuffer.UserError {
682            return .failed(error.message)
683        } catch {
684            return .failed("\(error)")
685        }
686        guard !view.rows.isEmpty else { return .failed("No entries for column view") }
687        return .external(.columnView(view))
688    }
689}
690
691/// C-c C-x e: `org-set-effort`. Offers the entry's `Effort_ALL` values; sets `Effort`.
692public struct SetEffort: OrgCommand {
693    public init() {}
694    public var id: String { "org.effort.set" }
695    public var title: String { "Set Effort" }
696    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
697    public func run(in context: EditContext) -> CommandStep {
698        guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
699        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
700        guard let answer = context.answers["effort"] else {
701            let current = buffer.saveExcursion { () -> String in
702                _ = try? buffer.backToHeading()
703                let end = buffer.saveExcursion { () -> Int in Capture.nextHeading(buffer); return buffer.point }
704                guard let line = buffer.searchForward("^[ \\t]*:Effort:[ \\t]+(.*?)[ \\t]*$", bound: end, caseInsensitive: true), let value = line[1] else { return "" }
705                return buffer.substring(value.lowerBound, value.upperBound)
706            }
707            let allowed = (buffer.inheritedProperty("Effort_ALL")?.value ?? Self.fileProperty(context.text, "Effort_ALL") ?? "")
708                .split(whereSeparator: \.isWhitespace).map(String.init)
709            return .prompt(Prompt(key: "effort", message: "Effort:", initial: current, choices: allowed, requireMatch: false))
710        }
711        let value = answer.trimmingCharacters(in: .whitespaces)
712        return commitBuffer(context) { buffer in
713            buffer.saveExcursion {
714                _ = try? buffer.backToHeading()
715                buffer.entryPut("Effort", value)
716            }
717        }
718    }
719
720    /// `#+PROPERTY: NAME value`.
721    static func fileProperty(_ text: String, _ name: String) -> String? {
722        text.firstMatch(of: try! Regex("(?im)^[ \\t]*#\\+PROPERTY:[ \\t]+" + NSRegularExpression.escapedPattern(for: name) + "[ \\t]+(.*?)[ \\t]*$"))
723            .map { String($0.output[1].substring!) }
724    }
725}