Sources/OrgCore/Capture/Capture.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgCore/Capture/Capture.swift history · blame · raw

991 lines · 48973 bytes

  1import Foundation
  2
  3// Capture (org-capture.el, Org 9.8.7): filling a template and placing the result in its
  4// target, as `org-capture` followed by `org-capture-finalize` leaves the target file.
  5
  6public struct CaptureTemplate: Sendable, Equatable, Identifiable {
  7    public enum Kind: String, Sendable, Equatable { case entry, item, checkitem, plain, tableLine = "table-line" }
  8
  9    /// `:tree-type`: what a date tree groups entries by.
 10    public enum TreeType: String, Sendable, Equatable { case day, week, month }
 11
 12    public enum Target: Sendable, Equatable {
 13        case file(String)
 14        case headline(file: String, headline: String)
 15        case outline(file: String, path: [String])
 16        /// `file+olp+datetree`: today's entry in a date tree, under `path` or at the top.
 17        case datetree(file: String, path: [String], tree: TreeType)
 18        /// `(id "…")`: the heading with that ID; the app finds its file.
 19        case id(String)
 20        /// `(clock)`: the clocked-in entry; the app turns it into `heading`.
 21        case clock
 22        /// The heading starting at `offset` in `file`.
 23        case heading(file: String, offset: Int)
 24
 25        /// The target file, or "" for `id` and `clock` until the app resolves them.
 26        public var file: String {
 27            switch self {
 28            case .file(let f), .headline(let f, _), .outline(let f, _), .datetree(let f, _, _), .heading(let f, _): f
 29            case .id, .clock: ""
 30            }
 31        }
 32    }
 33
 34    /// Template properties beyond the target (`org-capture-templates`).
 35    public struct Options: Sendable, Equatable {
 36        public var prepend = false
 37        /// `:immediate-finish`: file without showing the text.
 38        public var immediateFinish = false
 39        /// `:empty-lines`, `:empty-lines-before`, `:empty-lines-after`.
 40        public var emptyLines: Int?
 41        public var emptyLinesBefore: Int?
 42        public var emptyLinesAfter: Int?
 43        /// `:jump-to-captured`: show the entry after filing it.
 44        public var jumpToCaptured = false
 45        /// `:clock-in`, `:clock-keep`, `:clock-resume`.
 46        public var clockIn = false
 47        public var clockKeep = false
 48        public var clockResume = false
 49        /// `:table-line-pos`: `II-3` is the third line above the second rule.
 50        public var tableLinePos: String?
 51
 52        public init(
 53            prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
 54            emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false,
 55            tableLinePos: String? = nil
 56        ) {
 57            self.tableLinePos = tableLinePos
 58            self.prepend = prepend
 59            self.immediateFinish = immediateFinish
 60            self.emptyLines = emptyLines
 61            self.emptyLinesBefore = emptyLinesBefore
 62            self.emptyLinesAfter = emptyLinesAfter
 63            self.jumpToCaptured = jumpToCaptured
 64            self.clockIn = clockIn
 65            self.clockKeep = clockKeep
 66            self.clockResume = clockResume
 67        }
 68
 69        var before: Int? { emptyLinesBefore ?? emptyLines }
 70        var after: Int { emptyLinesAfter ?? emptyLines ?? 0 }
 71    }
 72
 73    public let key: String
 74    public let name: String
 75    public let kind: Kind
 76    public let target: Target
 77    public let template: String
 78    public let options: Options
 79    public var prepend: Bool { options.prepend }
 80    public var id: String { key }
 81
 82    public init(key: String, name: String, kind: Kind = .entry, target: Target, template: String, prepend: Bool = false, options: Options = Options()) {
 83        self.key = key
 84        self.name = name
 85        self.kind = kind
 86        self.target = target
 87        self.template = template
 88        var options = options
 89        if prepend { options.prepend = true }
 90        self.options = options
 91    }
 92
 93    /// The same template aimed at `target`.
 94    public func retargeted(_ target: Target) -> CaptureTemplate {
 95        CaptureTemplate(key: key, name: name, kind: kind, target: target, template: template, options: options)
 96    }
 97}
 98
 99/// What the escapes in a template stand for.
100public struct CaptureContext: Sendable {
101    public var now: Date
102    public var calendar: Calendar
103    /// `%i`: the selected text.
104    public var initial: String
105    /// `%a`: a link to where capture started, `[[target][description]]`, or empty.
106    public var annotation: String
107    /// `%c` and `%x`: the clipboard.
108    public var clipboard: String
109    /// `%f` and `%F`: the file capture started from.
110    public var file: String
111    /// `%n`.
112    public var userName: String
113    /// `%k` and `%K`: the clocked-in entry's title and a link to it, or empty.
114    public var clockHeading: String
115    public var clockLink: String
116    /// `%^g` and `%^G` offer these: the target file's tags, and every file's.
117    public var fileTags: [String]
118    public var allTags: [String]
119    /// `org-tags-column`, for aligning tags `%^g` adds to a heading.
120    public var tagsColumn: Int
121    /// `org-store-link-plist` as org-protocol sets it, for `%:link`, `%:description` and others.
122    public var linkProperties: [String: String] = [:]
123    /// `%[file]`: what relative paths are relative to, and the contents of a file by its
124    /// absolute path, nil when it can't be read.
125    public var directory = NSHomeDirectory()
126    public var readFile: @Sendable (String) -> String? = { _ in nil }
127
128    public init(
129        now: Date = Date(), calendar: Calendar = .current, initial: String = "", annotation: String = "", clipboard: String = "",
130        file: String = "", userName: String = "", clockHeading: String = "", clockLink: String = "",
131        fileTags: [String] = [], allTags: [String] = [], tagsColumn: Int = -77
132    ) {
133        self.now = now
134        self.calendar = calendar
135        self.initial = initial
136        self.annotation = annotation
137        self.clipboard = clipboard
138        self.file = file
139        self.userName = userName
140        self.clockHeading = clockHeading
141        self.clockLink = clockLink
142        self.fileTags = fileTags
143        self.allTags = allTags
144        self.tagsColumn = tagsColumn
145    }
146}
147
148public enum Capture {
149    public enum Failure: Error, Equatable {
150        case message(String)
151    }
152
153    /// A question the template asks before it can be filled: `%^{prompt|default|choice…}`,
154    /// or one of `%^g`, `%^G`, `%^t`, `%^T`, `%^u`, `%^U`, `%^C`, `%^L`, `%^{prop}p`.
155    public struct Question: Sendable, Equatable {
156        public enum Kind: Sendable, Equatable {
157            case text
158            /// Tags, separated by colons.
159            case tags
160            /// A date as `org-read-date` reads it (`+2d`, `fri 14:00`); empty is today.
161            case date(withTime: Bool, inactive: Bool)
162            /// `%^C` and `%^L`: text from the clipboard, inserted as a link with `link`.
163            case clipboard(link: Bool)
164            /// `%^{NAME}p`: the value of property `NAME`.
165            case property
166        }
167
168        public let prompt: String
169        public let defaultValue: String
170        public let choices: [String]
171        public let kind: Kind
172
173        public init(prompt: String, defaultValue: String, choices: [String], kind: Kind = .text) {
174            self.prompt = prompt
175            self.defaultValue = defaultValue
176            self.choices = choices
177            self.kind = kind
178        }
179    }
180
181    static let promptPattern = "%\\^(?:\\{([^}]*)\\})?([CgGLptTuU])?"
182
183    /// The questions `template` asks, in order.
184    public static func questions(_ template: String, context: CaptureContext = CaptureContext()) -> [Question] {
185        let embedded = Embedded(context, answers: [])
186        guard case .success(let expanded) = expand(template, context, embedded: embedded) else { return [] }
187        // `read-string` in `%(…)` asks first, as Org evaluates those before the prompts.
188        return embedded.questions + prompts(in: expanded).map { question($0.items, $0.key, context) }
189    }
190
191    static func question(_ items: [String]?, _ key: String?, _ context: CaptureContext) -> Question {
192        let prompt = items?.first
193        let defaultValue = items.map { $0.count > 1 ? $0[1] : "" } ?? ""
194        switch key {
195        case "g", "G": return Question(prompt: prompt ?? "Tags", defaultValue: "", choices: key == "g" ? context.fileTags : context.allTags, kind: .tags)
196        case "t", "T", "u", "U":
197            let upper = key == key?.uppercased()
198            return Question(prompt: prompt ?? "Date", defaultValue: "", choices: [], kind: .date(withTime: upper, inactive: key == "u" || key == "U"))
199        case "C", "L":
200            let values = [context.initial, context.clipboard].filter { !$0.isEmpty }
201            return Question(prompt: "Clipboard/kill value", defaultValue: context.initial, choices: values, kind: .clipboard(link: key == "L"))
202        case "p": return Question(prompt: prompt ?? "", defaultValue: defaultValue, choices: [], kind: .property)
203        default: return Question(prompt: prompt ?? "Enter string", defaultValue: defaultValue, choices: items.map { Array($0.dropFirst(2)) } ?? [])
204        }
205    }
206
207    /// The unescaped `%^` placeholders in `text`.
208    static func prompts(in text: String) -> [(range: NSRange, items: [String]?, key: String?)] {
209        let regex = try! NSRegularExpression(pattern: promptPattern)
210        let ns = text as NSString
211        return regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).compactMap { m in
212            guard !escaped(ns, at: m.range.location) else { return nil }
213            let items = m.range(at: 1).location == NSNotFound ? nil : ns.substring(with: m.range(at: 1)).components(separatedBy: "|")
214            let key = m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2))
215            return (m.range, items, key)
216        }
217    }
218
219    /// `org-capture-escaped-%` without its unescaping: an odd run of backslashes before `%`.
220    static func escaped(_ ns: NSString, at index: Int) -> Bool {
221        var i = index
222        while i > 0, ns.character(at: i - 1) == 92 { i -= 1 }
223        return (index - i) % 2 == 1
224    }
225
226    /// Where `%?` puts the cursor while the template is filled.
227    static let cursorMark = "\u{E000}"
228
229    /// `org-capture-fill-template`: the text and where `%?` puts the cursor. `answers` holds
230    /// the replies to `questions(template)` in order.
231    public static func fill(_ template: String, context: CaptureContext, answers: [String] = []) -> Result<(text: String, cursor: Int), Failure> {
232        let expanded: String
233        let embedded = Embedded(context, answers: answers)
234        switch expand(template, context, embedded: embedded) {
235        case .failure(let failure): return .failure(failure)
236        case .success(let text): expanded = text
237        }
238        let answers = Array(answers.dropFirst(embedded.used))
239        // Prompts, in order, answered in the text as it stands then, as org does.
240        var options = EditingOptions.org
241        options.tagsColumn = context.tagsColumn
242        let buffer = EmacsBuffer(expanded, point: 0, settings: .default, options: options)
243        buffer.now = context.now
244        buffer.calendar = context.calendar
245        var strings: [String] = []
246        var all: [String] = []
247        var index = 0
248        while let match = buffer.searchForward(promptPattern, caseInsensitive: false) {
249            let whole = match[0]!
250            if unescape(buffer, at: whole.lowerBound) { continue }
251            let start = buffer.point - whole.count
252            let items = match[1].map { buffer.substring($0.lowerBound, $0.upperBound).components(separatedBy: "|") }
253            let key = match[2].map { buffer.substring($0.lowerBound, $0.upperBound) }
254            let question = question(items, key, context)
255            let answer = index < answers.count ? answers[index] : ""
256            index += 1
257            buffer.deleteRegion(start, buffer.point)
258            buffer.point = start
259            switch question.kind {
260            case .text:
261                let value = answer.isEmpty ? question.defaultValue : answer
262                strings.append(value)
263                all.append(value)
264                buffer.insert(value)
265            case .tags:
266                let tags = answer.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
267                guard !tags.isEmpty else { continue }
268                all.append(":" + tags.joined(separator: ":") + ":")
269                if buffer.point == 0 || buffer.character(at: buffer.point - 1) != 58 { buffer.insert(":") }
270                buffer.insert(tags.joined(separator: ":"))
271                if buffer.point >= buffer.length || buffer.character(at: buffer.point) != 58 { buffer.insert(":") }
272                if buffer.lookingAtLine("^\\*+ ") { buffer.alignTags(onLineAt: buffer.point) }
273            case .date(let withTime, let inactive):
274                let result: ReadDate.Answer
275                if answer.trimmingCharacters(in: .whitespaces).isEmpty {
276                    let c = context.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: context.now)
277                    result = ReadDate.Answer(year: c.year!, month: c.month!, day: c.day!, hour: c.hour!, minute: c.minute!, timeGiven: false)
278                } else {
279                    result = buffer.readDate(answer, default: context.now)
280                }
281                let stamp = buffer.insertTimestamp(result.components(context.calendar), withTime: result.timeGiven || withTime, inactive: inactive, endTime: result.endTime)
282                all.append(stamp)
283            case .clipboard(let link):
284                let value = answer.isEmpty ? question.defaultValue : answer
285                all.append(value)
286                buffer.insert(link ? Links.makeString(value, nil) : value)
287            case .property:
288                let value = answer.isEmpty ? question.defaultValue : answer
289                buffer.saveExcursion { buffer.entryPut(question.prompt, value) }
290                all.append(value)
291            }
292        }
293        // `%\N`: the Nth `%^{…}` answer; `%\*N`: the Nth answer of any prompt.
294        var text = buffer.string
295        for (pattern, values) in [("%\\\\\\*([1-9][0-9]*)", all), ("%\\\\([1-9][0-9]*)", strings)] {
296            let regex = try! NSRegularExpression(pattern: pattern)
297            let ns = text as NSString
298            var out = text
299            for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).reversed() where !escaped(ns, at: m.range.location) {
300                let n = Int(ns.substring(with: m.range(at: 1))) ?? Int.max
301                out = (out as NSString).replacingCharacters(in: m.range, with: n <= values.count ? values[n - 1] : "")
302            }
303            text = out
304        }
305        // No blank lines before the text; it ends with one newline, or is empty.
306        var lines = text.components(separatedBy: "\n")
307        while let first = lines.first, first.trimmingCharacters(in: .whitespaces).isEmpty, lines.count > 1 { lines.removeFirst() }
308        var marked = lines.joined(separator: "\n")
309        let trimmed = marked.replacingOccurrences(of: "[ \\t\\n]+$", with: "", options: .regularExpression)
310        marked = trimmed.isEmpty ? "" : trimmed + "\n"
311        marked = marked.replacingOccurrences(of: "\t", with: "        ")
312        guard let range = marked.range(of: cursorMark) else { return .success((marked, marked.utf16.count > 0 ? marked.utf16.count - 1 : 0)) }
313        let offset = marked[..<range.lowerBound].utf16.count
314        marked.removeSubrange(range)
315        return .success((marked, offset))
316    }
317
318    /// `org-capture-escaped-%` at the `%` at `index`: drops half the backslashes before it;
319    /// true when it was escaped. Point follows the deletion.
320    static func unescape(_ buffer: EmacsBuffer, at index: Int) -> Bool {
321        var i = index
322        while i > 0, buffer.character(at: i - 1) == 92 { i -= 1 }
323        let n = index - i
324        guard n > 0 else { return false }
325        buffer.deleteRegion(i, i + (n + 1) / 2)
326        return n % 2 == 1
327    }
328
329    /// `%[file]`: the file's contents in place of each, as `org-capture-fill-template` inserts
330    /// them before the other escapes, so escapes in the file expand too.
331    static func insertFiles(_ template: String, _ context: CaptureContext) -> String {
332        let buffer = EmacsBuffer(template, point: 0)
333        var inserted = 0
334        // A file that inserts itself would never end; Emacs doesn't stop either.
335        while inserted < 100, let match = buffer.searchForward("%\\[(.+)\\]", caseInsensitive: false, move: true) {
336            let name = buffer.substring(match[1]!.lowerBound, match[1]!.upperBound)
337            let start = buffer.marker(match[0]!.lowerBound)
338            let end = buffer.marker(match[0]!.upperBound)
339            defer {
340                buffer.release(start)
341                buffer.release(end)
342            }
343            if unescape(buffer, at: start.position) { continue }
344            let expanded = name.hasPrefix("~") ? NSHomeDirectory() + name.dropFirst() : name
345            let path = ((expanded as NSString).isAbsolutePath ? expanded : (context.directory as NSString).appendingPathComponent(expanded) as String)
346            let file = (path as NSString).standardizingPath
347            buffer.deleteRegion(start.position, end.position)
348            buffer.point = start.position
349            if let contents = context.readFile(file) {
350                buffer.saveExcursion { buffer.insert(contents) }
351                inserted += 1
352            } else {
353                buffer.insert("%![could not insert \(file): (file-missing Opening input file No such file or directory \(file))]")
354            }
355        }
356        return buffer.string
357    }
358
359    /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…) and then `%(…)`, with `%^`
360    /// prompts and `%\N` left in place. `embedded` evaluates `%(…)`.
361    static func expand(_ template: String, _ context: CaptureContext, embedded: Embedded? = nil) -> Result<String, Failure> {
362        let template = insertFiles(template, context)
363        let embedded = embedded ?? Embedded(context, answers: [])
364        func stamp(_ active: Bool, _ withTime: Bool) -> String {
365            let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now)
366            let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1]
367            let body = String(format: "%04d-%02d-%02d %@", c.year!, c.month!, c.day!, day) + (withTime ? String(format: " %02d:%02d", c.hour!, c.minute!) : "")
368            return active ? "<\(body)>" : "[\(body)]"
369        }
370        let link = try! NSRegularExpression(pattern: "\\[\\[(.*?)\\](\\[.*?\\])?\\]")
371        func linkForm(_ template: String) -> String {
372            let ns = context.annotation as NSString
373            guard let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) else { return context.annotation }
374            return template.replacingOccurrences(of: "$1", with: ns.substring(with: m.range(at: 1)))
375        }
376        var text = ""
377        let chars = Array(template)
378        let sexps = embeddedSexps(chars)
379        // Where the `%(…)` forms being copied end; values put inside one are escaped as in a
380        // Lisp string.
381        var sexpEnds: [Int] = []
382        func put(_ value: String) {
383            text += sexpEnds.isEmpty ? value : value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
384        }
385        var i = 0
386        while i < chars.count {
387            while sexpEnds.last == i {
388                text += Self.sexpEndMark
389                sexpEnds.removeLast()
390            }
391            let c = chars[i]
392            guard c == "%", i + 1 < chars.count else {
393                text.append(c)
394                i += 1
395                continue
396            }
397            // A `%` after an odd run of backslashes stays, with half of them.
398            var slashes = 0
399            while slashes < text.count, text.dropLast(slashes).last == "\\" { slashes += 1 }
400            let next = chars[i + 1]
401            if slashes > 0, "aAcfFikKlLntTuUx:<?(".contains(next) {
402                text.removeLast((slashes + 1) / 2)
403                if slashes % 2 == 1 {
404                    text.append(c)
405                    i += 1
406                    continue
407                }
408            }
409            var consumed = 2
410            switch next {
411            case "?": text += cursorMark
412            case "i":
413                if !sexpEnds.isEmpty {
414                    put(context.initial)
415                    break
416                }
417                // Continuation lines keep the indentation of the line `%i` is on.
418                let lead = String(text.split(separator: "\n", omittingEmptySubsequences: false).last ?? "").prefix { $0 == " " || $0 == "\t" }
419                text += context.initial.replacingOccurrences(of: "\n", with: "\n" + lead)
420            case "a": put(context.annotation == "[[]]" ? "" : context.annotation)
421            case "A":
422                // The link, with its description asked for.
423                let ns = context.annotation as NSString
424                if let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) {
425                    put(ns.replacingCharacters(in: m.range, with: "[[" + ns.substring(with: m.range(at: 1)) + "][%^{Link description}]]"))
426                } else {
427                    put(context.annotation)
428                }
429            case "l": put(linkForm("[[$1]]"))
430            case "L": put(linkForm("$1"))
431            case "c", "x": put(context.clipboard)
432            case "f": put((context.file as NSString).lastPathComponent)
433            case "F": put(context.file)
434            case "n": put(context.userName)
435            case "k": put(context.clockHeading)
436            case "K": put(context.clockLink)
437            case "t": put(stamp(true, false))
438            case "T": put(stamp(true, true))
439            case "u": put(stamp(false, false))
440            case "U": put(stamp(false, true))
441            case "<":
442                guard let close = chars[(i + 2)...].firstIndex(of: ">"), !chars[(i + 2)..<close].contains("\n") else {
443                    text.append(c)
444                    consumed = 1
445                    break
446                }
447                put(strftime(String(chars[(i + 2)..<close]), context))
448                consumed = close - i + 1
449            case ":":
450                // A link property (`%:annotation`), from org-protocol or the capture's own.
451                var j = i + 2
452                while j < chars.count, chars[j].isLetter || chars[j] == "-" { j += 1 }
453                guard j > i + 2 else {
454                    text.append(c)
455                    consumed = 1
456                    break
457                }
458                let name = String(chars[(i + 2)..<j])
459                switch name {
460                case _ where context.linkProperties[name] != nil: put(context.linkProperties[name]!)
461                case "annotation": put(context.annotation)
462                case "initial": put(context.initial)
463                default: break
464                }
465                consumed = j - i
466            case "(":
467                // The form is copied with the escapes in it expanded, then evaluated.
468                if let end = sexps[i], sexpEnds.isEmpty {
469                    text += Self.sexpStartMark
470                    sexpEnds.append(end)
471                } else {
472                    text.append(c)
473                }
474                consumed = 1
475            default:
476                text.append(c)
477                consumed = 1
478            }
479            i += consumed
480        }
481        if !sexpEnds.isEmpty { text += Self.sexpEndMark }
482        // `%(…)`, in order.
483        var out = ""
484        var rest = Substring(text)
485        while let open = rest.firstIndex(of: Character(Self.sexpStartMark)) {
486            out += rest[..<open]
487            let body = rest[rest.index(after: open)...]
488            let close = body.firstIndex(of: Character(Self.sexpEndMark)) ?? body.endIndex
489            switch embedded.evaluate(String(body[..<close])) {
490            case .success(let value): out += value
491            case .failure(let failure): return .failure(failure)
492            }
493            rest = close == body.endIndex ? "" : body[body.index(after: close)...]
494        }
495        return .success(out + rest)
496    }
497
498    static let sexpStartMark = "\u{E001}"
499    static let sexpEndMark = "\u{E002}"
500
501    static func strftime(_ format: String, _ context: CaptureContext) -> String {
502        let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: context.now)
503        let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
504        let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
505        var out = ""
506        var chars = format.makeIterator()
507        while let ch = chars.next() {
508            guard ch == "%", let f = chars.next() else {
509                out.append(ch)
510                continue
511            }
512            switch f {
513            case "Y": out += String(format: "%04d", c.year!)
514            case "m": out += String(format: "%02d", c.month!)
515            case "d": out += String(format: "%02d", c.day!)
516            case "e": out += String(format: "%2d", c.day!)
517            case "H": out += String(format: "%02d", c.hour!)
518            case "M": out += String(format: "%02d", c.minute!)
519            case "S": out += String(format: "%02d", c.second!)
520            case "a": out += String(days[c.weekday! - 1].prefix(3))
521            case "A": out += days[c.weekday! - 1]
522            case "b": out += String(months[c.month! - 1].prefix(3))
523            case "B": out += months[c.month! - 1]
524            case "F": out += String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
525            case "R": out += String(format: "%02d:%02d", c.hour!, c.minute!)
526            case "%": out += "%"
527            default: out += "%" + String(f)
528            }
529        }
530        return out
531    }
532
533    // MARK: - Placing
534
535    /// The target file's text after capturing `text`, as `org-capture-finalize` leaves it.
536    /// `now` and `calendar` pick a date tree's day.
537    public static func place(
538        _ text: String, template: CaptureTemplate, in fileText: String, settings: OrgSettings = .default,
539        now: Date = Date(), calendar: Calendar = .current
540    ) -> Result<String, Failure> {
541        placement(text, template: template, in: fileText, settings: settings, now: now, calendar: calendar).map(\.text)
542    }
543
544    /// The new text, and where the captured entry starts in it.
545    public static func placement(
546        _ text: String, template: CaptureTemplate, in fileText: String, settings: OrgSettings = .default,
547        now: Date = Date(), calendar: Calendar = .current
548    ) -> Result<(text: String, start: Int), Failure> {
549        let buffer = EmacsBuffer(fileText, point: 0, settings: settings)
550        let start: Int
551        do {
552            let entryHeading = try locate(template.target, buffer, date: calendar.dateComponents([.year, .month, .day], from: now))
553            let options = template.options
554            switch template.kind {
555            case .entry: start = try placeEntry(text, options: options, heading: entryHeading, buffer)
556            case .plain: start = placePlain(text, options: options, heading: entryHeading, buffer)
557            case .item, .checkitem: start = try placeItem(text, checkbox: template.kind == .checkitem, options: options, heading: entryHeading, buffer)
558            case .tableLine: start = try placeTableLine(text, options: options, heading: entryHeading, buffer)
559            }
560        } catch let error as Failure {
561            return .failure(error)
562        } catch let error as EmacsBuffer.UserError {
563            return .failure(.message(error.message))
564        } catch {
565            return .failure(.message("\(error)"))
566        }
567        // Saving the target adds a final newline, as `require-final-newline` does in Org.
568        var result = buffer.text as String
569        if !result.isEmpty, !result.hasSuffix("\n") { result += "\n" }
570        return .success((result, start))
571    }
572
573    /// `org-capture-set-target-location`: point at the target heading, or nil for a file.
574    static func locate(_ target: CaptureTemplate.Target, _ buffer: EmacsBuffer, date: DateComponents) throws -> Int? {
575        switch target {
576        case .file:
577            return nil
578        case .id(let id):
579            buffer.point = 0
580            guard let match = buffer.searchForward("^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: id) + "[ \\t]*$", caseInsensitive: true) else {
581                throw Failure.message("Cannot find target ID \"\(id)\"")
582            }
583            buffer.point = match[0]!.lowerBound
584            buffer.backToHeadingOrPointMin()
585            return buffer.beforeFirstHeading ? nil : buffer.point
586        case .clock:
587            throw Failure.message("No running clock")
588        case .heading(_, let offset):
589            guard offset <= buffer.length else { throw Failure.message("The clocked entry moved; try again") }
590            buffer.point = buffer.lineStart(offset)
591            guard atHeading(buffer) else { throw Failure.message("The clocked entry moved; try again") }
592            return buffer.point
593        case .datetree(_, let path, let tree):
594            let parent = path.isEmpty ? nil : try locate(.outline(file: "", path: path), buffer, date: date)
595            return Datetree.findCreate(buffer, under: parent, tree: tree, date: date)
596        case .headline(_, let headline):
597            buffer.point = 0
598            let pattern = "^\\*+[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: headline) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
599            if let match = buffer.searchForward(pattern, caseInsensitive: false) {
600                return buffer.lineStart(match[0]!.lowerBound)
601            }
602            buffer.point = buffer.length
603            if !buffer.bolp { buffer.insert("\n") }
604            let start = buffer.point
605            buffer.insert("* " + headline + "\n")
606            return start
607        case .outline(_, let path):
608            var start = 0
609            var end = buffer.length
610            var level = 0
611            var found: Int?
612            for title in path {
613                buffer.point = start
614                let pattern = "^(\\*+)[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: title) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
615                var hit: Int?
616                while let match = buffer.searchForward(pattern, bound: end, caseInsensitive: false) {
617                    let stars = buffer.substring(match[1]!.lowerBound, match[1]!.upperBound).count
618                    if stars > level, level == 0 || stars == level + 1 || found != nil {
619                        hit = buffer.lineStart(match[0]!.lowerBound)
620                        level = stars
621                        break
622                    }
623                }
624                guard let hit else { throw Failure.message("Heading not found on outline path \(path.joined(separator: "/"))") }
625                found = hit
626                buffer.point = hit
627                start = hit
628                end = buffer.saveExcursion { () -> Int in
629                    endOfSubtree(buffer, heading: hit)
630                    return buffer.point
631                }
632            }
633            return found
634        }
635    }
636
637    static func headingLevel(_ buffer: EmacsBuffer, at line: Int) -> Int {
638        buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == "*" }.count
639    }
640
641    static func atHeading(_ buffer: EmacsBuffer) -> Bool {
642        buffer.lookingAtLine("^\\*+ ")
643    }
644
645    /// `outline-next-heading`.
646    static func nextHeading(_ buffer: EmacsBuffer) {
647        if let match = buffer.searchForward("\\n\\*+ ", caseInsensitive: false) {
648            buffer.point = match[0]!.lowerBound + 1
649        } else {
650            buffer.point = buffer.length
651        }
652    }
653
654    /// `org-end-of-subtree t t`: the start of the next heading at the same level or higher.
655    static func endOfSubtree(_ buffer: EmacsBuffer, heading: Int) {
656        let level = headingLevel(buffer, at: heading)
657        buffer.point = heading
658        while true {
659            guard let match = buffer.searchForward("\\n(\\*+) ", caseInsensitive: false) else {
660                buffer.point = buffer.length
661                return
662            }
663            let stars = match[1]!.count
664            if stars <= level {
665                buffer.point = match[0]!.lowerBound + 1
666                return
667            }
668            buffer.point = match[0]!.upperBound
669        }
670    }
671
672    static func previousLineEmpty(_ buffer: EmacsBuffer) -> Bool {
673        let start = buffer.lineStart(buffer.point)
674        guard start > 0 else { return false }
675        let previous = buffer.lineStart(start - 1)
676        return buffer.substring(previous, start - 1).trimmingCharacters(in: .whitespaces).isEmpty
677    }
678
679    /// `org--blank-before-heading-p` with `org-blank-before-new-entry` `(heading . auto)`.
680    static func blankBeforeHeading(_ buffer: EmacsBuffer) -> Bool {
681        buffer.saveExcursion {
682            let before = buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil && !atHeading(buffer)
683            if before {
684                nextHeading(buffer)
685                if buffer.point >= buffer.length, !atHeading(buffer) { return false }
686            }
687            // `org-back-to-heading`.
688            if !atHeading(buffer) {
689                buffer.point = buffer.lineStart(buffer.point)
690                if !atHeading(buffer), let match = buffer.searchBackward("^\\*+ ", caseInsensitive: false) {
691                    buffer.point = match[0]!.lowerBound
692                }
693            } else {
694                buffer.point = buffer.lineStart(buffer.point)
695            }
696            if buffer.point > 0 { return previousLineEmpty(buffer) }
697            let here = buffer.point
698            nextHeading(buffer)
699            if buffer.point < buffer.length || atHeading(buffer) { return previousLineEmpty(buffer) }
700            buffer.point = here
701            return false
702        }
703    }
704
705    /// `org-back-over-empty-lines`, deleting them.
706    static func deleteEmptyLinesBefore(_ buffer: EmacsBuffer) {
707        let pos = buffer.point
708        var start = pos
709        while start > 0 {
710            let lineStart = buffer.lineStart(start - 1)
711            guard buffer.substring(lineStart, start - 1).trimmingCharacters(in: .whitespaces).isEmpty, start - 1 >= lineStart else { break }
712            if lineStart == start - 1 || buffer.substring(lineStart, start).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
713                // A blank line precedes; but keep the newline that ends the previous text line.
714                if lineStart == 0 { start = 0; break }
715                start = lineStart
716            } else {
717                break
718            }
719        }
720        if start < pos { buffer.deleteRegion(start, pos) }
721        buffer.point = start
722    }
723
724    /// `org-capture-empty-lines-after` with no lines: blank lines after point go.
725    static func deleteEmptyLinesAfter(_ buffer: EmacsBuffer) {
726        deleteEmptyLinesBefore(buffer)
727        while buffer.looking("[ \\t]*\\n", caseInsensitive: false, setsMatch: false) != nil {
728            let end = buffer.lineEnd(buffer.point) + 1
729            buffer.deleteRegion(buffer.point, end)
730        }
731    }
732
733    /// `org-capture-place-entry`.
734    static func placeEntry(_ entry: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
735        let prepend = options.prepend
736        var template = entry
737        if template.range(of: "(?m)^\\*+ ", options: .regularExpression) == nil { template = "* " + template }
738        // `org-capture-verify-tree`: the first heading has the lowest level.
739        let levels = template.components(separatedBy: "\n").compactMap { line -> Int? in
740            let stars = line.prefix { $0 == "*" }.count
741            return stars > 0 && line.dropFirst(stars).first == " " ? stars : nil
742        }
743        if let first = levels.first, levels.contains(where: { $0 < first }) || !template.hasPrefix("*") {
744            throw Failure.message("Template is not a valid Org entry or tree")
745        }
746        var level = 1
747        if let heading {
748            level = headingLevel(buffer, at: heading) + 1
749            buffer.point = heading
750            if prepend {
751                buffer.point = buffer.lineEnd(heading)
752                nextHeading(buffer)
753            } else {
754                endOfSubtree(buffer, heading: heading)
755            }
756        } else if prepend {
757            buffer.point = 0
758            if !atHeading(buffer) { nextHeading(buffer) }
759        } else {
760            buffer.point = buffer.length
761        }
762        if !buffer.bolp { buffer.insert("\n") }
763        let blank = blankBeforeHeading(buffer) && !previousLineEmpty(buffer)
764        deleteEmptyLinesBefore(buffer)
765        buffer.insert(String(repeating: "\n", count: options.before ?? (blank ? 1 : 0)))
766        let start = buffer.point
767        // `org-paste-subtree` at `level`.
768        let oldLevel = levels.first ?? 1
769        let shift = level - oldLevel
770        var shifted = template
771        if shift != 0 {
772            shifted = template.components(separatedBy: "\n").map { line in
773                let stars = line.prefix { $0 == "*" }.count
774                guard stars > 0, line.dropFirst(stars).first == " " else { return line }
775                return String(repeating: "*", count: max(1, stars + shift)) + line.dropFirst(stars)
776            }.joined(separator: "\n")
777        }
778        if !shifted.hasSuffix("\n") { shifted += "\n" }
779        buffer.insert(shifted)
780        emptyLinesAfter(buffer, options.after)
781        return start
782    }
783
784    /// `org-capture-empty-lines-after`: exactly `n` blank lines after point, point kept.
785    static func emptyLinesAfter(_ buffer: EmacsBuffer, _ n: Int) {
786        deleteEmptyLinesAfter(buffer)
787        buffer.saveExcursion { buffer.insert(String(repeating: "\n", count: n)) }
788    }
789
790    /// `org-capture-place-plain-text`.
791    static func placePlain(_ text: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) -> Int {
792        let prepend = options.prepend
793        if let heading {
794            buffer.point = heading
795            if prepend {
796                buffer.point = buffer.lineEnd(heading)
797                if buffer.point < buffer.length { buffer.point += 1 }
798                skipMetaData(buffer)
799            } else {
800                buffer.point = buffer.lineEnd(heading)
801                nextHeading(buffer)
802            }
803        } else {
804            buffer.point = prepend ? 0 : buffer.length
805        }
806        if !buffer.bolp { buffer.insert("\n") }
807        deleteEmptyLinesBefore(buffer)
808        buffer.insert(String(repeating: "\n", count: options.before ?? 0))
809        let start = buffer.point
810        buffer.insert(text.hasSuffix("\n") || text.isEmpty ? text : text + "\n")
811        emptyLinesAfter(buffer, options.after)
812        return start
813    }
814
815    /// `org-capture-place-table-line`, then what `org-capture-finalize` does to the table: the
816    /// first table in the entry, or the file, gets the line, at its end, after its first rule
817    /// with `prepend`, or where `table-line-pos` says; a table is made when there's none.
818    static func placeTableLine(_ filled: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
819        let template = filled.trimmingCharacters(in: .whitespacesAndNewlines)
820        // `org-table-border-regexp`: a template that isn't a table line becomes one.
821        let text = template.range(of: "^[ \\t]*[^| \\t]", options: .regularExpression) != nil ? "| " + template : template + "\n"
822        var begin = 0
823        var end = buffer.length
824        if let heading {
825            begin = min(buffer.length, buffer.lineEnd(heading) + 1)
826            buffer.point = buffer.lineEnd(heading)
827            nextHeading(buffer)
828            end = buffer.point
829        }
830        var table: Range<Int>?
831        buffer.point = begin
832        while table == nil, let match = buffer.searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
833            buffer.point = match[0]!.lowerBound
834            if buffer.atTable { table = buffer.tableBegin()..<buffer.tableEnd() } else { buffer.point = match[0]!.upperBound }
835        }
836        if table == nil {
837            buffer.point = end
838            if !buffer.bolp { buffer.insert("\n") }
839            let origin = buffer.point
840            buffer.insert("|   |\n|---|\n")
841            table = origin..<buffer.point
842        }
843        let rows = buffer.substring(table!.lowerBound, table!.upperBound).components(separatedBy: "\n")
844        /// The start of the table's line `index`, within the table, as Org narrows to it.
845        func lineStart(_ index: Int) -> Int {
846            guard index > 0 else { return table!.lowerBound }
847            return buffer.saveExcursion {
848                buffer.point = table!.lowerBound
849                return buffer.forwardLine(index) == 0 ? min(buffer.point, table!.upperBound) : table!.upperBound
850            }
851        }
852        if let pos = options.tableLinePos {
853            guard let m = pos.firstMatch(of: /(I+)([-+][0-9]+)/) else { throw Failure.message("Invalid table line specification \"\(pos)\"") }
854            let hlines = rows.indices.filter { rows[$0].range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil }
855            guard m.1.count <= hlines.count else { throw Failure.message("Invalid table line specification \"\(pos)\"") }
856            guard let delta = Int(m.2.replacingOccurrences(of: "+", with: "")), (-999_999...999_999).contains(delta) else {
857                throw Failure.message("Invalid table line specification \"\(pos)\"")
858            }
859            // `forward-line` stops at the table's start, then one more line down.
860            buffer.point = lineStart(max(0, hlines[m.1.count - 1] + delta + (delta < 0 ? 0 : -1)) + 1)
861        } else if options.prepend {
862            if let rule = rows.firstIndex(where: { $0.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil }) {
863                let data = rows.indices.first { $0 > rule && rows[$0].range(of: "^[ \\t]*\\|[^-]", options: .regularExpression) != nil }
864                buffer.point = data.map(lineStart) ?? table!.upperBound
865            } else {
866                buffer.point = table!.lowerBound
867            }
868        } else {
869            buffer.point = table!.upperBound
870        }
871        if !buffer.bolp { buffer.insert("\n") }
872        let start = buffer.point
873        let lines = text.filter { $0 == "\n" }.count
874        buffer.insert(text)
875        // `org-capture-finalize`: align, or fix the formulas' row references and recalculate.
876        buffer.point = start
877        let row = buffer.substring(0, start).filter { $0 == "\n" }.count
878        if buffer.atTable {
879            if buffer.firstTblfm(after: buffer.tableEnd()) == nil {
880                buffer.tableAlign()
881            } else {
882                buffer.fixFormulas("@", replace: [:], limit: buffer.tableCurrentDataLine() - 1, delta: lines)
883                do {
884                    try buffer.tableRecalculate(all: true)
885                } catch let unsupported as Calc.Unsupported {
886                    throw Failure.message("The table's formulas need Emacs: \(unsupported.reason)")
887                }
888            }
889        }
890        buffer.point = 0
891        buffer.forwardLine(row)
892        return buffer.point
893    }
894
895    /// `org-end-of-meta-data t`: past planning, drawers and the property drawer.
896    static func skipMetaData(_ buffer: EmacsBuffer) {
897        while buffer.point < buffer.length {
898            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
899            let trimmed = line.trimmingCharacters(in: .whitespaces)
900            if trimmed.range(of: "^(SCHEDULED|DEADLINE|CLOSED):", options: .regularExpression) != nil {
901                buffer.forwardLine(1)
902            } else if trimmed.range(of: "^:[\\w-]+:$", options: .regularExpression) != nil {
903                while buffer.forwardLine(1) == 0 {
904                    if buffer.substring(buffer.point, buffer.lineEnd(buffer.point)).trimmingCharacters(in: .whitespaces).uppercased() == ":END:" {
905                        buffer.forwardLine(1)
906                        break
907                    }
908                }
909            } else {
910                break
911            }
912        }
913    }
914
915    /// `org-capture-place-item`: after the last item of the first list in the entry (the file
916    /// for a file target), or at the end of the entry's text.
917    static func placeItem(_ text: String, checkbox: Bool, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
918        let prepend = options.prepend
919        var item = text.trimmingCharacters(in: .newlines)
920        if item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]", options: .regularExpression) == nil {
921            let boxed = item.range(of: "^\\[[ X-]\\]", options: .regularExpression) != nil
922            item = "- " + (checkbox && !boxed ? "[ ] " : "") + item
923        } else if checkbox, item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]+\\[[ X-]\\]", options: .regularExpression) == nil {
924            item = item.replacingOccurrences(of: "^([ \\t]*([-+*]|[0-9]+[.)])[ \\t]+)", with: "$1[ ] ", options: .regularExpression)
925        }
926        let start: Int
927        let end: Int
928        if let heading {
929            start = min(buffer.length, buffer.lineEnd(heading) + 1)
930            buffer.point = buffer.lineEnd(heading)
931            nextHeading(buffer)
932            end = buffer.point
933        } else {
934            start = 0
935            end = buffer.length
936        }
937        // The first list's items in the range.
938        buffer.point = start
939        var items: [(start: Int, end: Int, indent: String)] = []
940        while buffer.point < end {
941            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
942            // A `*` bullet needs indentation; at the margin it starts a heading.
943            if let m = line.firstMatch(of: /^([ \t]*)([-+*]|[0-9]+[.)])[ \t]/), m.2 != "*" || !m.1.isEmpty {
944                if let first = items.first, String(m.1) != first.indent {
945                    // A nested item belongs to the current one.
946                } else {
947                    items.append((buffer.point, buffer.point, String(m.1)))
948                }
949            } else if !items.isEmpty, !line.trimmingCharacters(in: .whitespaces).isEmpty,
950                      line.prefix(while: { $0 == " " || $0 == "\t" }).count <= (items.first?.indent.count ?? 0) {
951                break
952            }
953            if buffer.forwardLine(1) != 0 { break }
954            if !items.isEmpty { items[items.count - 1].end = buffer.point }
955        }
956        if let first = items.first {
957            let indent = first.indent
958            let indented = item.components(separatedBy: "\n").enumerated().map { $0.offset == 0 ? indent + $0.element : indent + $0.element }.joined(separator: "\n")
959            if prepend {
960                buffer.point = first.start
961            } else {
962                buffer.point = items.last!.end
963                // Before blank lines that end the list.
964                while buffer.point > first.start {
965                    let previous = buffer.lineStart(buffer.point - 1)
966                    guard buffer.substring(previous, buffer.point - 1).trimmingCharacters(in: .whitespaces).isEmpty else { break }
967                    buffer.point = previous
968                }
969            }
970            if !buffer.bolp { buffer.insert("\n") }
971            // In an existing list, at most one blank line between items.
972            if !prepend {
973                deleteEmptyLinesBefore(buffer)
974                buffer.insert(String(repeating: "\n", count: min(1, options.before ?? 0)))
975            }
976            let at = buffer.point
977            buffer.insert(indented + "\n")
978            if prepend { emptyLinesAfter(buffer, min(1, options.after)) }
979            return at
980        } else {
981            buffer.point = prepend ? start : end
982            if !buffer.bolp { buffer.insert("\n") }
983            deleteEmptyLinesBefore(buffer)
984            buffer.insert(String(repeating: "\n", count: options.before ?? 0))
985            let at = buffer.point
986            buffer.insert(item + "\n")
987            emptyLinesAfter(buffer, options.after)
988            return at
989        }
990    }
991}