Sources/OrgCore/Agenda/AgendaSource.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgCore/Agenda/AgendaSource.swift history · blame · raw

356 lines · 18689 bytes

  1import Foundation
  2
  3/// What the agenda needs from one file, read once from its text: headings with their planning,
  4/// and the active timestamps and date ranges org's agenda would consider. Positions are UTF-16.
  5public struct AgendaSource: Sendable {
  6    public let path: String
  7
  8    struct Heading: Sendable {
  9        /// Start of the heading line.
 10        let start: Int
 11        let level: Int
 12        /// In an archived or commented tree, which the agenda skips.
 13        let skipped: Bool
 14        /// The title without keyword, priority and tags (`ITEM`).
 15        let title: String
 16        /// The priority cookie's value.
 17        let priority: String?
 18        let localTags: [String]
 19        /// Upper-cased keys of the entry's own drawer.
 20        let properties: [String: String]
 21        /// Planning timestamps with brackets, for property matches.
 22        let planning: [String: String]
 23        /// The first active and inactive timestamps in the entry (`TIMESTAMP`, `TIMESTAMP_IA`).
 24        let firstActive: String?
 25        let firstInactive: String?
 26        /// The heading line without its newline.
 27        let line: String
 28        /// The line after the stars.
 29        let head: String
 30        let todo: String?
 31        let isDone: Bool
 32        /// Inherited tags first; the flag marks inherited ones.
 33        let tags: [(name: String, inherited: Bool)]
 34        let category: String
 35        /// The planning timestamp without brackets, and the position of its `<`.
 36        let scheduled: (raw: String, offset: Int)?
 37        let deadline: (raw: String, offset: Int)?
 38        /// `STYLE: habit`.
 39        let isHabit: Bool
 40        /// `org-habit-parse-todo`, nil where it signals an error.
 41        let habit: Habit?
 42    }
 43
 44    struct Stamp: Sendable {
 45        let offset: Int
 46        let heading: Int
 47        /// From the `<` to the end of the line.
 48        let rest: String
 49    }
 50
 51    struct Block: Sendable {
 52        let start: String
 53        let end: String
 54        /// End of the range; org's marker sits there.
 55        let marker: Int
 56        let heading: Int
 57    }
 58
 59    /// A `CLOSED:`, `CLOCK:` or `- State "…"` line, for log mode (`org-agenda-get-progress`).
 60    struct Progress: Sendable {
 61        enum Kind: Sendable { case closed, clock, state }
 62        let kind: Kind
 63        let offset: Int
 64        let heading: Int
 65        /// `YYYY-MM-DD` of the first timestamp.
 66        let date: String
 67        /// The timestamp, from the keyword; a clock's ends with its end time (`[… 10:00-11:30]`).
 68        let timestamp: String
 69        /// A clock's duration, or `-`.
 70        let clocked: String
 71        /// The state a note records.
 72        let state: String?
 73        /// The first line of the note under it.
 74        let note: String?
 75    }
 76
 77    /// A `%%(…)` line (`org-agenda-get-sexps`).
 78    struct SexpLine: Sendable {
 79        /// Start of the line.
 80        let offset: Int
 81        /// The heading the line is under.
 82        let heading: Int
 83        let sexp: Sexp
 84        /// The rest of the line after the sexp.
 85        let entry: String
 86    }
 87
 88    let headings: [Heading]
 89    let stamps: [Stamp]
 90    let sexps: [SexpLine]
 91    let blocks: [Block]
 92    let progress: [Progress]
 93    /// The file's TODO keywords, active and done.
 94    let keywords: [String]
 95    let priorities: Priorities
 96
 97    public init(path: String, text: String, defaults: OrgSettings = .default) {
 98        self.path = path
 99        let tree = OrgParser.parse(text, defaults: defaults)
100        let model = DocumentModel(tree: tree)
101        let ns = text as NSString
102        let settings = tree.settings
103        keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
104        priorities = settings.priorities
105
106        var stampsByHeading: [Int: [String]] = [:]
107        var headingIndex = -1
108        func collect(_ node: SyntaxNode) {
109            for child in node.children {
110                if child.kind == .heading { headingIndex += 1 }
111                if child.kind == .timestamp, headingIndex >= 0 {
112                    stampsByHeading[headingIndex, default: []].append(child.text)
113                } else if child.kind != .block, child.kind != .planning {
114                    collect(child)
115                }
116            }
117        }
118        collect(tree.root)
119        func sectionStamps(_ index: Int) -> [String] { stampsByHeading[index] ?? [] }
120
121        var keywordCategory = SetupFile.keywords(tree.settings.setupKeywords).last { $0.key == "CATEGORY" }?.value.trimmingCharacters(in: .whitespaces)
122        var srcBodies: [Range<Int>] = []
123        var planningLines: [Range<Int>] = []
124        var timestampNodes: [Int] = []
125        var propertyLines: [Range<Int>] = []
126        func walk(_ node: SyntaxNode) {
127            for child in node.children {
128                switch child.kind {
129                case .keyword:
130                    let line = child.text.trimmingCharacters(in: .whitespacesAndNewlines)
131                    if line.uppercased().hasPrefix("#+CATEGORY:") {
132                        keywordCategory = line.dropFirst("#+CATEGORY:".count).trimmingCharacters(in: .whitespaces)
133                    }
134                case .block:
135                    if DocumentModel.isSrcBlock(child) {
136                        let lines = child.range
137                        let firstEnd = ns.range(of: "\n", range: NSRange(location: lines.lowerBound, length: lines.count)).location
138                        let lastStart = ns.lineRange(for: NSRange(location: max(lines.lowerBound, lines.upperBound - 1), length: 0)).location
139                        if firstEnd != NSNotFound, firstEnd + 1 <= lastStart { srcBodies.append((firstEnd + 1)..<lastStart) }
140                    }
141                case .planning:
142                    planningLines.append(child.range)
143                case .clock:
144                    break
145                case .nodeProperty:
146                    propertyLines.append(child.range)
147                case .timestamp:
148                    if child.text.hasPrefix("<") { timestampNodes.append(child.offset) }
149                default:
150                    walk(child)
151                }
152            }
153        }
154        walk(tree.root)
155
156        let fileName = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
157        let fileCategory = keywordCategory ?? model.property("CATEGORY", of: nil)?.value ?? fileName
158        let fileTags = model.fileTags
159        let fileArchived = fileTags.contains("ARCHIVE")
160
161        // Archived and commented trees are skipped whole, as `org-agenda-skip` does.
162        var skipped: [Bool] = []
163        var headings: [Heading] = []
164        for (index, info) in model.headings.enumerated() {
165            let own = info.localTags.contains("ARCHIVE") || Self.isCommented(info.title)
166            skipped.append(fileArchived || own || (info.parent.map { skipped[$0] } ?? false))
167            let line = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: info.headingRange.count))
168            let head = line.replacingOccurrences(of: "^\\*+[ \\t]+", with: "", options: .regularExpression)
169                .trimmingCharacters(in: .newlines)
170
171            var itags: [String] = fileTags
172            for ancestor in model.ancestors(of: index) { itags += model.headings[ancestor].localTags }
173            var tags: [(String, Bool)] = itags.map { ($0, true) } + info.localTags.map { ($0, false) }
174            // `delete-dups` over the reversed list: the most local copy of a tag stays.
175            var seen: Set<String> = []
176            tags = tags.reversed().filter { seen.insert($0.0).inserted }.reversed()
177
178            var category = fileCategory
179            for layer in ([index] + model.ancestors(of: index).reversed()) {
180                if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
181                    category = value
182                    break
183                }
184            }
185
186            var scheduled: (String, Int)?
187            var deadline: (String, Int)?
188            var planningValues: [String: String] = [:]
189            let afterHeading = info.headingRange.upperBound
190            if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
191                let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
192                let regex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>")
193                let pns = planningText as NSString
194                for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
195                    let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
196                    if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
197                }
198                let any = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])")
199                for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
200                    let key = pns.substring(with: m.range(at: 1))
201                    if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
202                }
203            }
204            var properties: [String: String] = [:]
205            for property in info.properties {
206                let key = property.key.uppercased()
207                if property.additive, let value = properties[key] {
208                    properties[key] = value + " " + property.value
209                } else {
210                    properties[key] = property.value
211                }
212            }
213            let ownStamps = sectionStamps(index)
214            let isHabit = properties["STYLE"]?.trimmingCharacters(in: .whitespaces) == "habit"
215            var habit: Habit?
216            if isHabit, let scheduled {
217                let end = index + 1 < model.headings.count ? model.headings[index + 1].headingRange.lowerBound : ns.length
218                let entry = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: end - info.headingRange.lowerBound))
219                habit = Habit.parse(entry: entry, scheduled: scheduled.0, doneKeywords: settings.todoSequences.flatMap { $0.done.map(\.name) })
220            }
221            headings.append(Heading(
222                start: info.headingRange.lowerBound, level: info.level, skipped: skipped[index],
223                title: info.title.trimmingCharacters(in: .whitespaces), priority: info.priority, localTags: info.localTags,
224                properties: properties, planning: planningValues,
225                firstActive: ownStamps.first { $0.hasPrefix("<") }, firstInactive: ownStamps.first { $0.hasPrefix("[") },
226                line: line.trimmingCharacters(in: .newlines), head: head, todo: info.todo, isDone: info.isDone,
227                tags: tags, category: category, scheduled: scheduled, deadline: deadline, isHabit: isHabit, habit: habit
228            ))
229        }
230        self.headings = headings
231
232        let starts = model.headings.map(\.headingRange.lowerBound)
233        func heading(at offset: Int) -> Int? {
234            var low = 0
235            var high = starts.count
236            while low < high {
237                let mid = (low + high) / 2
238                if starts[mid] <= offset { low = mid + 1 } else { high = mid }
239            }
240            return low == 0 ? nil : low - 1
241        }
242        func restOfLine(_ offset: Int) -> String {
243            let line = ns.lineRange(for: NSRange(location: offset, length: 0))
244            return ns.substring(with: NSRange(location: offset, length: NSMaxRange(line) - offset)).trimmingCharacters(in: .newlines)
245        }
246
247        // Timestamps: those the parser sees as timestamp objects, and dates in property lines.
248        var stampOffsets = timestampNodes
249        let datePattern = try! NSRegularExpression(pattern: "<[0-9]{4}-[0-9]{2}-[0-9]{2}")
250        for line in propertyLines {
251            for m in datePattern.matches(in: text, range: NSRange(location: line.lowerBound, length: line.count)) {
252                stampOffsets.append(m.range.location)
253            }
254        }
255        var stamps: [Stamp] = []
256        for offset in stampOffsets.sorted() {
257            guard let owner = heading(at: offset), !skipped[owner] else { continue }
258            let rest = restOfLine(offset)
259            guard rest.range(of: "^<([0-9]{4}-[0-9]{2}-[0-9]{2}|%%\\()", options: .regularExpression) != nil else { continue }
260            if Self.inDateRange(offset, ns) { continue }
261            stamps.append(Stamp(offset: offset, heading: owner, rest: rest))
262        }
263        self.stamps = stamps
264
265        // Sexp lines: org searches the raw text for `%%(` at the start of a line. Before the
266        // first heading org's agenda signals an error; they're left out.
267        var sexps: [SexpLine] = []
268        let sexpLine = try! NSRegularExpression(pattern: "^&?%%\\(", options: .anchorsMatchLines)
269        for m in sexpLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
270            guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
271            let open = NSMaxRange(m.range) - 1
272            let tail = ns.substring(with: NSRange(location: open, length: min(ns.length - open, 4096)))
273            guard let (sexp, length) = try? LispReader.readFirst(tail) else { continue }
274            let afterSexp = String(tail.dropFirst(length))
275            let lineRest = afterSexp.prefix { $0 != "\n" && $0 != "\r" }
276            let entry = lineRest.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
277            sexps.append(SexpLine(offset: m.range.location, heading: owner, sexp: sexp, entry: entry))
278        }
279        self.sexps = sexps
280
281        // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
282        var blocks: [Block] = []
283        let range = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>")
284        for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
285            let point = NSMaxRange(m.range)
286            let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
287            if line.range(of: "^\\s*#( |$|\\n)", options: .regularExpression) != nil { continue }
288            guard let owner = heading(at: max(0, point - 1)), !skipped[owner] else { continue }
289            if srcBodies.contains(where: { $0.contains(point) }) { continue }
290            blocks.append(Block(start: ns.substring(with: m.range(at: 1)), end: ns.substring(with: m.range(at: 2)), marker: point, heading: owner))
291        }
292        self.blocks = blocks
293
294        // Log lines: org searches the raw text, then the heading above each match.
295        let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
296        let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})")
297        let inactive = try! NSRegularExpression(pattern: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)\\]")
298        let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})")
299        let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
300        let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
301        var progress: [Progress] = []
302        for m in logLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
303            guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
304            let keyword = ns.substring(with: m.range(at: 1))
305            let kind: Progress.Kind = keyword == "CLOSED:" ? .closed : keyword == "CLOCK:" ? .clock : .state
306            var timestamp = restOfLine(m.range.location)
307            var clocked = "-"
308            let tns = timestamp as NSString
309            if let ts = inactive.firstMatch(in: timestamp, range: NSRange(location: 0, length: tns.length)) {
310                let rest = tns.substring(from: NSMaxRange(ts.range))
311                timestamp = tns.substring(to: NSMaxRange(ts.range))
312                let rns = rest as NSString
313                if kind == .clock, let end = clockEnd.firstMatch(in: rest, range: NSRange(location: 0, length: rns.length)) {
314                    timestamp = String(timestamp.dropLast()) + "-" + rns.substring(with: end.range(at: 1)) + "]"
315                    clocked = rns.substring(with: end.range(at: 2))
316                }
317            }
318            // The note: after a state line ending in `\\`, or a list item under a clock line.
319            var note: String?
320            let after = NSMaxRange(m.range)
321            let notePattern: NSRegularExpression? = switch kind {
322            case .state: stateNote
323            case .clock: clockNote
324            case .closed: nil
325            }
326            if let notePattern, let n = notePattern.firstMatch(in: text, options: .anchored, range: NSRange(location: after, length: ns.length - after)) {
327                note = ns.substring(with: n.range(at: 1))
328            }
329            progress.append(Progress(
330                kind: kind, offset: m.range.location, heading: owner, date: ns.substring(with: m.range(at: 3)), timestamp: timestamp,
331                clocked: clocked, state: m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2)), note: note
332            ))
333        }
334        self.progress = progress
335    }
336
337    /// `org-ts--internal-regexp`.
338    static let tsInternal = "[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?"
339
340    /// `org-element` reads a title starting with `COMMENT` as a commented heading.
341    static func isCommented(_ title: String) -> Bool {
342        title == "COMMENT" || title.hasPrefix("COMMENT ")
343    }
344
345    /// `org-at-date-range-p` with point just after the date that starts at `offset`.
346    static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
347        let point = offset + 11
348        let line = ns.lineRange(for: NSRange(location: offset, length: 0))
349        let regex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]")
350        for m in regex.matches(in: ns as String, range: line) {
351            if m.range.location > point { break }
352            if NSMaxRange(m.range) >= point { return true }
353        }
354        return false
355    }
356}