Sources/OrgCore/Links/Links.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgCore/Links/Links.swift

350 lines · 18291 bytes

27 symbols in this file
  1import Foundation
  2
  3/// A link as `org-element-link-parser` reads it.
  4public struct OrgLink: Sendable, Equatable {
  5    /// `https`, `file`, `id`, `denote`, `custom-id`, `coderef`, `fuzzy`, or another registered type.
  6    public let type: String
  7    public let path: String
  8    /// What follows `::` in a file link.
  9    public let searchOption: String?
 10    /// The link as written, unescaped and with abbreviations expanded.
 11    public let raw: String
 12    /// Where an `attachment` link starts in its file, whose entry holds the attachments.
 13    public var position: Int?
 14
 15    public init(type: String, path: String, searchOption: String? = nil, raw: String, position: Int? = nil) {
 16        self.type = type
 17        self.path = path
 18        self.searchOption = searchOption
 19        self.raw = raw
 20        self.position = position
 21    }
 22}
 23
 24public enum Links {
 25    /// `org-link-parameters` in Emacs with Org's default modules, org-attach's, Denote's and
 26    /// org-roam's.
 27    static let types = [
 28        "attachment", "id", "denote", "roam", "eww", "rmail", "mhe", "irc", "info", "gnus", "docview", "bibtex", "bbdb", "w3m", "doi", "file+sys", "file+emacs",
 29        "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp",
 30    ]
 31
 32    /// `org-link-types-re`: a registered type and its colon, longest names first.
 33    static let typesPattern = try! NSRegularExpression(
 34        pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):"
 35    )
 36
 37    /// Runs of backslashes before a bracket or the end.
 38    private static let escapes = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
 39
 40    /// `org-link-unescape`: halves each run of backslashes before a bracket or the end.
 41    static func unescape(_ s: String) -> String {
 42        let ns = s as NSString
 43        var out = s
 44        for m in escapes.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
 45            let run = m.range(at: 1)
 46            out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2))
 47        }
 48        return out
 49    }
 50
 51    /// `#+LINK: key template` lines of a file.
 52    public static func abbreviations(in text: String) -> [String: String] {
 53        var result: [String: String] = [:]
 54        let regex = try! NSRegularExpression(pattern: "^[ \\t]*#\\+LINK:[ \\t]+(\\S+)[ \\t]+(.*?)[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
 55        let ns = text as NSString
 56        for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) where result[ns.substring(with: m.range(at: 1))] == nil {
 57            result[ns.substring(with: m.range(at: 1))] = ns.substring(with: m.range(at: 2))
 58        }
 59        return result
 60    }
 61
 62    /// `org-link-expand-abbrev` for templates with `%s`, `%h`, or a plain prefix.
 63    static func expandAbbreviation(_ link: String, _ abbreviations: [String: String]) -> String {
 64        guard !abbreviations.isEmpty else { return link }
 65        let regex = try! NSRegularExpression(pattern: "^([^:]*)(::?(.*))?$")
 66        let ns = link as NSString
 67        guard let m = regex.firstMatch(in: link, range: NSRange(location: 0, length: ns.length)),
 68              let template = abbreviations[ns.substring(with: m.range(at: 1))] else { return link }
 69        let tag = m.range(at: 2).location == NSNotFound ? "" : ns.substring(with: m.range(at: 3))
 70        if template.contains("%s") {
 71            return template.replacingOccurrences(of: "%s", with: tag, options: [], range: template.range(of: "%s"))
 72        }
 73        if template.contains("%h") {
 74            let hex = tag.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&=+?#"))) ?? tag
 75            return template.replacingOccurrences(of: "%h", with: hex, options: [], range: template.range(of: "%h"))
 76        }
 77        return template + tag
 78    }
 79
 80    /// A bracket link's inside (`[[` to `]]` or `][`), as `org-element-link-parser` reads it.
 81    public static func parse(bracket inside: String, abbreviations: [String: String] = [:]) -> OrgLink {
 82        let joined = inside.contains("\n") ? inside.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression) : inside
 83        let raw = expandAbbreviation(unescape(joined), abbreviations)
 84        let ns = raw as NSString
 85        var type: String
 86        var path: String
 87        if raw.hasPrefix("/") || raw.hasPrefix("~") || raw.hasPrefix("./") || raw.hasPrefix("../") {
 88            type = "file"
 89            path = raw
 90        } else if let m = typesPattern.firstMatch(in: raw, range: NSRange(location: 0, length: ns.length)) {
 91            type = ns.substring(with: m.range(at: 1))
 92            path = ns.substring(from: NSMaxRange(m.range))
 93        } else if raw.hasPrefix("("), raw.hasSuffix(")"), raw.count >= 2 {
 94            type = "coderef"
 95            path = String(raw.dropFirst().dropLast())
 96        } else if raw.hasPrefix("#") {
 97            type = "custom-id"
 98            path = String(raw.dropFirst())
 99        } else {
100            type = "fuzzy"
101            path = raw
102        }
103        return fileParts(type: type, path: path, raw: raw)
104    }
105
106    /// A plain or angle link: `type:path` as written.
107    public static func parse(plain: String) -> OrgLink {
108        let ns = plain as NSString
109        guard let m = typesPattern.firstMatch(in: plain, range: NSRange(location: 0, length: ns.length)) else {
110            return OrgLink(type: "fuzzy", path: plain, raw: plain)
111        }
112        let path = ns.substring(from: NSMaxRange(m.range)).replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: "", options: .regularExpression)
113        return fileParts(type: ns.substring(with: m.range(at: 1)), path: path, raw: plain)
114    }
115
116    /// `file` and `file+app` links keep their `::search` apart.
117    static func fileParts(type: String, path: String, raw: String) -> OrgLink {
118        guard type == "file" || type.hasPrefix("file+") else { return OrgLink(type: type, path: path, raw: raw) }
119        var path = path
120        var search: String?
121        if let range = path.range(of: "::(.*)$", options: .regularExpression) {
122            search = String(path[range].dropFirst(2))
123            path.removeSubrange(range)
124        }
125        path = path.replacingOccurrences(of: "^///*([A-Za-z]:)?/", with: "$1/", options: .regularExpression)
126        return OrgLink(type: "file", path: path, searchOption: search, raw: raw)
127    }
128
129    /// The link at `offset`: the link node holding it, read with the file's abbreviations.
130    public static func link(at offset: Int, text: String, tree: OrgTree) -> (link: OrgLink, range: Range<Int>)? {
131        var found: SyntaxNode?
132        func walk(_ node: SyntaxNode) {
133            for child in node.children where child.range.lowerBound <= offset && offset < child.range.upperBound
134                || (child.range.upperBound == offset && child.kind == .link) {
135                if child.kind == .link { found = child }
136                walk(child)
137            }
138        }
139        walk(tree.root)
140        guard let node = found else { return nil }
141        let whole = node.text
142        var link: OrgLink
143        if whole.hasPrefix("[["), let path = node.linkPath {
144            link = parse(bracket: path, abbreviations: abbreviations(in: tree.settings.setupKeywords + text))
145        } else if whole.hasPrefix("<") && whole.hasSuffix(">") {
146            link = parse(plain: String(whole.dropFirst().dropLast()))
147        } else if tree.settings.radioTargets.contains(where: { words($0) == words(whole) }) {
148            link = OrgLink(type: "radio", path: whole, raw: whole)
149        } else {
150            link = parse(plain: whole)
151        }
152        if link.type == "attachment" { link.position = node.range.lowerBound }
153        return (link, node.range)
154    }
155
156    /// Words without case, as radio links match their targets.
157    static func words(_ s: String) -> [String] { s.lowercased().split(whereSeparator: \.isWhitespace).map(String.init) }
158
159    /// `org-link--search-radio-target`: the `<<<target>>>` a radio link's text names.
160    public static func searchRadio(_ target: String, tree: OrgTree) -> SearchResult {
161        var found: Int?
162        func walk(_ node: SyntaxNode) {
163            for child in node.children where found == nil {
164                if child.kind == .radioTarget, words(String(child.text.dropFirst(3).dropLast(3))) == words(target) {
165                    found = child.range.lowerBound
166                }
167                walk(child)
168            }
169        }
170        walk(tree.root)
171        return found.map { .found($0) } ?? .failed("No match for radio target: \(target)")
172    }
173
174    /// The file `org-attach-follow` opens for an `attachment` link: in the entry's attachment
175    /// folder (`OrgAttach.directory`) when it exists, else relative to the file's folder, as
176    /// `org-attach-expand` has it. Nil without a folder to start from.
177    public static func attachmentFile(_ link: OrgLink, tree: OrgTree, path: String?, idDir: String = "data/", inherit: Bool? = nil, isDirectory: (String) -> Bool) -> OrgLink? {
178        guard let path else { return nil }
179        let folder = (path as NSString).deletingLastPathComponent
180        let dir = OrgAttach.directory(tree: tree, at: link.position ?? 0, path: path, idDir: idDir, inherit: inherit, isDirectory: isDirectory) ?? folder
181        var file = link.path
182        var search: String?
183        if let range = file.range(of: "::") {
184            search = String(file[range.upperBound...])
185            file = String(file[..<range.lowerBound])
186        }
187        return OrgLink(type: "file", path: OrgAttach.expand(file, in: dir), searchOption: search, raw: link.raw)
188    }
189
190    // MARK: - Searching a file
191
192    public enum SearchResult: Sendable, Equatable {
193        case found(Int)
194        case failed(String)
195        /// `/regexp/`: `org-occur`'s sparse tree for the regular expression.
196        case occur(String)
197    }
198
199    /// The regular expression of a `[[/regexp/]]` link or a `file:…::/regexp/` search.
200    public static func regexpSearch(_ link: OrgLink) -> String? {
201        let s = link.type == "fuzzy" ? link.path : link.type == "file" ? (link.searchOption ?? "") : ""
202        guard s.count >= 2, s.hasPrefix("/"), s.hasSuffix("/") else { return nil }
203        return String(s.dropFirst().dropLast())
204    }
205
206    /// `org-link-search` in an org file: a `#custom-id`, a `<<target>>`, a `#+NAME:`, or a
207    /// heading with these words (`*` asks for a heading only).
208    public static func search(_ s: String, text: String, tree: OrgTree) -> SearchResult {
209        guard s.contains(where: { !$0.isWhitespace }) else { return .failed("Invalid search string \"\(s)\"") }
210        let ns = text as NSString
211        let all = NSRange(location: 0, length: ns.length)
212        let normalized = s.replacingOccurrences(of: "\\n[ \\t]*", with: " ", options: .regularExpression)
213        let starred = normalized.hasPrefix("*")
214        let words = (starred ? String(s.dropFirst()) : s).split(whereSeparator: \.isWhitespace).map(String.init)
215        let model = DocumentModel(tree: tree)
216
217        if normalized.hasPrefix("#") {
218            let id = String(normalized.dropFirst())
219            for heading in model.headings where heading.properties.contains(where: { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id }) {
220                return .found(heading.headingRange.lowerBound)
221            }
222            return .failed("No match for custom ID: \(id)")
223        }
224        if normalized.hasPrefix("("), normalized.hasSuffix(")") {
225            let name = String(normalized.dropFirst().dropLast())
226            return Coderef.search(name, text: text, tree: tree).map(SearchResult.found) ?? .failed("No match for coderef: \(name)")
227        }
228        if normalized.count >= 2, normalized.hasPrefix("/"), normalized.hasSuffix("/") {
229            return .occur(String(s.dropFirst().dropLast()))
230        }
231        let quoted = words.map(NSRegularExpression.escapedPattern(for:))
232        if !starred {
233            // A dedicated target, not part of a radio target.
234            let target = try! NSRegularExpression(pattern: "(?<!<)<<" + quoted.joined(separator: "(?:[ \\t\\n]+)") + ">>(?!>)", options: .caseInsensitive)
235            if let m = target.firstMatch(in: text, range: all) { return .found(m.range.location) }
236            let name = try! NSRegularExpression(pattern: "^[ \\t]*#\\+NAME: +" + quoted.joined(separator: "[ \\t]+") + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
237            if let m = name.firstMatch(in: text, range: all) { return .found(ns.lineRange(for: m.range).location) }
238        }
239        let upper = words.map { $0.uppercased() }
240        for heading in model.headings {
241            let title = normalizedTitle(heading.title)
242            if title.split(whereSeparator: \.isWhitespace).map({ $0.uppercased() }) == upper {
243                return .found(heading.headingRange.lowerBound)
244            }
245        }
246        return .failed("No match for fuzzy expression: \(normalized)")
247    }
248
249    /// `org-link--normalize-string` of a heading title: statistics cookies and runs of space go.
250    static func normalizedTitle(_ title: String) -> String {
251        var t = title
252        if t == "COMMENT" { t = "" } else if t.hasPrefix("COMMENT ") { t = String(t.dropFirst(8)) }
253        t = t.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression)
254        t = t.replacingOccurrences(of: "[ \\t]+", with: " ", options: .regularExpression)
255        return t.trimmingCharacters(in: .whitespaces)
256    }
257}
258
259/// `org-open-at-point` on a link, a citation or a timestamp (C-c C-o). A citation is followed
260/// as a `cite` link whose path is its keys, separated by `;`.
261public struct OpenLinkAtPoint: OrgCommand {
262    public init() {}
263    public var id: String { "org.link.open" }
264    public var title: String { "Open Link" }
265    public func applies(in context: EditContext) -> Bool {
266        Links.link(at: context.caret, text: context.text, tree: context.tree) != nil
267            || Citations.keys(at: context.caret, text: context.text, tree: context.tree) != nil
268            || Links.timestampDays(at: context.caret, text: context.text) != nil
269    }
270    public func run(in context: EditContext) -> CommandStep {
271        if let found = Links.link(at: context.caret, text: context.text, tree: context.tree) {
272            return .external(.openLink(found.link))
273        }
274        if let link = Links.citation(at: context.caret, text: context.text, tree: context.tree) {
275            return .external(.openLink(link))
276        }
277        if let days = Links.timestampDays(at: context.caret, text: context.text) {
278            return .external(.agenda(start: days.start, days: days.count))
279        }
280        return .failed("No link to follow here")
281    }
282}
283
284extension Links {
285    /// The citation at `offset` as a `cite` link to follow: its keys, separated by `;`.
286    public static func citation(at offset: Int, text: String, tree: OrgTree) -> OrgLink? {
287        guard let keys = Citations.keys(at: offset, text: text, tree: tree), !keys.isEmpty else { return nil }
288        let path = keys.joined(separator: ";")
289        return OrgLink(type: "cite", path: path, raw: "cite:" + path)
290    }
291}
292
293extension Links {
294    /// An `elisp:` link's form evaluated in `Elisp`: `org-link--open-elisp`'s message, the
295    /// error's, or why it needs Emacs.
296    public static func evaluateElisp(_ form: String) -> String {
297        let lisp = Elisp()
298        lisp.standardTime()
299        EmacsBuffer.defineLookups(lisp)
300        lisp.unboundUnsupported = true
301        do {
302            let value = try lisp.eval(try LispReader.readFirst(form).sexp)
303            if Elisp.containsClosure(value) { return "This link uses Emacs Lisp that runs only in Emacs." }
304            return "\(form) => \(try Elisp.format([.string("%s"), value]))"
305        } catch is Elisp.Unsupported {
306            return "This link uses Emacs Lisp that runs only in Emacs."
307        } catch {
308            return "\(error)"
309        }
310    }
311}
312
313extension Links {
314    /// `org-at-date-range-p` with INACTIVE-OK: the range starting at one of the two brackets
315    /// back from `offset` that reaches it.
316    static func dateRange(at offset: Int, text ns: NSString) -> [Range<Int>?]? {
317        let stamp = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?)[\\]>]"
318        let regex = try! NSRegularExpression(pattern: stamp + "--?-?" + stamp)
319        func char(_ i: Int) -> unichar? { i >= 0 && i < ns.length ? ns.character(at: i) : nil }
320        let brackets: Set<unichar> = [91, 60]
321        var p = offset
322        for _ in 0..<2 {
323            while let c = char(p - 1), !brackets.contains(c), c != 10, c != 13 { p -= 1 }
324            while let c = char(p - 1), brackets.contains(c) { p -= 1 }
325            if let m = regex.firstMatch(in: ns as String, options: .anchored, range: NSRange(location: p, length: ns.length - p)),
326               NSMaxRange(m.range) >= offset {
327                return (0..<m.numberOfRanges).map { i in m.range(at: i).location == NSNotFound ? nil : m.range(at: i).location..<NSMaxRange(m.range(at: i)) }
328            }
329        }
330        return nil
331    }
332
333    /// `org-follow-timestamp-link`: the agenda's first day and length for the date range or
334    /// timestamp at `offset`. Point just past a timestamp isn't on it.
335    public static func timestampDays(at offset: Int, text: String) -> (start: Int, count: Int)? {
336        let buffer = EmacsBuffer(text, point: offset)
337        func day(_ match: [Range<Int>?], _ group: Int) -> Int? {
338            guard let range = match[group] else { return nil }
339            let parts = buffer.substring(range.lowerBound, range.upperBound).prefix(10).split(separator: "-").compactMap { Int($0) }
340            return parts.count == 3 ? Days.absolute(year: parts[0], month: parts[1], day: parts[2]) : nil
341        }
342        if let range = dateRange(at: offset, text: text as NSString), let first = day(range, 1), let last = day(range, 2) {
343            return (first, last - first + 1)
344        }
345        if let (part, match) = buffer.atTimestamp(), part != .after, let first = day(match, 1) {
346            return (first, 1)
347        }
348        return nil
349    }
350}
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