Sources/OrgCore/Agenda/AgendaSkip.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgCore/Agenda/AgendaSkip.swift history · blame · raw

214 lines · 10492 bytes

  1import Foundation
  2
  3/// `org-agenda-skip-entry-if` and `org-agenda-skip-subtree-if` (Org 9.8.7) as
  4/// `org-agenda-skip-function`: an entry, or a whole subtree, is left out of a view when any
  5/// of the conditions holds.
  6public struct AgendaSkip: Sendable, Hashable {
  7    public enum Condition: Sendable, Hashable {
  8        case scheduled, notScheduled, deadline, notDeadline, timestamp, notTimestamp
  9        /// Emacs regexps.
 10        case regexp(String), notRegexp(String)
 11        case todo(Keywords), notTodo(Keywords)
 12    }
 13
 14    /// What `todo` and `nottodo` take: keywords (`*` for any), or the class `todo`, `done`
 15    /// or `any`.
 16    public enum Keywords: Sendable, Hashable {
 17        case list([String])
 18        case open, done, any
 19    }
 20
 21    public enum Failure: Error, Equatable {
 22        case message(String)
 23    }
 24
 25    public var subtree: Bool
 26    public var conditions: [Condition]
 27
 28    public init(subtree: Bool, conditions: [Condition]) {
 29        self.subtree = subtree
 30        self.conditions = conditions
 31    }
 32
 33    /// The arguments as Lisp writes them: `'scheduled 'regexp "\\<IGNORE\\>" 'todo '("DONE")`,
 34    /// the quotes optional. Nil, with the reason, for what `org-agenda-skip-if` doesn't take.
 35    public static func parse(_ text: String, subtree: Bool) -> Result<AgendaSkip, Failure> {
 36        let forms: [Sexp]
 37        do {
 38            forms = try LispReader.read("(" + text + ")").first?.sexp.elements ?? []
 39        } catch {
 40            return .failure(.message("can't read \(text)"))
 41        }
 42        func unquote(_ s: Sexp) -> Sexp {
 43            if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" { return items[1] }
 44            return s
 45        }
 46        let args = forms.map(unquote)
 47        var conditions: [Condition] = []
 48        var i = 0
 49        while i < args.count {
 50            guard let name = args[i].symbol else { return .failure(.message("\(args[i].description) isn't a condition")) }
 51            i += 1
 52            func next() -> Sexp? {
 53                defer { i += 1 }
 54                return i < args.count ? args[i] : nil
 55            }
 56            switch name {
 57            case "scheduled": conditions.append(.scheduled)
 58            case "notscheduled": conditions.append(.notScheduled)
 59            case "deadline": conditions.append(.deadline)
 60            case "notdeadline": conditions.append(.notDeadline)
 61            case "timestamp": conditions.append(.timestamp)
 62            case "nottimestamp": conditions.append(.notTimestamp)
 63            case "regexp", "notregexp":
 64                guard let re = next()?.string else { return .failure(.message("\(name) needs a string")) }
 65                conditions.append(name == "regexp" ? .regexp(re) : .notRegexp(re))
 66            case "todo", "nottodo":
 67                let keywords: Keywords
 68                switch next() {
 69                case .symbol("todo")?: keywords = .open
 70                case .symbol("done")?: keywords = .done
 71                case .symbol("any")?: keywords = .any
 72                case let arg?:
 73                    guard let items = arg.elements, items.allSatisfy({ $0.string != nil }) else { return .failure(.message("\(name) needs keywords or todo, done or any")) }
 74                    keywords = .list(items.compactMap(\.string))
 75                case nil: return .failure(.message("\(name) needs keywords or todo, done or any"))
 76                }
 77                conditions.append(name == "todo" ? .todo(keywords) : .notTodo(keywords))
 78            default:
 79                return .failure(.message("\(name) isn't supported"))
 80            }
 81        }
 82        return .success(AgendaSkip(subtree: subtree, conditions: conditions))
 83    }
 84
 85    /// The conditions as `parse` reads them.
 86    public var lisp: String {
 87        conditions.map { condition in
 88            func keywords(_ k: Keywords) -> String {
 89                switch k {
 90                case .list(let words): "(" + words.map { "\"\($0)\"" }.joined(separator: " ") + ")"
 91                case .open: "todo"
 92                case .done: "done"
 93                case .any: "any"
 94                }
 95            }
 96            func quoted(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }
 97            return switch condition {
 98            case .scheduled: "scheduled"
 99            case .notScheduled: "notscheduled"
100            case .deadline: "deadline"
101            case .notDeadline: "notdeadline"
102            case .timestamp: "timestamp"
103            case .notTimestamp: "nottimestamp"
104            case .regexp(let re): "regexp " + quoted(re)
105            case .notRegexp(let re): "notregexp " + quoted(re)
106            case .todo(let k): "todo " + keywords(k)
107            case .notTodo(let k): "nottodo " + keywords(k)
108            }
109        }.joined(separator: " ")
110    }
111
112
113    /// `org-agenda-skip-if` at the heading `index`: where the scan continues when it is skipped
114    /// (the next heading, or the end of the subtree), else nil. `caseFold` is the scan's
115    /// `case-fold-search`: nil for the day and TODO scans, t for tags and search.
116    func skipEnd(_ source: AgendaSource, heading index: Int, caseFold: Bool = false) -> Int? {
117        let heading = source.headings[index]
118        let ns = source.text as NSString
119        let begin = heading.start
120        let end: Int
121        if subtree {
122            // `org-end-of-subtree`: before the line break and blank lines ending it.
123            var e = source.headings[(index + 1)...].first { $0.level <= heading.level }?.start ?? ns.length
124            if e > begin, ns.character(at: e - 1) == 10 {
125                e -= 1
126                while e > begin, [10, 13, 9, 32].contains(ns.character(at: e - 1)) { e -= 1 }
127            }
128            end = e
129        } else {
130            end = index + 1 < source.headings.count ? source.headings[index + 1].start : ns.length
131        }
132        // The planning line is the one after the heading.
133        var planningEnd = end
134        if !subtree {
135            let first = NSMaxRange(ns.lineRange(for: NSRange(location: begin, length: 0)))
136            let second = first < ns.length ? ns.lineRange(for: NSRange(location: first, length: 0)) : NSRange(location: first, length: 0)
137            var lineEnd = NSMaxRange(second)
138            if lineEnd > second.location, ns.character(at: lineEnd - 1) == 10 { lineEnd -= 1 }
139            planningEnd = min(max(first, lineEnd), ns.length)
140        }
141        let fold: NSRegularExpression.Options = caseFold ? [.caseInsensitive, .anchorsMatchLines] : .anchorsMatchLines
142        let scheduledRegex = try? NSRegularExpression(pattern: "\\bSCHEDULED: *<([^>]+)>", options: fold)
143        let deadlineRegex = try? NSRegularExpression(pattern: "\\bDEADLINE: *<([^>]+)>", options: fold)
144        let timestampRegex = try? NSRegularExpression(pattern: "<(\(AgendaSource.tsInternal))>", options: fold)
145        func found(_ regex: NSRegularExpression?, _ limit: Int) -> Bool {
146            guard let regex, limit > begin else { return false }
147            return regex.firstMatch(in: source.text, range: NSRange(location: begin, length: limit - begin)) != nil
148        }
149        func todoRegex(_ keywords: Keywords) -> NSRegularExpression? {
150            let done = source.keywords.filter { !source.notDoneKeywords.contains($0) }
151            let words: [String] = switch keywords {
152            case .open: source.notDoneKeywords
153            case .done: done
154            case .any: source.keywords
155            case .list(let list): list.contains("*") ? source.keywords : list
156            }
157            guard !words.isEmpty else { return nil }
158            let alternatives = words.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
159            return try? NSRegularExpression(pattern: "^\\*+[ \\t]+\\b(?:" + alternatives + ")\\b", options: .anchorsMatchLines)
160        }
161        func regex(_ emacs: String) -> NSRegularExpression? {
162            try? NSRegularExpression(pattern: EmacsRegex.translate(emacs), options: fold)
163        }
164        // `org-agenda-skip-if` tests in this order, whatever order the conditions are in.
165        let c = conditions
166        let first: (Condition) -> String? = { if case .regexp(let re) = $0 { re } else { nil } }
167        let firstNot: (Condition) -> String? = { if case .notRegexp(let re) = $0 { re } else { nil } }
168        let todoArgument = c.first { if case .notTodo = $0 { true } else if case .todo = $0 { true } else { false } }
169        let notTodo = c.first { if case .notTodo = $0 { true } else { false } }
170        var holds = (c.contains(.scheduled) && found(scheduledRegex, planningEnd))
171            || (c.contains(.notScheduled) && !found(scheduledRegex, planningEnd))
172            || (c.contains(.deadline) && found(deadlineRegex, planningEnd))
173            || (c.contains(.notDeadline) && !found(deadlineRegex, planningEnd))
174            || (c.contains(.timestamp) && found(timestampRegex, end))
175            || (c.contains(.notTimestamp) && !found(timestampRegex, end))
176        if !holds, let re = c.lazy.compactMap(first).first { holds = found(regex(re), end) }
177        if !holds, let re = c.lazy.compactMap(firstNot).first { holds = !found(regex(re), end) }
178        // `nottodo` is looked for before `todo`.
179        if !holds, let condition = notTodo ?? todoArgument {
180            switch condition {
181            case .todo(let k): holds = found(todoRegex(k), end)
182            case .notTodo(let k): holds = !found(todoRegex(k), end)
183            default: break
184            }
185        }
186        return holds ? end : nil
187    }
188}
189
190/// `org-agenda-skip` for one scan of one file: candidates come in buffer order, and a skip
191/// moves the scan past the entry or subtree, leaving out the candidates there too.
192struct Skipper {
193    let skip: AgendaSkip?
194    let source: AgendaSource
195    let caseFold: Bool
196    var until = 0
197
198    init(_ skip: AgendaSkip?, _ source: AgendaSource, caseFold: Bool = false) {
199        self.skip = skip
200        self.source = source
201        self.caseFold = caseFold
202    }
203
204    /// Whether the candidate at `position`, in the heading `index`, is skipped.
205    mutating func skips(_ position: Int, heading index: Int) -> Bool {
206        guard let skip else { return false }
207        if position < until { return true }
208        if let end = skip.skipEnd(source, heading: index, caseFold: caseFold) {
209            until = end
210            return true
211        }
212        return false
213    }
214}