Sources/OrgCore/Links/Backlinks.swift
101 lines · 5075 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 /// Whether `link`, written in the file at `source`, leads to `target`.
23 public static func links(_ link: String, from source: String, to target: Target, home: String = NSHomeDirectory()) -> Bool {
24 let link = Links.unescape(link)
25 if link.lowercased().hasPrefix("id:") {
26 let id = link.dropFirst(3).components(separatedBy: "::")[0]
27 return target.id.map { $0 == id } ?? false
28 }
29 var path: String
30 var search: String
31 if link.lowercased().hasPrefix("denote:") {
32 let (identifier, denoteSearch) = Denote.split(String(link.dropFirst(7)))
33 guard Denote.identifier(ofFile: target.path) == identifier else { return false }
34 path = ""
35 search = denoteSearch ?? ""
36 if search.isEmpty { return target.title == nil }
37 } else if link.lowercased().hasPrefix("file:") {
38 let parts = link.dropFirst(5).components(separatedBy: "::")
39 path = parts[0]
40 search = parts.dropFirst().joined(separator: "::")
41 } else if ["/", "./", "../", "~/"].contains(where: link.hasPrefix) {
42 let parts = link.components(separatedBy: "::")
43 path = parts[0]
44 search = parts.dropFirst().joined(separator: "::")
45 } else if link.firstMatch(of: /^[a-zA-Z][-a-zA-Z0-9+]*:/) != nil {
46 return false
47 } else {
48 // Within the file.
49 guard source == target.path else { return false }
50 path = ""
51 search = link
52 }
53 if !path.isEmpty {
54 let directory = (source as NSString).deletingLastPathComponent
55 let expanded = Links.expand(path, directory: directory, home: home)
56 guard (expanded as NSString).standardizingPath == (target.path as NSString).standardizingPath else { return false }
57 if search.isEmpty { return target.title == nil }
58 }
59 guard let title = target.title else { return false }
60 if search.hasPrefix("#") { return target.customID.map { "#" + $0 == search } ?? false }
61 let wanted = search.hasPrefix("*") ? String(search.dropFirst()) : search
62 return Links.normalizedTitle(wanted) == Links.normalizedTitle(title)
63 }
64
65 /// The line of `body` with the link to `link` in it, links shown as they read (their
66 /// description, else what they link to), and the range of that link in the line. A line
67 /// longer than `width` keeps the part around the link.
68 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
69 let pattern = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
70 for line in body.split(whereSeparator: \.isNewline) {
71 guard line.contains("[[" + link + "]") else { continue }
72 var text = ""
73 var found: Range<Int>?
74 var rest = Substring(line)
75 while let match = rest.firstMatch(of: pattern) {
76 text += rest[..<match.range.lowerBound]
77 let shown = match.2.map(String.init) ?? String(match.1)
78 let start = text.utf16.count
79 text += shown
80 if found == nil, match.1 == link { found = start..<text.utf16.count }
81 rest = rest[match.range.upperBound...]
82 }
83 text += rest
84 guard var range = found else { continue }
85 // Trim, then cut to `width` around the link.
86 let leading = text.prefix { $0.isWhitespace }.utf16.count
87 text = text.trimmingCharacters(in: .whitespaces)
88 range = (range.lowerBound - leading)..<(range.upperBound - leading)
89 let ns = text as NSString
90 if ns.length > width {
91 let start = max(0, min(range.lowerBound - width / 3, ns.length - width))
92 let end = min(ns.length, start + width)
93 let lead = start > 0 ? "…" : "", trail = end < ns.length ? "…" : ""
94 text = lead + ns.substring(with: NSRange(location: start, length: end - start)) + trail
95 range = (range.lowerBound - start + lead.utf16.count)..<(range.upperBound - start + lead.utf16.count)
96 }
97 return (text, range)
98 }
99 return nil
100 }
101}