Sources/OrgCore/Links/Backlinks.swift

73fcba4bfb8709ee26c1b1ecee1b70ce400e5b7e
orgstar/Sources/OrgCore/Links/Backlinks.swift

116 lines · 6043 bytes

  1import Foundation
  2
  3/// Which links point at a file or one of its headings, read as `org-open-at-point` would
  4/// follow them: `id:`, `denote:`, `file:` with `::*Title` or `::#custom-id`, plain paths, and `*Title`,
  5/// `#custom-id` or a heading's exact title within the same file.
  6public enum Backlinks {
  7    public struct Target: Sendable, Equatable {
  8        public var path: String
  9        /// The heading, or nil for the file itself.
 10        public var title: String?
 11        public var id: String?
 12        public var customID: String?
 13
 14        public init(path: String, title: String? = nil, id: String? = nil, customID: String? = nil) {
 15            self.path = path
 16            self.title = title
 17            self.id = id
 18            self.customID = customID
 19        }
 20    }
 21
 22    /// A link type and its colon.
 23    nonisolated(unsafe) private static let typePrefix = /^[a-zA-Z][-a-zA-Z0-9+]*:/
 24    /// A bracket link: what it links to, and its description.
 25    nonisolated(unsafe) private static let bracketLink = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
 26
 27    /// Whether `link`, written in the file at `source`, leads to `target`.
 28    public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool {
 29        let link = Links.unescape(link)
 30        if link.lowercased().hasPrefix("id:") {
 31            let id = link.dropFirst(3).components(separatedBy: "::")[0]
 32            return target.id.map { $0 == id } ?? false
 33        }
 34        var path: String
 35        var search: String
 36        if link.lowercased().hasPrefix("denote:") {
 37            let (identifier, denoteSearch) = Denote.split(String(link.dropFirst(7)))
 38            guard Denote.identifier(ofFile: target.path) == identifier else { return false }
 39            path = ""
 40            search = denoteSearch ?? ""
 41            if search.isEmpty { return target.title == nil }
 42        } else if link.lowercased().hasPrefix("file:") {
 43            let parts = link.dropFirst(5).components(separatedBy: "::")
 44            path = parts[0]
 45            search = parts.dropFirst().joined(separator: "::")
 46        } else if ["/", "./", "../", "~/"].contains(where: link.hasPrefix) {
 47            let parts = link.components(separatedBy: "::")
 48            path = parts[0]
 49            search = parts.dropFirst().joined(separator: "::")
 50        } else if link.firstMatch(of: typePrefix) != nil {
 51            return false
 52        } else {
 53            // Within the file.
 54            guard source == target.path else { return false }
 55            path = ""
 56            search = link
 57        }
 58        if !path.isEmpty {
 59            let directory = (source as NSString).deletingLastPathComponent
 60            let expanded = Links.expand(path, directory: directory, home: home)
 61            guard (expanded as NSString).standardizingPath == (target.path as NSString).standardizingPath else { return false }
 62            if search.isEmpty { return target.title == nil }
 63        }
 64        guard let title = target.title else { return false }
 65        if search.hasPrefix("#") { return target.customID.map { "#" + $0 == search } ?? false }
 66        let wanted = search.hasPrefix("*") ? String(search.dropFirst()) : search
 67        return Links.normalizedTitle(wanted) == Links.normalizedTitle(title)
 68    }
 69
 70    /// Denote's Markdown link, `[description](denote:ID)`.
 71    nonisolated(unsafe) private static let markdownLink = /\[([^\]\n]*)\]\((denote:[^()\[\]\s]+)\)/
 72
 73    /// The line of `body` with the link to `link` in it, links shown as they read (their
 74    /// description, else what they link to), and the range of that link in the line. A line
 75    /// longer than `width` keeps the part around the link. Denote's Markdown links count too.
 76    public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
 77        for line in body.split(whereSeparator: \.isNewline) {
 78            guard line.contains("[[" + link + "]") || line.contains("](" + link + ")") else { continue }
 79            var text = ""
 80            var found: Range<Int>?
 81            var rest = Substring(line)
 82            while true {
 83                let bracket = rest.firstMatch(of: bracketLink), markdown = rest.firstMatch(of: markdownLink)
 84                let next: (range: Range<Substring.Index>, target: Substring, shown: String)
 85                if let bracket, markdown.map({ bracket.range.lowerBound <= $0.range.lowerBound }) ?? true {
 86                    next = (bracket.range, bracket.1, bracket.2.map(String.init) ?? String(bracket.1))
 87                } else if let markdown {
 88                    next = (markdown.range, markdown.2, markdown.1.isEmpty ? String(markdown.2) : String(markdown.1))
 89                } else {
 90                    break
 91                }
 92                text += rest[..<next.range.lowerBound]
 93                let start = text.utf16.count
 94                text += next.shown
 95                if found == nil, next.target == link { found = start..<text.utf16.count }
 96                rest = rest[next.range.upperBound...]
 97            }
 98            text += rest
 99            guard var range = found else { continue }
100            // Trim, then cut to `width` around the link.
101            let leading = text.prefix { $0.isWhitespace }.utf16.count
102            text = text.trimmingCharacters(in: .whitespaces)
103            range = (range.lowerBound - leading)..<(range.upperBound - leading)
104            let ns = text as NSString
105            if ns.length > width {
106                let start = max(0, min(range.lowerBound - width / 3, ns.length - width))
107                let end = min(ns.length, start + width)
108                let lead = start > 0 ? "…" : "", trail = end < ns.length ? "…" : ""
109                text = lead + ns.substring(with: NSRange(location: start, length: end - start)) + trail
110                range = (range.lowerBound - start + lead.utf16.count)..<(range.upperBound - start + lead.utf16.count)
111            }
112            return (text, range)
113        }
114        return nil
115    }
116}
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