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