Sources/OrgCore/Links/Links.swift

3f183dc5a69542840ae20a73ec755d1148b354dd
orgstar/Sources/OrgCore/Links/Links.swift history · blame · raw

213 lines · 11014 bytes

  1import Foundation
  2
  3/// A link as `org-element-link-parser` reads it.
  4public struct OrgLink: Sendable, Equatable {
  5    /// `https`, `file`, `id`, `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
 13    public init(type: String, path: String, searchOption: String? = nil, raw: String) {
 14        self.type = type
 15        self.path = path
 16        self.searchOption = searchOption
 17        self.raw = raw
 18    }
 19}
 20
 21public enum Links {
 22    /// `org-link-parameters` in Emacs with Org's default modules.
 23    static let types = [
 24        "id", "eww", "rmail", "mhe", "irc", "info", "gnus", "docview", "bibtex", "bbdb", "w3m", "doi", "file+sys", "file+emacs",
 25        "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp",
 26    ]
 27
 28    /// `org-link-types-re`: a registered type and its colon, longest names first.
 29    static let typesPattern = try! NSRegularExpression(
 30        pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):"
 31    )
 32
 33    /// `org-link-unescape`: halves each run of backslashes before a bracket or the end.
 34    static func unescape(_ s: String) -> String {
 35        let regex = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
 36        let ns = s as NSString
 37        var out = s
 38        for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
 39            let run = m.range(at: 1)
 40            out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2))
 41        }
 42        return out
 43    }
 44
 45    /// `#+LINK: key template` lines of a file.
 46    public static func abbreviations(in text: String) -> [String: String] {
 47        var result: [String: String] = [:]
 48        let regex = try! NSRegularExpression(pattern: "^[ \\t]*#\\+LINK:[ \\t]+(\\S+)[ \\t]+(.*?)[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
 49        let ns = text as NSString
 50        for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) where result[ns.substring(with: m.range(at: 1))] == nil {
 51            result[ns.substring(with: m.range(at: 1))] = ns.substring(with: m.range(at: 2))
 52        }
 53        return result
 54    }
 55
 56    /// `org-link-expand-abbrev` for templates with `%s`, `%h`, or a plain prefix.
 57    static func expandAbbreviation(_ link: String, _ abbreviations: [String: String]) -> String {
 58        let regex = try! NSRegularExpression(pattern: "^([^:]*)(::?(.*))?$")
 59        let ns = link as NSString
 60        guard let m = regex.firstMatch(in: link, range: NSRange(location: 0, length: ns.length)),
 61              let template = abbreviations[ns.substring(with: m.range(at: 1))] else { return link }
 62        let tag = m.range(at: 2).location == NSNotFound ? "" : ns.substring(with: m.range(at: 3))
 63        if template.contains("%s") {
 64            return template.replacingOccurrences(of: "%s", with: tag, options: [], range: template.range(of: "%s"))
 65        }
 66        if template.contains("%h") {
 67            let hex = tag.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&=+?#"))) ?? tag
 68            return template.replacingOccurrences(of: "%h", with: hex, options: [], range: template.range(of: "%h"))
 69        }
 70        return template + tag
 71    }
 72
 73    /// A bracket link's inside (`[[` to `]]` or `][`), as `org-element-link-parser` reads it.
 74    public static func parse(bracket inside: String, abbreviations: [String: String] = [:]) -> OrgLink {
 75        let joined = inside.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression)
 76        let raw = expandAbbreviation(unescape(joined), abbreviations)
 77        let ns = raw as NSString
 78        var type: String
 79        var path: String
 80        if raw.hasPrefix("/") || raw.hasPrefix("~") || raw.hasPrefix("./") || raw.hasPrefix("../") {
 81            type = "file"
 82            path = raw
 83        } else if let m = typesPattern.firstMatch(in: raw, range: NSRange(location: 0, length: ns.length)) {
 84            type = ns.substring(with: m.range(at: 1))
 85            path = ns.substring(from: NSMaxRange(m.range))
 86        } else if raw.hasPrefix("("), raw.hasSuffix(")"), raw.count >= 2 {
 87            type = "coderef"
 88            path = String(raw.dropFirst().dropLast())
 89        } else if raw.hasPrefix("#") {
 90            type = "custom-id"
 91            path = String(raw.dropFirst())
 92        } else {
 93            type = "fuzzy"
 94            path = raw
 95        }
 96        return fileParts(type: type, path: path, raw: raw)
 97    }
 98
 99    /// A plain or angle link: `type:path` as written.
100    public static func parse(plain: String) -> OrgLink {
101        let ns = plain as NSString
102        guard let m = typesPattern.firstMatch(in: plain, range: NSRange(location: 0, length: ns.length)) else {
103            return OrgLink(type: "fuzzy", path: plain, raw: plain)
104        }
105        let path = ns.substring(from: NSMaxRange(m.range)).replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: "", options: .regularExpression)
106        return fileParts(type: ns.substring(with: m.range(at: 1)), path: path, raw: plain)
107    }
108
109    /// `file` and `file+app` links keep their `::search` apart.
110    static func fileParts(type: String, path: String, raw: String) -> OrgLink {
111        guard type == "file" || type.hasPrefix("file+") else { return OrgLink(type: type, path: path, raw: raw) }
112        var path = path
113        var search: String?
114        if let range = path.range(of: "::(.*)$", options: .regularExpression) {
115            search = String(path[range].dropFirst(2))
116            path.removeSubrange(range)
117        }
118        path = path.replacingOccurrences(of: "^///*([A-Za-z]:)?/", with: "$1/", options: .regularExpression)
119        return OrgLink(type: "file", path: path, searchOption: search, raw: raw)
120    }
121
122    /// The link at `offset`: the link node holding it, read with the file's abbreviations.
123    public static func link(at offset: Int, text: String, tree: OrgTree) -> (link: OrgLink, range: Range<Int>)? {
124        var found: SyntaxNode?
125        func walk(_ node: SyntaxNode) {
126            for child in node.children where child.range.lowerBound <= offset && offset < child.range.upperBound
127                || (child.range.upperBound == offset && child.kind == .link) {
128                if child.kind == .link { found = child }
129                walk(child)
130            }
131        }
132        walk(tree.root)
133        guard let node = found else { return nil }
134        let whole = node.text
135        if whole.hasPrefix("[["), let path = node.tokens.first(where: { $0.kind == .linkPath }) {
136            return (parse(bracket: path.text, abbreviations: abbreviations(in: text)), node.range)
137        }
138        let plain = whole.hasPrefix("<") && whole.hasSuffix(">") ? String(whole.dropFirst().dropLast()) : whole
139        return (parse(plain: plain), node.range)
140    }
141
142    // MARK: - Searching a file
143
144    public enum SearchResult: Sendable, Equatable {
145        case found(Int)
146        case failed(String)
147    }
148
149    /// `org-link-search` in an org file: a `#custom-id`, a `<<target>>`, a `#+NAME:`, or a
150    /// heading with these words (`*` asks for a heading only).
151    public static func search(_ s: String, text: String, tree: OrgTree) -> SearchResult {
152        guard s.contains(where: { !$0.isWhitespace }) else { return .failed("Invalid search string \"\(s)\"") }
153        let ns = text as NSString
154        let all = NSRange(location: 0, length: ns.length)
155        let normalized = s.replacingOccurrences(of: "\\n[ \\t]*", with: " ", options: .regularExpression)
156        let starred = normalized.hasPrefix("*")
157        let words = (starred ? String(s.dropFirst()) : s).split(whereSeparator: \.isWhitespace).map(String.init)
158        let model = DocumentModel(tree: tree)
159
160        if normalized.hasPrefix("#") {
161            let id = String(normalized.dropFirst())
162            for heading in model.headings where heading.properties.contains(where: { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id }) {
163                return .found(heading.headingRange.lowerBound)
164            }
165            return .failed("No match for custom ID: \(id)")
166        }
167        if normalized.hasPrefix("("), normalized.hasSuffix(")") {
168            return .failed("Coderef links aren't supported")
169        }
170        if normalized.count >= 2, normalized.hasPrefix("/"), normalized.hasSuffix("/") {
171            return .failed("Regexp links aren't supported")
172        }
173        let quoted = words.map(NSRegularExpression.escapedPattern(for:))
174        if !starred {
175            // A dedicated target, not part of a radio target.
176            let target = try! NSRegularExpression(pattern: "(?<!<)<<" + quoted.joined(separator: "(?:[ \\t\\n]+)") + ">>(?!>)", options: .caseInsensitive)
177            if let m = target.firstMatch(in: text, range: all) { return .found(m.range.location) }
178            let name = try! NSRegularExpression(pattern: "^[ \\t]*#\\+NAME: +" + quoted.joined(separator: "[ \\t]+") + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
179            if let m = name.firstMatch(in: text, range: all) { return .found(ns.lineRange(for: m.range).location) }
180        }
181        let upper = words.map { $0.uppercased() }
182        for heading in model.headings {
183            let title = normalizedTitle(heading.title)
184            if title.split(whereSeparator: \.isWhitespace).map({ $0.uppercased() }) == upper {
185                return .found(heading.headingRange.lowerBound)
186            }
187        }
188        return .failed("No match for fuzzy expression: \(normalized)")
189    }
190
191    /// `org-link--normalize-string` of a heading title: statistics cookies and runs of space go.
192    static func normalizedTitle(_ title: String) -> String {
193        var t = title
194        if t == "COMMENT" { t = "" } else if t.hasPrefix("COMMENT ") { t = String(t.dropFirst(8)) }
195        t = t.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression)
196        t = t.replacingOccurrences(of: "[ \\t]+", with: " ", options: .regularExpression)
197        return t.trimmingCharacters(in: .whitespaces)
198    }
199}
200
201/// `org-open-at-point` on a link (C-c C-o).
202public struct OpenLinkAtPoint: OrgCommand {
203    public init() {}
204    public var id: String { "org.link.open" }
205    public var title: String { "Open Link" }
206    public func applies(in context: EditContext) -> Bool {
207        Links.link(at: context.caret, text: context.text, tree: context.tree) != nil
208    }
209    public func run(in context: EditContext) -> CommandStep {
210        guard let found = Links.link(at: context.caret, text: context.text, tree: context.tree) else { return .failed("No link to follow here") }
211        return .external(.openLink(found.link))
212    }
213}