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