Sources/OrgCore/Commands/Archive.swift

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