Sources/OrgCore/Links/Backlinks.swift
105 lines · 5276 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 /// The line of `body` with the link to `link` in it, links shown as they read (their
71 /// description, else what they link to), and the range of that link in the line. A line
72 /// longer than `width` keeps the part around the link.
73 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
74 for line in body.split(whereSeparator: \.isNewline) {
75 guard line.contains("[[" + link + "]") else { continue }
76 var text = ""
77 var found: Range<Int>?
78 var rest = Substring(line)
79 while let match = rest.firstMatch(of: bracketLink) {
80 text += rest[..<match.range.lowerBound]
81 let shown = match.2.map(String.init) ?? String(match.1)
82 let start = text.utf16.count
83 text += shown
84 if found == nil, match.1 == link { found = start..<text.utf16.count }
85 rest = rest[match.range.upperBound...]
86 }
87 text += rest
88 guard var range = found else { continue }
89 // Trim, then cut to `width` around the link.
90 let leading = text.prefix { $0.isWhitespace }.utf16.count
91 text = text.trimmingCharacters(in: .whitespaces)
92 range = (range.lowerBound - leading)..<(range.upperBound - leading)
93 let ns = text as NSString
94 if ns.length > width {
95 let start = max(0, min(range.lowerBound - width / 3, ns.length - width))
96 let end = min(ns.length, start + width)
97 let lead = start > 0 ? "…" : "", trail = end < ns.length ? "…" : ""
98 text = lead + ns.substring(with: NSRange(location: start, length: end - start)) + trail
99 range = (range.lowerBound - start + lead.utf16.count)..<(range.upperBound - start + lead.utf16.count)
100 }
101 return (text, range)
102 }
103 return nil
104 }
105}