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