Sources/OrgApp/LinkFollow.swift

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