Sources/OrgCore/Links/Links.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Links/Links.swift history · blame · raw

334 lines · 17389 bytes

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