Sources/OrgApp/LinkFollow.swift
123 lines · 6274 bytes
1import Foundation
2import OrgCore
3
4/// What following a link comes to.
5public enum LinkFollow: Equatable, Sendable {
6 /// Shown in Orgstar: a buffer opened or a heading revealed.
7 case shown
8 /// For the system to open: a web or mail address, or a file Orgstar doesn't edit.
9 case openExternally(URL)
10 case message(String)
11}
12
13extension DocumentSession {
14 /// Follows a link as `org-link-open` does: files open as buffers (with a `::` search),
15 /// `id:` and `denote:` links through the index, internal and radio links in the current file,
16 /// `attachment:` links in their entry's attachment folder, and web and mail links go to
17 /// their apps.
18 public func follow(_ link: OrgLink, workspace: WorkspaceModel?, isText: (String) -> Bool) -> LinkFollow {
19 switch link.type {
20 case "http", "https", "ftp", "mailto", "news":
21 return Self.url(link.raw)
22 case "doi":
23 return Self.url("https://doi.org/" + link.path)
24 case "file":
25 return followFile(link, isText: isText)
26 case "id":
27 guard let location = try? workspace?.index.headings(withID: link.path).first else {
28 return .message("No heading has the ID \(link.path)")
29 }
30 show(location)
31 return .shown
32 case "denote":
33 let (identifier, search) = Denote.split(link.path)
34 let paths = ((try? workspace?.index.files()) ?? []).map(\.path)
35 guard let file = Denote.file(withIdentifier: identifier, in: paths) else {
36 return .message("No file has the Denote identifier \(identifier)")
37 }
38 return followFile(OrgLink(type: "file", path: file, searchOption: search, raw: link.raw), isText: isText)
39 case "custom-id":
40 return searchCurrent("#" + link.path)
41 case "fuzzy":
42 return searchCurrent(link.path)
43 case "radio":
44 guard let document else { return .message("No file is open") }
45 return shown(Links.searchRadio(link.path, tree: document.tree))
46 case "attachment":
47 guard let tree = document?.tree,
48 let file = Links.attachmentFile(link, tree: tree, path: path, idDir: OrgPreferences.attachIDDir(), inherit: OrgPreferences.attachUseInheritance(), isDirectory: Self.isDirectory) else {
49 return .message("Need absolute `org-attach-id-dir' to attach in buffers without filename")
50 }
51 return followFile(file, isText: isText)
52 case "coderef":
53 return searchCurrent("(" + link.path + ")")
54 case "shell", "elisp":
55 return .message("orgstar doesn't run \(link.type) links")
56 default:
57 return .message("orgstar can't open \(link.type) links")
58 }
59 }
60
61 static func url(_ string: String) -> LinkFollow {
62 let allowed = CharacterSet.urlFragmentAllowed.union(.urlQueryAllowed).union(CharacterSet(charactersIn: "#%"))
63 guard let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: allowed) ?? string) else {
64 return .message("Not a link orgstar can open: \(string)")
65 }
66 return .openExternally(url)
67 }
68
69 /// A file link's path against the open file's folder, as Org resolves relative links.
70 public static func resolve(_ path: String, from current: String?) -> String {
71 let expanded = (path as NSString).expandingTildeInPath
72 if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
73 let folder = current.map { ($0 as NSString).deletingLastPathComponent } ?? NSHomeDirectory()
74 return ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
75 }
76
77 private func followFile(_ link: OrgLink, isText: (String) -> Bool) -> LinkFollow {
78 let target = link.path.isEmpty ? (path ?? "") : Self.resolve(link.path, from: path)
79 guard FileManager.default.fileExists(atPath: target) else { return .message("No file \(target)") }
80 guard Self.isOrgPath(target) || isText(target) else { return .openExternally(URL(fileURLWithPath: target)) }
81 open(target)
82 guard let option = link.searchOption, !option.isEmpty else { return .shown }
83 if let line = Int(option), let text = document?.text {
84 let ns = text as NSString
85 var offset = 0
86 for _ in 1..<max(1, line) where offset < ns.length { offset = NSMaxRange(ns.lineRange(for: NSRange(location: offset, length: 0))) }
87 reveal(offset)
88 return .shown
89 }
90 return searchCurrent(option)
91 }
92
93 /// An `attachment:` link's file in the file at `path` with `tree`, for inline images.
94 nonisolated public static func attachmentPath(_ name: String, at offset: Int, tree: OrgTree, path: String?) -> String? {
95 Links.attachmentFile(OrgLink(type: "attachment", path: name, raw: "attachment:" + name, position: offset), tree: tree, path: path,
96 idDir: OrgPreferences.attachIDDir(), inherit: OrgPreferences.attachUseInheritance(), isDirectory: isDirectory)?.path
97 }
98
99 nonisolated static func isDirectory(_ path: String) -> Bool {
100 var directory: ObjCBool = false
101 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
102 }
103
104 private func searchCurrent(_ s: String) -> LinkFollow {
105 guard let document else { return .message("No file is open") }
106 return shown(Links.search(s, text: document.text, tree: document.tree))
107 }
108
109 private func shown(_ result: Links.SearchResult) -> LinkFollow {
110 switch result {
111 case .found(let offset):
112 reveal(offset)
113 return .shown
114 case .failed(let message):
115 return .message(message)
116 case .occur(let regexp):
117 // The first match; the Mac's editor shows the sparse tree.
118 guard let text = document?.text, let matches = try? SparseTree.occur(regexp, in: text) else { return .message("Invalid regexp: \(regexp)") }
119 if let first = matches.points.first { reveal(first) }
120 return .message("\(matches.points.count) match(es) for regexp \(regexp)")
121 }
122 }
123}