Sources/OrgCore/Commands/Attach.swift
150 lines · 8200 bytes
15 symbols in this file
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 return directory(model: model, heading: entry(model, at: offset), path: path, idDir: idDir, inherit: inherit, noFSCheck: noFSCheck, isDirectory: isDirectory)
60 }
61
62 /// `directory(tree:at:…)` for heading `heading` of `model`, nil for the file's preamble.
63 static func directory(model: DocumentModel, heading: Int?, path: String, idDir: String, inherit: Bool?, noFSCheck: Bool, isDirectory: (String) -> Bool) -> String? {
64 let folder = (path as NSString).deletingLastPathComponent
65 func own(_ key: String, _ index: Int) -> String? {
66 model.headings[index].properties.last { $0.key.uppercased() == key && !$0.additive }?.value
67 }
68 func value(_ key: String) -> String? {
69 guard let heading else { return model.property(key, of: nil)?.value }
70 switch inherit {
71 case nil: return model.property(key, of: heading)?.value
72 case false?: return own(key, heading)
73 case true?: return ([heading] + model.ancestors(of: heading).reversed()).lazy.compactMap { own(key, $0) }.first ?? model.property(key, of: nil)?.value
74 }
75 }
76 var dir: String?
77 if let value = value("DIR") ?? value("ATTACH_DIR") {
78 dir = expand(value, in: folder)
79 } else if let id = value("ID"), !id.isEmpty {
80 dir = Self.folder(forID: id, idDir: idDir, in: folder, existing: true, isDirectory: isDirectory)
81 }
82 guard let dir else { return nil }
83 return noFSCheck || isDirectory(dir) ? dir : nil
84 }
85
86 /// The entry's own DIR property, which `org-attach-set-directory` starts from.
87 public static func dirProperty(tree: OrgTree, at offset: Int) -> String? {
88 let model = DocumentModel(tree: tree)
89 guard let heading = entry(model, at: offset) else { return model.property("DIR", of: nil)?.value }
90 return model.headings[heading].properties.last { $0.key.uppercased() == "DIR" && !$0.additive }?.value
91 }
92
93 /// `org-id-get` with `create`: the text with the entry's ID, made when it has none, and
94 /// the ID.
95 public static func ensuringID(_ text: String, at offset: Int, newID: () -> String = { UUID().uuidString.lowercased() }) -> (text: String, id: String) {
96 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
97 return buffer.saveExcursion {
98 buffer.backToHeadingOrPointMin()
99 if let id = buffer.entryID() { return (text, id) }
100 let id = newID()
101 buffer.entryPut("ID", id)
102 return (buffer.text as String, id)
103 }
104 }
105
106 /// Where text under a heading goes when `offset` is on its line: after the planning line,
107 /// drawers and clock lines (`org-end-of-meta-data` with FULL). `offset` itself on any other line.
108 public static func belowHeading(_ text: String, at offset: Int) -> Int {
109 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
110 return buffer.saveExcursion {
111 buffer.forwardLine(0)
112 guard buffer.atHeading else { return offset }
113 buffer.endOfMetaDataFull()
114 return buffer.point
115 }
116 }
117
118 /// `org-attach-tag`: the text with `tag` added to or removed from the entry's heading;
119 /// unchanged before the first heading.
120 public static func tagging(_ text: String, at offset: Int, on: Bool, tag: String = "ATTACH", options: EditingOptions = .org) -> String {
121 let tree = OrgParser.parse(text)
122 let context = EditContext(revision: 0, text: text, tree: tree, selection: [offset..<offset], options: options)
123 guard entryHeading(at: offset, in: tree) != nil,
124 case .commit(let result) = ToggleTag(tag: tag, on: on).run(in: context) else { return text }
125 return result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
126 }
127
128 /// The text with the entry's DIR property set to `dir`, or with DIR and ATTACH_DIR removed
129 /// for nil (`org-attach-set-directory`, `org-attach-unset-directory`).
130 public static func settingDirectory(_ text: String, at offset: Int, to dir: String?) -> String {
131 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
132 buffer.saveExcursion {
133 buffer.backToHeadingOrPointMin()
134 if let dir {
135 buffer.entryPut("DIR", dir)
136 } else {
137 buffer.entryDelete("DIR")
138 buffer.backToHeadingOrPointMin()
139 buffer.entryDelete("ATTACH_DIR")
140 }
141 }
142 return buffer.text as String
143 }
144
145 /// `org-attach-file-list`: the folder's names, without `.`, `..` and names ending in `~`,
146 /// sorted as `directory-files` sorts them.
147 public static func fileList(_ names: [String]) -> [String] {
148 names.filter { $0 != "." && $0 != ".." && !$0.hasSuffix("~") }.sorted { Array($0.utf8).lexicographicallyPrecedes(Array($1.utf8)) }
149 }
150}