Sources/OrgCore/Commands/Archive.swift
409 lines · 21796 bytes
20 symbols in this file
1import Foundation
2
3// Archiving (`org-archive-subtree`, Org 9.8.7) with `org-archive-location` and the defaults: context info time, file, olpath, category, todo and itags, inherited tags added only within
4// the same file, no marking DONE, the archive file's header for a new file.
5
6extension EmacsBuffer {
7 /// The first value of `#+NAME:` in the buffer, as `org-collect-keywords` with UNIQUE.
8 func keyword(_ name: String) -> String? {
9 saveExcursion {
10 point = 0
11 guard let match = searchForward("^[ \\t]*#\\+" + NSRegularExpression.escapedPattern(for: name) + ":[ \\t]*(.*?)[ \\t]*$") else {
12 return SetupFile.keywords(settings.setupKeywords).last { $0.key == name.uppercased() }?.value.trimmingCharacters(in: .whitespaces)
13 }
14 return substring(match[1]!.lowerBound, match[1]!.upperBound)
15 }
16 }
17
18 /// `org-back-to-heading-or-point-min`.
19 func backToHeadingOrPointMin() {
20 if beforeFirstHeading { point = 0 } else { _ = try? backToHeading() }
21 }
22
23 static let propertyDrawerPattern = "^[ \\t]*:PROPERTIES:[ \\t]*\\n(?:[ \\t]*:\\S+:(?:[ \\t].*)?[ \\t]*\\n)*?[ \\t]*:END:[ \\t]*$"
24
25 /// `org-insert-property-drawer`.
26 func insertPropertyDrawer() {
27 saveExcursion {
28 backToHeadingOrPointMin()
29 if beforeFirstHeading {
30 while bolp, lookingAt("^[ \\t]*#[ \\t]") != nil || lookingAt("^[ \\t]*#$") != nil { if forwardLine(1) != 0 { break } }
31 } else {
32 forwardLine(1)
33 if lookingAt(planningPattern) != nil { forwardLine(1) }
34 }
35 guard looking(Self.propertyDrawerPattern, caseInsensitive: true, setsMatch: false) == nil else { return }
36 if bolp, point > 0 { point -= 1 }
37 let begin = bobp ? point : point + 1
38 if !bobp { insert("\n") }
39 insert(":PROPERTIES:\n:END:")
40 if eobp || begin == 0 { insert("\n") }
41 }
42 }
43
44 /// `org-get-property-block` with FORCE: the body range of the entry's property drawer.
45 func propertyBlock(_ begin: Int) -> Range<Int> {
46 saveExcursion {
47 point = begin
48 if beforeFirstHeading {
49 while bolp, lookingAt("^[ \\t]*#[ \\t]") != nil || lookingAt("^[ \\t]*#$") != nil { if forwardLine(1) != 0 { break } }
50 } else {
51 forwardLine(1)
52 if lookingAt(planningPattern) != nil { forwardLine(1) }
53 }
54 if let match = looking(Self.propertyDrawerPattern) {
55 forwardLine(1)
56 return point..<lineStart(match[0]!.upperBound)
57 }
58 point = begin
59 insertPropertyDrawer()
60 let match = searchForward(Self.propertyDrawerPattern)!
61 let at = lineStart(match[0]!.upperBound)
62 return at..<at
63 }
64 }
65
66 /// `org-entry-put` for an ordinary property, with `org-property-format` "%-10s %s".
67 func entryPut(_ name: String, _ value: String) {
68 saveExcursion {
69 backToHeadingOrPointMin()
70 let range = propertyBlock(point)
71 point = range.lowerBound
72 let end = range.upperBound
73 if let match = searchForward("^[ \\t]*:" + NSRegularExpression.escapedPattern(for: name) + ":(?:[ \\t]+.*?)?[ \\t]*$", bound: end) {
74 deleteRegion(match[0]!.lowerBound, match[0]!.upperBound)
75 point = match[0]!.lowerBound
76 } else {
77 point = end
78 insert("\n")
79 point -= 1
80 }
81 insert(":" + name + ":")
82 insert(" " + value)
83 alignNodeProperty()
84 }
85 }
86
87 /// `org--align-node-property`, with the indentation `org-indent-line` gives property lines
88 /// when `org-adapt-indentation` is nil.
89 func alignNodeProperty() {
90 let start = lineStart(point)
91 let line = substring(start, lineEnd(point))
92 guard let match = line.range(of: "^([ \\t]*)(:\\S+:)(?:[ \\t]+(.*?))?[ \\t]*$", options: .regularExpression) else { return }
93 let parts = line[match]
94 let regex = try! NSRegularExpression(pattern: "^([ \\t]*)(:\\S+:)(?:[ \\t]+(.*?))?[ \\t]*$")
95 let groups = regex.firstMatch(in: String(parts), range: NSRange(location: 0, length: (String(parts) as NSString).length))!
96 let ns = String(parts) as NSString
97 let key = ns.substring(with: groups.range(at: 2))
98 let value = groups.range(at: 3).location == NSNotFound ? "" : ns.substring(with: groups.range(at: 3))
99 let padded = key.padding(toLength: max(10, (key as NSString).length), withPad: " ", startingAt: 0)
100 let new = (padded + " " + value).trimmingCharacters(in: .whitespaces)
101 let end = lineEnd(point)
102 let lineStartOffset = start
103 point = lineStartOffset
104 deleteRegion(lineStartOffset, end)
105 insert(new)
106 }
107
108 /// The entry's tags, and its inherited tags (file tags and ancestors' tags), in org's order.
109 func tags() -> (local: [String], inherited: [String]) {
110 saveExcursion {
111 guard (try? backToHeading()) != nil else { return ([], []) }
112 func lineTags(_ at: Int) -> [String] {
113 saveExcursion {
114 point = at
115 guard let match = lookingAt(SetTags.tagLine), let tags = match[2] else { return [] }
116 return substring(tags.lowerBound, tags.upperBound).split(separator: ":").map(String.init)
117 }
118 }
119 let local = lineTags(point)
120 var ancestors: [[String]] = []
121 while upHeadingSafe() != nil { ancestors.insert(lineTags(point), at: 0) }
122 var inherited: [String] = []
123 let fileTags = (keyword("FILETAGS") ?? "").split(whereSeparator: { $0 == ":" || $0 == " " || $0 == "\t" }).map(String.init)
124 for tag in fileTags + ancestors.flatMap({ $0 }) where settings.inheritsTag(tag) && !inherited.contains(tag) && !local.contains(tag) { inherited.append(tag) }
125 return (local, inherited)
126 }
127 }
128
129 /// `org-get-outline-path`: ancestors' titles without statistics cookies, links shown as
130 /// their descriptions.
131 func outlinePath() -> [String] {
132 saveExcursion {
133 guard (try? backToHeading()) != nil else { return [] }
134 var path: [String] = []
135 while upHeadingSafe() != nil {
136 let title = saveExcursion { () -> String in
137 guard let match = lookingAt(complexHeadingPattern), let title = match[4] else { return "" }
138 var text = substring(title.lowerBound, title.upperBound)
139 text = text.replacingOccurrences(of: "\\[[0-9]+%\\]|\\[[0-9]+/[0-9]+\\]", with: "", options: .regularExpression)
140 text = text.replacingOccurrences(of: "\\[\\[([^\\]]*)\\]\\[([^\\]]*)\\]\\]", with: "$2", options: .regularExpression)
141 text = text.replacingOccurrences(of: "\\[\\[([^\\]]*)\\]\\]", with: "$1", options: .regularExpression)
142 return text.trimmingCharacters(in: .whitespacesAndNewlines)
143 }
144 path.insert(title, at: 0)
145 }
146 return path
147 }
148 }
149
150 /// `org-update-statistics-cookies` with point on a heading.
151 func updateStatisticsCookies() {
152 guard atHeading else {
153 updateCheckboxCount()
154 return
155 }
156 saveExcursion {
157 let start = try! backToHeading()
158 let level = outlineLevel
159 var childLevel: Int?
160 let end = saveExcursion { () -> Int in
161 if outlineNextHeading() { childLevel = outlineLevel }
162 return point
163 }
164 let hasBoxes = saveExcursion { searchForward("^[ \\t]*([-+*]|[0-9]+[.)]) \\[[- X]\\]", bound: end) != nil }
165 let todoData = saveExcursion { searchForward(":COOKIE_DATA:.*\\btodo\\b", bound: end) != nil }
166 if hasBoxes, !todoData {
167 updateCheckboxCount()
168 } else if let childLevel, childLevel > level {
169 point = end
170 updateParentTodoStatistics()
171 } else {
172 point = start
173 while let match = searchForward("((\\[[0-9]*%\\])|(\\[[0-9]*/[0-9]*\\]))", bound: lineEnd(point)) {
174 replace(match[1]!, with: match[2] != nil ? "[100%]" : "[0/0]")
175 }
176 }
177 }
178 }
179}
180
181public enum Archive {
182 /// Where the entry at the caret goes: the archive file (the source itself for an in-file
183 /// location) and the heading to file it under, if any.
184 public struct Destination: Sendable, Equatable {
185 public let path: String
186 public let heading: String?
187 public var isSameFile: Bool
188 }
189
190 public static func destination(_ context: EditContext, sourcePath: String) -> Result<Destination, ArchiveError> {
191 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
192 guard !buffer.beforeFirstHeading else { return .failure(.message("Before first headline")) }
193 let spec = buffer.inheritedProperty("ARCHIVE")?.value ?? buffer.keyword("ARCHIVE") ?? context.options.archiveLocation ?? "%s_archive::"
194 guard let separator = spec.range(of: "::") else { return .failure(.message("Invalid archive location: \"\(spec)\"")) }
195 let name = (sourcePath as NSString).lastPathComponent
196 let fileFormat = String(spec[..<separator.lowerBound])
197 let headingFormat = String(spec[separator.upperBound...])
198 var path: String
199 if fileFormat.contains(where: { !$0.isWhitespace }) {
200 let file = fileFormat.replacingOccurrences(of: "%s", with: name)
201 let directory = (sourcePath as NSString).deletingLastPathComponent
202 path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: OrgPaths.home, options: .anchored)
203 } else {
204 path = sourcePath
205 }
206 // An encrypted file archives to an encrypted file: `diary.org.gpg` to
207 // `diary_archive.org.gpg`, not Org's `diary.org.gpg_archive`.
208 if sourcePath.hasSuffix(".gpg"), !path.hasSuffix(".gpg") {
209 path = path.hasSuffix(".org.gpg_archive") ? String(path.dropLast(".org.gpg_archive".count)) + "_archive.org.gpg" : path + ".gpg"
210 }
211 let heading = headingFormat.replacingOccurrences(of: "%s", with: name)
212 return .success(Destination(path: (path as NSString).standardizingPath, heading: heading.isEmpty ? nil : heading, isSameFile: path == sourcePath))
213 }
214
215 /// The file part of an archive location for a file at `sourcePath`; the file itself when
216 /// the location names none.
217 static func archiveFile(_ spec: String, sourcePath: String) -> String? {
218 guard let separator = spec.range(of: "::") else { return nil }
219 let fileFormat = String(spec[..<separator.lowerBound])
220 guard fileFormat.contains(where: { !$0.isWhitespace }) else { return sourcePath }
221 let file = fileFormat.replacingOccurrences(of: "%s", with: (sourcePath as NSString).lastPathComponent)
222 let directory = (sourcePath as NSString).deletingLastPathComponent
223 let path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: OrgPaths.home, options: .anchored)
224 return (path as NSString).standardizingPath
225 }
226
227 /// `org-all-archive-files`: the archive files of `text`, the file at `path`, that exist:
228 /// its `#+ARCHIVE:` or `org-archive-location`, then each `:ARCHIVE:` property's.
229 public static func allArchiveFiles(_ text: String, path: String, options: EditingOptions, fileManager: FileManager = .default) -> [String] {
230 let buffer = EmacsBuffer(text, point: 0, settings: OrgParser.parse(text).settings)
231 var specs = [buffer.keyword("ARCHIVE") ?? options.archiveLocation ?? "%s_archive::"]
232 let property = try! NSRegularExpression(pattern: "^[ \\t]*:ARCHIVE:[ \\t]+(.*?)[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
233 let ns = text as NSString
234 for m in property.matches(in: text, range: NSRange(location: 0, length: ns.length)) { specs.append(ns.substring(with: m.range(at: 1))) }
235 var files: [String] = []
236 for spec in specs {
237 guard let file = archiveFile(spec, sourcePath: path), !files.contains(file) else { continue }
238 files.append(file)
239 }
240 return files.filter { fileManager.fileExists(atPath: $0) }
241 }
242
243 /// `org-add-archive-files`: each existing file followed by its archive files, without repeats.
244 public static func addArchiveFiles(_ paths: [String], options: EditingOptions, read: (String) -> String?) -> [String] {
245 var out: [String] = []
246 for path in paths {
247 guard let text = read(path) else { continue }
248 for file in [path] + allArchiveFiles(text, path: path, options: options) where !out.contains(file) { out.append(file) }
249 }
250 return out
251 }
252
253 public enum ArchiveError: Error, Equatable {
254 case message(String)
255 }
256
257 public struct Edits: Sendable, Equatable {
258 /// For the source; for an in-file archive, everything happens here.
259 public let source: EditResult
260 /// For the archive file, against its text (empty when it doesn't exist yet).
261 public let archive: TextEdit?
262 }
263
264 /// `~/` for paths in the home folder, as `abbreviate-file-name`.
265 static func abbreviate(_ path: String) -> String {
266 let home = OrgPaths.home
267 return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
268 }
269
270 /// Archives the subtree at the caret. `archiveText` is the archive file's text, or nil
271 /// when it doesn't exist; it's ignored for an in-file destination.
272 public static func run(
273 _ context: EditContext, sourcePath: String, destination: Destination, archiveText: String?
274 ) -> Result<Edits, ArchiveError> {
275 let formatter = DateFormatter()
276 formatter.locale = Locale(identifier: "en_US_POSIX")
277 formatter.calendar = context.calendar
278 formatter.timeZone = context.calendar.timeZone
279 formatter.dateFormat = "yyyy-MM-dd EEE HH:mm"
280 let time = formatter.string(from: context.now)
281 let archive = destination.isSameFile ? nil : EmacsBuffer(archiveText ?? "", point: 0, settings: context.tree.settings, options: context.options)
282 var archiveEdit: TextEdit?
283 let step = commitBuffer(context) { source in
284 let target = archive ?? source
285 let level: Int
286 var headingText: String?
287 var heading = destination.heading
288 // `datetree/`: three levels of date headings, stars after it a heading below them.
289 var datetree: DateComponents?
290 var datetreeSubheading = false
291 if let h = heading, let m = h.firstMatch(of: /^datetree\/(\**)/) {
292 let nsub = m.1.count
293 heading = String(repeating: "*", count: 3 + nsub) + h[m.range.upperBound...]
294 datetreeSubheading = nsub > 0
295 let closed = source.saveExcursion { () -> String? in
296 _ = try? source.backToHeading()
297 source.forwardLine(1)
298 guard let line = source.lookingAt("^[ \\t]*(?:SCHEDULED|DEADLINE|CLOSED):.*$") else { return nil }
299 return source.substring(line[0]!.lowerBound, line[0]!.upperBound).firstMatch(of: /CLOSED: *\[([^\]]+)\]/).map { String($0.1) }
300 }
301 datetree = EmacsBuffer.parseTimeString(closed ?? time)
302 }
303 if let heading, let stars = heading.range(of: "^\\*+", options: .regularExpression) {
304 level = heading[stars].count
305 headingText = heading
306 } else {
307 level = 0
308 headingText = nil
309 }
310 let origin = source.marker(source.point)
311 defer { source.release(origin) }
312 try source.backToHeading()
313 let (local, inherited) = source.tags()
314 let category = source.inheritedProperty("CATEGORY")?.value ?? source.keyword("CATEGORY")
315 ?? ((sourcePath as NSString).lastPathComponent as NSString).deletingPathExtension
316 let todo = source.lookingAt(source.todoLinePattern)?[2].map { source.substring($0.lowerBound, $0.upperBound) }
317 let context: [(String, String)] = [
318 ("TIME", time), ("FILE", abbreviate(sourcePath)), ("OLPATH", source.outlinePath().joined(separator: "/")),
319 ("CATEGORY", category), ("TODO", todo ?? ""), ("ITAGS", inherited.joined(separator: " ")),
320 ]
321 let tree = try source.copySubtree()
322 try target.saveExcursion {
323 if !destination.isSameFile, archiveText == nil {
324 target.point = target.length
325 target.insert("\nArchived entries from file \(sourcePath)\n\n")
326 }
327 // The date's entry, as `org-datetree-find-date-create` then `org-narrow-to-subtree`.
328 let low = target.marker(0)
329 let high = target.marker(target.length, advances: true)
330 defer {
331 target.release(low)
332 target.release(high)
333 }
334 if let date = datetree {
335 let day = Datetree.findCreate(target, under: nil, tree: .day, date: date)
336 low.position = day
337 high.position = Datetree.narrowEnd(target, day, limit: target.length)
338 }
339 target.point = low.position
340 if let headingText, !(datetree != nil && !datetreeSubheading) {
341 let pattern = "^" + NSRegularExpression.escapedPattern(for: headingText) + "([ \\t]+:([[:alnum:]_@#%]+:)+)?[ \\t]*$"
342 if let match = target.searchForward(pattern, bound: high.position) {
343 target.point = match[0]!.upperBound
344 } else {
345 target.point = high.position
346 if !target.bolp { target.insert("\n") }
347 target.insert((datetree != nil ? "" : "\n") + headingText + "\n")
348 target.forwardLine(-1)
349 target.endOfLine()
350 }
351 target.endOfSubtree()
352 target.point = min(target.point, high.position)
353 target.skipBackward(EmacsBuffer.whitespace)
354 target.point = max(target.point, low.position)
355 let blanks = target.looking("[ \\t\\r\\n]*")!
356 let clipped = blanks[0]!.lowerBound..<min(blanks[0]!.upperBound, high.position)
357 let separator = datetree != nil ? "\n" : "\n\n"
358 target.replace(clipped, with: separator)
359 target.point = clipped.lowerBound + separator.count
360 } else {
361 target.point = high.position
362 if !(datetree != nil && target.bolp) { target.insert("\n") }
363 }
364 try target.pasteSubtree(level: max(1, level + (headingText == nil ? 0 : 1)), tree: tree, limit: datetree != nil ? high.position : nil)
365 if !inherited.isEmpty, destination.isSameFile {
366 let all = inherited + local
367 target.saveExcursion {
368 let line = target.saveExcursion { target.lookingAt(SetTags.tagLine) }
369 if let tags = line?[1] {
370 target.point = tags.lowerBound
371 target.skipBackward(EmacsBuffer.blanks)
372 target.deleteRegion(target.point, target.lineEnd(target.point))
373 } else {
374 target.endOfLine()
375 }
376 target.saveExcursion { target.insert(" :" + all.joined(separator: ":") + ":") }
377 }
378 target.alignTags(onLineAt: target.point)
379 }
380 for (key, value) in context where value.contains(where: { !$0.isWhitespace }) {
381 target.entryPut("ARCHIVE_" + key, value)
382 }
383 }
384 source.point = origin.position
385 let range = try source.subtreeRange()
386 source.deleteRegion(range.lowerBound, range.upperBound)
387 source.saveExcursion {
388 source.upHeadingSafe()
389 source.updateStatisticsCookies()
390 }
391 if source.looking("^[ \\t]*$", setsMatch: false) != nil {
392 source.endOfLine()
393 source.point = source.nextHeadingStart(after: source.point) ?? source.length
394 }
395 }
396 if let archive {
397 let original = archiveText ?? ""
398 if case .commit(let result) = commitBuffer(EditContext(revision: 0, text: original, tree: OrgParser.parse(original), selection: [0..<0]), { $0.replace(0..<$0.length, with: archive.string) }) {
399 archiveEdit = result.edits.first
400 }
401 }
402 switch step {
403 case .commit(let result): return .success(Edits(source: result, archive: archiveEdit))
404 case .failed(let message): return .failure(.message(message))
405 case .prompt: return .failure(.message("unexpected prompt"))
406 case .external: return .failure(.message("unexpected external request"))
407 }
408 }
409}