Sources/OrgApp/LinkFollow.swift
160 lines · 8577 bytes
10 symbols in this file
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 /// Files to choose one of to open: a Denote query link's matches.
12 case choose(prompt: String, paths: [String])
13 /// An `elisp:` link's form, to run with `evaluateLink` once the user agrees.
14 case elisp(String)
15}
16
17extension DocumentSession {
18 /// Follows a link as `org-link-open` does: files open as buffers (with a `::` search),
19 /// `id:` and `denote:` links through the index, internal and radio links in the current file,
20 /// `attachment:` links in their entry's attachment folder, and web and mail links go to
21 /// their apps.
22 public func follow(_ link: OrgLink, workspace: WorkspaceModel?, isText: (String) -> Bool) -> LinkFollow {
23 switch link.type {
24 case "http", "https", "ftp", "mailto", "news":
25 return Self.url(link.raw)
26 case "doi":
27 return Self.url("https://doi.org/" + link.path)
28 case "file":
29 return followFile(link, isText: isText)
30 case "id":
31 guard let location = try? workspace?.index.headings(withID: link.path).first else {
32 return .message("No heading has the ID \(link.path)")
33 }
34 show(location)
35 return .shown
36 case "denote":
37 let paths = ((try? workspace?.index.files()) ?? []).map(\.path)
38 if let query = Denote.query(link.path) {
39 // `denote-query-contents-link` and `denote-query-filenames-link`: the notes whose
40 // text, or name, the regexp matches.
41 guard let regex = try? NSRegularExpression(pattern: EmacsRegex.translate(query.regexp), options: [.caseInsensitive]) else {
42 return .message("Invalid regexp \(query.regexp)")
43 }
44 let matches = paths.filter { Denote.identifier(ofFile: $0) != nil }.filter { path in
45 let subject = query.contents ? (text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)) ?? "") : (path as NSString).lastPathComponent
46 return regex.firstMatch(in: subject, range: NSRange(location: 0, length: (subject as NSString).length)) != nil
47 }.sorted()
48 guard !matches.isEmpty else { return .message("No notes match \(query.regexp)") }
49 return .choose(prompt: "Notes matching \(query.regexp): ", paths: matches)
50 }
51 let (identifier, search) = Denote.split(link.path)
52 guard let file = Denote.file(withIdentifier: identifier, in: paths) else {
53 return .message("No file has the Denote identifier \(identifier)")
54 }
55 return followFile(OrgLink(type: "file", path: file, searchOption: search, raw: link.raw), isText: isText)
56 case "custom-id":
57 return searchCurrent("#" + link.path)
58 case "fuzzy":
59 return searchCurrent(link.path)
60 case "radio":
61 guard let document else { return .message("No file is open") }
62 return shown(Links.searchRadio(link.path, tree: document.tree))
63 case "attachment":
64 guard let tree = document?.tree,
65 let file = Links.attachmentFile(link, tree: tree, path: path, idDir: OrgPreferences.attachIDDir(), inherit: OrgPreferences.attachUseInheritance(), isDirectory: Self.isDirectory) else {
66 return .message("Need absolute `org-attach-id-dir' to attach in buffers without filename")
67 }
68 return followFile(file, isText: isText)
69 case "coderef":
70 return searchCurrent("(" + link.path + ")")
71 case "elisp":
72 // `org-link--open-elisp`: a form is evaluated, anything else is a command to call.
73 guard link.path.hasPrefix("(") else { return .message("orgstar doesn't run Emacs commands from elisp: links") }
74 return .elisp(link.path)
75 case "shell":
76 return .message("orgstar doesn't run shell links")
77 default:
78 return .message("orgstar can't open \(link.type) links")
79 }
80 }
81
82 /// Evaluates an `elisp:` link's form as `org-link--open-elisp` does: in Emacs, in a copy of
83 /// the open file, when `programs` has it, otherwise in `Elisp`. Returns the message to show.
84 public func evaluateLink(_ form: String) async -> String {
85 if let programs = Self.runner, let path, let text = document?.text {
86 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
87 do {
88 if let value = try await programs.evaluateLisp(form, text: text, point: caret(of: path) ?? 0, directory: directory) {
89 return "\(form) => \(value)"
90 }
91 } catch {
92 return "\(error)"
93 }
94 }
95 return Links.evaluateElisp(form)
96 }
97
98 static func url(_ string: String) -> LinkFollow {
99 let allowed = CharacterSet.urlFragmentAllowed.union(.urlQueryAllowed).union(CharacterSet(charactersIn: "#%"))
100 guard let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: allowed) ?? string) else {
101 return .message("Not a link orgstar can open: \(string)")
102 }
103 return .openExternally(url)
104 }
105
106 /// A file link's path against the open file's folder, as Org resolves relative links.
107 public static func resolve(_ path: String, from current: String?) -> String {
108 let expanded = OrgPaths.expandingTilde(path)
109 if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
110 let folder = current.map { ($0 as NSString).deletingLastPathComponent } ?? OrgPaths.home
111 return ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
112 }
113
114 private func followFile(_ link: OrgLink, isText: (String) -> Bool) -> LinkFollow {
115 let target = link.path.isEmpty ? (path ?? "") : Self.resolve(link.path, from: path)
116 guard FileManager.default.fileExists(atPath: target) else { return .message("No file \(target)") }
117 guard Self.isOrgPath(target) || isText(target) else { return .openExternally(URL(fileURLWithPath: target)) }
118 open(target)
119 guard let option = link.searchOption, !option.isEmpty else { return .shown }
120 if let line = Int(option), let text = document?.text {
121 let ns = text as NSString
122 var offset = 0
123 for _ in 1..<max(1, line) where offset < ns.length { offset = NSMaxRange(ns.lineRange(for: NSRange(location: offset, length: 0))) }
124 reveal(offset)
125 return .shown
126 }
127 return searchCurrent(option)
128 }
129
130 /// An `attachment:` link's file in the file at `path` with `tree`, for inline images.
131 nonisolated public static func attachmentPath(_ name: String, at offset: Int, tree: OrgTree, path: String?) -> String? {
132 Links.attachmentFile(OrgLink(type: "attachment", path: name, raw: "attachment:" + name, position: offset), tree: tree, path: path,
133 idDir: OrgPreferences.attachIDDir(), inherit: OrgPreferences.attachUseInheritance(), isDirectory: isDirectory)?.path
134 }
135
136 nonisolated static func isDirectory(_ path: String) -> Bool {
137 var directory: ObjCBool = false
138 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
139 }
140
141 private func searchCurrent(_ s: String) -> LinkFollow {
142 guard let document else { return .message("No file is open") }
143 return shown(Links.search(s, text: document.text, tree: document.tree))
144 }
145
146 private func shown(_ result: Links.SearchResult) -> LinkFollow {
147 switch result {
148 case .found(let offset):
149 reveal(offset)
150 return .shown
151 case .failed(let message):
152 return .message(message)
153 case .occur(let regexp):
154 // The first match; the Mac's editor shows the sparse tree.
155 guard let text = document?.text, let matches = try? SparseTree.occur(regexp, in: text) else { return .message("Invalid regexp: \(regexp)") }
156 if let first = matches.points.first { reveal(first) }
157 return .message("\(matches.points.count) match(es) for regexp \(regexp)")
158 }
159 }
160}