Sources/OrgCore/Agenda/AgendaSource.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Agenda/AgendaSource.swift history · blame · raw

432 lines · 23379 bytes

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