Sources/OrgApp/LinkFollow.swift

b7b7f8ef81367a5e787840c1b28d8a82bf7da545
orgstar/Sources/OrgApp/LinkFollow.swift history · blame · raw

86 lines · 3898 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:` links through the index, internal links in the current file, and web and mail
16    /// links go to their apps.
17    public func follow(_ link: OrgLink, workspace: WorkspaceModel?, isText: (String) -> Bool) -> LinkFollow {
18        switch link.type {
19        case "http", "https", "ftp", "mailto", "news":
20            return Self.url(link.raw)
21        case "doi":
22            return Self.url("https://doi.org/" + link.path)
23        case "file":
24            return followFile(link, isText: isText)
25        case "id":
26            guard let location = try? workspace?.index.headings(withID: link.path).first else {
27                return .message("No heading has the ID \(link.path)")
28            }
29            show(location)
30            return .shown
31        case "custom-id":
32            return searchCurrent("#" + link.path)
33        case "fuzzy":
34            return searchCurrent(link.path)
35        case "coderef":
36            return .message("Coderef links aren't supported")
37        case "shell", "elisp":
38            return .message("Orgstar doesn't run \(link.type) links")
39        default:
40            return .message("Orgstar can't open \(link.type) links")
41        }
42    }
43
44    static func url(_ string: String) -> LinkFollow {
45        let allowed = CharacterSet.urlFragmentAllowed.union(.urlQueryAllowed).union(CharacterSet(charactersIn: "#%"))
46        guard let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: allowed) ?? string) else {
47            return .message("Not a link Orgstar can open: \(string)")
48        }
49        return .openExternally(url)
50    }
51
52    /// A file link's path against the open file's folder, as Org resolves relative links.
53    public static func resolve(_ path: String, from current: String?) -> String {
54        let expanded = (path as NSString).expandingTildeInPath
55        if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
56        let folder = current.map { ($0 as NSString).deletingLastPathComponent } ?? FileManager.default.homeDirectoryForCurrentUser.path
57        return ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
58    }
59
60    private func followFile(_ link: OrgLink, isText: (String) -> Bool) -> LinkFollow {
61        let target = link.path.isEmpty ? (path ?? "") : Self.resolve(link.path, from: path)
62        guard FileManager.default.fileExists(atPath: target) else { return .message("No file \(target)") }
63        guard Self.isOrgPath(target) || isText(target) else { return .openExternally(URL(fileURLWithPath: target)) }
64        open(target)
65        guard let option = link.searchOption, !option.isEmpty else { return .shown }
66        if let line = Int(option), let text = document?.text {
67            let ns = text as NSString
68            var offset = 0
69            for _ in 1..<max(1, line) where offset < ns.length { offset = NSMaxRange(ns.lineRange(for: NSRange(location: offset, length: 0))) }
70            reveal(offset)
71            return .shown
72        }
73        return searchCurrent(option)
74    }
75
76    private func searchCurrent(_ s: String) -> LinkFollow {
77        guard let document else { return .message("No file is open") }
78        switch Links.search(s, text: document.text, tree: document.tree) {
79        case .found(let offset):
80            reveal(offset)
81            return .shown
82        case .failed(let message):
83            return .message(message)
84        }
85    }
86}