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 @@
11import Foundation
2import OrgCore
23
34/// `org-agenda-files` as the `(org-agenda-files)` function reads it: each entry a folder (its
45/// `.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 {
910 var out: [String] = []
1011 var seen: Set<String> = []
1112 func expand(_ entry: String, from base: String?) -> String {
12 let path = (entry as NSString).expandingTildeInPath
13 let path = OrgPaths.expandingTilde(entry)
1314 if path.hasPrefix("/") || base == nil { return (path as NSString).standardizingPath }
1415 return ((base! as NSString).appendingPathComponent(path) as NSString).standardizingPath
1516 }
Sources/OrgApp/AgendaSnapshot.swift +1 −1
@@ -223,7 +223,7 @@ public struct AgendaSnapshot: Codable, Equatable, Sendable {
223223 #if os(macOS)
224224 /// From the account's home folder, not a sandbox container's.
225225 static var macWidgetsFolder: URL {
226 let home = getpwuid(getuid())?.pointee.pw_dir.map { String(cString: $0) } ?? NSHomeDirectory()
226 let home = OrgPaths.home
227227 return URL(fileURLWithPath: home).appendingPathComponent("Library/Application Support/Orgstar/Widgets")
228228 }
229229 #endif
Sources/OrgApp/CaptureModel.swift +3 −3
@@ -172,14 +172,14 @@ extension DocumentSession {
172172 /// A template's file: absolute, `~/…`, or relative to `root`.
173173 public static func resolve(_ file: String, root: String?) -> String {
174174 if file.hasPrefix("/") { return file }
175 if file.hasPrefix("~") { return (file as NSString).expandingTildeInPath }
176 return ((root ?? NSHomeDirectory()) as NSString).appendingPathComponent(file)
175 if file.hasPrefix("~") { return OrgPaths.expandingTilde(file) }
176 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(file)
177177 }
178178
179179 /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
180180 public func captureAnnotation() -> String {
181181 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)
183183 guard let entry = outline.last(where: { $0.start <= caret }) else { return "[[file:\(abbreviated)]]" }
184184 return "[[file:\(abbreviated)::*\(entry.title)][\(entry.title)]]"
185185 }
Sources/OrgApp/Dailies.swift +1 −1
@@ -73,7 +73,7 @@ public struct Dailies: Sendable, Equatable {
7373 interval: OrgPreferences.denoteJournalInterval(defaults)))
7474 }
7575 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 }
7777 return Dailies(directory: OrgAttach.expand(OrgPreferences.dailiesDirectory(defaults), in: base),
7878 file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults), entry: OrgPreferences.dailiesEntry(defaults))
7979 }
Sources/OrgApp/DenoteNote.swift +2 −2
@@ -25,12 +25,12 @@ public enum DenoteNote {
2525
2626 static func paths(_ setting: String, roots: [String]) -> [String] {
2727 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) }
2929 }
3030
3131 /// A folder as the folder prompts show it, under `~` when it's in the home folder.
3232 public static func abbreviated(_ path: String) -> String {
33 let home = NSHomeDirectory()
33 let home = OrgPaths.home
3434 return path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
3535 }
3636
Sources/OrgApp/EmacsImport.swift +4 −4
@@ -71,7 +71,7 @@ public struct EmacsImport: Sendable {
7171
7272 /// Where an Emacs configuration usually is, first found first.
7373 public static func defaultLocations() -> [URL] {
74 let home = URL(fileURLWithPath: NSHomeDirectory())
74 let home = URL(fileURLWithPath: OrgPaths.home)
7575 let environment = ProcessInfo.processInfo.environment
7676 var candidates: [URL] = []
7777 if let doom = environment["DOOMDIR"] { candidates.append(URL(fileURLWithPath: doom)) }
@@ -87,7 +87,7 @@ public struct EmacsImport: Sendable {
8787
8888 /// Doom's org module and core defaults, if Doom is installed.
8989 static func doomDefaultFiles() -> [URL] {
90 let home = URL(fileURLWithPath: NSHomeDirectory())
90 let home = URL(fileURLWithPath: OrgPaths.home)
9191 let environment = ProcessInfo.processInfo.environment
9292 let installs = ([environment["EMACSDIR"]].compactMap { $0 }.map { URL(fileURLWithPath: $0) })
9393 + [".config/emacs", ".emacs.d"].map { home.appendingPathComponent($0) }
@@ -469,7 +469,7 @@ public struct EmacsImport: Sendable {
469469 var folders: Set<String> = []
470470 items.removeAll { item in
471471 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: "/"))
473473 return !folders.insert(key).inserted
474474 }
475475 for binding in scanner.bindings {
@@ -1090,7 +1090,7 @@ extension EmacsImport {
10901090 }
10911091 for item in items {
10921092 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
10941094 guard let workspace, FileManager.default.fileExists(atPath: url.path) else {
10951095 problems.append("\(path) doesn't exist")
10961096 continue
Sources/OrgApp/ImageYank.swift +2 −2
@@ -48,13 +48,13 @@ public enum ImageYank {
4848 /// file's folder, else absolute with `~` for the home folder.
4949 static func fileLink(_ path: String, from orgPath: String) -> String {
5050 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)
5252 return "[[file:\(target)]]"
5353 }
5454
5555 /// The folder a `directory` method names, made if missing.
5656 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)
5858 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
5959 return folder
6060 }
Sources/OrgApp/LinkFollow.swift +2 −2
@@ -83,9 +83,9 @@ extension DocumentSession {
8383
8484 /// A file link's path against the open file's folder, as Org resolves relative links.
8585 public static func resolve(_ path: String, from current: String?) -> String {
86 let expanded = (path as NSString).expandingTildeInPath
86 let expanded = OrgPaths.expandingTilde(path)
8787 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
8989 return ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
9090 }
9191
Sources/OrgApp/OrgPreferences.swift +1 −1
@@ -221,7 +221,7 @@ public enum OrgPreferences {
221221 }
222222 /// `org-icalendar-combined-agenda-file`, `~` expanded.
223223 public static func icalendarCombinedFile(_ defaults: UserDefaults = .standard) -> String {
224 (string("icalendarCombinedAgendaFile", defaults) as NSString).expandingTildeInPath
224 OrgPaths.expandingTilde(string("icalendarCombinedAgendaFile", defaults))
225225 }
226226 /// `org-stuck-projects`.
227227 public static func stuckProjects(_ defaults: UserDefaults = .standard) -> StuckProjects {
Sources/OrgApp/PDFExport.swift +1 −1
@@ -63,7 +63,7 @@ public enum PDFExport {
6363 } else if path.hasPrefix("/") {
6464 url = URL(fileURLWithPath: path)
6565 } else if path.hasPrefix("~/") {
66 url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath)
66 url = URL(fileURLWithPath: OrgPaths.expandingTilde(path))
6767 } else if !path.contains(":"), let directory {
6868 url = directory.appendingPathComponent(path)
6969 } else {
Sources/OrgApp/PlotChart.swift +2 −2
@@ -223,8 +223,8 @@ public enum PlotOutput {
223223 /// `file:` relative to the Org file's folder.
224224 public static func file(_ plot: TablePlot.Plot, directory: URL?) -> URL? {
225225 guard let name = plot.options.file, !name.isEmpty else { return nil }
226 let expanded = (name as NSString).expandingTildeInPath
227 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: NSHomeDirectory())).appendingPathComponent(expanded)
226 let expanded = OrgPaths.expandingTilde(name)
227 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: OrgPaths.home)).appendingPathComponent(expanded)
228228 }
229229
230230 /// 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 {
9191 /// Absolute, `~/…`, or relative to `root`.
9292 static func resolve(_ path: String, root: String?) -> String {
9393 if path.hasPrefix("/") { return path }
94 if path.hasPrefix("~") { return (path as NSString).expandingTildeInPath }
95 return ((root ?? NSHomeDirectory()) as NSString).appendingPathComponent(path)
94 if path.hasPrefix("~") { return OrgPaths.expandingTilde(path) }
95 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(path)
9696 }
9797
9898 public struct Failure: Error, Equatable, CustomStringConvertible {
Sources/OrgApp/RefileTargets.swift +1 −1
@@ -185,7 +185,7 @@ extension WorkspaceModel {
185185 case .paths(let list):
186186 let base = openPath.map { ($0 as NSString).deletingLastPathComponent } ?? rootPaths.first
187187 paths = list.map { entry in
188 let path = (entry as NSString).expandingTildeInPath
188 let path = OrgPaths.expandingTilde(entry)
189189 return ((path.hasPrefix("/") || base == nil ? path : (base! as NSString).appendingPathComponent(path)) as NSString).standardizingPath
190190 }
191191 }
Sources/OrgApp/RoamNode.swift +1 −1
@@ -8,7 +8,7 @@ public enum RoamNode {
88 /// `org-roam-directory`: the setting, else the first folder.
99 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
1010 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)
1212 }
1313
1414 /// `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 {
171171 public var linkProperties: [String: String] = [:]
172172 /// `%[file]`: what relative paths are relative to, and the contents of a file by its
173173 /// absolute path, nil when it can't be read.
174 public var directory = NSHomeDirectory()
174 public var directory = OrgPaths.home
175175 public var readFile: @Sendable (String) -> String? = { _ in nil }
176176
177177 public init(
@@ -390,7 +390,7 @@ public enum Capture {
390390 buffer.release(end)
391391 }
392392 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
394394 let path = ((expanded as NSString).isAbsolutePath ? expanded : (context.directory as NSString).appendingPathComponent(expanded) as String)
395395 let file = (path as NSString).standardizingPath
396396 buffer.deleteRegion(start.position, end.position)
Sources/OrgCore/Commands/Archive.swift +3 −3
@@ -199,7 +199,7 @@ public enum Archive {
199199 if fileFormat.contains(where: { !$0.isWhitespace }) {
200200 let file = fileFormat.replacingOccurrences(of: "%s", with: name)
201201 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)
203203 } else {
204204 path = sourcePath
205205 }
@@ -215,7 +215,7 @@ public enum Archive {
215215 guard fileFormat.contains(where: { !$0.isWhitespace }) else { return sourcePath }
216216 let file = fileFormat.replacingOccurrences(of: "%s", with: (sourcePath as NSString).lastPathComponent)
217217 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)
219219 return (path as NSString).standardizingPath
220220 }
221221
@@ -258,7 +258,7 @@ public enum Archive {
258258
259259 /// `~/` for paths in the home folder, as `abbreviate-file-name`.
260260 static func abbreviate(_ path: String) -> String {
261 let home = NSHomeDirectory()
261 let home = OrgPaths.home
262262 return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
263263 }
264264
Sources/OrgCore/Commands/Attach.swift +1 −1
@@ -17,7 +17,7 @@ public enum OrgAttach {
1717
1818 /// `expand-file-name` of `path` in `folder`: `.` and `..` resolved, symbolic links not.
1919 public static func expand(_ path: String, in folder: String) -> String {
20 let expanded = (path as NSString).expandingTildeInPath
20 let expanded = OrgPaths.expandingTilde(path)
2121 let absolute = expanded.hasPrefix("/") ? expanded : (folder as NSString).appendingPathComponent(expanded)
2222 return URL(fileURLWithPath: absolute).standardized.path
2323 }
Sources/OrgCore/Commands/ClockTable.swift +1 −1
@@ -435,7 +435,7 @@ extension EmacsBuffer {
435435 var expanded: [String] = []
436436 for item in list {
437437 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)
439439 if !file.hasPrefix("/"), let base { file = (base as NSString).appendingPathComponent(file) }
440440 file = (file as NSString).standardizingPath
441441 var isDirectory: ObjCBool = false
Sources/OrgCore/Commands/ColumnView.swift +1 −1
@@ -410,7 +410,7 @@ extension EmacsBuffer {
410410 case "local", "nil", "": break
411411 case let value where value.hasPrefix("file:"):
412412 // `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)))
414414 if !path.hasPrefix("/"), let file = options.filePath { path = ((file as NSString).deletingLastPathComponent as NSString).appendingPathComponent(path) }
415415 guard let text = path == options.filePath ? string : try? String(contentsOfFile: path, encoding: .utf8) else {
416416 throw UserError(message: "No such file: \"\(value)\"")
Sources/OrgCore/Compute/Tangle.swift +2 −2
@@ -153,7 +153,7 @@ public enum Tangle {
153153 lisp.define("expand-file-name") { lisp, args in
154154 try Elisp.arity(args, 1...2, "expand-file-name")
155155 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)))
157157 }
158158 lisp.define("file-name-directory") { _, args in
159159 try Elisp.arity(args, 1...1, "file-name-directory")
@@ -206,7 +206,7 @@ public enum Tangle {
206206
207207 /// `expand-file-name`.
208208 static func expand(_ name: String, in directory: String) -> String {
209 let expanded = (name as NSString).expandingTildeInPath
209 let expanded = OrgPaths.expandingTilde(name)
210210 let absolute = expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)
211211 return (absolute as NSString).standardizingPath
212212 }
Sources/OrgCore/Export/Citations.swift +1 −1
@@ -389,7 +389,7 @@ struct CiteProcessor {
389389 // Each `#+bibliography:` names one file.
390390 for m in text.matches(of: #/(?mi)^[ \t]*#\+bibliography:[ \t]*(.*?)[ \t]*$/#) {
391391 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)
393393 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? URL(fileURLWithPath: "/")).appendingPathComponent(path)
394394 guard let data = try? Data(contentsOf: url) else { continue }
395395 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 {
117117 target = String(spec[r.upperBound...])
118118 }
119119 let url = (file as NSString).isAbsolutePath || directory == nil
120 ? URL(fileURLWithPath: (file as NSString).expandingTildeInPath)
120 ? URL(fileURLWithPath: OrgPaths.expandingTilde(file))
121121 : directory!.appendingPathComponent(file)
122122 guard var included = try? String(contentsOf: url, encoding: .utf8) else {
123123 lines.append("")
Sources/OrgCore/Export/ExportScope.swift +1 −1
@@ -59,7 +59,7 @@ public enum ExportScope {
5959 /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
6060 public static func output(for source: URL, name: String?, extension ext: String) -> URL {
6161 guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
62 let expanded = (name as NSString).expandingTildeInPath
62 let expanded = OrgPaths.expandingTilde(name)
6363 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
6464 return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
6565 }
Sources/OrgCore/Links/Backlinks.swift +1 −1
@@ -20,7 +20,7 @@ public enum Backlinks {
2020 }
2121
2222 /// 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 {
2424 let link = Links.unescape(link)
2525 if link.lowercased().hasPrefix("id:") {
2626 let id = link.dropFirst(3).components(separatedBy: "::")[0]
Sources/OrgCore/Links/LinkStore.swift +1 −1
@@ -235,7 +235,7 @@ public struct InsertLink: OrgCommand {
235235 public let file: String?
236236 public let home: String
237237
238 public init(stored: [StoredLink] = [], file: String? = nil, home: String = NSHomeDirectory()) {
238 public init(stored: [StoredLink] = [], file: String? = nil, home: String = OrgPaths.home) {
239239 self.stored = stored
240240 self.file = file
241241 self.home = home
Sources/OrgCore/Parser/SetupFile.swift +1 −1
@@ -25,7 +25,7 @@ public enum SetupFile {
2525 var value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
2626 if value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") { value = String(value.dropFirst().dropLast()) }
2727 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)
2929 let path = ((expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded)) as NSString).standardizingPath
3030 guard !seen.contains(path), let contents = read(path) else { continue }
3131 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 {
5454 }
5555 return data.flatMap(NSImage.init(data:))
5656 }
57 let expanded = (path as NSString).expandingTildeInPath
57 let expanded = OrgPaths.expandingTilde(path)
5858 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
5959 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
6060 let key = "\(url.path)|\(modified)" as NSString
Sources/OrgPrograms/Gnuplot.swift +1 −1
@@ -24,7 +24,7 @@ extension PlotOutput {
2424 try data.write(to: dataFile, atomically: true, encoding: .utf8)
2525 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels)
2626 if let custom = plot.options["script"]?.description {
27 let path = (custom as NSString).expandingTildeInPath
27 let path = OrgPaths.expandingTilde(custom)
2828 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
2929 guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") }
3030 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 {
164164 keys = ""
165165 day = nil
166166 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) }
168168 context = CaptureContext(
169169 initial: commands.editor?.selectedText ?? "",
170170 annotation: session.captureAnnotation(),
Sources/Orgstar/ContentView.swift +1 −1
@@ -1192,7 +1192,7 @@ struct ContentView: View {
11921192 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
11931193 let context = editor.context()
11941194 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)))
11961196 case "org.id.store-link":
11971197 guard let editor = commands.editor, let path = session.path else { return }
11981198 if case .commit = editor.perform(CreateID()),
Sources/Orgstar/PaneView.swift +1 −1
@@ -109,7 +109,7 @@ struct PaneView: NSViewRepresentable {
109109 }
110110 editor.onAppCommand = onAppCommand
111111 editor.onOpenFile = { [weak session, weak commands] typed in
112 let expanded = (typed as NSString).expandingTildeInPath
112 let expanded = OrgPaths.expandingTilde(typed)
113113 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
114114 let target = expanded.hasPrefix("/") ? expanded : base.appendingPathComponent(expanded).standardizedFileURL.path
115115 guard FileManager.default.fileExists(atPath: target) else {
Sources/OrgstarMobile/EditorScreen.swift +1 −1
@@ -337,7 +337,7 @@ struct EditorScreen: View {
337337 case "org.link.store":
338338 let context = editor.editContext()
339339 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)
341341 case "org.id.store-link":
342342 if case .commit = editor.perform(CreateID()),
343343 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 {
9393 guard let url = URL(string: path) else { return nil }
9494 return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:))
9595 }
96 let expanded = (path as NSString).expandingTildeInPath
96 let expanded = OrgPaths.expandingTilde(path)
9797 let url: URL
9898 if expanded.hasPrefix("/") {
9999 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}