Sources/OrgCore/Commands/Archive.swift
366 lines · 18949 bytes
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 let 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: NSHomeDirectory(), options: .anchored)
203 } else {
204 path = sourcePath
205 }
206 let heading = headingFormat.replacingOccurrences(of: "%s", with: name)
207 return .success(Destination(path: (path as NSString).standardizingPath, heading: heading.isEmpty ? nil : heading, isSameFile: path == sourcePath))
208 }
209
210 public enum ArchiveError: Error, Equatable {
211 case message(String)
212 }
213
214 public struct Edits: Sendable, Equatable {
215 /// For the source; for an in-file archive, everything happens here.
216 public let source: EditResult
217 /// For the archive file, against its text (empty when it doesn't exist yet).
218 public let archive: TextEdit?
219 }
220
221 /// `~/` for paths in the home folder, as `abbreviate-file-name`.
222 static func abbreviate(_ path: String) -> String {
223 let home = NSHomeDirectory()
224 return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
225 }
226
227 /// Archives the subtree at the caret. `archiveText` is the archive file's text, or nil
228 /// when it doesn't exist; it's ignored for an in-file destination.
229 public static func run(
230 _ context: EditContext, sourcePath: String, destination: Destination, archiveText: String?
231 ) -> Result<Edits, ArchiveError> {
232 let formatter = DateFormatter()
233 formatter.locale = Locale(identifier: "en_US_POSIX")
234 formatter.calendar = context.calendar
235 formatter.timeZone = context.calendar.timeZone
236 formatter.dateFormat = "yyyy-MM-dd EEE HH:mm"
237 let time = formatter.string(from: context.now)
238 let archive = destination.isSameFile ? nil : EmacsBuffer(archiveText ?? "", point: 0, settings: context.tree.settings, options: context.options)
239 var archiveEdit: TextEdit?
240 let step = commitBuffer(context) { source in
241 let target = archive ?? source
242 let level: Int
243 var headingText: String?
244 var heading = destination.heading
245 // `datetree/`: three levels of date headings, stars after it a heading below them.
246 var datetree: DateComponents?
247 var datetreeSubheading = false
248 if let h = heading, let m = h.firstMatch(of: /^datetree\/(\**)/) {
249 let nsub = m.1.count
250 heading = String(repeating: "*", count: 3 + nsub) + h[m.range.upperBound...]
251 datetreeSubheading = nsub > 0
252 let closed = source.saveExcursion { () -> String? in
253 _ = try? source.backToHeading()
254 source.forwardLine(1)
255 guard let line = source.lookingAt("^[ \\t]*(?:SCHEDULED|DEADLINE|CLOSED):.*$") else { return nil }
256 return source.substring(line[0]!.lowerBound, line[0]!.upperBound).firstMatch(of: /CLOSED: *\[([^\]]+)\]/).map { String($0.1) }
257 }
258 datetree = EmacsBuffer.parseTimeString(closed ?? time)
259 }
260 if let heading, let stars = heading.range(of: "^\\*+", options: .regularExpression) {
261 level = heading[stars].count
262 headingText = heading
263 } else {
264 level = 0
265 headingText = nil
266 }
267 let origin = source.marker(source.point)
268 defer { source.release(origin) }
269 try source.backToHeading()
270 let (local, inherited) = source.tags()
271 let category = source.inheritedProperty("CATEGORY")?.value ?? source.keyword("CATEGORY")
272 ?? ((sourcePath as NSString).lastPathComponent as NSString).deletingPathExtension
273 let todo = source.lookingAt(source.todoLinePattern)?[2].map { source.substring($0.lowerBound, $0.upperBound) }
274 let context: [(String, String)] = [
275 ("TIME", time), ("FILE", abbreviate(sourcePath)), ("OLPATH", source.outlinePath().joined(separator: "/")),
276 ("CATEGORY", category), ("TODO", todo ?? ""), ("ITAGS", inherited.joined(separator: " ")),
277 ]
278 let tree = try source.copySubtree()
279 try target.saveExcursion {
280 if !destination.isSameFile, archiveText == nil {
281 target.point = target.length
282 target.insert("\nArchived entries from file \(sourcePath)\n\n")
283 }
284 // The date's entry, as `org-datetree-find-date-create` then `org-narrow-to-subtree`.
285 let low = target.marker(0)
286 let high = target.marker(target.length, advances: true)
287 defer {
288 target.release(low)
289 target.release(high)
290 }
291 if let date = datetree {
292 let day = Datetree.findCreate(target, under: nil, tree: .day, date: date)
293 low.position = day
294 high.position = Datetree.narrowEnd(target, day, limit: target.length)
295 }
296 target.point = low.position
297 if let headingText, !(datetree != nil && !datetreeSubheading) {
298 let pattern = "^" + NSRegularExpression.escapedPattern(for: headingText) + "([ \\t]+:([[:alnum:]_@#%]+:)+)?[ \\t]*$"
299 if let match = target.searchForward(pattern, bound: high.position) {
300 target.point = match[0]!.upperBound
301 } else {
302 target.point = high.position
303 if !target.bolp { target.insert("\n") }
304 target.insert((datetree != nil ? "" : "\n") + headingText + "\n")
305 target.forwardLine(-1)
306 target.endOfLine()
307 }
308 target.endOfSubtree()
309 target.point = min(target.point, high.position)
310 target.skipBackward(EmacsBuffer.whitespace)
311 target.point = max(target.point, low.position)
312 let blanks = target.looking("[ \\t\\r\\n]*")!
313 let clipped = blanks[0]!.lowerBound..<min(blanks[0]!.upperBound, high.position)
314 let separator = datetree != nil ? "\n" : "\n\n"
315 target.replace(clipped, with: separator)
316 target.point = clipped.lowerBound + separator.count
317 } else {
318 target.point = high.position
319 if !(datetree != nil && target.bolp) { target.insert("\n") }
320 }
321 try target.pasteSubtree(level: max(1, level + (headingText == nil ? 0 : 1)), tree: tree, limit: datetree != nil ? high.position : nil)
322 if !inherited.isEmpty, destination.isSameFile {
323 let all = inherited + local
324 target.saveExcursion {
325 let line = target.saveExcursion { target.lookingAt(SetTags.tagLine) }
326 if let tags = line?[1] {
327 target.point = tags.lowerBound
328 target.skipBackward(EmacsBuffer.blanks)
329 target.deleteRegion(target.point, target.lineEnd(target.point))
330 } else {
331 target.endOfLine()
332 }
333 target.saveExcursion { target.insert(" :" + all.joined(separator: ":") + ":") }
334 }
335 target.alignTags(onLineAt: target.point)
336 }
337 for (key, value) in context where value.contains(where: { !$0.isWhitespace }) {
338 target.entryPut("ARCHIVE_" + key, value)
339 }
340 }
341 source.point = origin.position
342 let range = try source.subtreeRange()
343 source.deleteRegion(range.lowerBound, range.upperBound)
344 source.saveExcursion {
345 source.upHeadingSafe()
346 source.updateStatisticsCookies()
347 }
348 if source.looking("^[ \\t]*$", setsMatch: false) != nil {
349 source.endOfLine()
350 source.point = source.nextHeadingStart(after: source.point) ?? source.length
351 }
352 }
353 if let archive {
354 let original = archiveText ?? ""
355 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) }) {
356 archiveEdit = result.edits.first
357 }
358 }
359 switch step {
360 case .commit(let result): return .success(Edits(source: result, archive: archiveEdit))
361 case .failed(let message): return .failure(.message(message))
362 case .prompt: return .failure(.message("unexpected prompt"))
363 case .external: return .failure(.message("unexpected external request"))
364 }
365 }
366}