Sources/OrgCore/Links/Links.swift
258 lines · 13483 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: tree.settings.setupKeywords + 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 or a timestamp (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 || Links.timestampDays(at: context.caret, text: context.text) != nil
209 }
210 public func run(in context: EditContext) -> CommandStep {
211 if let found = Links.link(at: context.caret, text: context.text, tree: context.tree) {
212 return .external(.openLink(found.link))
213 }
214 if let days = Links.timestampDays(at: context.caret, text: context.text) {
215 return .external(.agenda(start: days.start, days: days.count))
216 }
217 return .failed("No link to follow here")
218 }
219}
220
221extension Links {
222 /// `org-at-date-range-p` with INACTIVE-OK: the range starting at one of the two brackets
223 /// back from `offset` that reaches it.
224 static func dateRange(at offset: Int, text ns: NSString) -> [Range<Int>?]? {
225 let stamp = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?)[\\]>]"
226 let regex = try! NSRegularExpression(pattern: stamp + "--?-?" + stamp)
227 func char(_ i: Int) -> unichar? { i >= 0 && i < ns.length ? ns.character(at: i) : nil }
228 let brackets: Set<unichar> = [91, 60]
229 var p = offset
230 for _ in 0..<2 {
231 while let c = char(p - 1), !brackets.contains(c), c != 10, c != 13 { p -= 1 }
232 while let c = char(p - 1), brackets.contains(c) { p -= 1 }
233 if let m = regex.firstMatch(in: ns as String, options: .anchored, range: NSRange(location: p, length: ns.length - p)),
234 NSMaxRange(m.range) >= offset {
235 return (0..<m.numberOfRanges).map { i in m.range(at: i).location == NSNotFound ? nil : m.range(at: i).location..<NSMaxRange(m.range(at: i)) }
236 }
237 }
238 return nil
239 }
240
241 /// `org-follow-timestamp-link`: the agenda's first day and length for the date range or
242 /// timestamp at `offset`. Point just past a timestamp isn't on it.
243 public static func timestampDays(at offset: Int, text: String) -> (start: Int, count: Int)? {
244 let buffer = EmacsBuffer(text, point: offset)
245 func day(_ match: [Range<Int>?], _ group: Int) -> Int? {
246 guard let range = match[group] else { return nil }
247 let parts = buffer.substring(range.lowerBound, range.upperBound).prefix(10).split(separator: "-").compactMap { Int($0) }
248 return parts.count == 3 ? Days.absolute(year: parts[0], month: parts[1], day: parts[2]) : nil
249 }
250 if let range = dateRange(at: offset, text: text as NSString), let first = day(range, 1), let last = day(range, 2) {
251 return (first, last - first + 1)
252 }
253 if let (part, match) = buffer.atTimestamp(), part != .after, let first = day(match, 1) {
254 return (first, 1)
255 }
256 return nil
257 }
258}