Sources/OrgCore/Capture/Capture.swift
662 lines · 31291 bytes
1import Foundation
2
3// Capture (org-capture.el, Org 9.8.7): filling a template and placing the result in its
4// target, as `org-capture` followed by `org-capture-finalize` leaves the target file.
5
6public struct CaptureTemplate: Sendable, Equatable, Identifiable {
7 public enum Kind: String, Sendable, Equatable { case entry, item, checkitem, plain }
8
9 /// `:tree-type`: what a date tree groups entries by.
10 public enum TreeType: String, Sendable, Equatable { case day, week, month }
11
12 public enum Target: Sendable, Equatable {
13 case file(String)
14 case headline(file: String, headline: String)
15 case outline(file: String, path: [String])
16 /// `file+olp+datetree`: today's entry in a date tree, under `path` or at the top.
17 case datetree(file: String, path: [String], tree: TreeType)
18 /// `(id "…")`: the heading with that ID; the app finds its file.
19 case id(String)
20 /// `(clock)`: the clocked-in entry; the app turns it into `heading`.
21 case clock
22 /// The heading starting at `offset` in `file`.
23 case heading(file: String, offset: Int)
24
25 /// The target file, or "" for `id` and `clock` until the app resolves them.
26 public var file: String {
27 switch self {
28 case .file(let f), .headline(let f, _), .outline(let f, _), .datetree(let f, _, _), .heading(let f, _): f
29 case .id, .clock: ""
30 }
31 }
32 }
33
34 /// Template properties beyond the target (`org-capture-templates`).
35 public struct Options: Sendable, Equatable {
36 public var prepend = false
37 /// `:immediate-finish`: file without showing the text.
38 public var immediateFinish = false
39 /// `:empty-lines`, `:empty-lines-before`, `:empty-lines-after`.
40 public var emptyLines: Int?
41 public var emptyLinesBefore: Int?
42 public var emptyLinesAfter: Int?
43 /// `:jump-to-captured`: show the entry after filing it.
44 public var jumpToCaptured = false
45 /// `:clock-in`, `:clock-keep`, `:clock-resume`.
46 public var clockIn = false
47 public var clockKeep = false
48 public var clockResume = false
49
50 public init(
51 prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
52 emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false
53 ) {
54 self.prepend = prepend
55 self.immediateFinish = immediateFinish
56 self.emptyLines = emptyLines
57 self.emptyLinesBefore = emptyLinesBefore
58 self.emptyLinesAfter = emptyLinesAfter
59 self.jumpToCaptured = jumpToCaptured
60 self.clockIn = clockIn
61 self.clockKeep = clockKeep
62 self.clockResume = clockResume
63 }
64
65 var before: Int? { emptyLinesBefore ?? emptyLines }
66 var after: Int { emptyLinesAfter ?? emptyLines ?? 0 }
67 }
68
69 public let key: String
70 public let name: String
71 public let kind: Kind
72 public let target: Target
73 public let template: String
74 public let options: Options
75 public var prepend: Bool { options.prepend }
76 public var id: String { key }
77
78 public init(key: String, name: String, kind: Kind = .entry, target: Target, template: String, prepend: Bool = false, options: Options = Options()) {
79 self.key = key
80 self.name = name
81 self.kind = kind
82 self.target = target
83 self.template = template
84 var options = options
85 if prepend { options.prepend = true }
86 self.options = options
87 }
88
89 /// The same template aimed at `target`.
90 public func retargeted(_ target: Target) -> CaptureTemplate {
91 CaptureTemplate(key: key, name: name, kind: kind, target: target, template: template, options: options)
92 }
93}
94
95/// What the escapes in a template stand for.
96public struct CaptureContext: Sendable {
97 public var now: Date
98 public var calendar: Calendar
99 /// `%i`: the selected text.
100 public var initial: String
101 /// `%a`: a link to where capture started, `[[target][description]]`, or empty.
102 public var annotation: String
103 /// `%c`: the clipboard.
104 public var clipboard: String
105 /// `%f` and `%F`: the file capture started from.
106 public var file: String
107 /// `%n`.
108 public var userName: String
109
110 public init(now: Date = Date(), calendar: Calendar = .current, initial: String = "", annotation: String = "", clipboard: String = "", file: String = "", userName: String = "") {
111 self.now = now
112 self.calendar = calendar
113 self.initial = initial
114 self.annotation = annotation
115 self.clipboard = clipboard
116 self.file = file
117 self.userName = userName
118 }
119}
120
121public enum Capture {
122 public enum Failure: Error, Equatable {
123 case message(String)
124 }
125
126 /// A `%^{prompt|default|choice…}` the template asks before it can be filled.
127 public struct Question: Sendable, Equatable {
128 public let prompt: String
129 public let defaultValue: String
130 public let choices: [String]
131 }
132
133 /// The prompts in `template`, in order.
134 public static func questions(_ template: String) -> [Question] {
135 let regex = try! NSRegularExpression(pattern: "(?<!%)%\\^\\{([^}]*)\\}")
136 let ns = template as NSString
137 return regex.matches(in: template, range: NSRange(location: 0, length: ns.length)).map { m in
138 let items = ns.substring(with: m.range(at: 1)).components(separatedBy: "|")
139 return Question(prompt: items[0], defaultValue: items.count > 1 ? items[1] : "", choices: Array(items.dropFirst(2)))
140 }
141 }
142
143 /// `org-capture-fill-template`: the text and where `%?` puts the cursor. `answers` holds
144 /// the replies to `questions(template)` in order.
145 public static func fill(_ template: String, context: CaptureContext, answers: [String] = []) -> Result<(text: String, cursor: Int), Failure> {
146 func stamp(_ active: Bool, _ withTime: Bool) -> String {
147 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: context.now)
148 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][(c.weekday ?? 1) - 1]
149 let body = String(format: "%04d-%02d-%02d %@", c.year!, c.month!, c.day!, day) + (withTime ? String(format: " %02d:%02d", c.hour!, c.minute!) : "")
150 return active ? "<\(body)>" : "[\(body)]"
151 }
152 let link = try! NSRegularExpression(pattern: "\\[\\[(.*?)\\](\\[.*?\\])?\\]")
153 func linkForm(_ template: String) -> String {
154 let ns = context.annotation as NSString
155 guard let m = link.firstMatch(in: context.annotation, range: NSRange(location: 0, length: ns.length)) else { return context.annotation }
156 return template.replacingOccurrences(of: "$1", with: ns.substring(with: m.range(at: 1)))
157 }
158 var text = ""
159 var answerIndex = 0
160 var answered: [String] = []
161 var cursor: Int?
162 let chars = Array(template)
163 var i = 0
164 while i < chars.count {
165 let c = chars[i]
166 guard c == "%", i + 1 < chars.count else {
167 text.append(c)
168 i += 1
169 continue
170 }
171 let next = chars[i + 1]
172 if next == "%" {
173 text.append("%")
174 i += 2
175 continue
176 }
177 var consumed = 2
178 switch next {
179 case "?": cursor = text.utf16.count
180 case "i":
181 // Continuation lines keep the indentation of the line `%i` is on.
182 let lead = String(text.split(separator: "\n", omittingEmptySubsequences: false).last ?? "").prefix { $0 == " " || $0 == "\t" }
183 text += context.initial.replacingOccurrences(of: "\n", with: "\n" + lead)
184 case "a": text += context.annotation == "[[]]" ? "" : context.annotation
185 case "l": text += linkForm("[[$1]]")
186 case "L": text += linkForm("$1")
187 case "c": text += context.clipboard
188 case "f": text += (context.file as NSString).lastPathComponent
189 case "F": text += context.file
190 case "n": text += context.userName
191 case "t": text += stamp(true, false)
192 case "T": text += stamp(true, true)
193 case "u": text += stamp(false, false)
194 case "U": text += stamp(false, true)
195 case "<":
196 guard let close = chars[(i + 2)...].firstIndex(of: ">") else { return .failure(.message("Unclosed %< in the template")) }
197 text += strftime(String(chars[(i + 2)..<close]), context)
198 consumed = close - i + 1
199 case "^":
200 guard i + 2 < chars.count, chars[i + 2] == "{", let close = chars[(i + 3)...].firstIndex(of: "}") else {
201 return .failure(.message("Template escapes like %^\(i + 2 < chars.count ? String(chars[i + 2]) : "") aren't supported yet."))
202 }
203 let after = close + 1 < chars.count ? chars[close + 1] : " "
204 if "CgGLptTuU".contains(after) { return .failure(.message("Template escapes like %^{…}\(after) aren't supported yet.")) }
205 let items = String(chars[(i + 3)..<close]).components(separatedBy: "|")
206 var answer = answerIndex < answers.count ? answers[answerIndex] : ""
207 if answer.isEmpty, items.count > 1 { answer = items[1] }
208 answerIndex += 1
209 answered.append(answer)
210 text += answer
211 consumed = close - i + 1
212 case "\\":
213 var j = i + 2
214 var digits = ""
215 while j < chars.count, chars[j].isNumber {
216 digits.append(chars[j])
217 j += 1
218 }
219 if let n = Int(digits), n >= 1, n <= answered.count {
220 text += answered[n - 1]
221 consumed = j - i
222 } else {
223 text.append(c)
224 consumed = 1
225 }
226 case "(", "[", "k", "K", "x", "A", ":":
227 return .failure(.message("Template escapes like %\(next) aren't supported yet."))
228 default:
229 text.append(c)
230 consumed = 1
231 }
232 i += consumed
233 }
234 // No blank lines before the text; it ends with one newline, or is empty.
235 var marked = text
236 let marker = "\u{0}CURSOR\u{0}"
237 if let cursor {
238 let index = String.Index(utf16Offset: cursor, in: marked)
239 marked.insert(contentsOf: marker, at: index)
240 }
241 var lines = marked.components(separatedBy: "\n")
242 while let first = lines.first, first.trimmingCharacters(in: .whitespaces).isEmpty, lines.count > 1 { lines.removeFirst() }
243 marked = lines.joined(separator: "\n")
244 let trimmed = marked.replacingOccurrences(of: "[ \\t\\n]+$", with: "", options: .regularExpression)
245 marked = trimmed.isEmpty ? "" : trimmed + "\n"
246 marked = marked.replacingOccurrences(of: "\t", with: " ")
247 guard let range = marked.range(of: marker) else { return .success((marked, marked.utf16.count > 0 ? marked.utf16.count - 1 : 0)) }
248 let offset = marked[..<range.lowerBound].utf16.count
249 marked.removeSubrange(range)
250 return .success((marked, offset))
251 }
252
253 static func strftime(_ format: String, _ context: CaptureContext) -> String {
254 let c = context.calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: context.now)
255 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
256 let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
257 var out = ""
258 var chars = format.makeIterator()
259 while let ch = chars.next() {
260 guard ch == "%", let f = chars.next() else {
261 out.append(ch)
262 continue
263 }
264 switch f {
265 case "Y": out += String(format: "%04d", c.year!)
266 case "m": out += String(format: "%02d", c.month!)
267 case "d": out += String(format: "%02d", c.day!)
268 case "e": out += String(format: "%2d", c.day!)
269 case "H": out += String(format: "%02d", c.hour!)
270 case "M": out += String(format: "%02d", c.minute!)
271 case "S": out += String(format: "%02d", c.second!)
272 case "a": out += String(days[c.weekday! - 1].prefix(3))
273 case "A": out += days[c.weekday! - 1]
274 case "b": out += String(months[c.month! - 1].prefix(3))
275 case "B": out += months[c.month! - 1]
276 case "F": out += String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
277 case "R": out += String(format: "%02d:%02d", c.hour!, c.minute!)
278 case "%": out += "%"
279 default: out += "%" + String(f)
280 }
281 }
282 return out
283 }
284
285 // MARK: - Placing
286
287 /// The target file's text after capturing `text`, as `org-capture-finalize` leaves it.
288 /// `now` and `calendar` pick a date tree's day.
289 public static func place(
290 _ text: String, template: CaptureTemplate, in fileText: String, settings: OrgSettings = .default,
291 now: Date = Date(), calendar: Calendar = .current
292 ) -> Result<String, Failure> {
293 placement(text, template: template, in: fileText, settings: settings, now: now, calendar: calendar).map(\.text)
294 }
295
296 /// The new text, and where the captured entry starts in it.
297 public static func placement(
298 _ text: String, template: CaptureTemplate, in fileText: String, settings: OrgSettings = .default,
299 now: Date = Date(), calendar: Calendar = .current
300 ) -> Result<(text: String, start: Int), Failure> {
301 let buffer = EmacsBuffer(fileText, point: 0, settings: settings)
302 let start: Int
303 do {
304 let entryHeading = try locate(template.target, buffer, date: calendar.dateComponents([.year, .month, .day], from: now))
305 let options = template.options
306 switch template.kind {
307 case .entry: start = try placeEntry(text, options: options, heading: entryHeading, buffer)
308 case .plain: start = placePlain(text, options: options, heading: entryHeading, buffer)
309 case .item, .checkitem: start = try placeItem(text, checkbox: template.kind == .checkitem, options: options, heading: entryHeading, buffer)
310 }
311 } catch let error as Failure {
312 return .failure(error)
313 } catch let error as EmacsBuffer.UserError {
314 return .failure(.message(error.message))
315 } catch {
316 return .failure(.message("\(error)"))
317 }
318 // Saving the target adds a final newline, as `require-final-newline` does in Org.
319 var result = buffer.text as String
320 if !result.isEmpty, !result.hasSuffix("\n") { result += "\n" }
321 return .success((result, start))
322 }
323
324 /// `org-capture-set-target-location`: point at the target heading, or nil for a file.
325 static func locate(_ target: CaptureTemplate.Target, _ buffer: EmacsBuffer, date: DateComponents) throws -> Int? {
326 switch target {
327 case .file:
328 return nil
329 case .id(let id):
330 buffer.point = 0
331 guard let match = buffer.searchForward("^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: id) + "[ \\t]*$", caseInsensitive: true) else {
332 throw Failure.message("Cannot find target ID \"\(id)\"")
333 }
334 buffer.point = match[0]!.lowerBound
335 buffer.backToHeadingOrPointMin()
336 return buffer.beforeFirstHeading ? nil : buffer.point
337 case .clock:
338 throw Failure.message("No running clock")
339 case .heading(_, let offset):
340 guard offset <= buffer.length else { throw Failure.message("The clocked entry moved; try again") }
341 buffer.point = buffer.lineStart(offset)
342 guard atHeading(buffer) else { throw Failure.message("The clocked entry moved; try again") }
343 return buffer.point
344 case .datetree(_, let path, let tree):
345 let parent = path.isEmpty ? nil : try locate(.outline(file: "", path: path), buffer, date: date)
346 return Datetree.findCreate(buffer, under: parent, tree: tree, date: date)
347 case .headline(_, let headline):
348 buffer.point = 0
349 let pattern = "^\\*+[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: headline) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
350 if let match = buffer.searchForward(pattern, caseInsensitive: false) {
351 return buffer.lineStart(match[0]!.lowerBound)
352 }
353 buffer.point = buffer.length
354 if !buffer.bolp { buffer.insert("\n") }
355 let start = buffer.point
356 buffer.insert("* " + headline + "\n")
357 return start
358 case .outline(_, let path):
359 var start = 0
360 var end = buffer.length
361 var level = 0
362 var found: Int?
363 for title in path {
364 buffer.point = start
365 let pattern = "^(\\*+)[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: title) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
366 var hit: Int?
367 while let match = buffer.searchForward(pattern, bound: end, caseInsensitive: false) {
368 let stars = buffer.substring(match[1]!.lowerBound, match[1]!.upperBound).count
369 if stars > level, level == 0 || stars == level + 1 || found != nil {
370 hit = buffer.lineStart(match[0]!.lowerBound)
371 level = stars
372 break
373 }
374 }
375 guard let hit else { throw Failure.message("Heading not found on outline path \(path.joined(separator: "/"))") }
376 found = hit
377 buffer.point = hit
378 start = hit
379 end = buffer.saveExcursion { () -> Int in
380 endOfSubtree(buffer, heading: hit)
381 return buffer.point
382 }
383 }
384 return found
385 }
386 }
387
388 static func headingLevel(_ buffer: EmacsBuffer, at line: Int) -> Int {
389 buffer.substring(line, buffer.lineEnd(line)).prefix { $0 == "*" }.count
390 }
391
392 static func atHeading(_ buffer: EmacsBuffer) -> Bool {
393 buffer.lookingAtLine("^\\*+ ")
394 }
395
396 /// `outline-next-heading`.
397 static func nextHeading(_ buffer: EmacsBuffer) {
398 if let match = buffer.searchForward("\\n\\*+ ", caseInsensitive: false) {
399 buffer.point = match[0]!.lowerBound + 1
400 } else {
401 buffer.point = buffer.length
402 }
403 }
404
405 /// `org-end-of-subtree t t`: the start of the next heading at the same level or higher.
406 static func endOfSubtree(_ buffer: EmacsBuffer, heading: Int) {
407 let level = headingLevel(buffer, at: heading)
408 buffer.point = heading
409 while true {
410 guard let match = buffer.searchForward("\\n(\\*+) ", caseInsensitive: false) else {
411 buffer.point = buffer.length
412 return
413 }
414 let stars = match[1]!.count
415 if stars <= level {
416 buffer.point = match[0]!.lowerBound + 1
417 return
418 }
419 buffer.point = match[0]!.upperBound
420 }
421 }
422
423 static func previousLineEmpty(_ buffer: EmacsBuffer) -> Bool {
424 let start = buffer.lineStart(buffer.point)
425 guard start > 0 else { return false }
426 let previous = buffer.lineStart(start - 1)
427 return buffer.substring(previous, start - 1).trimmingCharacters(in: .whitespaces).isEmpty
428 }
429
430 /// `org--blank-before-heading-p` with `org-blank-before-new-entry` `(heading . auto)`.
431 static func blankBeforeHeading(_ buffer: EmacsBuffer) -> Bool {
432 buffer.saveExcursion {
433 let before = buffer.searchBackward("^\\*+ ", caseInsensitive: false) == nil && !atHeading(buffer)
434 if before {
435 nextHeading(buffer)
436 if buffer.point >= buffer.length, !atHeading(buffer) { return false }
437 }
438 // `org-back-to-heading`.
439 if !atHeading(buffer) {
440 buffer.point = buffer.lineStart(buffer.point)
441 if !atHeading(buffer), let match = buffer.searchBackward("^\\*+ ", caseInsensitive: false) {
442 buffer.point = match[0]!.lowerBound
443 }
444 } else {
445 buffer.point = buffer.lineStart(buffer.point)
446 }
447 if buffer.point > 0 { return previousLineEmpty(buffer) }
448 let here = buffer.point
449 nextHeading(buffer)
450 if buffer.point < buffer.length || atHeading(buffer) { return previousLineEmpty(buffer) }
451 buffer.point = here
452 return false
453 }
454 }
455
456 /// `org-back-over-empty-lines`, deleting them.
457 static func deleteEmptyLinesBefore(_ buffer: EmacsBuffer) {
458 let pos = buffer.point
459 var start = pos
460 while start > 0 {
461 let lineStart = buffer.lineStart(start - 1)
462 guard buffer.substring(lineStart, start - 1).trimmingCharacters(in: .whitespaces).isEmpty, start - 1 >= lineStart else { break }
463 if lineStart == start - 1 || buffer.substring(lineStart, start).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
464 // A blank line precedes; but keep the newline that ends the previous text line.
465 if lineStart == 0 { start = 0; break }
466 start = lineStart
467 } else {
468 break
469 }
470 }
471 if start < pos { buffer.deleteRegion(start, pos) }
472 buffer.point = start
473 }
474
475 /// `org-capture-empty-lines-after` with no lines: blank lines after point go.
476 static func deleteEmptyLinesAfter(_ buffer: EmacsBuffer) {
477 deleteEmptyLinesBefore(buffer)
478 while buffer.looking("[ \\t]*\\n", caseInsensitive: false, setsMatch: false) != nil {
479 let end = buffer.lineEnd(buffer.point) + 1
480 buffer.deleteRegion(buffer.point, end)
481 }
482 }
483
484 /// `org-capture-place-entry`.
485 static func placeEntry(_ entry: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
486 let prepend = options.prepend
487 var template = entry
488 if template.range(of: "(?m)^\\*+ ", options: .regularExpression) == nil { template = "* " + template }
489 // `org-capture-verify-tree`: the first heading has the lowest level.
490 let levels = template.components(separatedBy: "\n").compactMap { line -> Int? in
491 let stars = line.prefix { $0 == "*" }.count
492 return stars > 0 && line.dropFirst(stars).first == " " ? stars : nil
493 }
494 if let first = levels.first, levels.contains(where: { $0 < first }) || !template.hasPrefix("*") {
495 throw Failure.message("Template is not a valid Org entry or tree")
496 }
497 var level = 1
498 if let heading {
499 level = headingLevel(buffer, at: heading) + 1
500 buffer.point = heading
501 if prepend {
502 buffer.point = buffer.lineEnd(heading)
503 nextHeading(buffer)
504 } else {
505 endOfSubtree(buffer, heading: heading)
506 }
507 } else if prepend {
508 buffer.point = 0
509 if !atHeading(buffer) { nextHeading(buffer) }
510 } else {
511 buffer.point = buffer.length
512 }
513 if !buffer.bolp { buffer.insert("\n") }
514 let blank = blankBeforeHeading(buffer) && !previousLineEmpty(buffer)
515 deleteEmptyLinesBefore(buffer)
516 buffer.insert(String(repeating: "\n", count: options.before ?? (blank ? 1 : 0)))
517 let start = buffer.point
518 // `org-paste-subtree` at `level`.
519 let oldLevel = levels.first ?? 1
520 let shift = level - oldLevel
521 var shifted = template
522 if shift != 0 {
523 shifted = template.components(separatedBy: "\n").map { line in
524 let stars = line.prefix { $0 == "*" }.count
525 guard stars > 0, line.dropFirst(stars).first == " " else { return line }
526 return String(repeating: "*", count: max(1, stars + shift)) + line.dropFirst(stars)
527 }.joined(separator: "\n")
528 }
529 if !shifted.hasSuffix("\n") { shifted += "\n" }
530 buffer.insert(shifted)
531 emptyLinesAfter(buffer, options.after)
532 return start
533 }
534
535 /// `org-capture-empty-lines-after`: exactly `n` blank lines after point, point kept.
536 static func emptyLinesAfter(_ buffer: EmacsBuffer, _ n: Int) {
537 deleteEmptyLinesAfter(buffer)
538 buffer.saveExcursion { buffer.insert(String(repeating: "\n", count: n)) }
539 }
540
541 /// `org-capture-place-plain-text`.
542 static func placePlain(_ text: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) -> Int {
543 let prepend = options.prepend
544 if let heading {
545 buffer.point = heading
546 if prepend {
547 buffer.point = buffer.lineEnd(heading)
548 if buffer.point < buffer.length { buffer.point += 1 }
549 skipMetaData(buffer)
550 } else {
551 buffer.point = buffer.lineEnd(heading)
552 nextHeading(buffer)
553 }
554 } else {
555 buffer.point = prepend ? 0 : buffer.length
556 }
557 if !buffer.bolp { buffer.insert("\n") }
558 deleteEmptyLinesBefore(buffer)
559 buffer.insert(String(repeating: "\n", count: options.before ?? 0))
560 let start = buffer.point
561 buffer.insert(text.hasSuffix("\n") || text.isEmpty ? text : text + "\n")
562 emptyLinesAfter(buffer, options.after)
563 return start
564 }
565
566 /// `org-end-of-meta-data t`: past planning, drawers and the property drawer.
567 static func skipMetaData(_ buffer: EmacsBuffer) {
568 while buffer.point < buffer.length {
569 let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
570 let trimmed = line.trimmingCharacters(in: .whitespaces)
571 if trimmed.range(of: "^(SCHEDULED|DEADLINE|CLOSED):", options: .regularExpression) != nil {
572 buffer.forwardLine(1)
573 } else if trimmed.range(of: "^:[\\w-]+:$", options: .regularExpression) != nil {
574 while buffer.forwardLine(1) == 0 {
575 if buffer.substring(buffer.point, buffer.lineEnd(buffer.point)).trimmingCharacters(in: .whitespaces).uppercased() == ":END:" {
576 buffer.forwardLine(1)
577 break
578 }
579 }
580 } else {
581 break
582 }
583 }
584 }
585
586 /// `org-capture-place-item`: after the last item of the first list in the entry (the file
587 /// for a file target), or at the end of the entry's text.
588 static func placeItem(_ text: String, checkbox: Bool, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
589 let prepend = options.prepend
590 var item = text.trimmingCharacters(in: .newlines)
591 if item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]", options: .regularExpression) == nil {
592 let boxed = item.range(of: "^\\[[ X-]\\]", options: .regularExpression) != nil
593 item = "- " + (checkbox && !boxed ? "[ ] " : "") + item
594 } else if checkbox, item.range(of: "^[ \\t]*([-+*]|[0-9]+[.)])[ \\t]+\\[[ X-]\\]", options: .regularExpression) == nil {
595 item = item.replacingOccurrences(of: "^([ \\t]*([-+*]|[0-9]+[.)])[ \\t]+)", with: "$1[ ] ", options: .regularExpression)
596 }
597 let start: Int
598 let end: Int
599 if let heading {
600 start = min(buffer.length, buffer.lineEnd(heading) + 1)
601 buffer.point = buffer.lineEnd(heading)
602 nextHeading(buffer)
603 end = buffer.point
604 } else {
605 start = 0
606 end = buffer.length
607 }
608 // The first list's items in the range.
609 buffer.point = start
610 var items: [(start: Int, end: Int, indent: String)] = []
611 while buffer.point < end {
612 let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
613 // A `*` bullet needs indentation; at the margin it starts a heading.
614 if let m = line.firstMatch(of: /^([ \t]*)([-+*]|[0-9]+[.)])[ \t]/), m.2 != "*" || !m.1.isEmpty {
615 if let first = items.first, String(m.1) != first.indent {
616 // A nested item belongs to the current one.
617 } else {
618 items.append((buffer.point, buffer.point, String(m.1)))
619 }
620 } else if !items.isEmpty, !line.trimmingCharacters(in: .whitespaces).isEmpty,
621 line.prefix(while: { $0 == " " || $0 == "\t" }).count <= (items.first?.indent.count ?? 0) {
622 break
623 }
624 if buffer.forwardLine(1) != 0 { break }
625 if !items.isEmpty { items[items.count - 1].end = buffer.point }
626 }
627 if let first = items.first {
628 let indent = first.indent
629 let indented = item.components(separatedBy: "\n").enumerated().map { $0.offset == 0 ? indent + $0.element : indent + $0.element }.joined(separator: "\n")
630 if prepend {
631 buffer.point = first.start
632 } else {
633 buffer.point = items.last!.end
634 // Before blank lines that end the list.
635 while buffer.point > first.start {
636 let previous = buffer.lineStart(buffer.point - 1)
637 guard buffer.substring(previous, buffer.point - 1).trimmingCharacters(in: .whitespaces).isEmpty else { break }
638 buffer.point = previous
639 }
640 }
641 if !buffer.bolp { buffer.insert("\n") }
642 // In an existing list, at most one blank line between items.
643 if !prepend {
644 deleteEmptyLinesBefore(buffer)
645 buffer.insert(String(repeating: "\n", count: min(1, options.before ?? 0)))
646 }
647 let at = buffer.point
648 buffer.insert(indented + "\n")
649 if prepend { emptyLinesAfter(buffer, min(1, options.after)) }
650 return at
651 } else {
652 buffer.point = prepend ? start : end
653 if !buffer.bolp { buffer.insert("\n") }
654 deleteEmptyLinesBefore(buffer)
655 buffer.insert(String(repeating: "\n", count: options.before ?? 0))
656 let at = buffer.point
657 buffer.insert(item + "\n")
658 emptyLinesAfter(buffer, options.after)
659 return at
660 }
661 }
662}