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