Sources/OrgCore/Capture/Capture.swift

b7b7f8ef81367a5e787840c1b28d8a82bf7da545
orgstar/Sources/OrgCore/Capture/Capture.swift history · blame · raw

825 lines · 39918 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 }
  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
 50        public init(
 51            prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
 52            emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false
 53        ) {
 54            self.prepend = prepend
 55            self.immediateFinish = immediateFinish
 56            self.emptyLines = emptyLines
 57            self.emptyLinesBefore = emptyLinesBefore
 58            self.emptyLinesAfter = emptyLinesAfter
 59            self.jumpToCaptured = jumpToCaptured
 60            self.clockIn = clockIn
 61            self.clockKeep = clockKeep
 62            self.clockResume = clockResume
 63        }
 64
 65        var before: Int? { emptyLinesBefore ?? emptyLines }
 66        var after: Int { emptyLinesAfter ?? emptyLines ?? 0 }
 67    }
 68
 69    public let key: String
 70    public let name: String
 71    public let kind: Kind
 72    public let target: Target
 73    public let template: String
 74    public let options: Options
 75    public var prepend: Bool { options.prepend }
 76    public var id: String { key }
 77
 78    public init(key: String, name: String, kind: Kind = .entry, target: Target, template: String, prepend: Bool = false, options: Options = Options()) {
 79        self.key = key
 80        self.name = name
 81        self.kind = kind
 82        self.target = target
 83        self.template = template
 84        var options = options
 85        if prepend { options.prepend = true }
 86        self.options = options
 87    }
 88
 89    /// The same template aimed at `target`.
 90    public func retargeted(_ target: Target) -> CaptureTemplate {
 91        CaptureTemplate(key: key, name: name, kind: kind, target: target, template: template, options: options)
 92    }
 93}
 94
 95/// What the escapes in a template stand for.
 96public struct CaptureContext: Sendable {
 97    public var now: Date
 98    public var calendar: Calendar
 99    /// `%i`: the selected text.
100    public var initial: String
101    /// `%a`: a link to where capture started, `[[target][description]]`, or empty.
102    public var annotation: String
103    /// `%c` and `%x`: the clipboard.
104    public var clipboard: String
105    /// `%f` and `%F`: the file capture started from.
106    public var file: String
107    /// `%n`.
108    public var userName: String
109    /// `%k` and `%K`: the clocked-in entry's title and a link to it, or empty.
110    public var clockHeading: String
111    public var clockLink: String
112    /// `%^g` and `%^G` offer these: the target file's tags, and every file's.
113    public var fileTags: [String]
114    public var allTags: [String]
115    /// `org-tags-column`, for aligning tags `%^g` adds to a heading.
116    public var tagsColumn: Int
117
118    public init(
119        now: Date = Date(), calendar: Calendar = .current, initial: String = "", annotation: String = "", clipboard: String = "",
120        file: String = "", userName: String = "", clockHeading: String = "", clockLink: String = "",
121        fileTags: [String] = [], allTags: [String] = [], tagsColumn: Int = -77
122    ) {
123        self.now = now
124        self.calendar = calendar
125        self.initial = initial
126        self.annotation = annotation
127        self.clipboard = clipboard
128        self.file = file
129        self.userName = userName
130        self.clockHeading = clockHeading
131        self.clockLink = clockLink
132        self.fileTags = fileTags
133        self.allTags = allTags
134        self.tagsColumn = tagsColumn
135    }
136}
137
138public enum Capture {
139    public enum Failure: Error, Equatable {
140        case message(String)
141    }
142
143    /// A question the template asks before it can be filled: `%^{prompt|default|choice…}`,
144    /// or one of `%^g`, `%^G`, `%^t`, `%^T`, `%^u`, `%^U`, `%^C`, `%^L`, `%^{prop}p`.
145    public struct Question: Sendable, Equatable {
146        public enum Kind: Sendable, Equatable {
147            case text
148            /// Tags, separated by colons.
149            case tags
150            /// A date as `org-read-date` reads it (`+2d`, `fri 14:00`); empty is today.
151            case date(withTime: Bool, inactive: Bool)
152            /// `%^C` and `%^L`: text from the clipboard, inserted as a link with `link`.
153            case clipboard(link: Bool)
154            /// `%^{NAME}p`: the value of property `NAME`.
155            case property
156        }
157
158        public let prompt: String
159        public let defaultValue: String
160        public let choices: [String]
161        public let kind: Kind
162
163        public init(prompt: String, defaultValue: String, choices: [String], kind: Kind = .text) {
164            self.prompt = prompt
165            self.defaultValue = defaultValue
166            self.choices = choices
167            self.kind = kind
168        }
169    }
170
171    static let promptPattern = "%\\^(?:\\{([^}]*)\\})?([CgGLptTuU])?"
172
173    /// The questions `template` asks, in order.
174    public static func questions(_ template: String, context: CaptureContext = CaptureContext()) -> [Question] {
175        guard case .success(let expanded) = expand(template, context) else { return [] }
176        return prompts(in: expanded).map { question($0.items, $0.key, context) }
177    }
178
179    static func question(_ items: [String]?, _ key: String?, _ context: CaptureContext) -> Question {
180        let prompt = items?.first
181        let defaultValue = items.map { $0.count > 1 ? $0[1] : "" } ?? ""
182        switch key {
183        case "g", "G": return Question(prompt: prompt ?? "Tags", defaultValue: "", choices: key == "g" ? context.fileTags : context.allTags, kind: .tags)
184        case "t", "T", "u", "U":
185            let upper = key == key?.uppercased()
186            return Question(prompt: prompt ?? "Date", defaultValue: "", choices: [], kind: .date(withTime: upper, inactive: key == "u" || key == "U"))
187        case "C", "L":
188            let values = [context.initial, context.clipboard].filter { !$0.isEmpty }
189            return Question(prompt: "Clipboard/kill value", defaultValue: context.initial, choices: values, kind: .clipboard(link: key == "L"))
190        case "p": return Question(prompt: prompt ?? "", defaultValue: defaultValue, choices: [], kind: .property)
191        default: return Question(prompt: prompt ?? "Enter string", defaultValue: defaultValue, choices: items.map { Array($0.dropFirst(2)) } ?? [])
192        }
193    }
194
195    /// The unescaped `%^` placeholders in `text`.
196    static func prompts(in text: String) -> [(range: NSRange, items: [String]?, key: String?)] {
197        let regex = try! NSRegularExpression(pattern: promptPattern)
198        let ns = text as NSString
199        return regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).compactMap { m in
200            guard !escaped(ns, at: m.range.location) else { return nil }
201            let items = m.range(at: 1).location == NSNotFound ? nil : ns.substring(with: m.range(at: 1)).components(separatedBy: "|")
202            let key = m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2))
203            return (m.range, items, key)
204        }
205    }
206
207    /// `org-capture-escaped-%` without its unescaping: an odd run of backslashes before `%`.
208    static func escaped(_ ns: NSString, at index: Int) -> Bool {
209        var i = index
210        while i > 0, ns.character(at: i - 1) == 92 { i -= 1 }
211        return (index - i) % 2 == 1
212    }
213
214    /// Where `%?` puts the cursor while the template is filled.
215    static let cursorMark = "\u{E000}"
216
217    /// `org-capture-fill-template`: the text and where `%?` puts the cursor. `answers` holds
218    /// the replies to `questions(template)` in order.
219    public static func fill(_ template: String, context: CaptureContext, answers: [String] = []) -> Result<(text: String, cursor: Int), Failure> {
220        let expanded: String
221        switch expand(template, context) {
222        case .failure(let failure): return .failure(failure)
223        case .success(let text): expanded = text
224        }
225        // Prompts, in order, answered in the text as it stands then, as org does.
226        var options = EditingOptions.org
227        options.tagsColumn = context.tagsColumn
228        let buffer = EmacsBuffer(expanded, point: 0, settings: .default, options: options)
229        buffer.now = context.now
230        buffer.calendar = context.calendar
231        var strings: [String] = []
232        var all: [String] = []
233        var index = 0
234        while let match = buffer.searchForward(promptPattern, caseInsensitive: false) {
235            let whole = match[0]!
236            if unescape(buffer, at: whole.lowerBound) { continue }
237            let start = buffer.point - whole.count
238            let items = match[1].map { buffer.substring($0.lowerBound, $0.upperBound).components(separatedBy: "|") }
239            let key = match[2].map { buffer.substring($0.lowerBound, $0.upperBound) }
240            let question = question(items, key, context)
241            let answer = index < answers.count ? answers[index] : ""
242            index += 1
243            buffer.deleteRegion(start, buffer.point)
244            buffer.point = start
245            switch question.kind {
246            case .text:
247                let value = answer.isEmpty ? question.defaultValue : answer
248                strings.append(value)
249                all.append(value)
250                buffer.insert(value)
251            case .tags:
252                let tags = answer.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
253                guard !tags.isEmpty else { continue }
254                all.append(":" + tags.joined(separator: ":") + ":")
255                if buffer.point == 0 || buffer.character(at: buffer.point - 1) != 58 { buffer.insert(":") }
256                buffer.insert(tags.joined(separator: ":"))
257                if buffer.point >= buffer.length || buffer.character(at: buffer.point) != 58 { buffer.insert(":") }
258                if buffer.lookingAtLine("^\\*+ ") { buffer.alignTags(onLineAt: buffer.point) }
259            case .date(let withTime, let inactive):
260                let result: ReadDate.Answer
261                if answer.trimmingCharacters(in: .whitespaces).isEmpty {
262                    let c = context.calendar.dateComponents([.year, .month, .day, .hour, .minute], from: context.now)
263                    result = ReadDate.Answer(year: c.year!, month: c.month!, day: c.day!, hour: c.hour!, minute: c.minute!, timeGiven: false)
264                } else {
265                    result = buffer.readDate(answer, default: context.now)
266                }
267                let stamp = buffer.insertTimestamp(result.components(context.calendar), withTime: result.timeGiven || withTime, inactive: inactive, endTime: result.endTime)
268                all.append(stamp)
269            case .clipboard(let link):
270                let value = answer.isEmpty ? question.defaultValue : answer
271                all.append(value)
272                buffer.insert(link ? Links.makeString(value, nil) : value)
273            case .property:
274                let value = answer.isEmpty ? question.defaultValue : answer
275                buffer.saveExcursion { buffer.entryPut(question.prompt, value) }
276                all.append(value)
277            }
278        }
279        // `%\N`: the Nth `%^{…}` answer; `%\*N`: the Nth answer of any prompt.
280        var text = buffer.string
281        for (pattern, values) in [("%\\\\\\*([1-9][0-9]*)", all), ("%\\\\([1-9][0-9]*)", strings)] {
282            let regex = try! NSRegularExpression(pattern: pattern)
283            let ns = text as NSString
284            var out = text
285            for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).reversed() where !escaped(ns, at: m.range.location) {
286                let n = Int(ns.substring(with: m.range(at: 1)))!
287                out = (out as NSString).replacingCharacters(in: m.range, with: n <= values.count ? values[n - 1] : "")
288            }
289            text = out
290        }
291        // No blank lines before the text; it ends with one newline, or is empty.
292        var lines = text.components(separatedBy: "\n")
293        while let first = lines.first, first.trimmingCharacters(in: .whitespaces).isEmpty, lines.count > 1 { lines.removeFirst() }
294        var marked = lines.joined(separator: "\n")
295        let trimmed = marked.replacingOccurrences(of: "[ \\t\\n]+$", with: "", options: .regularExpression)
296        marked = trimmed.isEmpty ? "" : trimmed + "\n"
297        marked = marked.replacingOccurrences(of: "\t", with: "        ")
298        guard let range = marked.range(of: cursorMark) else { return .success((marked, marked.utf16.count > 0 ? marked.utf16.count - 1 : 0)) }
299        let offset = marked[..<range.lowerBound].utf16.count
300        marked.removeSubrange(range)
301        return .success((marked, offset))
302    }
303
304    /// `org-capture-escaped-%` at the `%` at `index`: drops half the backslashes before it;
305    /// true when it was escaped. Point follows the deletion.
306    static func unescape(_ buffer: EmacsBuffer, at index: Int) -> Bool {
307        var i = index
308        while i > 0, buffer.character(at: i - 1) == 92 { i -= 1 }
309        let n = index - i
310        guard n > 0 else { return false }
311        buffer.deleteRegion(i, i + (n + 1) / 2)
312        return n % 2 == 1
313    }
314
315    /// The escapes that need no answer (`%a`, `%t`, `%<…>`, `%?`…), with `%^` prompts and `%\N`
316    /// left in place.
317    static func expand(_ template: String, _ context: CaptureContext) -> Result<String, Failure> {
318        func stamp(_ active: Bool, _ withTime: Bool) -> String {
319            let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now)
320            let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1]
321            let body = String(format: "%04d-%02d-%02d %@", c.year!, c.month!, c.day!, day) + (withTime ? String(format: " %02d:%02d", c.hour!, c.minute!) : "")
322            return active ? "<\(body)>" : "[\(body)]"
323        }
324        let link = try! NSRegularExpression(pattern: "\\[\\[(.*?)\\](\\[.*?\\])?\\]")
325        func linkForm(_ template: String) -> String {
326            let ns = context.annotation as NSString
327            guard let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) else { return context.annotation }
328            return template.replacingOccurrences(of: "$1", with: ns.substring(with: m.range(at: 1)))
329        }
330        var text = ""
331        let chars = Array(template)
332        var i = 0
333        while i < chars.count {
334            let c = chars[i]
335            guard c == "%", i + 1 < chars.count else {
336                text.append(c)
337                i += 1
338                continue
339            }
340            // A `%` after an odd run of backslashes stays, with half of them.
341            var slashes = 0
342            while slashes < text.count, text.dropLast(slashes).last == "\\" { slashes += 1 }
343            let next = chars[i + 1]
344            if slashes > 0, "aAcfFikKlLntTuUx:<?".contains(next) {
345                text.removeLast((slashes + 1) / 2)
346                if slashes % 2 == 1 {
347                    text.append(c)
348                    i += 1
349                    continue
350                }
351            }
352            var consumed = 2
353            switch next {
354            case "?": text += cursorMark
355            case "i":
356                // Continuation lines keep the indentation of the line `%i` is on.
357                let lead = String(text.split(separator: "\n", omittingEmptySubsequences: false).last ?? "").prefix { $0 == " " || $0 == "\t" }
358                text += context.initial.replacingOccurrences(of: "\n", with: "\n" + lead)
359            case "a": text += context.annotation == "[[]]" ? "" : context.annotation
360            case "A":
361                // The link, with its description asked for.
362                let ns = context.annotation as NSString
363                if let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) {
364                    text += ns.replacingCharacters(in: m.range, with: "[[" + ns.substring(with: m.range(at: 1)) + "][%^{Link description}]]")
365                } else {
366                    text += context.annotation
367                }
368            case "l": text += linkForm("[[$1]]")
369            case "L": text += linkForm("$1")
370            case "c", "x": text += context.clipboard
371            case "f": text += (context.file as NSString).lastPathComponent
372            case "F": text += context.file
373            case "n": text += context.userName
374            case "k": text += context.clockHeading
375            case "K": text += context.clockLink
376            case "t": text += stamp(true, false)
377            case "T": text += stamp(true, true)
378            case "u": text += stamp(false, false)
379            case "U": text += stamp(false, true)
380            case "<":
381                guard let close = chars[(i + 2)...].firstIndex(of: ">"), !chars[(i + 2)..<close].contains("\n") else {
382                    text.append(c)
383                    consumed = 1
384                    break
385                }
386                text += strftime(String(chars[(i + 2)..<close]), context)
387                consumed = close - i + 1
388            case ":":
389                // A link property (`%:annotation`); only the capture's own are known.
390                var j = i + 2
391                while j < chars.count, chars[j].isLetter || chars[j] == "-" { j += 1 }
392                guard j > i + 2 else {
393                    text.append(c)
394                    consumed = 1
395                    break
396                }
397                switch String(chars[(i + 2)..<j]) {
398                case "annotation": text += context.annotation
399                case "initial": text += context.initial
400                default: break
401                }
402                consumed = j - i
403            case "(":
404                return .failure(.message("Template escapes like %( run Emacs Lisp, which Orgstar doesn't."))
405            case "[":
406                return .failure(.message("Template escapes like %[file] aren't supported yet."))
407            default:
408                text.append(c)
409                consumed = 1
410            }
411            i += consumed
412        }
413        return .success(text)
414    }
415
416    static func strftime(_ format: String, _ context: CaptureContext) -> String {
417        let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: context.now)
418        let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
419        let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
420        var out = ""
421        var chars = format.makeIterator()
422        while let ch = chars.next() {
423            guard ch == "%", let f = chars.next() else {
424                out.append(ch)
425                continue
426            }
427            switch f {
428            case "Y": out += String(format: "%04d", c.year!)
429            case "m": out += String(format: "%02d", c.month!)
430            case "d": out += String(format: "%02d", c.day!)
431            case "e": out += String(format: "%2d", c.day!)
432            case "H": out += String(format: "%02d", c.hour!)
433            case "M": out += String(format: "%02d", c.minute!)
434            case "S": out += String(format: "%02d", c.second!)
435            case "a": out += String(days[c.weekday! - 1].prefix(3))
436            case "A": out += days[c.weekday! - 1]
437            case "b": out += String(months[c.month! - 1].prefix(3))
438            case "B": out += months[c.month! - 1]
439            case "F": out += String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
440            case "R": out += String(format: "%02d:%02d", c.hour!, c.minute!)
441            case "%": out += "%"
442            default: out += "%" + String(f)
443            }
444        }
445        return out
446    }
447
448    // MARK: - Placing
449
450    /// The target file's text after capturing `text`, as `org-capture-finalize` leaves it.
451    /// `now` and `calendar` pick a date tree's day.
452    public static func place(
453        _ text: String, template: CaptureTemplate, in fileText: String, settings: OrgSettings = .default,
454        now: Date = Date(), calendar: Calendar = .current
455    ) -> Result<String, Failure> {
456        placement(text, template: template, in: fileText, settings: settings, now: now, calendar: calendar).map(\.text)
457    }
458
459    /// The new text, and where the captured entry starts in it.
460    public static func placement(
461        _ text: String, template: CaptureTemplate, in fileText: String, settings: OrgSettings = .default,
462        now: Date = Date(), calendar: Calendar = .current
463    ) -> Result<(text: String, start: Int), Failure> {
464        let buffer = EmacsBuffer(fileText, point: 0, settings: settings)
465        let start: Int
466        do {
467            let entryHeading = try locate(template.target, buffer, date: calendar.dateComponents([.year, .month, .day], from: now))
468            let options = template.options
469            switch template.kind {
470            case .entry: start = try placeEntry(text, options: options, heading: entryHeading, buffer)
471            case .plain: start = placePlain(text, options: options, heading: entryHeading, buffer)
472            case .item, .checkitem: start = try placeItem(text, checkbox: template.kind == .checkitem, options: options, heading: entryHeading, buffer)
473            }
474        } catch let error as Failure {
475            return .failure(error)
476        } catch let error as EmacsBuffer.UserError {
477            return .failure(.message(error.message))
478        } catch {
479            return .failure(.message("\(error)"))
480        }
481        // Saving the target adds a final newline, as `require-final-newline` does in Org.
482        var result = buffer.text as String
483        if !result.isEmpty, !result.hasSuffix("\n") { result += "\n" }
484        return .success((result, start))
485    }
486
487    /// `org-capture-set-target-location`: point at the target heading, or nil for a file.
488    static func locate(_ target: CaptureTemplate.Target, _ buffer: EmacsBuffer, date: DateComponents) throws -> Int? {
489        switch target {
490        case .file:
491            return nil
492        case .id(let id):
493            buffer.point = 0
494            guard let match = buffer.searchForward("^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: id) + "[ \\t]*$", caseInsensitive: true) else {
495                throw Failure.message("Cannot find target ID \"\(id)\"")
496            }
497            buffer.point = match[0]!.lowerBound
498            buffer.backToHeadingOrPointMin()
499            return buffer.beforeFirstHeading ? nil : buffer.point
500        case .clock:
501            throw Failure.message("No running clock")
502        case .heading(_, let offset):
503            guard offset <= buffer.length else { throw Failure.message("The clocked entry moved; try again") }
504            buffer.point = buffer.lineStart(offset)
505            guard atHeading(buffer) else { throw Failure.message("The clocked entry moved; try again") }
506            return buffer.point
507        case .datetree(_, let path, let tree):
508            let parent = path.isEmpty ? nil : try locate(.outline(file: "", path: path), buffer, date: date)
509            return Datetree.findCreate(buffer, under: parent, tree: tree, date: date)
510        case .headline(_, let headline):
511            buffer.point = 0
512            let pattern = "^\\*+[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: headline) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
513            if let match = buffer.searchForward(pattern, caseInsensitive: false) {
514                return buffer.lineStart(match[0]!.lowerBound)
515            }
516            buffer.point = buffer.length
517            if !buffer.bolp { buffer.insert("\n") }
518            let start = buffer.point
519            buffer.insert("* " + headline + "\n")
520            return start
521        case .outline(_, let path):
522            var start = 0
523            var end = buffer.length
524            var level = 0
525            var found: Int?
526            for title in path {
527                buffer.point = start
528                let pattern = "^(\\*+)[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: title) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
529                var hit: Int?
530                while let match = buffer.searchForward(pattern, bound: end, caseInsensitive: false) {
531                    let stars = buffer.substring(match[1]!.lowerBound, match[1]!.upperBound).count
532                    if stars > level, level == 0 || stars == level + 1 || found != nil {
533                        hit = buffer.lineStart(match[0]!.lowerBound)
534                        level = stars
535                        break
536                    }
537                }
538                guard let hit else { throw Failure.message("Heading not found on outline path \(path.joined(separator: "/"))") }
539                found = hit
540                buffer.point = hit
541                start = hit
542                end = buffer.saveExcursion { () -> Int in
543                    endOfSubtree(buffer, heading: hit)
544                    return buffer.point
545                }
546            }
547            return found
548        }
549    }
550
551    static func headingLevel(_ buffer: EmacsBuffer, at line: Int) -> Int {
552        buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == "*" }.count
553    }
554
555    static func atHeading(_ buffer: EmacsBuffer) -> Bool {
556        buffer.lookingAtLine("^\\*+ ")
557    }
558
559    /// `outline-next-heading`.
560    static func nextHeading(_ buffer: EmacsBuffer) {
561        if let match = buffer.searchForward("\\n\\*+ ", caseInsensitive: false) {
562            buffer.point = match[0]!.lowerBound + 1
563        } else {
564            buffer.point = buffer.length
565        }
566    }
567
568    /// `org-end-of-subtree t t`: the start of the next heading at the same level or higher.
569    static func endOfSubtree(_ buffer: EmacsBuffer, heading: Int) {
570        let level = headingLevel(buffer, at: heading)
571        buffer.point = heading
572        while true {
573            guard let match = buffer.searchForward("\\n(\\*+) ", caseInsensitive: false) else {
574                buffer.point = buffer.length
575                return
576            }
577            let stars = match[1]!.count
578            if stars <= level {
579                buffer.point = match[0]!.lowerBound + 1
580                return
581            }
582            buffer.point = match[0]!.upperBound
583        }
584    }
585
586    static func previousLineEmpty(_ buffer: EmacsBuffer) -> Bool {
587        let start = buffer.lineStart(buffer.point)
588        guard start > 0 else { return false }
589        let previous = buffer.lineStart(start - 1)
590        return buffer.substring(previous, start - 1).trimmingCharacters(in: .whitespaces).isEmpty
591    }
592
593    /// `org--blank-before-heading-p` with `org-blank-before-new-entry` `(heading . auto)`.
594    static func blankBeforeHeading(_ buffer: EmacsBuffer) -> Bool {
595        buffer.saveExcursion {
596            let before = buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil && !atHeading(buffer)
597            if before {
598                nextHeading(buffer)
599                if buffer.point >= buffer.length, !atHeading(buffer) { return false }
600            }
601            // `org-back-to-heading`.
602            if !atHeading(buffer) {
603                buffer.point = buffer.lineStart(buffer.point)
604                if !atHeading(buffer), let match = buffer.searchBackward("^\\*+ ", caseInsensitive: false) {
605                    buffer.point = match[0]!.lowerBound
606                }
607            } else {
608                buffer.point = buffer.lineStart(buffer.point)
609            }
610            if buffer.point > 0 { return previousLineEmpty(buffer) }
611            let here = buffer.point
612            nextHeading(buffer)
613            if buffer.point < buffer.length || atHeading(buffer) { return previousLineEmpty(buffer) }
614            buffer.point = here
615            return false
616        }
617    }
618
619    /// `org-back-over-empty-lines`, deleting them.
620    static func deleteEmptyLinesBefore(_ buffer: EmacsBuffer) {
621        let pos = buffer.point
622        var start = pos
623        while start > 0 {
624            let lineStart = buffer.lineStart(start - 1)
625            guard buffer.substring(lineStart, start - 1).trimmingCharacters(in: .whitespaces).isEmpty, start - 1 >= lineStart else { break }
626            if lineStart == start - 1 || buffer.substring(lineStart, start).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
627                // A blank line precedes; but keep the newline that ends the previous text line.
628                if lineStart == 0 { start = 0; break }
629                start = lineStart
630            } else {
631                break
632            }
633        }
634        if start < pos { buffer.deleteRegion(start, pos) }
635        buffer.point = start
636    }
637
638    /// `org-capture-empty-lines-after` with no lines: blank lines after point go.
639    static func deleteEmptyLinesAfter(_ buffer: EmacsBuffer) {
640        deleteEmptyLinesBefore(buffer)
641        while buffer.looking("[ \\t]*\\n", caseInsensitive: false, setsMatch: false) != nil {
642            let end = buffer.lineEnd(buffer.point) + 1
643            buffer.deleteRegion(buffer.point, end)
644        }
645    }
646
647    /// `org-capture-place-entry`.
648    static func placeEntry(_ entry: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
649        let prepend = options.prepend
650        var template = entry
651        if template.range(of: "(?m)^\\*+ ", options: .regularExpression) == nil { template = "* " + template }
652        // `org-capture-verify-tree`: the first heading has the lowest level.
653        let levels = template.components(separatedBy: "\n").compactMap { line -> Int? in
654            let stars = line.prefix { $0 == "*" }.count
655            return stars > 0 && line.dropFirst(stars).first == " " ? stars : nil
656        }
657        if let first = levels.first, levels.contains(where: { $0 < first }) || !template.hasPrefix("*") {
658            throw Failure.message("Template is not a valid Org entry or tree")
659        }
660        var level = 1
661        if let heading {
662            level = headingLevel(buffer, at: heading) + 1
663            buffer.point = heading
664            if prepend {
665                buffer.point = buffer.lineEnd(heading)
666                nextHeading(buffer)
667            } else {
668                endOfSubtree(buffer, heading: heading)
669            }
670        } else if prepend {
671            buffer.point = 0
672            if !atHeading(buffer) { nextHeading(buffer) }
673        } else {
674            buffer.point = buffer.length
675        }
676        if !buffer.bolp { buffer.insert("\n") }
677        let blank = blankBeforeHeading(buffer) && !previousLineEmpty(buffer)
678        deleteEmptyLinesBefore(buffer)
679        buffer.insert(String(repeating: "\n", count: options.before ?? (blank ? 1 : 0)))
680        let start = buffer.point
681        // `org-paste-subtree` at `level`.
682        let oldLevel = levels.first ?? 1
683        let shift = level - oldLevel
684        var shifted = template
685        if shift != 0 {
686            shifted = template.components(separatedBy: "\n").map { line in
687                let stars = line.prefix { $0 == "*" }.count
688                guard stars > 0, line.dropFirst(stars).first == " " else { return line }
689                return String(repeating: "*", count: max(1, stars + shift)) + line.dropFirst(stars)
690            }.joined(separator: "\n")
691        }
692        if !shifted.hasSuffix("\n") { shifted += "\n" }
693        buffer.insert(shifted)
694        emptyLinesAfter(buffer, options.after)
695        return start
696    }
697
698    /// `org-capture-empty-lines-after`: exactly `n` blank lines after point, point kept.
699    static func emptyLinesAfter(_ buffer: EmacsBuffer, _ n: Int) {
700        deleteEmptyLinesAfter(buffer)
701        buffer.saveExcursion { buffer.insert(String(repeating: "\n", count: n)) }
702    }
703
704    /// `org-capture-place-plain-text`.
705    static func placePlain(_ text: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) -> Int {
706        let prepend = options.prepend
707        if let heading {
708            buffer.point = heading
709            if prepend {
710                buffer.point = buffer.lineEnd(heading)
711                if buffer.point < buffer.length { buffer.point += 1 }
712                skipMetaData(buffer)
713            } else {
714                buffer.point = buffer.lineEnd(heading)
715                nextHeading(buffer)
716            }
717        } else {
718            buffer.point = prepend ? 0 : buffer.length
719        }
720        if !buffer.bolp { buffer.insert("\n") }
721        deleteEmptyLinesBefore(buffer)
722        buffer.insert(String(repeating: "\n", count: options.before ?? 0))
723        let start = buffer.point
724        buffer.insert(text.hasSuffix("\n") || text.isEmpty ? text : text + "\n")
725        emptyLinesAfter(buffer, options.after)
726        return start
727    }
728
729    /// `org-end-of-meta-data t`: past planning, drawers and the property drawer.
730    static func skipMetaData(_ buffer: EmacsBuffer) {
731        while buffer.point < buffer.length {
732            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
733            let trimmed = line.trimmingCharacters(in: .whitespaces)
734            if trimmed.range(of: "^(SCHEDULED|DEADLINE|CLOSED):", options: .regularExpression) != nil {
735                buffer.forwardLine(1)
736            } else if trimmed.range(of: "^:[\\w-]+:$", options: .regularExpression) != nil {
737                while buffer.forwardLine(1) == 0 {
738                    if buffer.substring(buffer.point, buffer.lineEnd(buffer.point)).trimmingCharacters(in: .whitespaces).uppercased() == ":END:" {
739                        buffer.forwardLine(1)
740                        break
741                    }
742                }
743            } else {
744                break
745            }
746        }
747    }
748
749    /// `org-capture-place-item`: after the last item of the first list in the entry (the file
750    /// for a file target), or at the end of the entry's text.
751    static func placeItem(_ text: String, checkbox: Bool, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
752        let prepend = options.prepend
753        var item = text.trimmingCharacters(in: .newlines)
754        if item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]", options: .regularExpression) == nil {
755            let boxed = item.range(of: "^\\[[ X-]\\]", options: .regularExpression) != nil
756            item = "- " + (checkbox && !boxed ? "[ ] " : "") + item
757        } else if checkbox, item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]+\\[[ X-]\\]", options: .regularExpression) == nil {
758            item = item.replacingOccurrences(of: "^([ \\t]*([-+*]|[0-9]+[.)])[ \\t]+)", with: "$1[ ] ", options: .regularExpression)
759        }
760        let start: Int
761        let end: Int
762        if let heading {
763            start = min(buffer.length, buffer.lineEnd(heading) + 1)
764            buffer.point = buffer.lineEnd(heading)
765            nextHeading(buffer)
766            end = buffer.point
767        } else {
768            start = 0
769            end = buffer.length
770        }
771        // The first list's items in the range.
772        buffer.point = start
773        var items: [(start: Int, end: Int, indent: String)] = []
774        while buffer.point < end {
775            let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
776            // A `*` bullet needs indentation; at the margin it starts a heading.
777            if let m = line.firstMatch(of: /^([ \t]*)([-+*]|[0-9]+[.)])[ \t]/), m.2 != "*" || !m.1.isEmpty {
778                if let first = items.first, String(m.1) != first.indent {
779                    // A nested item belongs to the current one.
780                } else {
781                    items.append((buffer.point, buffer.point, String(m.1)))
782                }
783            } else if !items.isEmpty, !line.trimmingCharacters(in: .whitespaces).isEmpty,
784                      line.prefix(while: { $0 == " " || $0 == "\t" }).count <= (items.first?.indent.count ?? 0) {
785                break
786            }
787            if buffer.forwardLine(1) != 0 { break }
788            if !items.isEmpty { items[items.count - 1].end = buffer.point }
789        }
790        if let first = items.first {
791            let indent = first.indent
792            let indented = item.components(separatedBy: "\n").enumerated().map { $0.offset == 0 ? indent + $0.element : indent + $0.element }.joined(separator: "\n")
793            if prepend {
794                buffer.point = first.start
795            } else {
796                buffer.point = items.last!.end
797                // Before blank lines that end the list.
798                while buffer.point > first.start {
799                    let previous = buffer.lineStart(buffer.point - 1)
800                    guard buffer.substring(previous, buffer.point - 1).trimmingCharacters(in: .whitespaces).isEmpty else { break }
801                    buffer.point = previous
802                }
803            }
804            if !buffer.bolp { buffer.insert("\n") }
805            // In an existing list, at most one blank line between items.
806            if !prepend {
807                deleteEmptyLinesBefore(buffer)
808                buffer.insert(String(repeating: "\n", count: min(1, options.before ?? 0)))
809            }
810            let at = buffer.point
811            buffer.insert(indented + "\n")
812            if prepend { emptyLinesAfter(buffer, min(1, options.after)) }
813            return at
814        } else {
815            buffer.point = prepend ? start : end
816            if !buffer.bolp { buffer.insert("\n") }
817            deleteEmptyLinesBefore(buffer)
818            buffer.insert(String(repeating: "\n", count: options.before ?? 0))
819            let at = buffer.point
820            buffer.insert(item + "\n")
821            emptyLinesAfter(buffer, options.after)
822            return at
823        }
824    }
825}