Commit 7f9206ed92

7f9206ed923fb3c450e55516cdc8eb07d35da3a0

parent: 213799f3f0

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 05:47 UTC

Expand ~ from the real home folder

- Add OrgPaths.home (getpwuid on macOS, NSHomeDirectory on iOS) with expandingTilde and abbreviatingWithTilde
- Route every ~ expansion, abbreviation and home fallback through it
- The default configuration folder stays in NSHomeDirectory, the container in the sandbox

Layout: unified · split

Sources/OrgApp/AgendaFiles.swift +2 −1
@@ -1,4 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore
2 3
3/// `org-agenda-files` as the `(org-agenda-files)` function reads it: each entry a folder (its 4/// `org-agenda-files` as the `(org-agenda-files)` function reads it: each entry a folder (its
4/// `.org` files not starting with a dot, in name order, not below it), an `.org` file, or a 5/// `.org` files not starting with a dot, in name order, not below it), an `.org` file, or a
@@ -9,7 +10,7 @@ public enum AgendaFiles {
9 var out: [String] = [] 10 var out: [String] = []
10 var seen: Set<String> = [] 11 var seen: Set<String> = []
11 func expand(_ entry: String, from base: String?) -> String { 12 func expand(_ entry: String, from base: String?) -> String {
12 let path = (entry as NSString).expandingTildeInPath 13 let path = OrgPaths.expandingTilde(entry)
13 if path.hasPrefix("/") || base == nil { return (path as NSString).standardizingPath } 14 if path.hasPrefix("/") || base == nil { return (path as NSString).standardizingPath }
14 return ((base! as NSString).appendingPathComponent(path) as NSString).standardizingPath 15 return ((base! as NSString).appendingPathComponent(path) as NSString).standardizingPath
15 } 16 }
Sources/OrgApp/AgendaSnapshot.swift +1 −1
@@ -223,7 +223,7 @@ public struct AgendaSnapshot: Codable, Equatable, Sendable {
223 #if os(macOS) 223 #if os(macOS)
224 /// From the account's home folder, not a sandbox container's. 224 /// From the account's home folder, not a sandbox container's.
225 static var macWidgetsFolder: URL { 225 static var macWidgetsFolder: URL {
226 let home = getpwuid(getuid())?.pointee.pw_dir.map { String(cString: $0) } ?? NSHomeDirectory() 226 let home = OrgPaths.home
227 return URL(fileURLWithPath: home).appendingPathComponent("Library/Application Support/Orgstar/Widgets") 227 return URL(fileURLWithPath: home).appendingPathComponent("Library/Application Support/Orgstar/Widgets")
228 } 228 }
229 #endif 229 #endif
Sources/OrgApp/CaptureModel.swift +3 −3
@@ -172,14 +172,14 @@ extension DocumentSession {
172 /// A template's file: absolute, `~/…`, or relative to `root`. 172 /// A template's file: absolute, `~/…`, or relative to `root`.
173 public static func resolve(_ file: String, root: String?) -> String { 173 public static func resolve(_ file: String, root: String?) -> String {
174 if file.hasPrefix("/") { return file } 174 if file.hasPrefix("/") { return file }
175 if file.hasPrefix("~") { return (file as NSString).expandingTildeInPath } 175 if file.hasPrefix("~") { return OrgPaths.expandingTilde(file) }
176 return ((root ?? NSHomeDirectory()) as NSString).appendingPathComponent(file) 176 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(file)
177 } 177 }
178 178
179 /// `%a`: a link to the heading at the caret, as `org-store-link` makes one. 179 /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
180 public func captureAnnotation() -> String { 180 public func captureAnnotation() -> String {
181 guard let path, self.document != nil else { return "" } 181 guard let path, self.document != nil else { return "" }
182 let abbreviated = path.hasPrefix(NSHomeDirectory()) ? "~" + path.dropFirst(NSHomeDirectory().count) : Substring(path) 182 let abbreviated = path.hasPrefix(OrgPaths.home) ? "~" + path.dropFirst(OrgPaths.home.count) : Substring(path)
183 guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" } 183 guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
184 return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]" 184 return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
185 } 185 }
Sources/OrgApp/Dailies.swift +1 −1
@@ -73,7 +73,7 @@ public struct Dailies: Sendable, Equatable {
73 interval: OrgPreferences.denoteJournalInterval(defaults))) 73 interval: OrgPreferences.denoteJournalInterval(defaults)))
74 } 74 }
75 let roam = OrgPreferences.roamDirectory(defaults) 75 let roam = OrgPreferences.roamDirectory(defaults)
76 guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) else { return nil } 76 guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? OrgPaths.home) else { return nil }
77 return Dailies(directory: OrgAttach.expand(OrgPreferences.dailiesDirectory(defaults), in: base), 77 return Dailies(directory: OrgAttach.expand(OrgPreferences.dailiesDirectory(defaults), in: base),
78 file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults), entry: OrgPreferences.dailiesEntry(defaults)) 78 file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults), entry: OrgPreferences.dailiesEntry(defaults))
79 } 79 }
Sources/OrgApp/DenoteNote.swift +2 −2
@@ -25,12 +25,12 @@ public enum DenoteNote {
25 25
26 static func paths(_ setting: String, roots: [String]) -> [String] { 26 static func paths(_ setting: String, roots: [String]) -> [String] {
27 setting.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } 27 setting.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
28 .map { OrgAttach.expand($0, in: roots.first ?? NSHomeDirectory()) } 28 .map { OrgAttach.expand($0, in: roots.first ?? OrgPaths.home) }
29 } 29 }
30 30
31 /// A folder as the folder prompts show it, under `~` when it's in the home folder. 31 /// A folder as the folder prompts show it, under `~` when it's in the home folder.
32 public static func abbreviated(_ path: String) -> String { 32 public static func abbreviated(_ path: String) -> String {
33 let home = NSHomeDirectory() 33 let home = OrgPaths.home
34 return path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path 34 return path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
35 } 35 }
36 36
Sources/OrgApp/EmacsImport.swift +4 −4
@@ -71,7 +71,7 @@ public struct EmacsImport: Sendable {
71 71
72 /// Where an Emacs configuration usually is, first found first. 72 /// Where an Emacs configuration usually is, first found first.
73 public static func defaultLocations() -> [URL] { 73 public static func defaultLocations() -> [URL] {
74 let home = URL(fileURLWithPath: NSHomeDirectory()) 74 let home = URL(fileURLWithPath: OrgPaths.home)
75 let environment = ProcessInfo.processInfo.environment 75 let environment = ProcessInfo.processInfo.environment
76 var candidates: [URL] = [] 76 var candidates: [URL] = []
77 if let doom = environment["DOOMDIR"] { candidates.append(URL(fileURLWithPath: doom)) } 77 if let doom = environment["DOOMDIR"] { candidates.append(URL(fileURLWithPath: doom)) }
@@ -87,7 +87,7 @@ public struct EmacsImport: Sendable {
87 87
88 /// Doom's org module and core defaults, if Doom is installed. 88 /// Doom's org module and core defaults, if Doom is installed.
89 static func doomDefaultFiles() -> [URL] { 89 static func doomDefaultFiles() -> [URL] {
90 let home = URL(fileURLWithPath: NSHomeDirectory()) 90 let home = URL(fileURLWithPath: OrgPaths.home)
91 let environment = ProcessInfo.processInfo.environment 91 let environment = ProcessInfo.processInfo.environment
92 let installs = ([environment["EMACSDIR"]].compactMap { $0 }.map { URL(fileURLWithPath: $0) }) 92 let installs = ([environment["EMACSDIR"]].compactMap { $0 }.map { URL(fileURLWithPath: $0) })
93 + [".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) } 93 + [".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) }
@@ -469,7 +469,7 @@ public struct EmacsImport: Sendable {
469 var folders: Set<String> = [] 469 var folders: Set<String> = []
470 items.removeAll { item in 470 items.removeAll { item in
471 guard case .folder(let path) = item.change else { return false } 471 guard case .folder(let path) = item.change else { return false }
472 let key = (path as NSString).expandingTildeInPath.trimmingCharacters(in: CharacterSet(charactersIn: "/")) 472 let key = OrgPaths.expandingTilde(path).trimmingCharacters(in: CharacterSet(charactersIn: "/"))
473 return !folders.insert(key).inserted 473 return !folders.insert(key).inserted
474 } 474 }
475 for binding in scanner.bindings { 475 for binding in scanner.bindings {
@@ -1090,7 +1090,7 @@ extension EmacsImport {
1090 } 1090 }
1091 for item in items { 1091 for item in items {
1092 guard case .folder(let path) = item.change else { continue } 1092 guard case .folder(let path) = item.change else { continue }
1093 let url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath).standardizedFileURL 1093 let url = URL(fileURLWithPath: OrgPaths.expandingTilde(path)).standardizedFileURL
1094 guard let workspace, FileManager.default.fileExists(atPath: url.path) else { 1094 guard let workspace, FileManager.default.fileExists(atPath: url.path) else {
1095 problems.append("\(path) doesn't exist") 1095 problems.append("\(path) doesn't exist")
1096 continue 1096 continue
Sources/OrgApp/ImageYank.swift +2 −2
@@ -48,13 +48,13 @@ public enum ImageYank {
48 /// file's folder, else absolute with `~` for the home folder. 48 /// file's folder, else absolute with `~` for the home folder.
49 static func fileLink(_ path: String, from orgPath: String) -> String { 49 static func fileLink(_ path: String, from orgPath: String) -> String {
50 let folder = (orgPath as NSString).deletingLastPathComponent + "/" 50 let folder = (orgPath as NSString).deletingLastPathComponent + "/"
51 let target = path.hasPrefix(folder) ? String(path.dropFirst(folder.count)) : (path as NSString).abbreviatingWithTildeInPath 51 let target = path.hasPrefix(folder) ? String(path.dropFirst(folder.count)) : OrgPaths.abbreviatingWithTilde(path)
52 return "[[file:\(target)]]" 52 return "[[file:\(target)]]"
53 } 53 }
54 54
55 /// The folder a `directory` method names, made if missing. 55 /// The folder a `directory` method names, made if missing.
56 static func folder(_ dir: String, for entry: Attachments.Entry) throws -> String { 56 static func folder(_ dir: String, for entry: Attachments.Entry) throws -> String {
57 let folder = OrgAttach.expand((dir as NSString).expandingTildeInPath, in: (entry.path as NSString).deletingLastPathComponent) 57 let folder = OrgAttach.expand(OrgPaths.expandingTilde(dir), in: (entry.path as NSString).deletingLastPathComponent)
58 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) 58 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
59 return folder 59 return folder
60 } 60 }
Sources/OrgApp/LinkFollow.swift +2 −2
@@ -83,9 +83,9 @@ extension DocumentSession {
83 83
84 /// A file link's path against the open file's folder, as Org resolves relative links. 84 /// A file link's path against the open file's folder, as Org resolves relative links.
85 public static func resolve(_ path: String, from current: String?) -> String { 85 public static func resolve(_ path: String, from current: String?) -> String {
86 let expanded = (path as NSString).expandingTildeInPath 86 let expanded = OrgPaths.expandingTilde(path)
87 if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath } 87 if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
88 let folder = current.map { ($0 as NSString).deletingLastPathComponent } ?? NSHomeDirectory() 88 let folder = current.map { ($0 as NSString).deletingLastPathComponent } ?? OrgPaths.home
89 return ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath 89 return ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
90 } 90 }
91 91
Sources/OrgApp/OrgPreferences.swift +1 −1
@@ -221,7 +221,7 @@ public enum OrgPreferences {
221 } 221 }
222 /// `org-icalendar-combined-agenda-file`, `~` expanded. 222 /// `org-icalendar-combined-agenda-file`, `~` expanded.
223 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String { 223 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String {
224 (string("icalendarCombinedAgendaFile", defaults) as NSString).expandingTildeInPath 224 OrgPaths.expandingTilde(string("icalendarCombinedAgendaFile", defaults))
225 } 225 }
226 /// `org-stuck-projects`. 226 /// `org-stuck-projects`.
227 public static func stuckProjects(_ defaults: UserDefaults = .standard) -> StuckProjects { 227 public static func stuckProjects(_ defaults: UserDefaults = .standard) -> StuckProjects {
Sources/OrgApp/PDFExport.swift +1 −1
@@ -63,7 +63,7 @@ public enum PDFExport {
63 } else if path.hasPrefix("/") { 63 } else if path.hasPrefix("/") {
64 url = URL(fileURLWithPath: path) 64 url = URL(fileURLWithPath: path)
65 } else if path.hasPrefix("~/") { 65 } else if path.hasPrefix("~/") {
66 url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath) 66 url = URL(fileURLWithPath: OrgPaths.expandingTilde(path))
67 } else if !path.contains(":"), let directory { 67 } else if !path.contains(":"), let directory {
68 url = directory.appendingPathComponent(path) 68 url = directory.appendingPathComponent(path)
69 } else { 69 } else {
Sources/OrgApp/PlotChart.swift +2 −2
@@ -223,8 +223,8 @@ public enum PlotOutput {
223 /// `file:` relative to the Org file's folder. 223 /// `file:` relative to the Org file's folder.
224 public static func file(_ plot: TablePlot.Plot, directory: URL?) -> URL? { 224 public static func file(_ plot: TablePlot.Plot, directory: URL?) -> URL? {
225 guard let name = plot.options.file, !name.isEmpty else { return nil } 225 guard let name = plot.options.file, !name.isEmpty else { return nil }
226 let expanded = (name as NSString).expandingTildeInPath 226 let expanded = OrgPaths.expandingTilde(name)
227 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: NSHomeDirectory())).appendingPathComponent(expanded) 227 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: OrgPaths.home)).appendingPathComponent(expanded)
228 } 228 }
229 229
230 /// The chart as gnuplot's default 640×480, as PNG, JPEG or PDF by the file's extension. 230 /// The chart as gnuplot's default 640×480, as PNG, JPEG or PDF by the file's extension.
Sources/OrgApp/Publish.swift +2 −2
@@ -91,8 +91,8 @@ public enum Publish {
91 /// Absolute, `~/…`, or relative to `root`. 91 /// Absolute, `~/…`, or relative to `root`.
92 static func resolve(_ path: String, root: String?) -> String { 92 static func resolve(_ path: String, root: String?) -> String {
93 if path.hasPrefix("/") { return path } 93 if path.hasPrefix("/") { return path }
94 if path.hasPrefix("~") { return (path as NSString).expandingTildeInPath } 94 if path.hasPrefix("~") { return OrgPaths.expandingTilde(path) }
95 return ((root ?? NSHomeDirectory()) as NSString).appendingPathComponent(path) 95 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(path)
96 } 96 }
97 97
98 public struct Failure: Error, Equatable, CustomStringConvertible { 98 public struct Failure: Error, Equatable, CustomStringConvertible {
Sources/OrgApp/RefileTargets.swift +1 −1
@@ -185,7 +185,7 @@ extension WorkspaceModel {
185 case .paths(let list): 185 case .paths(let list):
186 let base = openPath.map { ($0 as NSString).deletingLastPathComponent } ?? rootPaths.first 186 let base = openPath.map { ($0 as NSString).deletingLastPathComponent } ?? rootPaths.first
187 paths = list.map { entry in 187 paths = list.map { entry in
188 let path = (entry as NSString).expandingTildeInPath 188 let path = OrgPaths.expandingTilde(entry)
189 return ((path.hasPrefix("/") || base == nil ? path : (base! as NSString).appendingPathComponent(path)) as NSString).standardizingPath 189 return ((path.hasPrefix("/") || base == nil ? path : (base! as NSString).appendingPathComponent(path)) as NSString).standardizingPath
190 } 190 }
191 } 191 }
Sources/OrgApp/RoamNode.swift +1 −1
@@ -8,7 +8,7 @@ public enum RoamNode {
8 /// `org-roam-directory`: the setting, else the first folder. 8 /// `org-roam-directory`: the setting, else the first folder.
9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? { 9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
10 let roam = OrgPreferences.roamDirectory(defaults) 10 let roam = OrgPreferences.roamDirectory(defaults)
11 return roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) 11 return roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? OrgPaths.home)
12 } 12 }
13 13
14 /// `org-roam-node-slugify`: without the combining marks org-roam drops, everything but 14 /// `org-roam-node-slugify`: without the combining marks org-roam drops, everything but
Sources/OrgCore/Capture/Capture.swift +2 −2
@@ -171,7 +171,7 @@ public struct CaptureContext: Sendable {
171 public var linkProperties: [String: String] = [:] 171 public var linkProperties: [String: String] = [:]
172 /// `%[file]`: what relative paths are relative to, and the contents of a file by its 172 /// `%[file]`: what relative paths are relative to, and the contents of a file by its
173 /// absolute path, nil when it can't be read. 173 /// absolute path, nil when it can't be read.
174 public var directory = NSHomeDirectory() 174 public var directory = OrgPaths.home
175 public var readFile: @Sendable (String) -> String? = { _ in nil } 175 public var readFile: @Sendable (String) -> String? = { _ in nil }
176 176
177 public init( 177 public init(
@@ -390,7 +390,7 @@ public enum Capture {
390 buffer.release(end) 390 buffer.release(end)
391 } 391 }
392 if unescape(buffer, at: start.position) { continue } 392 if unescape(buffer, at: start.position) { continue }
393 let expanded = name.hasPrefix("~") ? NSHomeDirectory() + name.dropFirst() : name 393 let expanded = name.hasPrefix("~") ? OrgPaths.home + name.dropFirst() : name
394 let path = ((expanded as NSString).isAbsolutePath ? expanded : (context.directory as NSString).appendingPathComponent(expanded) as String) 394 let path = ((expanded as NSString).isAbsolutePath ? expanded : (context.directory as NSString).appendingPathComponent(expanded) as String)
395 let file = (path as NSString).standardizingPath 395 let file = (path as NSString).standardizingPath
396 buffer.deleteRegion(start.position, end.position) 396 buffer.deleteRegion(start.position, end.position)
Sources/OrgCore/Commands/Archive.swift +3 −3
@@ -199,7 +199,7 @@ public enum Archive {
199 if fileFormat.contains(where: { !$0.isWhitespace }) { 199 if fileFormat.contains(where: { !$0.isWhitespace }) {
200 let file = fileFormat.replacingOccurrences(of: "%s", with: name) 200 let file = fileFormat.replacingOccurrences(of: "%s", with: name)
201 let directory = (sourcePath as NSString).deletingLastPathComponent 201 let directory = (sourcePath as NSString).deletingLastPathComponent
202 path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: NSHomeDirectory(), options: .anchored) 202 path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: OrgPaths.home, options: .anchored)
203 } else { 203 } else {
204 path = sourcePath 204 path = sourcePath
205 } 205 }
@@ -215,7 +215,7 @@ public enum Archive {
215 guard fileFormat.contains(where: { !$0.isWhitespace }) else { return sourcePath } 215 guard fileFormat.contains(where: { !$0.isWhitespace }) else { return sourcePath }
216 let file = fileFormat.replacingOccurrences(of: "%s", with: (sourcePath as NSString).lastPathComponent) 216 let file = fileFormat.replacingOccurrences(of: "%s", with: (sourcePath as NSString).lastPathComponent)
217 let directory = (sourcePath as NSString).deletingLastPathComponent 217 let directory = (sourcePath as NSString).deletingLastPathComponent
218 let path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: NSHomeDirectory(), options: .anchored) 218 let path = ((file as NSString).isAbsolutePath ? file : (directory as NSString).appendingPathComponent(file)).replacingOccurrences(of: "~", with: OrgPaths.home, options: .anchored)
219 return (path as NSString).standardizingPath 219 return (path as NSString).standardizingPath
220 } 220 }
221 221
@@ -258,7 +258,7 @@ public enum Archive {
258 258
259 /// `~/` for paths in the home folder, as `abbreviate-file-name`. 259 /// `~/` for paths in the home folder, as `abbreviate-file-name`.
260 static func abbreviate(_ path: String) -> String { 260 static func abbreviate(_ path: String) -> String {
261 let home = NSHomeDirectory() 261 let home = OrgPaths.home
262 return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path 262 return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
263 } 263 }
264 264
Sources/OrgCore/Commands/Attach.swift +1 −1
@@ -17,7 +17,7 @@ public enum OrgAttach {
17 17
18 /// `expand-file-name` of `path` in `folder`: `.` and `..` resolved, symbolic links not. 18 /// `expand-file-name` of `path` in `folder`: `.` and `..` resolved, symbolic links not.
19 public static func expand(_ path: String, in folder: String) -> String { 19 public static func expand(_ path: String, in folder: String) -> String {
20 let expanded = (path as NSString).expandingTildeInPath 20 let expanded = OrgPaths.expandingTilde(path)
21 let absolute = expanded.hasPrefix("/") ? expanded : (folder as NSString).appendingPathComponent(expanded) 21 let absolute = expanded.hasPrefix("/") ? expanded : (folder as NSString).appendingPathComponent(expanded)
22 return URL(fileURLWithPath: absolute).standardized.path 22 return URL(fileURLWithPath: absolute).standardized.path
23 } 23 }
Sources/OrgCore/Commands/ClockTable.swift +1 −1
@@ -435,7 +435,7 @@ extension EmacsBuffer {
435 var expanded: [String] = [] 435 var expanded: [String] = []
436 for item in list { 436 for item in list {
437 guard let name = item.string else { throw UserError(message: "Unknown scope: \(scopeValue.description)") } 437 guard let name = item.string else { throw UserError(message: "Unknown scope: \(scopeValue.description)") }
438 var file = (name as NSString).expandingTildeInPath 438 var file = OrgPaths.expandingTilde(name)
439 if !file.hasPrefix("/"), let base { file = (base as NSString).appendingPathComponent(file) } 439 if !file.hasPrefix("/"), let base { file = (base as NSString).appendingPathComponent(file) }
440 file = (file as NSString).standardizingPath 440 file = (file as NSString).standardizingPath
441 var isDirectory: ObjCBool = false 441 var isDirectory: ObjCBool = false
Sources/OrgCore/Commands/ColumnView.swift +1 −1
@@ -410,7 +410,7 @@ extension EmacsBuffer {
410 case "local", "nil", "": break 410 case "local", "nil", "": break
411 case let value where value.hasPrefix("file:"): 411 case let value where value.hasPrefix("file:"):
412 // `file:PATH`: the whole file, read from disk; relative to this file's folder. 412 // `file:PATH`: the whole file, read from disk; relative to this file's folder.
413 var path = (String(value.dropFirst(5)) as NSString).expandingTildeInPath 413 var path = OrgPaths.expandingTilde(String(value.dropFirst(5)))
414 if !path.hasPrefix("/"), let file = options.filePath { path = ((file as NSString).deletingLastPathComponent as NSString).appendingPathComponent(path) } 414 if !path.hasPrefix("/"), let file = options.filePath { path = ((file as NSString).deletingLastPathComponent as NSString).appendingPathComponent(path) }
415 guard let text = path == options.filePath ? string : try? String(contentsOfFile: path, encoding: .utf8) else { 415 guard let text = path == options.filePath ? string : try? String(contentsOfFile: path, encoding: .utf8) else {
416 throw UserError(message: "No such file: \"\(value)\"") 416 throw UserError(message: "No such file: \"\(value)\"")
Sources/OrgCore/Compute/Tangle.swift +2 −2
@@ -153,7 +153,7 @@ public enum Tangle {
153 lisp.define("expand-file-name") { lisp, args in 153 lisp.define("expand-file-name") { lisp, args in
154 try Elisp.arity(args, 1...2, "expand-file-name") 154 try Elisp.arity(args, 1...2, "expand-file-name")
155 let base = args.count > 1 && !Elisp.isNil(args[1]) ? try string(args, 1) : (try Elisp.string(lisp.value("default-directory"))) 155 let base = args.count > 1 && !Elisp.isNil(args[1]) ? try string(args, 1) : (try Elisp.string(lisp.value("default-directory")))
156 return .string(expand(try string(args, 0), in: (base as NSString).expandingTildeInPath)) 156 return .string(expand(try string(args, 0), in: OrgPaths.expandingTilde(base)))
157 } 157 }
158 lisp.define("file-name-directory") { _, args in 158 lisp.define("file-name-directory") { _, args in
159 try Elisp.arity(args, 1...1, "file-name-directory") 159 try Elisp.arity(args, 1...1, "file-name-directory")
@@ -206,7 +206,7 @@ public enum Tangle {
206 206
207 /// `expand-file-name`. 207 /// `expand-file-name`.
208 static func expand(_ name: String, in directory: String) -> String { 208 static func expand(_ name: String, in directory: String) -> String {
209 let expanded = (name as NSString).expandingTildeInPath 209 let expanded = OrgPaths.expandingTilde(name)
210 let absolute = expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded) 210 let absolute = expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)
211 return (absolute as NSString).standardizingPath 211 return (absolute as NSString).standardizingPath
212 } 212 }
Sources/OrgCore/Export/Citations.swift +1 −1
@@ -389,7 +389,7 @@ struct CiteProcessor {
389 // Each `#+bibliography:` names one file. 389 // Each `#+bibliography:` names one file.
390 for m in text.matches(of: #/(?mi)^[ \t]*#\+bibliography:[ \t]*(.*?)[ \t]*$/#) { 390 for m in text.matches(of: #/(?mi)^[ \t]*#\+bibliography:[ \t]*(.*?)[ \t]*$/#) {
391 for name in [String(m.1)].map({ $0.count > 1 && $0.hasPrefix("\"") && $0.hasSuffix("\"") ? String($0.dropFirst().dropLast()) : $0 }) where !name.isEmpty { 391 for name in [String(m.1)].map({ $0.count > 1 && $0.hasPrefix("\"") && $0.hasSuffix("\"") ? String($0.dropFirst().dropLast()) : $0 }) where !name.isEmpty {
392 let path = (name as NSString).expandingTildeInPath 392 let path = OrgPaths.expandingTilde(name)
393 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? URL(fileURLWithPath: "/")).appendingPathComponent(path) 393 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? URL(fileURLWithPath: "/")).appendingPathComponent(path)
394 guard let data = try? Data(contentsOf: url) else { continue } 394 guard let data = try? Data(contentsOf: url) else { continue }
395 let parsed = url.pathExtension.lowercased() == "json" ? Self.parseJSON(data) : Self.parseBibTeX(String(decoding: data, as: UTF8.self)) 395 let parsed = url.pathExtension.lowercased() == "json" ? Self.parseJSON(data) : Self.parseBibTeX(String(decoding: data, as: UTF8.self))
Sources/OrgCore/Export/ExportOptions.swift +1 −1
@@ -117,7 +117,7 @@ public enum ExportPreprocess {
117 target = String(spec[r.upperBound...]) 117 target = String(spec[r.upperBound...])
118 } 118 }
119 let url = (file as NSString).isAbsolutePath || directory == nil 119 let url = (file as NSString).isAbsolutePath || directory == nil
120 ? URL(fileURLWithPath: (file as NSString).expandingTildeInPath) 120 ? URL(fileURLWithPath: OrgPaths.expandingTilde(file))
121 : directory!.appendingPathComponent(file) 121 : directory!.appendingPathComponent(file)
122 guard var included = try? String(contentsOf: url, encoding: .utf8) else { 122 guard var included = try? String(contentsOf: url, encoding: .utf8) else {
123 lines.append("") 123 lines.append("")
Sources/OrgCore/Export/ExportScope.swift +1 −1
@@ -59,7 +59,7 @@ public enum ExportScope {
59 /// expanded) with its extension replaced by `ext`, or the source's name with `ext`. 59 /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
60 public static func output(for source: URL, name: String?, extension ext: String) -> URL { 60 public static func output(for source: URL, name: String?, extension ext: String) -> URL {
61 guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) } 61 guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
62 let expanded = (name as NSString).expandingTildeInPath 62 let expanded = OrgPaths.expandingTilde(name)
63 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded) 63 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
64 return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL 64 return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
65 } 65 }
Sources/OrgCore/Links/Backlinks.swift +1 −1
@@ -20,7 +20,7 @@ public enum Backlinks {
20 } 20 }
21 21
22 /// Whether `link`, written in the file at `source`, leads to `target`. 22 /// Whether `link`, written in the file at `source`, leads to `target`.
23 public static func links(_ link: String, from source: String, to target: Target, home: String = NSHomeDirectory()) -> Bool { 23 public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool {
24 let link = Links.unescape(link) 24 let link = Links.unescape(link)
25 if link.lowercased().hasPrefix("id:") { 25 if link.lowercased().hasPrefix("id:") {
26 let id = link.dropFirst(3).components(separatedBy: "::")[0] 26 let id = link.dropFirst(3).components(separatedBy: "::")[0]
Sources/OrgCore/Links/LinkStore.swift +1 −1
@@ -235,7 +235,7 @@ public struct InsertLink: OrgCommand {
235 public let file: String? 235 public let file: String?
236 public let home: String 236 public let home: String
237 237
238 public init(stored: [StoredLink] = [], file: String? = nil, home: String = NSHomeDirectory()) { 238 public init(stored: [StoredLink] = [], file: String? = nil, home: String = OrgPaths.home) {
239 self.stored = stored 239 self.stored = stored
240 self.file = file 240 self.file = file
241 self.home = home 241 self.home = home
Sources/OrgCore/Parser/SetupFile.swift +1 −1
@@ -25,7 +25,7 @@ public enum SetupFile {
25 var value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces) 25 var value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
26 if value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") { value = String(value.dropFirst().dropLast()) } 26 if value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") { value = String(value.dropFirst().dropLast()) }
27 guard !value.isEmpty, value.range(of: "^[a-zA-Z][a-zA-Z0-9+.-]*://", options: .regularExpression) == nil else { continue } 27 guard !value.isEmpty, value.range(of: "^[a-zA-Z][a-zA-Z0-9+.-]*://", options: .regularExpression) == nil else { continue }
28 let expanded = (value as NSString).expandingTildeInPath 28 let expanded = OrgPaths.expandingTilde(value)
29 let path = ((expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)) as NSString).standardizingPath 29 let path = ((expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)) as NSString).standardizingPath
30 guard !seen.contains(path), let contents = read(path) else { continue } 30 guard !seen.contains(path), let contents = read(path) else { continue }
31 out += lines(in: contents, directory: (path as NSString).deletingLastPathComponent, read: read, own: true, seen: seen.union([path])) 31 out += lines(in: contents, directory: (path as NSString).deletingLastPathComponent, read: read, own: true, seen: seen.union([path]))
Sources/OrgCore/Paths.swift added +28
@@ -0,0 +1,28 @@
1import Foundation
2
3/// Paths as written in Org files and settings, where `~` is the home folder.
4public enum OrgPaths {
5 /// The account's home folder. On the Mac this is the real one even in the sandbox, where
6 /// `NSHomeDirectory()` and `expandingTildeInPath` give the app's container.
7 public static let home: String = {
8 #if os(macOS)
9 getpwuid(getuid())?.pointee.pw_dir.map { String(cString: $0) } ?? NSHomeDirectory()
10 #else
11 NSHomeDirectory()
12 #endif
13 }()
14
15 /// `path` with a leading `~` or `~/` taken from `home`; otherwise, `~user` included, as
16 /// `expandingTildeInPath` gives it.
17 public static func expandingTilde(_ path: String, home: String = home) -> String {
18 guard path == "~" || path.hasPrefix("~/") else { return (path as NSString).expandingTildeInPath }
19 return ((home + path.dropFirst()) as NSString).expandingTildeInPath
20 }
21
22 /// `path` with `home` at its start written as `~`, as `abbreviatingWithTildeInPath` does.
23 public static func abbreviatingWithTilde(_ path: String, home: String = home) -> String {
24 let normalized = path.hasPrefix("~") ? path : (path as NSString).expandingTildeInPath
25 if normalized == home { return "~" }
26 return normalized.hasPrefix(home + "/") ? "~" + normalized.dropFirst(home.count) : normalized
27 }
28}
Sources/OrgEditorAppKit/OrgEditor+Images.swift +1 −1
@@ -54,7 +54,7 @@ extension OrgEditor {
54 } 54 }
55 return data.flatMap(NSImage.init(data:)) 55 return data.flatMap(NSImage.init(data:))
56 } 56 }
57 let expanded = (path as NSString).expandingTildeInPath 57 let expanded = OrgPaths.expandingTilde(path)
58 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded) 58 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
59 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0 59 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
60 let key = "\(url.path)|\(modified)" as NSString 60 let key = "\(url.path)|\(modified)" as NSString
Sources/OrgPrograms/Gnuplot.swift +1 −1
@@ -24,7 +24,7 @@ extension PlotOutput {
24 try data.write(to: dataFile, atomically: true, encoding: .utf8) 24 try data.write(to: dataFile, atomically: true, encoding: .utf8)
25 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels) 25 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels)
26 if let custom = plot.options["script"]?.description { 26 if let custom = plot.options["script"]?.description {
27 let path = (custom as NSString).expandingTildeInPath 27 let path = OrgPaths.expandingTilde(custom)
28 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path) 28 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
29 guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") } 29 guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") }
30 script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true) 30 script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true)
Sources/Orgstar/CaptureView.swift +1 −1
@@ -164,7 +164,7 @@ struct CaptureView: View {
164 keys = "" 164 keys = ""
165 day = nil 165 day = nil
166 let clocked = clock.running 166 let clocked = clock.running
167 let clockFile = clocked.map { Links.abbreviate($0.path, home: NSHomeDirectory()) } 167 let clockFile = clocked.map { Links.abbreviate($0.path, home: OrgPaths.home) }
168 context = CaptureContext( 168 context = CaptureContext(
169 initial: commands.editor?.selectedText ?? "", 169 initial: commands.editor?.selectedText ?? "",
170 annotation: session.captureAnnotation(), 170 annotation: session.captureAnnotation(),
Sources/Orgstar/ContentView.swift +1 −1
@@ -1192,7 +1192,7 @@ struct ContentView: View {
1192 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") } 1192 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
1193 let context = editor.context() 1193 let context = editor.context()
1194 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil 1194 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1195 commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: NSHomeDirectory()))) 1195 commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1196 case "org.id.store-link": 1196 case "org.id.store-link":
1197 guard let editor = commands.editor, let path = session.path else { return } 1197 guard let editor = commands.editor, let path = session.path else { return }
1198 if case .commit = editor.perform(CreateID()), 1198 if case .commit = editor.perform(CreateID()),
Sources/Orgstar/PaneView.swift +1 −1
@@ -109,7 +109,7 @@ struct PaneView: NSViewRepresentable {
109 } 109 }
110 editor.onAppCommand = onAppCommand 110 editor.onAppCommand = onAppCommand
111 editor.onOpenFile = { [weak session, weak commands] typed in 111 editor.onOpenFile = { [weak session, weak commands] typed in
112 let expanded = (typed as NSString).expandingTildeInPath 112 let expanded = OrgPaths.expandingTilde(typed)
113 let base = URL(fileURLWithPath: path).deletingLastPathComponent() 113 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
114 let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path 114 let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path
115 guard FileManager.default.fileExists(atPath: target) else { 115 guard FileManager.default.fileExists(atPath: target) else {
Sources/OrgstarMobile/EditorScreen.swift +1 −1
@@ -337,7 +337,7 @@ struct EditorScreen: View {
337 case "org.link.store": 337 case "org.link.store":
338 let context = editor.editContext() 338 let context = editor.editContext()
339 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil 339 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
340 message = StoredLink.add(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks) 340 message = StoredLink.add(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)), to: &model.storedLinks)
341 case "org.id.store-link": 341 case "org.id.store-link":
342 if case .commit = editor.perform(CreateID()), 342 if case .commit = editor.perform(CreateID()),
343 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) { 343 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
Sources/OrgstarMobile/MobileEditor+Display.swift +1 −1
@@ -93,7 +93,7 @@ extension MobileEditor {
93 guard let url = URL(string: path) else { return nil } 93 guard let url = URL(string: path) else { return nil }
94 return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:)) 94 return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:))
95 } 95 }
96 let expanded = (path as NSString).expandingTildeInPath 96 let expanded = OrgPaths.expandingTilde(path)
97 let url: URL 97 let url: URL
98 if expanded.hasPrefix("/") { 98 if expanded.hasPrefix("/") {
99 url = URL(fileURLWithPath: expanded) 99 url = URL(fileURLWithPath: expanded)
Tests/OrgCoreTests/PathsTests.swift added +41
@@ -0,0 +1,41 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct PathsTests {
6 /// Unsandboxed, the real home folder is the one Foundation gives.
7 @Test func homeIsFoundationsOutsideTheSandbox() {
8 #expect(OrgPaths.home == NSHomeDirectory())
9 #expect(OrgPaths.expandingTilde("~/org/a.org") == ("~/org/a.org" as NSString).expandingTildeInPath)
10 }
11
12 @Test func tildeExpandsToTheGivenHome() {
13 let home = "/Users/someone"
14 #expect(OrgPaths.expandingTilde("~", home: home) == home)
15 #expect(OrgPaths.expandingTilde("~/", home: home) == home)
16 #expect(OrgPaths.expandingTilde("~/org//notes/", home: home) == "/Users/someone/org/notes")
17 #expect(OrgPaths.expandingTilde("/srv/org/", home: home) == "/srv/org")
18 #expect(OrgPaths.expandingTilde("org/a.org", home: home) == "org/a.org")
19 #expect(OrgPaths.expandingTilde("~~", home: home) == "~~")
20 #expect(OrgPaths.expandingTilde("", home: home) == "")
21 }
22
23 @Test func otherUsersHomesAreFoundations() {
24 #expect(OrgPaths.expandingTilde("~root/x", home: "/Users/someone") == ("~root/x" as NSString).expandingTildeInPath)
25 }
26
27 @Test func abbreviatesTheGivenHome() {
28 let home = "/Users/someone"
29 #expect(OrgPaths.abbreviatingWithTilde("/Users/someone", home: home) == "~")
30 #expect(OrgPaths.abbreviatingWithTilde("/Users/someone/", home: home) == "~")
31 #expect(OrgPaths.abbreviatingWithTilde("/Users/someone/org//a.org", home: home) == "~/org/a.org")
32 #expect(OrgPaths.abbreviatingWithTilde("/Users/someoneelse/a.org", home: home) == "/Users/someoneelse/a.org")
33 #expect(OrgPaths.abbreviatingWithTilde("~/a.org", home: home) == "~/a.org")
34 }
35
36 @Test func abbreviatingMatchesFoundationOutsideTheSandbox() {
37 for path in [NSHomeDirectory(), NSHomeDirectory() + "/org//a.org/", "/tmp/a.org", "relative/a"] {
38 #expect(OrgPaths.abbreviatingWithTilde(path) == (path as NSString).abbreviatingWithTildeInPath)
39 }
40 }
41}