Sources/OrgCore/Export/ICalendarExport.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Export/ICalendarExport.swift history · blame · raw

551 lines · 29364 bytes

38 symbols in this file
  1import Foundation
  2
  3/// The `org-icalendar-*` variables (ox-icalendar.el, Org 9.8.7).
  4public struct ICalendarOptions: Sendable, Equatable {
  5    /// `org-icalendar-include-todo`.
  6    public enum IncludeTodo: Sendable, Equatable {
  7        case none
  8        /// `t`: entries not done.
  9        case unfinished
 10        case all
 11        /// Not done, and not blocked by children or an `ORDERED` parent.
 12        case unblocked
 13        case keywords([String])
 14    }
 15
 16    /// `org-icalendar-include-body`.
 17    public enum Body: Sendable, Equatable {
 18        case none, all
 19        case characters(Int)
 20    }
 21
 22    /// `org-icalendar-use-deadline`: `event-if-not-todo`, `event-if-todo`,
 23    /// `event-if-todo-not-done`, `todo-due`.
 24    public var useDeadline: [String] = ["event-if-not-todo", "todo-due"]
 25    /// `org-icalendar-use-scheduled`: as `useDeadline`, with `todo-start`.
 26    public var useScheduled: [String] = ["todo-start"]
 27    public var includeTodo = IncludeTodo.none
 28    /// `org-icalendar-exclude-tags`, unless the file has `#+ICALENDAR_EXCLUDE_TAGS`.
 29    public var excludeTags: [String] = []
 30    /// `org-icalendar-categories`: `category`, `todo-state`, `local-tags`, `all-tags`.
 31    public var categories = ["local-tags", "category"]
 32    /// `org-icalendar-with-timestamps`: `active`, `inactive`, `t`, `nil`, unless the file's
 33    /// `#+OPTIONS` has `<:`.
 34    public var withTimestamps = "active"
 35    public var includeBody = Body.all
 36    /// `org-icalendar-alarm-time`, minutes; 0 for none.
 37    public var alarmTime = 0
 38    public var forceAlarm = false
 39    public var scheduledSummaryPrefix = "S: "
 40    public var deadlineSummaryPrefix = "DL: "
 41    /// `org-icalendar-todo-unscheduled-start`: `recurring-deadline-warning`,
 42    /// `deadline-warning`, `current-datetime`, `nil`.
 43    public var todoUnscheduledStart = "recurring-deadline-warning"
 44    /// `org-icalendar-timezone`; nil or empty for the time zone's abbreviation.
 45    public var timezone: String?
 46    /// `org-icalendar-date-time-format`: `:%Y%m%dT%H%M%S`, or with `Z` for UTC.
 47    public var dateTimeFormat = ":%Y%m%dT%H%M%S"
 48    /// `org-icalendar-ttl`, unless the file has `#+ICAL-TTL`.
 49    public var ttl: String?
 50    public var combinedName = "OrgMode"
 51    public var combinedDescription = ""
 52    /// `org-agenda-default-appointment-duration`, minutes.
 53    public var appointmentDuration: Int?
 54    /// `user-full-name`: the owner when a file has no `#+AUTHOR`, and of a combined calendar.
 55    public var userFullName = ""
 56
 57    public init() {}
 58}
 59
 60/// iCalendar export (`org-icalendar-export-to-ics`, `org-icalendar-combine-agenda-files`):
 61/// VEVENTs from deadlines, scheduled dates and other timestamps, VTODOs from tasks, with
 62/// lines folded at 75 characters and CRLF line ends. Diary sexps are left out.
 63public enum ICalendarExport {
 64    /// The calendar for a file named `name` (its base name is the calendar's), or for the
 65    /// subtree at `subtree` alone.
 66    public static func calendar(
 67        _ text: String, name: String, settings: OrgSettings = .default, options: ICalendarOptions = ICalendarOptions(),
 68        subtree: Int? = nil, now: Date = Date(), calendar: Calendar = .current
 69    ) -> String {
 70        let file = File(text, name: name, settings: settings, options: options, subtree: subtree, now: now, calendar: calendar)
 71        let author = file.keyword("AUTHOR") ?? options.userFullName
 72        return vcalendar(
 73            name: (name as NSString).deletingPathExtension, owner: file.export.author ? file.ascii.inlineString(author) : "",
 74            timezone: zone(options, calendar), description: file.title, ttl: file.keyword("ICAL-TTL") ?? options.ttl, contents: file.components()
 75        )
 76    }
 77
 78    /// One calendar of every file's entries, named `combinedName`.
 79    public static func combined(
 80        _ files: [(name: String, text: String, settings: OrgSettings)], options: ICalendarOptions = ICalendarOptions(),
 81        now: Date = Date(), calendar: Calendar = .current
 82    ) -> String {
 83        let contents = files.map {
 84            File($0.text, name: $0.name, settings: $0.settings, options: options, subtree: nil, now: now, calendar: calendar).components()
 85        }.joined()
 86        return vcalendar(name: options.combinedName, owner: options.userFullName, timezone: zone(options, calendar),
 87                         description: options.combinedDescription, ttl: options.ttl, contents: contents)
 88    }
 89
 90    static func zone(_ options: ICalendarOptions, _ calendar: Calendar) -> String {
 91        if let tz = options.timezone, !tz.isEmpty { return tz }
 92        return calendar.timeZone.abbreviation() ?? calendar.timeZone.identifier
 93    }
 94
 95    /// `org-icalendar--vcalendar`, folded, with CRLF line ends.
 96    static func vcalendar(name: String, owner: String, timezone: String, description: String, ttl: String?, contents: String) -> String {
 97        var out = "BEGIN:VCALENDAR\nVERSION:2.0\nX-WR-CALNAME:\(cleanup(name))\nPRODID:-//\(cleanup(owner))//Emacs with Org mode//EN\n"
 98            + "X-WR-TIMEZONE:\(cleanup(timezone))\nX-WR-CALDESC:\(cleanup(description))\n"
 99        if let ttl { out += "X-PUBLISHED-TTL:\(cleanup(ttl))\n" }
100        out += "CALSCALE:GREGORIAN\n" + contents + "END:VCALENDAR\n"
101        return fold(out).replacingOccurrences(of: "\n", with: "\r\n")
102    }
103
104    /// `org-icalendar-cleanup-string`: `\`, `,` and `;` escaped, newlines as `\n`.
105    static func cleanup(_ s: String) -> String {
106        var out = ""
107        for c in s {
108            if c == "\\" || c == "," || c == ";" { out.append("\\") }
109            out.append(c)
110        }
111        return out.replacing(#/[ \t]*\n/#, with: "\\n")
112    }
113
114    /// `org-icalendar-fold-string`: lines over 75 characters continue on lines starting with a
115    /// space.
116    static func fold(_ s: String) -> String {
117        let lines = s.components(separatedBy: "\n").filter { !$0.isEmpty }
118        return lines.map { line -> String in
119            let scalars = Array(line.unicodeScalars)
120            guard scalars.count > 75 else { return line }
121            var parts = [String(String.UnicodeScalarView(scalars[0..<75]))]
122            var start = 75
123            while start < scalars.count {
124                let end = min(start + 74, scalars.count)
125                parts.append(" " + String(String.UnicodeScalarView(scalars[start..<end])))
126                start = end
127            }
128            return parts.joined(separator: "\n")
129        }.joined(separator: "\n") + "\n"
130    }
131
132    /// `org-export--skip-timestamp-p` for a timestamp written `text`.
133    static func skipsTimestamp(_ text: String, with: String) -> Bool {
134        let diary = text.hasPrefix("<%%")
135        let active = text.hasPrefix("<")
136        switch with {
137        case "nil": return true
138        case "active": return !active
139        case "active-exclude-diary": return !active || diary
140        case "inactive": return active
141        default: return false
142        }
143    }
144
145    // MARK: - A file's entries
146
147    struct File {
148        let text: String
149        let source: NSString
150        let tree: OrgTree
151        let model: DocumentModel
152        let options: ICalendarOptions
153        var export: ExportOptions
154        let ascii: ASCIIText
155        let name: String
156        let subtree: Int?
157        let now: Date
158        let calendar: Calendar
159        let selected: Set<Int>?
160        let headingIndex: [Int: Int]
161        let settings: OrgSettings
162
163        init(_ text: String, name: String, settings: OrgSettings, options: ICalendarOptions, subtree: Int?, now: Date, calendar: Calendar) {
164            let text = ExportPreprocess.macros(text, path: name, now: now, setup: settings.setupKeywords)
165            self.text = text
166            source = text as NSString
167            tree = OrgParser.parse(text, defaults: settings)
168            model = DocumentModel(tree: tree)
169            self.options = options
170            self.settings = settings
171            var export = ExportOptions.parse(settings.setupKeywords + "\n" + text)
172            export.excludeTags = Self.keyword("ICALENDAR_EXCLUDE_TAGS", tree: tree, settings: settings)
173                .map { $0.split(whereSeparator: \.isWhitespace).map(String.init) } ?? options.excludeTags
174            if export.timestamps == nil { export.timestamps = options.withTimestamps }
175            self.export = export
176            var ascii = ASCIIText(options: export)
177            var numbers = Array(repeating: 0, count: max(1, export.headlineLevels))
178            for heading in model.headings where heading.level <= export.headlineLevels {
179                numbers[heading.level - 1] += 1
180                for deeper in heading.level..<numbers.count { numbers[deeper] = 0 }
181                let plain = Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)
182                if ascii.headingNumbers[plain] == nil { ascii.headingNumbers[plain] = numbers.prefix(heading.level).map(String.init).joined(separator: ".") }
183            }
184            self.ascii = ascii
185            self.name = name
186            self.subtree = subtree
187            self.now = now
188            self.calendar = calendar
189            selected = HTMLRenderer.selection(tree, tags: export.selectTags)
190            headingIndex = Dictionary(model.headings.enumerated().map { ($1.headingRange.lowerBound, $0) }, uniquingKeysWith: { a, _ in a })
191        }
192
193        static func keyword(_ key: String, tree: OrgTree, settings: OrgSettings) -> String? {
194            var value: String?
195            let lines = settings.setupKeywords.split(separator: "\n").map(String.init)
196                + tree.root.descendants().filter { $0.kind == .keyword }.map(\.text)
197            for line in lines {
198                if let m = line.firstMatch(of: #/(?i)^[ \t]*#\+([^:\s]+):[ \t]*(.*?)[ \t]*\n?$/#), m.1.uppercased() == key { value = String(m.2) }
199            }
200            return value
201        }
202
203        func keyword(_ key: String) -> String? { Self.keyword(key, tree: tree, settings: settings) }
204
205        /// The heading whose subtree is exported.
206        var subtreeHeading: Int? { subtree.flatMap { offset in model.headings.lastIndex { $0.headingRange.lowerBound <= offset } } }
207
208        /// `#+TITLE`; for a subtree, its `EXPORT_TITLE` or title.
209        var title: String {
210            if let index = subtreeHeading {
211                return ascii.inlineString(property("EXPORT_TITLE", index) ?? Links.displayFormat(model.headings[index].title).trimmingCharacters(in: .whitespaces))
212            }
213            return keyword("TITLE").map { ascii.inlineString($0) } ?? ""
214        }
215
216        /// The components of every entry, in order.
217        func components() -> String {
218            var out = ""
219            for node in tree.root.children where node.kind == .section { out += section(node) }
220            return out
221        }
222
223        func section(_ node: SyntaxNode) -> String {
224            guard let heading = node.firstChild(.heading), let index = headingIndex[heading.range.lowerBound] else { return "" }
225            let info = model.headings[index]
226            if subtree != nil, let target = subtreeHeading {
227                // Only the subtree at `subtree`, as Org narrows to it.
228                if model.ancestors(of: target).contains(index) { return node.children.filter { $0.kind == .section }.map(section).joined() }
229                if index != target, !model.ancestors(of: index).contains(target) { return "" }
230            }
231            let what = HTMLRenderer.sectionExport(heading, options: export, selected: selected)
232            if what == .nothing { return "" }
233            let title = Links.displayFormat(info.title).trimmingCharacters(in: .whitespaces)
234            if title == "Footnotes" { return "" }
235            let body = what == .all ? node.children.filter { ![.heading, .section, .planning, .propertyDrawer].contains($0.kind) } : []
236            var out = entry(index, heading: heading, body: body, end: node.children.first { $0.kind == .section }?.range.lowerBound ?? node.range.upperBound)
237            if what == .all { for child in node.children where child.kind == .section { out += section(child) } }
238            return out
239        }
240
241        // MARK: Entries
242
243        func property(_ key: String, _ index: Int) -> String? { model.property(key, of: index)?.value }
244
245        func entry(_ index: Int, heading: SyntaxNode, body: [SyntaxNode], end: Int) -> String {
246            let info = model.headings[index]
247            let todoType: String? = info.todo == nil ? nil : info.isDone ? "done" : "todo"
248            let uid = info.id ?? UUID().uuidString
249            let titleNode = heading.firstChild(.title)
250            let summary = cleanup(model.headings[index].properties.contains { $0.key.uppercased() == "SUMMARY" } || model.inherits("SUMMARY")
251                ? property("SUMMARY", index) ?? titleNode.map { ascii.inline($0) }?.trimmingCharacters(in: .whitespaces) ?? ""
252                : titleNode.map { ascii.inline($0) }?.trimmingCharacters(in: .whitespaces) ?? "")
253            let location = property("LOCATION", index).map(cleanup)
254            let klass = property("CLASS", index).map(cleanup)
255            var description: String?
256            if let own = property("DESCRIPTION", index) {
257                description = own
258            } else {
259                let contents = ascii.elements(body, end: end, source: source, width: ascii.width(level: info.level))
260                if contents.contains(where: { !$0.isWhitespace }) {
261                    let trimmed = contents.trimmingCharacters(in: .whitespacesAndNewlines)
262                    switch options.includeBody {
263                    case .none: description = nil
264                    case .all: description = trimmed
265                    case .characters(let n): description = String(trimmed.unicodeScalars.prefix(n))
266                    }
267                }
268            }
269            description = description.map(cleanup)
270            let categories = self.categories(index)
271            let timezone = property("TIMEZONE", index)
272            var out = ""
273            func wants(_ list: [String]) -> Bool {
274                switch todoType {
275                case "todo": list.contains("event-if-todo-not-done") || list.contains("event-if-todo")
276                case "done": list.contains("event-if-todo")
277                default: list.contains("event-if-not-todo")
278                }
279            }
280            let entry = Entry(uid: uid, summary: summary, location: location, description: description, categories: categories, timezone: timezone, klass: klass, warnTime: info.properties.last { $0.key.uppercased() == "APPT_WARNTIME" }.flatMap { Int($0.value.trimmingCharacters(in: .whitespaces)) })
281            if let deadline = info.deadline, wants(options.useDeadline) {
282                out += vevent(entry, deadline, uid: "DL-" + uid, summary: cleanup(options.deadlineSummaryPrefix) + summary)
283            }
284            if let scheduled = info.scheduled, wants(options.useScheduled) {
285                out += vevent(entry, scheduled, uid: "SC-" + uid, summary: cleanup(options.scheduledSummaryPrefix) + summary)
286            }
287            var counter = 0
288            for text in timestamps(titleNode) + body.flatMap(timestamps) where !skipsTimestamp(text, with: export.timestamps ?? "active") {
289                guard !text.hasPrefix("<%%"), let stamp = Timestamp.parse(text) else { continue }
290                counter += 1
291                out += vevent(entry, stamp, uid: "TS\(counter)-" + uid, summary: summary)
292            }
293            if let todoType, includesTodo(index, todoType: todoType) {
294                out += vtodo(entry, index, todoType: todoType)
295            }
296            return out
297        }
298
299        struct Entry {
300            let uid: String
301            let summary: String
302            let location: String?
303            let description: String?
304            let categories: String
305            let timezone: String?
306            let klass: String?
307            let warnTime: Int?
308        }
309
310        /// The timestamps `org-element-map` finds, leaving out what the export ignores.
311        func timestamps(_ node: SyntaxNode?) -> [String] {
312            guard let node else { return [] }
313            switch node.kind {
314            case .timestamp: return [node.text]
315            case .planning, .propertyDrawer, .clock, .comment, .keyword, .block, .inlineTask, .fixedWidth, .heading, .section: return []
316            case .drawer:
317                if node.text.firstMatch(of: /^[ \t]*:LOGBOOK:/) != nil { return [] }
318            default: break
319            }
320            return node.children.flatMap(timestamps)
321        }
322
323        func categories(_ index: Int) -> String {
324            let info = model.headings[index]
325            var out: [String] = []
326            func tags(_ list: [String]) -> [String] { list.filter { !export.selectTags.contains($0) && !export.excludeTags.contains($0) } }
327            for kind in options.categories {
328                switch kind {
329                case "category":
330                    out.append(property("CATEGORY", index) ?? keyword("CATEGORY") ?? (name as NSString).deletingPathExtension)
331                case "todo-state": if let todo = info.todo { out.append(todo) }
332                case "local-tags": out += tags(info.localTags)
333                case "all-tags": out += tags(model.tags(of: index).map(\.value))
334                default: break
335                }
336            }
337            var seen: Set<String> = []
338            return out.filter { seen.insert($0).inserted }.joined(separator: ",")
339        }
340
341        func includesTodo(_ index: Int, todoType: String) -> Bool {
342            switch options.includeTodo {
343            case .none: return false
344            case .all: return true
345            case .unfinished: return todoType == "todo"
346            case .keywords(let list): return model.headings[index].todo.map(list.contains) ?? false
347            case .unblocked: return !blocked(index)
348            }
349        }
350
351        /// `org-icalendar-blocked-headline-p`.
352        func blocked(_ index: Int) -> Bool {
353            let level = model.headings[index].level
354            for child in model.headings[(index + 1)...].prefix(while: { $0.level > level }) where child.todo != nil && !child.isDone { return true }
355            var current = index
356            for parent in model.ancestors(of: index).reversed() {
357                guard model.headings[parent].todo != nil else { return false }
358                let ordered = model.headings[parent].properties.last { $0.key.uppercased() == "ORDERED" }?.value
359                if let ordered, !ordered.isEmpty, ordered != "nil" {
360                    let siblings = model.headings.indices.filter { model.headings[$0].parent == parent && $0 < current }
361                    if siblings.contains(where: { model.headings[$0].todo != nil && !model.headings[$0].isDone }) { return true }
362                } else {
363                    current = parent
364                }
365            }
366            return false
367        }
368
369        // MARK: Components
370
371        func vevent(_ entry: Entry, _ stamp: Timestamp, uid: String, summary: String) -> String {
372            var out = "BEGIN:VEVENT\n" + dtstamp + "\nUID:" + uid + "\n"
373            out += convert(stamp, "DTSTART", end: false, tz: entry.timezone) + "\n"
374            out += convert(stamp, "DTEND", end: true, tz: entry.timezone) + "\n"
375            if let r = stamp.repeater { out += rrule(r.interval) + "\n" }
376            out += "SUMMARY:" + summary + "\n"
377            if let l = entry.location, l.contains(where: { !$0.isWhitespace }) { out += "LOCATION:\(l)\n" }
378            if let c = entry.klass, c.contains(where: { !$0.isWhitespace }) { out += "CLASS:\(c)\n" }
379            if let d = entry.description, d.contains(where: { !$0.isWhitespace }) { out += "DESCRIPTION:\(d)\n" }
380            out += "CATEGORIES:" + entry.categories + "\n"
381            out += valarm(entry, stamp, summary: summary)
382            return out + "END:VEVENT\n"
383        }
384
385        var dtstamp: String {
386            var utc = Calendar(identifier: .gregorian)
387            utc.timeZone = TimeZone(identifier: "UTC")!
388            return "DTSTAMP:" + format(now, "%Y%m%dT%H%M%SZ", utc)
389        }
390
391        func rrule(_ interval: Timestamp.Interval) -> String {
392            let freq = ["h": "HOURLY", "d": "DAILY", "w": "WEEKLY", "m": "MONTHLY", "y": "YEARLY"][String(interval.unit.rawValue)]!
393            return "RRULE:FREQ=\(freq);INTERVAL=\(interval.value)"
394        }
395
396        func valarm(_ entry: Entry, _ stamp: Timestamp, summary: String) -> String {
397            let alarm = entry.warnTime
398            guard (alarm.map { $0 > 0 } ?? false) || options.alarmTime > 0 || options.forceAlarm, stamp.start.hour != nil else { return "" }
399            let minutes: Int
400            if let alarm, options.forceAlarm { minutes = alarm } else if let alarm, alarm != 0 { minutes = alarm } else { minutes = options.alarmTime }
401            return "BEGIN:VALARM\nACTION:DISPLAY\nDESCRIPTION:\(summary)\nTRIGGER:-P0DT0H\(minutes)M0S\nEND:VALARM\n"
402        }
403
404        /// `org-icalendar--repeater-type`: only `+` repeaters repeat a VTODO.
405        static func repeats(_ stamp: Timestamp?) -> Bool {
406            guard let r = stamp?.repeater, r.interval.value > 0 else { return false }
407            return r.kind == .cumulate
408        }
409
410        func vtodo(_ entry: Entry, _ index: Int, todoType: String) -> String {
411            let info = model.headings[index]
412            let sc = options.useScheduled.contains("todo-start") ? info.scheduled : nil
413            let dl = options.useDeadline.contains("todo-due") ? info.deadline : nil
414            let scRepeats = Self.repeats(sc)
415            let dlRepeats = Self.repeats(dl)
416            let repeatInterval = sc?.repeater?.interval ?? dl?.repeater?.interval
417            let until = scRepeats && !dlRepeats ? dl : nil
418            var start: Timestamp? = sc
419            if start == nil {
420                switch options.todoUnscheduledStart {
421                case "current-datetime":
422                    let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: now)
423                    start = Timestamp(active: true, start: .init(year: c.year!, month: c.month!, day: c.day!, hour: c.hour, minute: c.minute), end: nil, repeater: nil, warning: nil)
424                case "deadline-warning" where dl != nil, "recurring-deadline-warning" where dlRepeats:
425                    start = shifted(dl!, days: -warningDays(dl!))
426                default: break
427                }
428            }
429            var out = "BEGIN:VTODO\nUID:TODO-" + entry.uid + "\n" + dtstamp + "\n"
430            if let start { out += convert(start, "DTSTART", end: false, tz: entry.timezone) + "\n" }
431            if let dl, until == nil { out += convert(dl, "DUE", end: false, tz: entry.timezone) + "\n" }
432            if dlRepeats, repeatInterval != dl?.repeater?.interval {
433                // Different repeaters on SCHEDULED and DEADLINE: no RRULE, as Org warns.
434            } else if dlRepeats, sc != nil, !scRepeats {
435                // A repeater on DEADLINE but not SCHEDULED: no RRULE either.
436            } else if scRepeats || dlRepeats, let repeatInterval {
437                out += rrule(repeatInterval)
438                if let until {
439                    let local = entry.timezone == nil && options.dateTimeFormat == ":%Y%m%dT%H%M%S"
440                    let date = self.date(until.start.year, until.start.month, until.start.day, until.start.hour ?? 0, until.start.minute ?? 0)
441                    var utc = Calendar(identifier: .gregorian)
442                    utc.timeZone = TimeZone(identifier: "UTC")!
443                    out += ";UNTIL=" + (start?.start.minute == nil ? format(date, "%Y%m%d", calendar)
444                        : local ? format(date, "%Y%m%dT%H%M%S", calendar) : format(date, "%Y%m%dT%H%M%SZ", utc))
445                }
446                out += "\n"
447            }
448            out += "SUMMARY:" + entry.summary + "\n"
449            if let l = entry.location, l.contains(where: { !$0.isWhitespace }) { out += "LOCATION:\(l)\n" }
450            if let c = entry.klass, c.contains(where: { !$0.isWhitespace }) { out += "CLASS:\(c)\n" }
451            if let d = entry.description, d.contains(where: { !$0.isWhitespace }) { out += "DESCRIPTION:\(d)\n" }
452            out += "CATEGORIES:" + entry.categories + "\n" + "SEQUENCE:1\n"
453            out += "PRIORITY:\(priority(info.priority))\n"
454            out += "STATUS:" + (todoType == "todo" ? "NEEDS-ACTION" : "COMPLETED") + "\n"
455            return out + "END:VTODO\n"
456        }
457
458        func priority(_ cookie: String?) -> Int {
459            func code(_ s: String) -> Int { Int(s) ?? Int(s.unicodeScalars.first?.value ?? 66) }
460            let p = settings.priorities
461            let highest = code(p.highest), lowest = code(p.lowest)
462            let value = code(cookie ?? p.default)
463            guard lowest != highest else { return 5 }
464            return Int((9 - 8 * (Double(lowest - value) / Double(lowest - highest))).rounded(.down))
465        }
466
467        /// `org-get-wdays`: the deadline's warning period in days.
468        func warningDays(_ stamp: Timestamp) -> Int {
469            guard let w = stamp.warning else { return settings.deadlineWarningDays }
470            let n = Double(w.interval.value)
471            switch w.interval.unit {
472            case .hour: return Int((n / 24).rounded(.down))
473            case .day: return Int(n)
474            case .week: return Int(n * 7)
475            case .month: return Int((n * 30.4).rounded(.down))
476            case .year: return Int((n * 365.25).rounded(.down))
477            }
478        }
479
480        func shifted(_ stamp: Timestamp, days: Int) -> Timestamp {
481            var copy = stamp
482            let absolute = Days.absolute(year: stamp.start.year, month: stamp.start.month, day: stamp.start.day) + days
483            let d = Days.date(absolute)
484            (copy.start.year, copy.start.month, copy.start.day) = (d.year, d.month, d.day)
485            copy.end = nil
486            return copy
487        }
488
489        func date(_ y: Int, _ m: Int, _ d: Int, _ h: Int, _ mi: Int) -> Date {
490            calendar.date(from: DateComponents(year: y, month: m, day: d, hour: h, minute: mi, second: 0)) ?? now
491        }
492
493        /// `org-icalendar-convert-timestamp`.
494        func convert(_ stamp: Timestamp, _ keyword: String, end: Bool, tz: String?) -> String {
495            let s = stamp.start
496            let e = stamp.end ?? stamp.start
497            let timed = s.minute != nil || s.hour != nil
498            let equal = stamp.end == nil || (s.year, s.month, s.day, s.hour, s.minute) == (e.year, e.month, e.day, e.hour, e.minute)
499            let mi = !timed ? 0 : !end ? (s.minute ?? 0) : (options.appointmentDuration != nil && equal) ? (e.minute ?? 0) + options.appointmentDuration! : (e.minute ?? 0)
500            let h = !timed ? 0 : !end ? (s.hour ?? 0) : (!equal || options.appointmentDuration != nil) ? (e.hour ?? 0) : (e.hour ?? 0) + 2
501            let d = !end ? s.day : !timed ? e.day + 1 : e.day
502            let m = end ? e.month : s.month
503            let y = end ? e.year : s.year
504            let date = self.date(y, m, d, h, mi)
505            var utc = Calendar(identifier: .gregorian)
506            utc.timeZone = TimeZone(identifier: "UTC")!
507            if tz == "UTC" { return keyword + format(date, ":%Y%m%dT%H%M%SZ", utc) }
508            if !timed { return keyword + format(date, ";VALUE=DATE:%Y%m%d", calendar) }
509            if let tz { return keyword + ";TZID=" + tz + format(date, ":%Y%m%dT%H%M%S", calendar) }
510            let pattern = options.dateTimeFormat.replacingOccurrences(of: "%Z", with: options.timezone ?? "")
511            return keyword + format(date, pattern, options.dateTimeFormat.hasSuffix("Z") ? utc : calendar)
512        }
513
514        /// `format-time-string` for `%Y %m %d %H %M %S`.
515        func format(_ date: Date, _ pattern: String, _ calendar: Calendar) -> String {
516            let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
517            var out = ""
518            var i = pattern.startIndex
519            while i < pattern.endIndex {
520                let ch = pattern[i]
521                let next = pattern.index(after: i)
522                if ch == "%", next < pattern.endIndex {
523                    switch pattern[next] {
524                    case "Y": out += String(format: "%04d", c.year!)
525                    case "m": out += String(format: "%02d", c.month!)
526                    case "d": out += String(format: "%02d", c.day!)
527                    case "H": out += String(format: "%02d", c.hour!)
528                    case "M": out += String(format: "%02d", c.minute!)
529                    case "S": out += String(format: "%02d", c.second!)
530                    case "%": out += "%"
531                    default: out += String(pattern[i...next])
532                    }
533                    i = pattern.index(after: next)
534                } else {
535                    out.append(ch)
536                    i = next
537                }
538            }
539            return out
540        }
541    }
542}
543
544extension ASCIIText {
545    /// A line of Org text's objects, as a title is exported.
546    func inlineString(_ text: String) -> String {
547        let tree = OrgParser.parse(text)
548        guard let paragraph = tree.root.descendants().first(where: { $0.kind == .paragraph }) else { return text }
549        return inline(paragraph).trimmingCharacters(in: .whitespacesAndNewlines)
550    }
551}