Sources/OrgCore/Commands/Statistics.swift

a866e469a3568bf7a2829a8dd2a56317ced4736e
orgstar/Sources/OrgCore/Commands/Statistics.swift history · blame · raw

138 lines · 6748 bytes

  1import Foundation
  2
  3// TODO statistics cookies (`org-update-parent-todo-statistics`, Org 9.8.7) with
  4// `org-provide-todo-statistics` t and `org-hierarchical-todo-statistics` t.
  5
  6extension EmacsBuffer {
  7    /// A property of the entry at `heading` from its property drawer, or nil.
  8    func localProperty(_ name: String, heading: Int) -> String? {
  9        saveExcursion {
 10            point = heading
 11            forwardLine(1)
 12            if lookingAt(planningPattern) != nil { forwardLine(1) }
 13            guard lookingAt("^[ \\t]*:PROPERTIES:[ \\t]*$") != nil else { return nil }
 14            forwardLine(1)
 15            while !eobp, lookingAt("^[ \\t]*:END:[ \\t]*$") == nil {
 16                if let match = lookingAt("^[ \\t]*:([^:\\s]+):(?:[ \\t]+(.*?))?[ \\t]*$"),
 17                   substring(match[1]!.lowerBound, match[1]!.upperBound).caseInsensitiveCompare(name) == .orderedSame {
 18                    return match[2].map { substring($0.lowerBound, $0.upperBound) } ?? ""
 19                }
 20                if forwardLine(1) != 0 { break }
 21            }
 22            return nil
 23        }
 24    }
 25
 26    var planningPattern: String { "^[ \\t]*(?:SCHEDULED|DEADLINE|CLOSED):" }
 27
 28    /// A property with inheritance: the entry, then its ancestors. Returns the value and the
 29    /// heading it came from.
 30    func inheritedProperty(_ name: String) -> (value: String, from: Int)? {
 31        saveExcursion {
 32            guard (try? backToHeading()) != nil else { return nil }
 33            while true {
 34                if let value = localProperty(name, heading: point) { return (value, point) }
 35                let level = outlineLevel
 36                guard level > 1, let parent = saveExcursion({ () -> Int? in
 37                    while let previous = previousHeadingStart(before: point) {
 38                        point = previous
 39                        if headingLevel(atLine: previous)! < level { return previous }
 40                    }
 41                    return nil
 42                }) else { return nil }
 43                point = parent
 44            }
 45        }
 46    }
 47
 48    /// `org-up-heading-safe`: the parent heading's level, with point on it, or nil.
 49    @discardableResult
 50    func upHeadingSafe() -> Int? {
 51        guard let start = try? backToHeading() else { return nil }
 52        let level = headingLevel(atLine: start)!
 53        var at = start
 54        // A top-level heading has no parent; without this the walk goes to the top of the file.
 55        while level > 1, let previous = previousHeadingStart(before: at) {
 56            at = previous
 57            if let parentLevel = headingLevel(atLine: previous), parentLevel < level {
 58                point = previous
 59                return parentLevel
 60            }
 61        }
 62        point = start
 63        return nil
 64    }
 65
 66    /// `org-update-parent-todo-statistics` for the heading at point.
 67    func updateParentTodoStatistics() {
 68        let property = saveExcursion { () -> (value: String, from: Int)? in
 69            upHeadingSafe()
 70            return inheritedProperty("COOKIE_DATA")
 71        }
 72        let recursive = property.map { $0.value.range(of: "\\brecursive\\b", options: .regularExpression) != nil } ?? false
 73        let limit = property?.from ?? 0
 74        var first = true
 75        saveExcursion {
 76            beginningOfLine()
 77            let toggleLevel = outlineLevel
 78            while let level = upHeadingSafe(), recursive || first, point >= limit {
 79                first = false
 80                let data = (localProperty("COOKIE_DATA", heading: point) ?? "").lowercased()
 81                if data.range(of: "\\bcheckbox\\b", options: .regularExpression) != nil { return }
 82                let headingStart = point
 83                while let match = searchForward("((\\[[0-9]*%\\])|(\\[[0-9]*/[0-9]*\\]))", bound: lineEnd(point)) {
 84                    let cookieStart = match[0]!.lowerBound
 85                    let isPercent = match[2] != nil
 86                    guard isStatisticsCookie(at: cookieStart, headingStart: headingStart) else { continue }
 87                    var all = 0, done = 0
 88                    let after = point
 89                    point = headingStart
 90                    guard outlineNextHeading() else { return }
 91                    while let heading = lookingAt(complexHeadingPattern), let l1 = heading[1].map({ $0.count }), l1 > level {
 92                        let keyword = (recursive || l1 == toggleLevel) ? heading[2].map { substring($0.lowerBound, $0.upperBound) } : nil
 93                        if let keyword {
 94                            all += 1
 95                            if settings.isDone(keyword) { done += 1 }
 96                        }
 97                        outlineNextHeading()
 98                    }
 99                    point = after
100                    let new = isPercent ? "[\(Int((100.0 * Double(done) / Double(max(1, all))).rounded(.down)))%]" : "[\(done)/\(all)]"
101                    if new != substring(cookieStart, match[0]!.upperBound) {
102                        let length = match[0]!.upperBound - cookieStart
103                        point = cookieStart
104                        insert(new)
105                        deleteRegion(point, point + length)
106                        let tags = saveExcursion { () -> [Range<Int>?]? in
107                            beginningOfLine()
108                            return lookingAt(SetTags.tagLine)
109                        }
110                        if let tagsRange = tags?[1], point < tagsRange.lowerBound { alignTags(onLineAt: point) }
111                    }
112                }
113                point = headingStart
114            }
115        }
116    }
117
118    /// Whether the cookie text at `offset` on a heading line parses as a statistics cookie.
119    private func isStatisticsCookie(at offset: Int, headingStart: Int) -> Bool {
120        let line = substring(headingStart, lineEnd(headingStart)) + "\n"
121        let tree = OrgParser.parse(line, defaults: settings)
122        return tree.root.descendants().contains { $0.kind == .statisticsCookie && $0.range.contains(offset - headingStart) }
123    }
124}
125
126/// Applies a command's result to a buffer, runs `then` on it, and commits the combined change:
127/// for commands org follows with more edits, such as statistics updates.
128func followUp(_ context: EditContext, _ step: CommandStep, _ then: (EmacsBuffer) throws -> Void) -> CommandStep {
129    guard case .commit(let result) = step, !result.edits.isEmpty else { return step }
130    let caret = result.selection?.first?.lowerBound ?? context.caret
131    return commitBuffer(context) { buffer in
132        for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) {
133            buffer.replace(edit.range, with: edit.replacement)
134        }
135        buffer.point = caret
136        try then(buffer)
137    }
138}