Sources/OrgApp/LinkFollow.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgApp/LinkFollow.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form