Commit 06941b2cf2

06941b2cf25c6ccc1629723cd7951910ce15e67a

parent: ea98aa3032

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 14:28 UTC

org-attach commands

Attach (copy, move, hard and symbolic links), from URL, new, open, reveal, delete, delete all, sync, set and unset DIR, for the ID-based layout with the ATTACH tag; org-attach-id-dir and org-attach-use-inheritance. iOS: More ▸ Attachments, the photo library, and files shared to orgstar.

Closes #42

Layout: unified · split

Sources/OrgApp/AttachActions.swift added +213
@@ -0,0 +1,213 @@
1import Foundation
2import OrgCore
3
4/// The `app.attach.` commands for the entry at the caret, with the platform's questions,
5/// file picker and file opening.
6@MainActor
7public struct AttachActions {
8 /// The open file's entry at the caret; nil when no file is open.
9 public var entry: () -> Attachments.Entry?
10 public var apply: (String) -> Void
11 public var show: (String) -> Void
12 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
13 public var storeLink: (StoredLink) -> Void
14 /// Opens a file as following a `file:` link does.
15 public var open: (String) -> Void
16 /// Shows a folder in the system's file browser.
17 public var reveal: (String) -> Void
18 /// Asks for files to attach with a method.
19 public var pick: (Attachments.Method) -> Void
20
21 public init(
22 entry: @escaping () -> Attachments.Entry?, apply: @escaping (String) -> Void, show: @escaping (String) -> Void,
23 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, storeLink: @escaping (StoredLink) -> Void,
24 open: @escaping (String) -> Void, reveal: @escaping (String) -> Void, pick: @escaping (Attachments.Method) -> Void
25 ) {
26 self.entry = entry
27 self.apply = apply
28 self.show = show
29 self.ask = ask
30 self.storeLink = storeLink
31 self.open = open
32 self.reveal = reveal
33 self.pick = pick
34 }
35
36 public static let methods: [String: Attachments.Method] = [
37 "app.attach.attach": .cp, "app.attach.move": .mv, "app.attach.link": .ln, "app.attach.symlink": .lns,
38 ]
39
40 private func yes(_ question: String, _ then: @escaping (Bool) -> Void) {
41 ask(Prompt(key: "confirm", message: question + " (yes or no)", choices: ["yes", "no"])) { then($0 == "yes") }
42 }
43
44 /// Runs `body` on the entry and applies its text, or shows what went wrong.
45 private func change(_ body: (inout Attachments.Entry) throws -> String?) {
46 guard var entry = entry() else { return show("No file is open") }
47 let original = entry.text
48 do {
49 let message = try body(&entry)
50 if entry.text != original { apply(entry.text) }
51 if let message { show(message) }
52 } catch {
53 if entry.text != original { apply(entry.text) }
54 show((error as? Attachments.Failure)?.description ?? error.localizedDescription)
55 }
56 }
57
58 public func run(_ id: String) {
59 if let method = Self.methods[id] { return pick(method) }
60 switch id {
61 case "app.attach.url":
62 ask(Prompt(key: "url", message: "URL of the file to attach:")) { answer in
63 guard let answer, !answer.isEmpty else { return }
64 download(answer)
65 }
66 case "app.attach.new":
67 ask(Prompt(key: "name", message: "Create attachment named:")) { name in
68 guard let name, !name.isEmpty else { return }
69 var file: String?
70 change { entry in
71 file = try Attachments.create(name, in: &entry)
72 return "New attachment \(name)"
73 }
74 if let file { open(file) }
75 }
76 case "app.attach.sync":
77 var empty: String?
78 change { entry in
79 empty = Attachments.sync(&entry)
80 return nil
81 }
82 if let empty {
83 yes("Attachment directory is empty. Delete?") { delete in
84 if delete { try? FileManager.default.removeItem(atPath: empty) }
85 }
86 }
87 case "app.attach.open":
88 guard let entry = entry() else { return show("No file is open") }
89 guard let dir = Attachments.directory(entry) else { return show("No attachment directory exist") }
90 let files = Attachments.files(in: dir)
91 if files.count == 1 { return open((dir as NSString).appendingPathComponent(files[0])) }
92 guard !files.isEmpty else { return show("No attachments in \(dir)") }
93 ask(Prompt(key: "file", message: "Open attachment:", choices: files)) { file in
94 if let file { open((dir as NSString).appendingPathComponent(file)) }
95 }
96 case "app.attach.reveal":
97 var dir: String?
98 change { entry in
99 dir = try Attachments.directoryCreating(&entry)
100 return nil
101 }
102 if let dir { reveal(dir) }
103 case "app.attach.delete":
104 guard let entry = entry() else { return show("No file is open") }
105 guard let dir = Attachments.directory(entry) else { return show("No attachment directory exist") }
106 ask(Prompt(key: "file", message: "Delete attachment:", choices: Attachments.files(in: dir))) { file in
107 guard let file else { return }
108 change { entry in
109 try Attachments.delete(file, in: entry)
110 return "Deleted attachment \(file)"
111 }
112 }
113 case "app.attach.delete-all":
114 guard let entry = entry() else { return show("No file is open") }
115 guard Attachments.directory(entry) != nil else { return show("No attachment directory exist") }
116 yes("Really remove all attachments of this entry?") { remove in
117 guard remove else { return }
118 change { entry in
119 try Attachments.deleteAll(&entry)
120 return "Attachment directory removed"
121 }
122 }
123 case "app.attach.set-directory":
124 guard let entry = entry() else { return show("No file is open") }
125 let current = OrgAttach.dirProperty(tree: OrgParser.parse(entry.text), at: entry.offset)
126 ask(Prompt(key: "dir", message: "Attachment directory:", initial: current ?? "", requireMatch: false)) { answer in
127 guard let answer, !answer.isEmpty else { return }
128 var moved: (new: String, old: String?)?
129 change { entry in
130 moved = Attachments.setDirectory(answer, in: &entry)
131 return nil
132 }
133 if let moved, let old = moved.old { offerMove(from: old, to: moved.new) }
134 }
135 case "app.attach.unset-directory":
136 var moved: (old: String?, new: String?)?
137 change { entry in
138 moved = Attachments.unsetDirectory(&entry)
139 return nil
140 }
141 if let moved, let old = moved.old { offerMove(from: old, to: moved.new) }
142 default:
143 show("Unknown attachment command \(id)")
144 }
145 }
146
147 /// `org-attach-set-directory`'s questions after the folder changes.
148 private func offerMove(from old: String, to new: String?) {
149 func offerDelete() {
150 yes("Delete \(old)") { delete in
151 if delete { try? FileManager.default.removeItem(atPath: old) }
152 }
153 }
154 guard let new else { return offerDelete() }
155 yes("Copy over attachments from old directory?") { copy in
156 if copy {
157 do { try Attachments.copyContents(of: old, to: new) } catch { return show(error.localizedDescription) }
158 }
159 offerDelete()
160 }
161 }
162
163 /// `org-attach-attach` for each picked file.
164 public func attach(_ urls: [URL], method: Attachments.Method) {
165 change { entry in
166 var names: [String] = []
167 for url in urls {
168 let scoped = url.startAccessingSecurityScopedResource()
169 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
170 let link = try Attachments.attach(url, method: method, to: &entry)
171 storeLink(link)
172 names.append(link.description ?? url.lastPathComponent)
173 }
174 return Self.attached(names)
175 }
176 }
177
178 /// `data` attached as `name`, as a photo or a download is.
179 public func attach(_ data: Data, named name: String) {
180 change { entry in
181 let link = try Attachments.attach(data, named: name, to: &entry)
182 storeLink(link)
183 return Self.attached([name])
184 }
185 }
186
187 static func attached(_ names: [String]) -> String? {
188 switch names.count {
189 case 0: nil
190 case 1: "File \"\(names[0])\" is now an attachment"
191 default: "\(names.count) files are now attachments"
192 }
193 }
194
195 /// `org-attach-url`: the file downloaded, then attached as the URL's last part.
196 private func download(_ address: String) {
197 guard let url = URL(string: address), url.scheme != nil else { return show("Not a URL: \(address)") }
198 let name = Attachments.name(ofURL: address)
199 guard !name.isEmpty else { return show("No file name in \(address)") }
200 show("Downloading \(address)…")
201 Task { @MainActor in
202 do {
203 let (data, response) = try await URLSession.shared.data(from: url)
204 if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
205 return show("Can't download \(address): HTTP \(http.statusCode)")
206 }
207 attach(data, named: name)
208 } catch {
209 show("Can't download \(address): \(error.localizedDescription)")
210 }
211 }
212 }
213}
Sources/OrgApp/AttachmentInbox.swift added +42
@@ -0,0 +1,42 @@
1import Foundation
2
3/// Files shared from other apps to attach, waiting for the app to ask which entry they go to:
4/// a folder for each share in the app group's container, which the share extension writes.
5public struct AttachmentInbox: Sendable {
6 public let folder: URL
7
8 /// The app group's inbox; nil when the app isn't entitled to the group.
9 public init?(group: String = CaptureInbox.group) {
10 guard let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) else { return nil }
11 folder = container.appendingPathComponent("Attachments")
12 }
13
14 public init(folder: URL) {
15 self.folder = folder
16 }
17
18 /// `files` copied in as one share.
19 public func add(_ files: [URL]) throws {
20 let batch = folder.appendingPathComponent(String(format: "%020.6f", Date().timeIntervalSince1970) + "-" + UUID().uuidString)
21 try FileManager.default.createDirectory(at: batch, withIntermediateDirectories: true)
22 for file in files {
23 try FileManager.default.copyItem(at: file, to: batch.appendingPathComponent(file.lastPathComponent))
24 }
25 }
26
27 /// The waiting shares, oldest first.
28 public func batches() -> [URL] {
29 let names = ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted()
30 return names.map { folder.appendingPathComponent($0) }
31 }
32
33 /// A share's files, by name.
34 public static func files(in batch: URL) -> [URL] {
35 ((try? FileManager.default.contentsOfDirectory(atPath: batch.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted().map { batch.appendingPathComponent($0) }
36 }
37
38 /// The share and whatever is left of it.
39 public func remove(_ batch: URL) {
40 try? FileManager.default.removeItem(at: batch)
41 }
42}
Sources/OrgApp/Attachments.swift added +201
@@ -0,0 +1,201 @@
1import Foundation
2import OrgCore
3
4/// org-attach's commands on the file system, with `org-attach-preferred-new-method` `id`,
5/// `org-attach-auto-tag` "ATTACH" and `org-attach-store-link-p` `attached`. Each takes the
6/// file's text and returns it as the command leaves it.
7public enum Attachments {
8 /// `org-attach-method`.
9 public enum Method: String, Sendable {
10 case cp, mv, ln, lns
11 }
12
13 public struct Failure: Error, Equatable, CustomStringConvertible {
14 public let description: String
15 public init(_ description: String) { self.description = description }
16 }
17
18 /// Where an entry is: its file's text and path, and an offset in the entry.
19 public struct Entry: Sendable {
20 public var text: String
21 public let offset: Int
22 public let path: String
23 public let idDir: String
24 /// `org-attach-use-inheritance`, as `OrgAttach.directory` takes it.
25 public let inherit: Bool?
26 public let options: EditingOptions
27
28 public init(text: String, offset: Int, path: String, idDir: String = OrgPreferences.attachIDDir(),
29 inherit: Bool? = OrgPreferences.attachUseInheritance(), options: EditingOptions = .org) {
30 self.text = text
31 self.offset = offset
32 self.path = path
33 self.idDir = idDir
34 self.inherit = inherit
35 self.options = options
36 }
37 }
38
39 static func isDirectory(_ path: String) -> Bool {
40 var directory: ObjCBool = false
41 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
42 }
43
44 /// `org-attach-dir`: the entry's attachment folder when it exists.
45 public static func directory(_ entry: Entry, noFSCheck: Bool = false) -> String? {
46 OrgAttach.directory(tree: OrgParser.parse(entry.text), at: entry.offset, path: entry.path, idDir: entry.idDir, inherit: entry.inherit, noFSCheck: noFSCheck, isDirectory: isDirectory)
47 }
48
49 /// `org-attach-dir-get-create`: the folder, made if missing; an entry without DIR or ID
50 /// gets an ID.
51 public static func directoryCreating(_ entry: inout Entry, newID: () -> String = { UUID().uuidString.lowercased() }) throws -> String {
52 var dir = directory(entry, noFSCheck: true)
53 if dir == nil {
54 let (text, id) = OrgAttach.ensuringID(entry.text, at: entry.offset, newID: newID)
55 entry.text = text
56 dir = OrgAttach.folder(forID: id, idDir: entry.idDir, in: (entry.path as NSString).deletingLastPathComponent, existing: false, isDirectory: isDirectory)
57 }
58 guard let dir else { throw Failure("No attachment directory is associated with the current node") }
59 try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
60 return dir
61 }
62
63 static func tag(_ entry: inout Entry, on: Bool) {
64 entry.text = OrgAttach.tagging(entry.text, at: entry.offset, on: on, options: entry.options)
65 }
66
67 static func stored(_ name: String) -> StoredLink {
68 StoredLink(link: "attachment:" + name, description: name)
69 }
70
71 /// `org-attach-attach`: `source` moved, copied or linked into the folder. The link it
72 /// stores.
73 @discardableResult
74 public static func attach(_ source: URL, method: Method, to entry: inout Entry) throws -> StoredLink {
75 let dir = try directoryCreating(&entry)
76 let name = source.standardizedFileURL.lastPathComponent
77 let target = (dir as NSString).appendingPathComponent(name)
78 let files = FileManager.default
79 switch method {
80 case .mv: try files.moveItem(atPath: source.path, toPath: target)
81 case .cp: try files.copyItem(atPath: source.path, toPath: target)
82 case .ln: try files.linkItem(atPath: source.path, toPath: target)
83 case .lns: try files.createSymbolicLink(atPath: target, withDestinationPath: source.path)
84 }
85 tag(&entry, on: true)
86 return stored(name)
87 }
88
89 /// `org-attach-url` and `org-attach-buffer`: `data` written as `name` in the folder.
90 @discardableResult
91 public static func attach(_ data: Data, named name: String, to entry: inout Entry) throws -> StoredLink {
92 guard !name.isEmpty, !name.contains("/") else { throw Failure("No file name to attach as") }
93 let dir = try directoryCreating(&entry)
94 let target = (dir as NSString).appendingPathComponent(name)
95 guard !FileManager.default.fileExists(atPath: target) else { throw Failure("File exists: \(target)") }
96 try data.write(to: URL(fileURLWithPath: target))
97 tag(&entry, on: true)
98 return stored(name)
99 }
100
101 /// The name `org-attach-url` gives a download: the URL after its last slash.
102 public static func name(ofURL url: String) -> String {
103 url.split(separator: "/", omittingEmptySubsequences: false).last.map(String.init) ?? ""
104 }
105
106 /// `org-attach-new`: the path of `name` in the folder, made empty if missing, to open.
107 public static func create(_ name: String, in entry: inout Entry) throws -> String {
108 let dir = try directoryCreating(&entry)
109 tag(&entry, on: true)
110 let file = OrgAttach.expand(name, in: dir)
111 if !FileManager.default.fileExists(atPath: file) {
112 try FileManager.default.createDirectory(atPath: (file as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
113 try Data().write(to: URL(fileURLWithPath: file))
114 }
115 return file
116 }
117
118 /// `org-attach-file-list`.
119 public static func files(in dir: String) -> [String] {
120 OrgAttach.fileList((try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? [])
121 }
122
123 /// `org-attach-delete-one`.
124 public static func delete(_ name: String, in entry: Entry) throws {
125 guard let dir = directory(entry) else { throw Failure("No attachment directory exist") }
126 let file = OrgAttach.expand(name, in: dir)
127 guard FileManager.default.fileExists(atPath: file) else { throw Failure("No such attachment: \(file)") }
128 try FileManager.default.removeItem(atPath: file)
129 }
130
131 /// `org-attach-delete-all`: the folder and everything in it, and the tag.
132 public static func deleteAll(_ entry: inout Entry) throws {
133 guard let dir = directory(entry) else { return }
134 try FileManager.default.removeItem(atPath: dir)
135 tag(&entry, on: false)
136 }
137
138 /// `org-attach-sync`: the tag on when the folder has files, off when it hasn't or is
139 /// missing. The folder when it's empty, for the caller to offer to delete.
140 public static func sync(_ entry: inout Entry) -> String? {
141 guard let dir = directory(entry) else {
142 tag(&entry, on: false)
143 return nil
144 }
145 let files = files(in: dir)
146 tag(&entry, on: !files.isEmpty)
147 return ((try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? []).isEmpty ? dir : nil
148 }
149
150 /// `org-attach-set-directory`'s DIR: `dir` expanded against the file's folder, absolute as
151 /// with `org-attach-dir-relative` nil. The old folder when it existed and is another.
152 public static func setDirectory(_ dir: String, in entry: inout Entry) -> (new: String, old: String?) {
153 let old = directory(entry)
154 let new = OrgAttach.expand(dir, in: (entry.path as NSString).deletingLastPathComponent)
155 entry.text = OrgAttach.settingDirectory(entry.text, at: entry.offset, to: dir.hasSuffix("/") ? new + "/" : new)
156 return (new, old.flatMap { $0 == new ? nil : $0 })
157 }
158
159 /// `org-attach-unset-directory`: DIR and ATTACH_DIR removed. The old and new folders when
160 /// they differ.
161 public static func unsetDirectory(_ entry: inout Entry) -> (old: String?, new: String?) {
162 let old = directory(entry)
163 entry.text = OrgAttach.settingDirectory(entry.text, at: entry.offset, to: nil)
164 let new = directory(entry)
165 return old == new ? (nil, nil) : (old, new)
166 }
167
168 /// `copy-directory` of the old folder's contents into the new one, which is made if
169 /// missing; files there already are kept.
170 public static func copyContents(of old: String, to new: String) throws {
171 let files = FileManager.default
172 try files.createDirectory(atPath: new, withIntermediateDirectories: true)
173 for name in try files.contentsOfDirectory(atPath: old) {
174 let target = (new as NSString).appendingPathComponent(name)
175 if !files.fileExists(atPath: target) { try files.copyItem(atPath: (old as NSString).appendingPathComponent(name), toPath: target) }
176 }
177 }
178}
179
180extension DocumentSession {
181 /// `files` moved into the attachment folder of the entry at `offset` of `path`, open or
182 /// not. A message for the echo area.
183 public func attach(_ files: [URL], to path: String, at offset: Int) -> String {
184 guard let text = text(of: path) else { return "Can't read \((path as NSString).lastPathComponent)" }
185 var entry = Attachments.Entry(text: text, offset: offset, path: path, options: options)
186 var names: [String] = []
187 var failure: String?
188 for file in files {
189 do {
190 names.append(try Attachments.attach(file, method: .mv, to: &entry).description ?? file.lastPathComponent)
191 } catch {
192 failure = (error as? Attachments.Failure)?.description ?? error.localizedDescription
193 break
194 }
195 }
196 if entry.text != text, case .failed(let message) = perform(ReplaceText(old: text, new: entry.text), path: path, at: offset, expect: nil) {
197 return message
198 }
199 return failure ?? AttachActions.attached(names) ?? "Nothing to attach"
200 }
201}
Sources/OrgApp/DocumentSession.swift +8
@@ -190,6 +190,14 @@ public final class DocumentSession {
190190 return entries.first { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == truename }
191191 }
192192
193 /// The text of `path`: its buffer's when it's open, else what's on disk.
194 public func text(of path: String) -> String? {
195 if let entry = entry(path) { return entry.buffer.document.text }
196 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
197 let state = loaded(bytes, path: path)
198 return state.isEditable ? state.text : nil
199 }
200
193201 /// The buffer's name as uniquify writes it (`post-forward-angle-brackets`): the file name,
194202 /// with as many of its folders as tell it apart from other open files of the same name.
195203 public func bufferName(_ path: String) -> String {
Sources/OrgApp/EmacsImport.swift +5
@@ -543,6 +543,11 @@ public struct EmacsImport: Sendable {
543543 else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count {
544544 add(name, .string(keywords.joined(separator: " ")))
545545 } else { note("unexpected value \(value.description)") }
546 case "org-attach-id-dir":
547 guard let dir = value.string else { return note("not a string") }
548 add(name, .string(dir))
549 case "org-attach-use-inheritance":
550 if value.symbol == "selective" { add(name, .string("selective")) } else { add(name, .string(truthy ? "t" : "nil")) }
546551 case "org-crypt-tag-matcher":
547552 guard let tag = value.string, tag.range(of: "^[\\w@#%]+$", options: .regularExpression) != nil else { return note("not a single tag") }
548553 add(name, .string(tag))
Sources/OrgApp/LinkFollow.swift +1 −1
@@ -38,7 +38,7 @@ extension DocumentSession {
3838 return shown(Links.searchRadio(link.path, tree: document.tree))
3939 case "attachment":
4040 guard let tree = document?.tree,
41 let file = Links.attachmentFile(link, tree: tree, path: path, isDirectory: Self.isDirectory) else {
41 let file = Links.attachmentFile(link, tree: tree, path: path, idDir: OrgPreferences.attachIDDir(), inherit: OrgPreferences.attachUseInheritance(), isDirectory: Self.isDirectory) else {
4242 return .message("Need absolute `org-attach-id-dir' to attach in buffers without filename")
4343 }
4444 return followFile(file, isText: isText)
Sources/OrgApp/OrgPreferences.swift +13
@@ -145,6 +145,19 @@ public enum OrgPreferences {
145145 options.userFullName = NSFullUserName()
146146 return options
147147 }
148 /// `org-attach-id-dir`, relative to an org file's folder unless absolute.
149 public static func attachIDDir(_ defaults: UserDefaults = .standard) -> String {
150 let dir = string("attachIDDir", defaults)
151 return dir.isEmpty ? "data/" : dir
152 }
153 /// `org-attach-use-inheritance`: nil for `selective`, else whether DIR and ID inherit.
154 public static func attachUseInheritance(_ defaults: UserDefaults = .standard) -> Bool? {
155 switch string("attachUseInheritance", defaults) {
156 case "t": true
157 case "nil": false
158 default: nil
159 }
160 }
148161 /// `org-crypt-tag-matcher`, a tag.
149162 public static func cryptTag(_ defaults: UserDefaults = .standard) -> String {
150163 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces)
Sources/OrgApp/UserConfig.swift +5
@@ -147,6 +147,11 @@ public enum UserConfig {
147147 comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""),
148148 Setting(section: "", key: "org-startup-with-latex-preview", defaultsKey: "startupWithLatexPreview", kind: .bool, fallback: .bool(false),
149149 comment: "show LaTeX fragments as typeset math when a file opens; #+STARTUP: (no)latexpreview overrides", legacy: ""),
150 Setting(section: "", key: "org-attach-id-dir", defaultsKey: "attachIDDir", kind: .string, fallback: .string("data/"),
151 comment: "the folder attachment folders named by ID go in, relative to the org file's folder unless absolute", legacy: ""),
152 Setting(section: "", key: "org-attach-use-inheritance", defaultsKey: "attachUseInheritance",
153 kind: .choice([("selective", "selective"), ("t", "t"), ("nil", "nil")]), fallback: .string("selective"),
154 comment: "whether DIR and ID inherit for attachments: selective (as org-use-property-inheritance), t or nil", legacy: ""),
150155 Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"),
151156 comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""),
152157 Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages",
Sources/OrgCore/Commands/Attach.swift added +134
@@ -0,0 +1,134 @@
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 = (path as NSString).expandingTildeInPath
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}
Sources/OrgCore/Commands/Command.swift +18
@@ -219,6 +219,24 @@ public struct PrecomputedEdit: OrgCommand {
219219 }
220220}
221221
222/// The text replaced by `new`, as long as it is still `old`: a change computed outside the
223/// buffer, such as attaching a file.
224public struct ReplaceText: OrgCommand {
225 public let old: String
226 public let new: String
227 public init(old: String, new: String) {
228 self.old = old
229 self.new = new
230 }
231 public var id: String { "internal.replace-text" }
232 public var title: String { "Replace Text" }
233 public func applies(in context: EditContext) -> Bool { context.text == old }
234 public func run(in context: EditContext) -> CommandStep {
235 guard context.text == old else { return .failed("The file changed; try again.") }
236 return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(old, new)))
237 }
238}
239
222240/// Things a command asks for besides text changes; the platform layer carries them out.
223241public enum Effect: Sendable, Equatable {
224242 case message(String)
Sources/OrgCore/Keymap/PresetDoom.swift +36
@@ -220,6 +220,42 @@ extension KeymapPreset {
220220 command = "org.edit-special"
221221 mode = "normal"
222222 [[bind]]
223 keys = "SPC m a a"
224 command = "app.attach.attach"
225 mode = "normal"
226 [[bind]]
227 keys = "SPC m a d"
228 command = "app.attach.delete"
229 mode = "normal"
230 [[bind]]
231 keys = "SPC m a D"
232 command = "app.attach.delete-all"
233 mode = "normal"
234 [[bind]]
235 keys = "SPC m a n"
236 command = "app.attach.new"
237 mode = "normal"
238 [[bind]]
239 keys = "SPC m a o"
240 command = "app.attach.open"
241 mode = "normal"
242 [[bind]]
243 keys = "SPC m a r"
244 command = "app.attach.reveal"
245 mode = "normal"
246 [[bind]]
247 keys = "SPC m a u"
248 command = "app.attach.url"
249 mode = "normal"
250 [[bind]]
251 keys = "SPC m a s"
252 command = "app.attach.set-directory"
253 mode = "normal"
254 [[bind]]
255 keys = "SPC m a S"
256 command = "app.attach.sync"
257 mode = "normal"
258 [[bind]]
223259 keys = "SPC m s c"
224260 command = "org.subtree.clone"
225261 mode = "normal"
Sources/OrgCore/Keymap/PresetEmacs.swift +78
@@ -194,6 +194,84 @@ extension KeymapPreset {
194194 keys = "C-c C-x C-l"
195195 command = "org.latex-preview"
196196 [[bind]]
197 keys = "C-c C-a a"
198 command = "app.attach.attach"
199 [[bind]]
200 keys = "C-c C-a C-a"
201 command = "app.attach.attach"
202 [[bind]]
203 keys = "C-c C-a c"
204 command = "app.attach.attach"
205 [[bind]]
206 keys = "C-c C-a C-c"
207 command = "app.attach.attach"
208 [[bind]]
209 keys = "C-c C-a m"
210 command = "app.attach.move"
211 [[bind]]
212 keys = "C-c C-a C-m"
213 command = "app.attach.move"
214 [[bind]]
215 keys = "C-c C-a l"
216 command = "app.attach.link"
217 [[bind]]
218 keys = "C-c C-a C-l"
219 command = "app.attach.link"
220 [[bind]]
221 keys = "C-c C-a y"
222 command = "app.attach.symlink"
223 [[bind]]
224 keys = "C-c C-a C-y"
225 command = "app.attach.symlink"
226 [[bind]]
227 keys = "C-c C-a u"
228 command = "app.attach.url"
229 [[bind]]
230 keys = "C-c C-a C-u"
231 command = "app.attach.url"
232 [[bind]]
233 keys = "C-c C-a n"
234 command = "app.attach.new"
235 [[bind]]
236 keys = "C-c C-a C-n"
237 command = "app.attach.new"
238 [[bind]]
239 keys = "C-c C-a z"
240 command = "app.attach.sync"
241 [[bind]]
242 keys = "C-c C-a C-z"
243 command = "app.attach.sync"
244 [[bind]]
245 keys = "C-c C-a o"
246 command = "app.attach.open"
247 [[bind]]
248 keys = "C-c C-a C-o"
249 command = "app.attach.open"
250 [[bind]]
251 keys = "C-c C-a f"
252 command = "app.attach.reveal"
253 [[bind]]
254 keys = "C-c C-a C-f"
255 command = "app.attach.reveal"
256 [[bind]]
257 keys = "C-c C-a d"
258 command = "app.attach.delete"
259 [[bind]]
260 keys = "C-c C-a C-d"
261 command = "app.attach.delete"
262 [[bind]]
263 keys = "C-c C-a D"
264 command = "app.attach.delete-all"
265 [[bind]]
266 keys = "C-c C-a s"
267 command = "app.attach.set-directory"
268 [[bind]]
269 keys = "C-c C-a C-s"
270 command = "app.attach.set-directory"
271 [[bind]]
272 keys = "C-c C-a S"
273 command = "app.attach.unset-directory"
274 [[bind]]
197275 keys = "C-c \\" g"
198276 command = "app.plot"
199277 [[bind]]
Sources/OrgCore/Links/Links.swift +8 −26
@@ -167,38 +167,20 @@ public enum Links {
167167 return found.map { .found($0) } ?? .failed("No match for radio target: \(target)")
168168 }
169169
170 /// The file `org-attach-follow` opens for an `attachment` link, with org-attach's
171 /// defaults: in the entry's DIR property (or the older ATTACH_DIR), else in the folder for
172 /// its ID under `data/` that exists (`org-attach-id-to-path-function-list`), both relative
173 /// to the file's folder. Without an existing folder the file is relative to the file's
174 /// folder, as `org-attach-expand` has it. Nil without a folder to start from.
175 public static func attachmentFile(_ link: OrgLink, tree: OrgTree, path: String?, isDirectory: (String) -> Bool) -> OrgLink? {
176 let model = DocumentModel(tree: tree)
177 let offset = link.position ?? 0
178 let heading = model.headings.lastIndex { $0.sectionRange.contains(offset) }
179 let folder = path.map { ($0 as NSString).deletingLastPathComponent }
180 func absolute(_ p: String, in folder: String?) -> String? {
181 let expanded = (p as NSString).expandingTildeInPath
182 if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
183 return folder.map { (($0 as NSString).appendingPathComponent(expanded) as NSString).standardizingPath }
184 }
185 var candidates: [String] = []
186 if let dir = model.property("DIR", of: heading) ?? model.property("ATTACH_DIR", of: heading) {
187 candidates = [dir.value]
188 } else if let id = model.property("ID", of: heading)?.value, let first = id.first {
189 let chars = Array(id)
190 if chars.count > 2 { candidates.append("data/" + String(chars[..<2]) + "/" + String(chars[2...])) }
191 if chars.count > 6 { candidates.append("data/" + String(chars[..<6]) + "/" + String(chars[6...])) }
192 candidates.append("data/__/\(first)/\(id)")
193 }
194 let dir = candidates.lazy.compactMap { absolute($0, in: folder) }.first(where: isDirectory) ?? folder
170 /// The file `org-attach-follow` opens for an `attachment` link: in the entry's attachment
171 /// folder (`OrgAttach.directory`) when it exists, else relative to the file's folder, as
172 /// `org-attach-expand` has it. Nil without a folder to start from.
173 public static func attachmentFile(_ link: OrgLink, tree: OrgTree, path: String?, idDir: String = "data/", inherit: Bool? = nil, isDirectory: (String) -> Bool) -> OrgLink? {
174 guard let path else { return nil }
175 let folder = (path as NSString).deletingLastPathComponent
176 let dir = OrgAttach.directory(tree: tree, at: link.position ?? 0, path: path, idDir: idDir, inherit: inherit, isDirectory: isDirectory) ?? folder
195177 var file = link.path
196178 var search: String?
197179 if let range = file.range(of: "::") {
198180 search = String(file[range.upperBound...])
199181 file = String(file[..<range.lowerBound])
200182 }
201 return absolute(file, in: dir).map { OrgLink(type: "file", path: $0, searchOption: search, raw: link.raw) }
183 return OrgLink(type: "file", path: OrgAttach.expand(file, in: dir), searchOption: search, raw: link.raw)
202184 }
203185
204186 // MARK: - Searching a file
Sources/OrgEditorAppKit/EditorCommands.swift +13
@@ -108,6 +108,19 @@ public enum EditorCommands {
108108 EditorCommand(id: "app.table-import", title: "Import Table from File…", action: .app),
109109 EditorCommand(id: "app.table-export", title: "Export Table to File…", action: .app),
110110 EditorCommand(id: "app.plot", title: "Plot Table", action: .app),
111 EditorCommand(id: "app.attach.attach", title: "Attach File…", action: .app),
112 EditorCommand(id: "app.attach.move", title: "Attach File by Moving…", action: .app),
113 EditorCommand(id: "app.attach.link", title: "Attach File as Hard Link…", action: .app),
114 EditorCommand(id: "app.attach.symlink", title: "Attach File as Symbolic Link…", action: .app),
115 EditorCommand(id: "app.attach.url", title: "Attach File from URL…", action: .app),
116 EditorCommand(id: "app.attach.new", title: "New Attachment…", action: .app),
117 EditorCommand(id: "app.attach.open", title: "Open Attachment…", action: .app),
118 EditorCommand(id: "app.attach.reveal", title: "Show Attachment Folder", action: .app),
119 EditorCommand(id: "app.attach.delete", title: "Delete Attachment…", action: .app),
120 EditorCommand(id: "app.attach.delete-all", title: "Delete All Attachments…", action: .app),
121 EditorCommand(id: "app.attach.sync", title: "Sync Attachments", action: .app),
122 EditorCommand(id: "app.attach.set-directory", title: "Set Attachment Folder…", action: .app),
123 EditorCommand(id: "app.attach.unset-directory", title: "Unset Attachment Folder", action: .app),
111124 EditorCommand(id: "app.crypt.encrypt-entry", title: "Encrypt Entry…", action: .app),
112125 EditorCommand(id: "app.crypt.open-entry", title: "Decrypt Entry…", action: .app),
113126 EditorCommand(id: "app.crypt.decrypt-entry", title: "Decrypt Entry in File…", action: .app),
Sources/Orgstar/ContentView.swift +26
@@ -670,6 +670,30 @@ struct ContentView: View {
670670 }
671671 }
672672
673 /// org-attach's commands for the entry at the caret.
674 private var attachActions: AttachActions {
675 AttachActions(
676 entry: { [commands, session] in
677 guard let editor = commands.editor, let path = session.path else { return nil }
678 let context = editor.context()
679 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
680 },
681 apply: applyText, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
682 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
683 open: { [session, workspace, commands] file in
684 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace) { commands.show(message) }
685 },
686 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
687 pick: { method in
688 let panel = NSOpenPanel()
689 panel.canChooseDirectories = true
690 panel.allowsMultipleSelection = true
691 panel.message = "File to keep as an attachment"
692 guard panel.runModal() == .OK else { return }
693 attachActions.attach(panel.urls, method: method)
694 })
695 }
696
673697 /// The sheet a panel shows.
674698 @ViewBuilder
675699 private func panelView(_ panel: Panel) -> some View {
@@ -1088,6 +1112,8 @@ struct ContentView: View {
10881112 plotTable()
10891113 case let id where id.hasPrefix("app.crypt."):
10901114 crypt(id)
1115 case let id where id.hasPrefix("app.attach."):
1116 attachActions.run(id)
10911117 default:
10921118 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
10931119 }
Sources/OrgstarMobile/AgendaScreen.swift +2 −1
@@ -1128,6 +1128,7 @@ struct RefileSheet: View {
11281128 /// `org-refile-allow-creating-parent-nodes`: `parent/new` in the search field offers to
11291129 /// add the heading.
11301130 var create: ((RefileTarget, String) -> Void)?
1131 var title = "Refile to"
11311132 let choose: (RefileTarget?) -> Void
11321133 @State private var query = ""
11331134
@@ -1173,7 +1174,7 @@ struct RefileSheet: View {
11731174 }
11741175 }
11751176 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
1176 .navigationTitle("Refile to")
1177 .navigationTitle(title)
11771178 .navigationBarTitleDisplayMode(.inline)
11781179 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { choose(nil) } } }
11791180 }
Sources/OrgstarMobile/EditorScreen.swift +106 −7
@@ -2,6 +2,8 @@
22import OrgApp
33import OrgCore
44import OrgDocument
5import PhotosUI
6import QuickLook
57import SwiftUI
68import UIKit
79import UniformTypeIdentifiers
@@ -44,6 +46,12 @@ struct EditorScreen: View {
4446 @State private var importingTable = false
4547 /// The table at the caret, for `org-table-export`'s save dialog.
4648 @State private var exportedTable: TableFile?
49 /// org-attach's file picker is up, for this method.
50 @State private var attaching: Attachments.Method?
51 @State private var attachingPhotos = false
52 @State private var photos: [PhotosPickerItem] = []
53 /// A file shown in Quick Look.
54 @State private var previewed: URL?
4755
4856 enum Sheet: Identifiable {
4957 case palette, conflict, syncCopies, recovery
@@ -102,6 +110,19 @@ struct EditorScreen: View {
102110 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
103111 }
104112 RecentClockMenu(clock: clock) { editor?.run($0) }
113 Menu("Attachments", systemImage: "paperclip") {
114 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
115 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
116 Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
117 Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
118 Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
119 Button("Show Attachment Folder", systemImage: "folder") { attachActions.run("app.attach.reveal") }
120 Button("Delete Attachment…", systemImage: "trash") { attachActions.run("app.attach.delete") }
121 Button("Delete All Attachments…", systemImage: "trash.slash") { attachActions.run("app.attach.delete-all") }
122 Button("Sync Attachments", systemImage: "arrow.triangle.2.circlepath") { attachActions.run("app.attach.sync") }
123 Button("Set Attachment Folder…", systemImage: "folder.badge.gearshape") { attachActions.run("app.attach.set-directory") }
124 Button("Unset Attachment Folder", systemImage: "folder.badge.minus") { attachActions.run("app.attach.unset-directory") }
125 }
105126 Menu("Encryption", systemImage: "lock") {
106127 Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
107128 Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
@@ -178,6 +199,24 @@ struct EditorScreen: View {
178199 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
179200 importTable(result)
180201 }
202 .background {
203 // A second importer on the same view would replace the first.
204 Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
205 allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
206 let method = attaching ?? .cp
207 switch result {
208 case .success(let urls): attachActions.attach(urls, method: method)
209 case .failure(let error): message = error.localizedDescription
210 }
211 }
212 }
213 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
214 .onChange(of: photos) { _, items in
215 guard !items.isEmpty else { return }
216 photos = []
217 attachPhotos(items)
218 }
219 .quickLookPreview($previewed)
181220 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
182221 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
183222 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
@@ -252,13 +291,7 @@ struct EditorScreen: View {
252291 editor.onChange = { [weak session] in session?.bufferChanged(path) }
253292 editor.onMessage = { message = $0 }
254293 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
255 editor.onLink = { link in
256 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
257 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
258 case .openExternally(let url): openURL(url)
259 case .message(let text): message = text
260 }
261 }
294 editor.onLink = { link in follow(link) }
262295 editor.onEditBlock = { edit in sheet = .block(edit) }
263296 editor.onColumnView = { view in sheet = .columns(view) }
264297 editor.onTangle = { scope in message = session.tangle(scope) }
@@ -280,6 +313,8 @@ struct EditorScreen: View {
280313 plotTable()
281314 } else if id.hasPrefix("app.crypt.") {
282315 crypt(id)
316 } else if id.hasPrefix("app.attach.") {
317 attachActions.run(id)
283318 } else if id == "app.toggle-markup" {
284319 model.showMarkup.toggle()
285320 } else if MobileEditor.linkCommands.contains(id) {
@@ -301,6 +336,51 @@ struct EditorScreen: View {
301336}
302337
303338extension EditorScreen {
339 /// Follows a link; files the editor doesn't open show in Quick Look.
340 private func follow(_ link: OrgLink) {
341 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
342 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
343 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
344 case .message(let text): message = text
345 }
346 }
347
348 /// org-attach's commands for the entry at the caret.
349 private var attachActions: AttachActions {
350 AttachActions(
351 entry: {
352 guard let editor else { return nil }
353 let context = editor.editContext()
354 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
355 },
356 apply: { new in
357 guard let editor else { return }
358 let context = editor.editContext()
359 let caret = min(context.caret, (new as NSString).length)
360 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
361 },
362 show: { message = $0 },
363 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
364 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
365 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
366 reveal: { dir in
367 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
368 },
369 pick: { attaching = $0 })
370 }
371
372 /// Photos and videos attached under the names Photos gives them.
373 private func attachPhotos(_ items: [PhotosPickerItem]) {
374 Task { @MainActor in
375 var urls: [URL] = []
376 for item in items {
377 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
378 }
379 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
380 if !urls.isEmpty { attachActions.attach(urls, method: .mv) }
381 }
382 }
383
304384 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
305385 private func importTable(_ result: Result<URL, Error>) {
306386 guard case .success(let url) = result, let editor else { return }
@@ -657,6 +737,10 @@ struct CommandPalette: View {
657737 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
658738 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
659739 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
740 ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
741 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
742 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
743 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
660744 ]
661745
662746 /// The commands that apply at the caret and their keys, worked out once when the palette
@@ -728,6 +812,21 @@ struct PlotScreen: View {
728812 }
729813 }
730814}
815/// A file from the photo picker, copied out of the picker's temporary place with its name.
816struct PickedFile: Transferable {
817 let url: URL
818
819 static var transferRepresentation: some TransferRepresentation {
820 FileRepresentation(importedContentType: .item) { received in
821 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
822 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
823 let url = folder.appendingPathComponent(received.file.lastPathComponent)
824 try FileManager.default.copyItem(at: received.file, to: url)
825 return PickedFile(url: url)
826 }
827 }
828}
829
731830/// The passphrase sheet for org-crypt, its new text applied in the editor.
732831struct CryptScreen: View {
733832 let request: CryptRequest
Sources/OrgstarMobile/MobileEditor.swift +3 −1
@@ -301,7 +301,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
301301 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.latex-preview", "editor.toggle-truncate-lines": return true
302302 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
303303 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
304 case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase": return onAppCommand != nil
304 case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase", "app.attach.attach", "app.attach.url",
305 "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
306 "app.attach.set-directory", "app.attach.unset-directory": return onAppCommand != nil
305307 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
306308 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
307309 case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
Sources/OrgstarMobile/OrgstarMobileApp.swift +22
@@ -77,6 +77,12 @@ extension View {
7777 }
7878}
7979
80/// A share of files from the share extension.
81struct SharedFiles: Identifiable {
82 let id = UUID()
83 let batch: URL
84}
85
8086/// An org-protocol capture, or a plain one.
8187struct CaptureRequest: Identifiable {
8288 let id = UUID()
@@ -101,6 +107,8 @@ struct RootView: View {
101107 @State private var capture: CaptureRequest?
102108 /// Captures from the share extension after the one showing.
103109 @State private var waiting: [CaptureRequest] = []
110 /// Files from the share extension, waiting for the entry to attach them to.
111 @State private var sharedFiles: SharedFiles?
104112 @State private var tab = AppTab.agenda
105113 @State private var agendaPath = NavigationPath()
106114 @State private var hour = 0
@@ -232,6 +240,19 @@ struct RootView: View {
232240 .sheet(item: $capture, onDismiss: showWaiting) { request in
233241 CaptureScreen(workspace: workspace, session: session, request: request)
234242 }
243 .sheet(item: $sharedFiles) { shared in
244 RefileSheet(targets: workspace.refileTargets(openPath: nil, document: nil, settings: RefileSettings(targets: [.init(files: .workspace, spec: .all)])),
245 title: "Attach to") { target in
246 sharedFiles = nil
247 if let target {
248 message = session.attach(AttachmentInbox.files(in: shared.batch), to: target.path, at: target.start ?? 0)
249 } else {
250 message = "The shared files weren't attached"
251 }
252 AttachmentInbox()?.remove(shared.batch)
253 takeShared()
254 }
255 }
235256 .task {
236257 takeShared()
237258 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
@@ -285,6 +306,7 @@ struct RootView: View {
285306 private func takeShared() {
286307 waiting += (model.inbox?.take() ?? []).compactMap(CaptureRequest.init(link:))
287308 if capture == nil { showWaiting() }
309 if sharedFiles == nil, let batch = AttachmentInbox()?.batches().first { sharedFiles = SharedFiles(batch: batch) }
288310 }
289311
290312 private func showWaiting() {
Sources/OrgstarShare/ShareViewController.swift +78 −22
@@ -6,7 +6,8 @@ import UIKit
66import UniformTypeIdentifiers
77
88/// The share sheet's Orgstar: the shared page or text with a template and a note, left for the
9/// app, which opens its capture sheet with them the next time it's active.
9/// app, which opens its capture sheet with them the next time it's active; or shared files,
10/// which the app asks to attach to an entry.
1011@objc(ShareViewController)
1112final class ShareViewController: UIViewController {
1213 override func viewDidLoad() {
@@ -19,6 +20,9 @@ final class ShareViewController: UIViewController {
1920 let form = ShareForm(shared: shared, templates: inbox?.templates() ?? [], available: inbox != nil) { link in
2021 if let link { try? inbox?.add(link) }
2122 context?.completeRequest(returningItems: nil)
23 } attach: { files in
24 try? AttachmentInbox()?.add(files)
25 context?.completeRequest(returningItems: nil)
2226 }
2327 let host = UIHostingController(rootView: form)
2428 addChild(host)
@@ -30,11 +34,40 @@ final class ShareViewController: UIViewController {
3034 }
3135}
3236
33/// What the other app shared: a page's address and title, or text.
37/// What the other app shared: a page's address and title, text, or files.
3438struct Shared {
3539 var url: URL?
3640 var title = ""
3741 var text = ""
42 /// Copies of shared files, photos and videos.
43 var files: [URL] = []
44
45 /// Whether the item is a file to attach rather than a page or text.
46 static func isFile(_ provider: NSItemProvider) -> Bool {
47 provider.registeredContentTypes.contains { type in
48 type.conforms(to: .fileURL) || ([.image, .movie, .audio, .pdf, .archive] as [UTType]).contains { type.conforms(to: $0) }
49 }
50 }
51
52 /// A copy of the provider's file, under its own name.
53 @MainActor
54 static func copy(_ provider: NSItemProvider) async -> URL? {
55 guard let type = provider.registeredContentTypes.first(where: { !$0.conforms(to: .fileURL) }) ?? provider.registeredContentTypes.first else { return nil }
56 return await withCheckedContinuation { continuation in
57 _ = provider.loadFileRepresentation(for: type, openInPlace: false) { url, _, _ in
58 guard let url else { return continuation.resume(returning: nil) }
59 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
60 let copy = folder.appendingPathComponent(url.lastPathComponent)
61 do {
62 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
63 try FileManager.default.copyItem(at: url, to: copy)
64 continuation.resume(returning: copy)
65 } catch {
66 continuation.resume(returning: nil)
67 }
68 }
69 }
70 }
3871
3972 @MainActor
4073 static func load(_ items: [NSExtensionItem]) async -> Shared {
@@ -42,7 +75,9 @@ struct Shared {
4275 for item in items {
4376 if shared.title.isEmpty, let title = item.attributedTitle?.string ?? item.attributedContentText?.string { shared.title = title }
4477 for provider in item.attachments ?? [] {
45 if shared.url == nil, provider.hasItemConformingToTypeIdentifier(UTType.url.identifier),
78 if isFile(provider) {
79 if let file = await copy(provider) { shared.files.append(file) }
80 } else if shared.url == nil, provider.hasItemConformingToTypeIdentifier(UTType.url.identifier),
4681 let url = try? await provider.loadItem(forTypeIdentifier: UTType.url.identifier) as? URL {
4782 shared.url = url
4883 } else if shared.text.isEmpty, provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier),
@@ -62,6 +97,8 @@ struct ShareForm: View {
6297 let templates: [CaptureInbox.Template]
6398 let available: Bool
6499 let finish: (String?) -> Void
100 /// Leaves the files for the app to attach.
101 let attach: ([URL]) -> Void
65102 @State private var title = ""
66103 @State private var note = ""
67104 @State private var template: String?
@@ -72,23 +109,16 @@ struct ShareForm: View {
72109 if !available {
73110 Text("orgstar's shared folder isn't available.").foregroundStyle(.red)
74111 }
75 if !templates.isEmpty {
76 Picker("Template", selection: $template) {
77 ForEach(templates, id: \.key) { Text($0.name).tag(Optional($0.key)) }
78 }
79 }
80 if let url = shared.url {
81 Section("Link") {
82 TextField("Title", text: $title)
83 Text(url.absoluteString).font(.footnote).foregroundStyle(.secondary).lineLimit(2)
112 if !shared.files.isEmpty {
113 Section {
114 ForEach(shared.files, id: \.self) { Text($0.lastPathComponent) }
115 } header: {
116 Text("Attach")
117 } footer: {
118 Text("orgstar asks which entry to attach them to when you next open it.")
84119 }
85 }
86 Section("Text") {
87 TextEditor(text: $note).frame(minHeight: 120)
88 }
89 Section {
90 } footer: {
91 Text("orgstar files it with the template when you next open it.")
120 } else {
121 captureSections
92122 }
93123 }
94124 .navigationTitle("orgstar")
@@ -96,10 +126,14 @@ struct ShareForm: View {
96126 .toolbar {
97127 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
98128 ToolbarItem(placement: .confirmationAction) {
99 Button("Capture") {
100 finish(OrgProtocol.captureURL(template: template, url: shared.url?.absoluteString, title: title, body: note))
129 if shared.files.isEmpty {
130 Button("Capture") {
131 finish(OrgProtocol.captureURL(template: template, url: shared.url?.absoluteString, title: title, body: note))
132 }
133 .disabled(!available)
134 } else {
135 Button("Attach") { attach(shared.files) }.disabled(!available)
101136 }
102 .disabled(!available)
103137 }
104138 }
105139 }
@@ -109,5 +143,27 @@ struct ShareForm: View {
109143 template = templates.first?.key
110144 }
111145 }
146
147 @ViewBuilder
148 private var captureSections: some View {
149 if !templates.isEmpty {
150 Picker("Template", selection: $template) {
151 ForEach(templates, id: \.key) { Text($0.name).tag(Optional($0.key)) }
152 }
153 }
154 if let url = shared.url {
155 Section("Link") {
156 TextField("Title", text: $title)
157 Text(url.absoluteString).font(.footnote).foregroundStyle(.secondary).lineLimit(2)
158 }
159 }
160 Section("Text") {
161 TextEditor(text: $note).frame(minHeight: 120)
162 }
163 Section {
164 } footer: {
165 Text("orgstar files it with the template when you next open it.")
166 }
167 }
112168}
113169#endif
Tests/OrgAppTests/AttachmentsTests.swift added +210
@@ -0,0 +1,210 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// org-attach's commands against Emacs: the text after each step, the link stored and the
8/// files left, run in the same folder.
9struct AttachmentsTests {
10 static let id = "6a1b2c3d-0000-4000-8000-000000000001"
11 static let notes = """
12 * Task
13 Body.
14 * Done :work:
15 :PROPERTIES:
16 :ID: 20240101T120000
17 :END:
18 * Moved
19
20 """
21
22 static func setUp(_ folder: URL) throws {
23 try? FileManager.default.removeItem(at: folder)
24 try FileManager.default.createDirectory(at: folder.appendingPathComponent("src"), withIntermediateDirectories: true)
25 try FileManager.default.createDirectory(at: folder.appendingPathComponent("data/202401/01T120000"), withIntermediateDirectories: true)
26 try notes.write(to: folder.appendingPathComponent("notes.org"), atomically: true, encoding: .utf8)
27 for name in ["a", "b", "c", "d", "e", "f"] {
28 try "\(name)\n".write(to: folder.appendingPathComponent("src/\(name).txt"), atomically: true, encoding: .utf8)
29 }
30 }
31
32 /// Every file and folder under `folder`, relative, sorted.
33 static func listing(_ folder: URL) -> [String] {
34 let base = folder.path + "/"
35 let paths = FileManager.default.enumerator(atPath: folder.path)?.allObjects as? [String] ?? []
36 return paths.filter { !$0.hasPrefix(base) }.sorted()
37 }
38
39 @Test func commandsMatchEmacs() throws {
40 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-\(UUID().uuidString)").resolvingSymlinksInPath()
41 defer { try? FileManager.default.removeItem(at: folder) }
42 try Self.setUp(folder)
43 let dir = folder.path
44 let form = #"""
45 (progn
46 (require 'org) (require 'org-attach) (require 'json)
47 (let ((out nil))
48 (cl-letf (((symbol-function 'org-id-new) (lambda (&rest _) "\#(Self.id)"))
49 ((symbol-function 'yes-or-no-p) (lambda (&rest _) nil))
50 ((symbol-function 'read-directory-name) (lambda (&rest _) "\#(dir)/elsewhere/")))
51 (with-current-buffer (find-file-noselect "\#(dir)/notes.org")
52 (cl-flet ((at (h) (goto-char (point-min)) (re-search-forward (concat "^\\* " h)) (beginning-of-line))
53 (rec () (push (buffer-substring-no-properties (point-min) (point-max)) out)))
54 (at "Task") (org-attach-attach "\#(dir)/src/a.txt") (rec) (push (caar org-stored-links) out)
55 (at "Task") (org-attach-attach "\#(dir)/src/b.txt" nil 'mv) (rec)
56 (at "Task") (org-attach-attach "\#(dir)/src/e.txt" nil 'ln)
57 (at "Task") (org-attach-attach "\#(dir)/src/f.txt" nil 'lns) (rec)
58 (at "Task") (org-attach-delete-one "a.txt") (rec)
59 (at "Task") (org-attach-sync) (rec)
60 (at "Task") (push (string-join (directory-files (org-attach-dir) nil "^[^.]") " ") out)
61 (at "Task") (org-attach-delete-all t) (rec)
62 (at "Task") (org-attach-sync) (rec)
63 (at "Done") (org-attach-attach "\#(dir)/src/c.txt") (rec)
64 (at "Moved") (org-attach-set-directory) (org-attach-attach "\#(dir)/src/d.txt") (rec)
65 (at "Moved") (org-attach-unset-directory) (rec))))
66 (with-temp-file "\#(dir)/out.json" (insert (json-encode (vconcat (nreverse out)))))))
67 """#
68 let process = Process()
69 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
70 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
71 let pipe = Pipe()
72 process.standardOutput = pipe
73 process.standardError = pipe
74 try process.run()
75 let log = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
76 process.waitUntilExit()
77 let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: folder.appendingPathComponent("out.json")))
78 try FileManager.default.removeItem(at: folder.appendingPathComponent("out.json"))
79 let emacsFiles = Self.listing(folder)
80
81 try Self.setUp(folder)
82 let path = folder.appendingPathComponent("notes.org").path
83 var entry = Attachments.Entry(text: Self.notes, offset: 0, path: path, idDir: "data/")
84 var ours: [String] = []
85 func at(_ heading: String) {
86 entry = Attachments.Entry(text: entry.text, offset: (entry.text as NSString).range(of: "* " + heading).location, path: path, idDir: "data/")
87 }
88 func rec() { ours.append(entry.text) }
89 func src(_ name: String) -> URL { folder.appendingPathComponent("src/\(name).txt") }
90 at("Task"); _ = try Attachments.directoryCreating(&entry, newID: { Self.id })
91 let link = try Attachments.attach(src("a"), method: .cp, to: &entry); rec(); ours.append(link.link)
92 at("Task"); try Attachments.attach(src("b"), method: .mv, to: &entry); rec()
93 at("Task"); try Attachments.attach(src("e"), method: .ln, to: &entry)
94 at("Task"); try Attachments.attach(src("f"), method: .lns, to: &entry); rec()
95 at("Task"); try Attachments.delete("a.txt", in: entry); rec()
96 at("Task"); _ = Attachments.sync(&entry); rec()
97 at("Task"); ours.append(Attachments.files(in: Attachments.directory(entry)!).joined(separator: " "))
98 at("Task"); try Attachments.deleteAll(&entry); rec()
99 at("Task"); _ = Attachments.sync(&entry); rec()
100 at("Done"); try Attachments.attach(src("c"), method: .cp, to: &entry); rec()
101 at("Moved"); _ = Attachments.setDirectory(dir + "/elsewhere/", in: &entry); try Attachments.attach(src("d"), method: .cp, to: &entry); rec()
102 at("Moved"); _ = Attachments.unsetDirectory(&entry); rec()
103 try entry.text.write(toFile: path, atomically: true, encoding: .utf8)
104
105 #expect(ours.count == emacs.count, "\(log)")
106 for (index, (mine, theirs)) in zip(ours, emacs).enumerated() {
107 #expect(mine == theirs, "step \(index)")
108 }
109 // Emacs leaves the buffer unsaved.
110 #expect(Self.listing(folder).filter { $0 != "notes.org" } == emacsFiles.filter { $0 != "notes.org" })
111 }
112
113 /// `org-attach-dir` without the file system check, for each inheritance setting.
114 @Test func inheritanceMatchesEmacs() throws {
115 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-\(UUID().uuidString)").resolvingSymlinksInPath()
116 defer { try? FileManager.default.removeItem(at: folder) }
117 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
118 let text = """
119 #+PROPERTY: DIR top/
120 * Parent
121 :PROPERTIES:
122 :ID: aabbcc
123 :END:
124 ** Child
125 ** Child with DIR
126 :PROPERTIES:
127 :DIR: ~/own/
128 :END:
129 *** Grandchild
130 * Plain
131
132 """
133 let path = folder.appendingPathComponent("notes.org").path
134 try text.write(toFile: path, atomically: true, encoding: .utf8)
135 let headings = ["Parent", "Child", "Child with DIR", "Grandchild", "Plain"]
136 let settings = ["selective": nil, "t": true, "nil": false] as [String: Bool?]
137 let tree = OrgParser.parse(text)
138 for (symbol, inherit) in settings {
139 let form = #"""
140 (progn (require 'org) (require 'org-attach)
141 (setq org-attach-use-inheritance '\#(symbol) org-use-property-inheritance '("DIR"))
142 (with-current-buffer (find-file-noselect "\#(path)")
143 (dolist (h '(\#(headings.map { "\"\($0)\"" }.joined(separator: " "))))
144 (goto-char (point-min)) (re-search-forward (concat "^\\*+ " h "$"))
145 (princ (format "%s\n" (let ((d (org-attach-dir nil t))) (if d (directory-file-name (expand-file-name d)) "none")))))))
146 """#
147 let process = Process()
148 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
149 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
150 let pipe = Pipe()
151 process.standardOutput = pipe
152 process.standardError = pipe
153 try process.run()
154 let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
155 process.waitUntilExit()
156 let emacs = output.split(separator: "\n").map(String.init).filter { $0.hasPrefix("/") || $0 == "none" }
157 var withDIR = tree.settings
158 withDIR.propertyInheritance = .only(["DIR"])
159 let ours = headings.map { heading in
160 OrgAttach.directory(tree: OrgParser.parse(text, defaults: withDIR), at: (text as NSString).range(of: "* " + heading + "\n").location,
161 path: path, inherit: inherit, noFSCheck: true) { _ in false } ?? "none"
162 }
163 #expect(ours == emacs, "\(symbol): \(output)")
164 }
165 }
166
167 @Test func expandKeepsPrivate() {
168 #expect(OrgAttach.expand("other/", in: "/private/tmp/n") == "/private/tmp/n/other")
169 #expect(OrgAttach.expand("../x", in: "/private/tmp/n") == "/private/tmp/x")
170 }
171
172 @Test func urlNames() {
173 #expect(Attachments.name(ofURL: "https://example.com/a/b.png") == "b.png")
174 #expect(Attachments.name(ofURL: "https://example.com/a/b.png?x=1") == "b.png?x=1")
175 #expect(Attachments.name(ofURL: "https://example.com/") == "")
176 }
177
178 @Test func folderForID() {
179 let none: (String) -> Bool = { _ in false }
180 #expect(OrgAttach.folder(forID: "abcdef12", idDir: "data/", in: "/n", existing: false, isDirectory: none) == "/n/data/ab/cdef12")
181 #expect(OrgAttach.folder(forID: "ab", idDir: "data/", in: "/n", existing: false, isDirectory: none) == "/n/data/__/a/ab")
182 #expect(OrgAttach.folder(forID: "abcdef12", idDir: "~/.attach/", in: "/n", existing: true, isDirectory: { $0 == "/n/data" || $0 == "/n/data/abcdef/12" })
183 == "/n/data/abcdef/12")
184 }
185}
186
187@MainActor
188struct AttachmentInboxTests {
189 @Test func sharedFilesAttachToAnEntryOfAClosedFile() throws {
190 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-inbox-\(UUID().uuidString)").resolvingSymlinksInPath()
191 defer { try? FileManager.default.removeItem(at: folder) }
192 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
193 let shared = folder.appendingPathComponent("photo.jpg")
194 try Data("jpeg".utf8).write(to: shared)
195 let inbox = AttachmentInbox(folder: folder.appendingPathComponent("inbox"))
196 try inbox.add([shared])
197 let batch = try #require(inbox.batches().first)
198 #expect(AttachmentInbox.files(in: batch).map(\.lastPathComponent) == ["photo.jpg"])
199
200 let notes = folder.appendingPathComponent("notes.org").path
201 try "* Trip\n:PROPERTIES:\n:ID: abcdef\n:END:\n".write(toFile: notes, atomically: true, encoding: .utf8)
202 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
203 let message = session.attach(AttachmentInbox.files(in: batch), to: notes, at: 0)
204 inbox.remove(batch)
205 #expect(message == "File \"photo.jpg\" is now an attachment")
206 #expect(try String(contentsOfFile: notes, encoding: .utf8).hasPrefix("* Trip" + String(repeating: " ", count: 63) + ":ATTACH:\n"))
207 #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("data/ab/cdef/photo.jpg").path))
208 #expect(inbox.batches().isEmpty)
209 }
210}
docs/manual/guide/03-keys.org +25
@@ -1008,6 +1008,26 @@ When a key appears in several rows, it runs the command whose condition holds at
10081008| Truncate or Wrap Long Lines (=editor.toggle-truncate-lines=) | =C-x x t= | — | =SPC t w= (N) | Switches between wrapping and truncating long lines (=toggle-truncate-lines=). |
10091009| Quit orgstar (=app.quit=) | — | — | =SPC q q= (N) | Quits orgstar (=save-buffers-kill-terminal=). |
10101010
1011** Attachments
1012
1013The Emacs keys also work with Control on the last key (=C-c C-a C-a=), as in Org's dispatcher. See [[file:04-outlines.org][Outlines]].
1014
1015| Command | Emacs | Mac | Doom | What it does |
1016|-+-+-+-+-|
1017| Attach File… (=app.attach.attach=) | =C-c C-a a=, =C-c C-a c= | — | =SPC m a a= (N) | Asks for files and copies them into the entry's attachment folder (=org-attach-attach=). |
1018| Attach File by Moving… (=app.attach.move=) | =C-c C-a m= | — | — | Moves the files there (=org-attach-attach-mv=). |
1019| Attach File as Hard Link… (=app.attach.link=) | =C-c C-a l= | — | — | Makes hard links to the files there (=org-attach-attach-ln=). |
1020| Attach File as Symbolic Link… (=app.attach.symlink=) | =C-c C-a y= | — | — | Makes symbolic links to the files there (=org-attach-attach-lns=). |
1021| Attach File from URL… (=app.attach.url=) | =C-c C-a u= | — | =SPC m a u= (N) | Downloads a URL into the folder (=org-attach-url=). |
1022| New Attachment… (=app.attach.new=) | =C-c C-a n= | — | =SPC m a n= (N) | Makes an empty file of that name in the folder and opens it (=org-attach-new=). |
1023| Open Attachment… (=app.attach.open=) | =C-c C-a o= | — | =SPC m a o= (N) | Opens the attachment, asking which when there are several (=org-attach-open=). |
1024| Show Attachment Folder (=app.attach.reveal=) | =C-c C-a f= | — | =SPC m a r= (N) | Shows the folder in the Finder, or the Files app on iOS, making it if missing (=org-attach-reveal=). |
1025| Delete Attachment… (=app.attach.delete=) | =C-c C-a d= | — | =SPC m a d= (N) | Deletes one attachment (=org-attach-delete-one=). |
1026| Delete All Attachments… (=app.attach.delete-all=) | =C-c C-a D= | — | =SPC m a D= (N) | Deletes the folder and removes the =ATTACH= tag (=org-attach-delete-all=). |
1027| Sync Attachments (=app.attach.sync=) | =C-c C-a z= | — | =SPC m a S= (N) | Sets or removes the =ATTACH= tag as the folder has files, and offers to delete an empty folder (=org-attach-sync=). |
1028| Set Attachment Folder… (=app.attach.set-directory=) | =C-c C-a s= | — | =SPC m a s= (N) | Sets the entry's =DIR= property (=org-attach-set-directory=). |
1029| Unset Attachment Folder (=app.attach.unset-directory=) | =C-c C-a S= | — | — | Removes =DIR= (=org-attach-unset-directory=). |
1030
10111031** Unbound commands
10121032
10131033No preset binds these. Run them from the palette or a menu, or bind them in =keymap.toml=.
@@ -1024,6 +1044,11 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key
10241044| Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). |
10251045| Export Table to File… (=app.table-export=) | Writes the table at point to a CSV or TSV file (=org-table-export=). |
10261046| Plot Table (=app.plot=) | Plots the table at point as its =#+PLOT:= lines say (=org-plot/gnuplot=, =C-c " g= in the Emacs and Doom presets). |
1047| Encrypt Entry… (=app.crypt.encrypt-entry=) | Encrypts the entry at point with a passphrase (=org-encrypt-entry=). See [[file:04-outlines.org][Outlines]]. |
1048| Decrypt Entry… (=app.crypt.open-entry=) | Shows the entry's decrypted text in a sheet, to read or change. |
1049| Decrypt Entry in File… (=app.crypt.decrypt-entry=) | Puts the decrypted text in the file (=org-decrypt-entry=). |
1050| Encrypt Tagged Entries… (=app.crypt.encrypt-entries=) | Encrypts every entry with the =crypt= tag (=org-encrypt-entries=). |
1051| Forget Encryption Passphrase (=app.crypt.forget-passphrase=) | Removes the file's passphrase from the Keychain. |
10271052| Show or Hide Outline (=app.toggle-outline=) | Shows or hides the outline pane. View ▸ Show or Hide Outline, =⌥⌘O=. |
10281053| Show or Hide Backlinks (=app.toggle-backlinks=) | Shows or hides the backlinks pane. View ▸ Show or Hide Backlinks. |
10291054| Show or Hide Columns and Clock (=app.toggle-inspector=) | Shows or hides the columns and clock inspector. View ▸ Show or Hide Columns and Clock, =⌥⌘I=. |
docs/manual/guide/04-outlines.org +28 −1
@@ -883,6 +883,33 @@ subtree at the caret under a sibling heading named =Archive= with the =ARCHIVE=
883883creating it at the end of the parent's children if needed. The moved entry gets an
884884=ARCHIVE_TIME= property, and the =Archive= sibling is folded.
885885
886* Attachments
887
888An entry's attachments are files in a folder that belongs to it, as with org-attach. The folder is the entry's =DIR= property when it has one, relative to the file's folder unless absolute. Otherwise it comes from the entry's =ID=: =data/ab/cdef…= for the ID =abcdef…=, under the org file's folder. The first attachment gives an entry without either an =ID= property, and it gets the =ATTACH= tag. =attachment:= links open files in the folder (see [[file:09-links.org][Links]]).
889
890| Command | Emacs | What it does |
891|-+-+-|
892| Attach File… | =C-c C-a a= | Asks for files or folders and copies them into the folder. |
893| Attach File by Moving…, as Hard Link…, as Symbolic Link… | =C-c C-a m=, =l=, =y= | The same, moving the files or linking to them. |
894| Attach File from URL… | =C-c C-a u= | Downloads the URL as the name after its last =/=. |
895| New Attachment… | =C-c C-a n= | Makes an empty file in the folder and opens it. |
896| Open Attachment… | =C-c C-a o= | Opens the attachment, or asks which. Org files open in orgstar; others open in their app, or in Quick Look on iOS. |
897| Show Attachment Folder | =C-c C-a f= | Shows the folder in the Finder (the Files app on iOS), making it if missing. |
898| Delete Attachment… | =C-c C-a d= | Asks for an attachment and deletes it. |
899| Delete All Attachments… | =C-c C-a D= | Asks, then deletes the folder and everything in it, and removes the =ATTACH= tag. |
900| Sync Attachments | =C-c C-a z= | Adds =ATTACH= when the folder has files, removes it when it hasn't, and offers to delete an empty folder. |
901| Set Attachment Folder… | =C-c C-a s= | Asks for a folder and sets =DIR= to its full path. When the entry had a folder already, offers to copy its files over and to delete it. |
902| Unset Attachment Folder | =C-c C-a S= | Removes =DIR=, with the same offers when the folder changes. |
903
904The Doom keys are under =SPC m a=; see [[file:03-keys.org][Keys]]. Attaching a file stores an =attachment:= link to it, for Insert Link (=C-c C-l=). Deleting removes files for good, without the Trash.
905
906On iOS the commands are under More ▸ Attachments, with Attach Photo or Video… for the photo library. Moving and linking aren't offered there. Files, photos and videos shared to orgstar from another app are attached too: the share sheet offers Attach, and orgstar asks for the entry when it next opens.
907
908| Setting | Default | What it does |
909|-+-+-|
910| =org-attach-id-dir= | ="data/"= | The folder ID-based folders go in, relative to the org file's folder unless absolute. Folders under =data/= are still found when it's something else. |
911| =org-attach-use-inheritance= | ="selective"= | Whether =DIR= and =ID= come from an ancestor: =selective= follows =org-use-property-inheritance=, ="t"= always, ="nil"= never. Doom sets =t=. |
912
886913* Encrypted entries
887914
888915orgstar reads and writes entries encrypted by org-crypt with a passphrase (=org-crypt-key= nil, symmetric encryption). The text after the entry's planning line, property drawer and logbook, through the end of its subtree, is replaced by an OpenPGP message under the heading:
@@ -903,7 +930,7 @@ ww0ECQMI…
903930| Encrypt Tagged Entries… (=app.crypt.encrypt-entries=) | Encrypts every entry with the =crypt= tag, its own or inherited, that isn't encrypted yet (=org-encrypt-entries=). A tagged entry's tagged children go inside its message. |
904931| Forget Encryption Passphrase (=app.crypt.forget-passphrase=) | Removes the current file's passphrase from the Keychain. |
905932
906The commands have no keys, as in Org; run them from the Org menu or the palette, or bind them in =keymap.toml=. On iOS they are under More ▸ Encryption.
933The commands have no keys, as in Org; run them from the command palette, or bind them in =keymap.toml=. On iOS they are under More ▸ Encryption.
907934
908935Remember in the Keychain stores the passphrase for the file. The next command on that file uses it after Touch ID, Face ID or the device password, without asking. =org-crypt-tag-matcher= in =config.toml= sets the tag; it must be a single tag, not a match expression.
909936
docs/manual/guide/09-links.org +8 −5
@@ -104,14 +104,17 @@ After =::=, a file link can carry a search option:
104104** Attachment links
105105
106106An =attachment:= link names a file in the attachment folder of the entry that holds
107the link, with org-attach's default settings. Relative folders are resolved against
108the folder of the file that holds the link:
107the link (see [[file:04-outlines.org][Outlines]] for the attachment commands). Relative folders are resolved
108against the folder of the file that holds the link:
109109
1101101. When the entry has a =DIR= property, or the older =ATTACH_DIR=, that folder.
1111112. Otherwise, for an entry with an =ID=, the first of these folders that exists:
112 =data/= followed by the ID's first two characters, =/= and the rest of the ID;
113 =data/= followed by its first six characters, =/= and the rest;
114 =data/__/=, the ID's first character, =/= and the whole ID.
112 =org-attach-id-dir= (=data/=) followed by the ID's first two characters, =/= and
113 the rest of the ID; followed by its first six characters, =/= and the rest;
114 =__/=, the ID's first character, =/= and the whole ID. When =org-attach-id-dir= is
115 something else, the same folders under =data/= are found too.
116
117=org-attach-use-inheritance= decides whether =DIR= and =ID= may come from an ancestor.
115118
116119When the folder does not exist, the path is relative to the file's own folder. The file then opens as a =file:= link would, and
117120a search option after =::= works the same way.
docs/manual/guide/13-configuration.org +5
@@ -160,6 +160,7 @@ These settings have no control in the Settings window. Some are in the View menu
160160| =org-archive-location= | |
161161| =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist= | |
162162| =org-track-ordered-property-with-tag= | |
163| =org-attach-id-dir=, =org-attach-use-inheritance= | |
163164| =org-crypt-tag-matcher= | |
164165| =org-agenda-start-on-weekday= | |
165166| =org-deadline-warning-days= | |
@@ -209,6 +210,8 @@ A key you remove from the file goes back to its default. A key that isn't in the
209210| =org-tags-exclude-from-inheritance= | string | =""= | Tags that never inherit, separated by spaces. Read at launch. Mirrors =org-tags-exclude-from-inheritance=. |
210211| =org-tag-alist= | string | =""= | The tags Set Tags offers in files without =#+TAGS=, in =#+TAGS= syntax with keys and groups, rows separated by =\n=. Mirrors =org-tag-alist=. |
211212| =org-track-ordered-property-with-tag= | string | ="nil"= | A tag that Toggle ORDERED Property adds and removes with the property: ="t"= for the tag =ORDERED=, or a tag name. Mirrors =org-track-ordered-property-with-tag=. |
213| =org-attach-id-dir= | string | ="data/"= | The folder ID-based attachment folders go in, relative to the org file's folder unless absolute. See [[file:04-outlines.org][Outlines]]. Mirrors =org-attach-id-dir=. |
214| =org-attach-use-inheritance= | string | ="selective"= | Whether attachment folders come from an ancestor's =DIR= or =ID=: =selective=, ="t"= or ="nil"=. Mirrors =org-attach-use-inheritance=. |
212215| =org-crypt-tag-matcher= | string | ="crypt"= | The tag Encrypt Tagged Entries… encrypts. A single tag. See [[file:04-outlines.org][Outlines]]. Mirrors =org-crypt-tag-matcher=. |
213216| =org-startup-indented= | boolean | =true= | Indent bodies under their headings, as =org-indent-mode=. =#+STARTUP: indent= / =noindent= override it. Mirrors =org-startup-indented=. |
214217| =org-hide-leading-stars= | boolean | =false= | Show only a heading's last star, without indentation. =#+STARTUP: hidestars= / =showstars= override it. Mirrors =org-hide-leading-stars=. |
@@ -567,6 +570,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
567570| =org-agenda-log-mode-items= | The symbols =closed=, =clock= and =state= of the list, separated by spaces |
568571| =org-agenda-todo-ignore-scheduled=, =-deadlines=, =-timestamp= | The symbol or number as a string; =org-agenda-todo-ignore-with-date= and =org-agenda-tags-todo-honor-ignore-options= as booleans |
569572| =org-track-ordered-property-with-tag= | A tag name as given; =t= becomes ="t"=, =nil= ="nil"= |
573| =org-attach-id-dir= | The same key, when the value is a string or an =expand-file-name= form |
574| =org-attach-use-inheritance= | =selective=, or =t= / =nil= as ="t"= / ="nil"= |
570575| =org-crypt-tag-matcher= | The same key, when the value is a single tag |
571576| =org-archive-location= | The same key, when the value is a =file::heading= string |
572577| =org-structure-template-alist= | =[org-structure-template-alist]=: each =("key" . "type")= entry that isn't one of Org's, from =setq= or =(add-to-list 'org-structure-template-alist …)= |
docs/manual/guide/14-ios.org +3 −1
@@ -133,6 +133,8 @@ Cancel answers nothing, as =C-g= does.
133133
134134=C-c '= on a block, and =C-c `= on a table field, open the text in a sheet of its own; Save puts it back. A src block's code is colored as its language, as in the editor.
135135
136More ▸ Attachments has the org-attach commands and Attach Photo or Video…; files shared to orgstar can be attached to an entry. See [[file:04-outlines.org][Outlines]].
137
136138More ▸ Encryption has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A remembered passphrase is used after Face ID, Touch ID or the device passcode.
137139
138140** Hardware keyboard
@@ -351,7 +353,7 @@ These settings from =config.toml= apply on iOS:
351353- =[theme]= (=font=, =font-size=, =line-spacing=, =heading-size-step=, =theme-file= and colours), =[theme.light]=, =[theme.dark]=, =[theme.todo]=, =[theme.category]=
352354- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=
353355- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks=
354- =org-crypt-tag-matcher=
356- =org-crypt-tag-matcher=, =org-attach-id-dir=, =org-attach-use-inheritance=
355357- =org-archive-location=, =[org-structure-template-alist]=
356358- =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist=
357359- =org-use-speed-commands=, with a hardware keyboard
docs/manual/guide/15-alongside-emacs.org +1
@@ -248,6 +248,7 @@ Other:
248248- =display-line-numbers-type= has no relative or visual mode.
249249- The agenda's text search (see [[file:07-agenda.org][The agenda]]) covers the agenda files only: =org-agenda-text-search-extra-files= and =org-agenda-search-view-max-outline-level= aren't supported. It runs from the view menu rather than the dispatcher's =s= and =S=, and the search view's =[=, =]=, ={= and =}= keys, which add words and regexps to the search, aren't supported.
250250- In regexps, =\<=, =\>= and =\b= use Org's word syntax but don't find a word boundary where the script changes between two word characters, as Emacs does (for example between an emoji and a letter).
251- org-attach: =org-attach-method= is always =cp= for Attach File… (the other methods have their own commands), =org-attach-auto-tag= is always =ATTACH=, =org-attach-preferred-new-method= is always =id=, and =org-attach-id-to-path-function-list= is Org's default. The dispatcher's =b=, =O= and =F= keys and =org-attach-archive-delete= aren't supported. Delete All Attachments… asks once and deletes the folder with what's in it.
251252- org-crypt works with symmetric encryption only (=org-crypt-key= nil); public keys and =org-crypt-use-before-save-magic= aren't supported. =org-crypt-tag-matcher= is a single tag.
252253- =org-track-ordered-property-with-tag= isn't supported; Toggle ORDERED Property sets only the property.
253254- When TODO dependencies refuse a change on a =COMMENT= heading, the heading keeps =COMMENT=. Org removes it before the check and doesn't put it back.
ios/OrgstarShare/Info.plist +1 −1
@@ -23,7 +23,7 @@
2323 <key>NSExtensionPrincipalClass</key>
2424 <string>ShareViewController</string>
2525 <key>NSExtensionAttributes</key>
26 <dict><key>NSExtensionActivationRule</key><dict><key>NSExtensionActivationSupportsWebURLWithMaxCount</key><integer>1</integer><key>NSExtensionActivationSupportsText</key><true/></dict></dict>
26 <dict><key>NSExtensionActivationRule</key><dict><key>NSExtensionActivationSupportsWebURLWithMaxCount</key><integer>1</integer><key>NSExtensionActivationSupportsText</key><true/><key>NSExtensionActivationSupportsImageWithMaxCount</key><integer>10</integer><key>NSExtensionActivationSupportsMovieWithMaxCount</key><integer>10</integer><key>NSExtensionActivationSupportsFileWithMaxCount</key><integer>10</integer></dict></dict>
2727 </dict>
2828</dict>
2929</plist>
scripts/build-ios-app.sh +1 −1
@@ -164,7 +164,7 @@ appex OrgstarQuickLook quicklook com.apple.quicklook.preview PreviewProvider \
164164 "<key>QLSupportedContentTypes</key><array><string>org.orgmode.org</string></array><key>QLIsDataBasedPreview</key><true/>"
165165# Capture from the share sheet: a page's link or text.
166166appex OrgstarShare share com.apple.share-services ShareViewController \
167 "<key>NSExtensionActivationRule</key><dict><key>NSExtensionActivationSupportsWebURLWithMaxCount</key><integer>1</integer><key>NSExtensionActivationSupportsText</key><true/></dict>" \
167 "<key>NSExtensionActivationRule</key><dict><key>NSExtensionActivationSupportsWebURLWithMaxCount</key><integer>1</integer><key>NSExtensionActivationSupportsText</key><true/><key>NSExtensionActivationSupportsImageWithMaxCount</key><integer>10</integer><key>NSExtensionActivationSupportsMovieWithMaxCount</key><integer>10</integer><key>NSExtensionActivationSupportsFileWithMaxCount</key><integer>10</integer></dict>" \
168168 "$entitlements"
169169
170170codesign --force --sign - --entitlements "$entitlements" "$app"