Sources/OrgCore/Commands/Attach.swift

134 lines · 7230 bytes

  1import Foundation
  2
  3/// org-attach (org-attach.el, Org 9.8.7) with its defaults: where an entry's attachments are,
  4/// and the text changes its commands make. The file system is the caller's; `isDirectory`
  5/// answers for it.
  6public enum OrgAttach {
  7    /// `org-attach-id-to-path-function-list`: the uuid, timestamp and fallback folder formats.
  8    public static func idFolders(_ id: String) -> [String] {
  9        let chars = Array(id)
 10        guard let first = chars.first else { return [] }
 11        var folders: [String] = []
 12        if chars.count > 2 { folders.append(String(chars[..<2]) + "/" + String(chars[2...])) }
 13        if chars.count > 6 { folders.append(String(chars[..<6]) + "/" + String(chars[6...])) }
 14        folders.append("__/\(first)/\(id)")
 15        return folders
 16    }
 17
 18    /// `expand-file-name` of `path` in `folder`: `.` and `..` resolved, symbolic links not.
 19    public static func expand(_ path: String, in folder: String) -> String {
 20        let expanded = OrgPaths.expandingTilde(path)
 21        let absolute = expanded.hasPrefix("/") ? expanded : (folder as NSString).appendingPathComponent(expanded)
 22        return URL(fileURLWithPath: absolute).standardized.path
 23    }
 24
 25    /// `org-attach-dir-from-id`: the first folder for `id` under `idDir` that exists, or under
 26    /// `data/` when `idDir` is something else; with `existing` false, or when none exists, the
 27    /// first format's folder under `idDir`.
 28    public static func folder(forID id: String, idDir: String, in folder: String, existing: Bool, isDirectory: (String) -> Bool) -> String? {
 29        let base = expand(idDir, in: folder)
 30        let fallbacks = [expand("data/", in: folder)].filter { $0 != base && isDirectory($0) }
 31        var preferred: String?
 32        var first: String?
 33        for name in idFolders(id) where preferred == nil {
 34            let candidate = expand(name, in: base)
 35            if !existing || isDirectory(candidate) {
 36                preferred = candidate
 37            } else if first == nil {
 38                first = candidate
 39            }
 40            if existing, !isDirectory(candidate), let fallback = fallbacks.map({ expand(name, in: $0) }).first(where: isDirectory) {
 41                preferred = fallback
 42            }
 43        }
 44        return preferred ?? first
 45    }
 46
 47    /// The heading index of the entry at `offset`, nil before the first heading.
 48    static func entry(_ model: DocumentModel, at offset: Int) -> Int? {
 49        model.headings.lastIndex { $0.headingRange.lowerBound <= offset }
 50    }
 51
 52    /// `org-attach-dir` for the entry at `offset` of the file at `path`: its DIR property (or the
 53    /// older ATTACH_DIR), else its ID's folder. `inherit` is `org-attach-use-inheritance`: nil
 54    /// for `selective` (as `org-use-property-inheritance` has it), true to look in the
 55    /// ancestors too, false for the entry's own. Nil when there is no folder, or, unless
 56    /// `noFSCheck`, when the folder doesn't exist.
 57    public static func directory(tree: OrgTree, at offset: Int, path: String, idDir: String = "data/", inherit: Bool? = nil, noFSCheck: Bool = false, isDirectory: (String) -> Bool) -> String? {
 58        let model = DocumentModel(tree: tree)
 59        let heading = entry(model, at: offset)
 60        let folder = (path as NSString).deletingLastPathComponent
 61        func own(_ key: String, _ index: Int) -> String? {
 62            model.headings[index].properties.last { $0.key.uppercased() == key && !$0.additive }?.value
 63        }
 64        func value(_ key: String) -> String? {
 65            guard let heading else { return model.property(key, of: nil)?.value }
 66            switch inherit {
 67            case nil: return model.property(key, of: heading)?.value
 68            case false?: return own(key, heading)
 69            case true?: return ([heading] + model.ancestors(of: heading).reversed()).lazy.compactMap { own(key, $0) }.first ?? model.property(key, of: nil)?.value
 70            }
 71        }
 72        var dir: String?
 73        if let value = value("DIR") ?? value("ATTACH_DIR") {
 74            dir = expand(value, in: folder)
 75        } else if let id = value("ID"), !id.isEmpty {
 76            dir = Self.folder(forID: id, idDir: idDir, in: folder, existing: true, isDirectory: isDirectory)
 77        }
 78        guard let dir else { return nil }
 79        return noFSCheck || isDirectory(dir) ? dir : nil
 80    }
 81
 82    /// The entry's own DIR property, which `org-attach-set-directory` starts from.
 83    public static func dirProperty(tree: OrgTree, at offset: Int) -> String? {
 84        let model = DocumentModel(tree: tree)
 85        guard let heading = entry(model, at: offset) else { return model.property("DIR", of: nil)?.value }
 86        return model.headings[heading].properties.last { $0.key.uppercased() == "DIR" && !$0.additive }?.value
 87    }
 88
 89    /// `org-id-get` with `create`: the text with the entry's ID, made when it has none, and
 90    /// the ID.
 91    public static func ensuringID(_ text: String, at offset: Int, newID: () -> String = { UUID().uuidString.lowercased() }) -> (text: String, id: String) {
 92        let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
 93        return buffer.saveExcursion {
 94            buffer.backToHeadingOrPointMin()
 95            if let id = buffer.entryID() { return (text, id) }
 96            let id = newID()
 97            buffer.entryPut("ID", id)
 98            return (buffer.text as String, id)
 99        }
100    }
101
102    /// `org-attach-tag`: the text with `tag` added to or removed from the entry's heading;
103    /// unchanged before the first heading.
104    public static func tagging(_ text: String, at offset: Int, on: Bool, tag: String = "ATTACH", options: EditingOptions = .org) -> String {
105        let tree = OrgParser.parse(text)
106        let context = EditContext(revision: 0, text: text, tree: tree, selection: [offset..<offset], options: options)
107        guard entryHeading(at: offset, in: tree) != nil,
108              case .commit(let result) = ToggleTag(tag: tag, on: on).run(in: context) else { return text }
109        return result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
110    }
111
112    /// The text with the entry's DIR property set to `dir`, or with DIR and ATTACH_DIR removed
113    /// for nil (`org-attach-set-directory`, `org-attach-unset-directory`).
114    public static func settingDirectory(_ text: String, at offset: Int, to dir: String?) -> String {
115        let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
116        buffer.saveExcursion {
117            buffer.backToHeadingOrPointMin()
118            if let dir {
119                buffer.entryPut("DIR", dir)
120            } else {
121                buffer.entryDelete("DIR")
122                buffer.backToHeadingOrPointMin()
123                buffer.entryDelete("ATTACH_DIR")
124            }
125        }
126        return buffer.text as String
127    }
128
129    /// `org-attach-file-list`: the folder's names, without `.`, `..` and names ending in `~`,
130    /// sorted as `directory-files` sorts them.
131    public static func fileList(_ names: [String]) -> [String] {
132        names.filter { $0 != "." && $0 != ".." && !$0.hasSuffix("~") }.sorted { Array($0.utf8).lexicographicallyPrecedes(Array($1.utf8)) }
133    }
134}