Sources/OrgCore/Links/Links.swift
335 lines · 17480 bytes
26 symbols in this file
1import Foundation
2
3/// A link as `org-element-link-parser` reads it.
4public struct OrgLink: Sendable, Equatable {
5 /// `https`, `file`, `id`, `denote`, `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 /// Where an `attachment` link starts in its file, whose entry holds the attachments.
13 public var position: Int?
14
15 public init(type: String, path: String, searchOption: String? = nil, raw: String, position: Int? = nil) {
16 self.type = type
17 self.path = path
18 self.searchOption = searchOption
19 self.raw = raw
20 self.position = position
21 }
22}
23
24public enum Links {
25 /// `org-link-parameters` in Emacs with Org's default modules, org-attach's and Denote's.
26 static let types = [
27 "attachment", "id", "denote", "eww", "rmail", "mhe", "irc", "info", "gnus", "docview", "bibtex", "bbdb", "w3m", "doi", "file+sys", "file+emacs",
28 "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp",
29 ]
30
31 /// `org-link-types-re`: a registered type and its colon, longest names first.
32 static let typesPattern = try! NSRegularExpression(
33 pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):"
34 )
35
36 /// Runs of backslashes before a bracket or the end.
37 private static let escapes = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])")
38
39 /// `org-link-unescape`: halves each run of backslashes before a bracket or the end.
40 static func unescape(_ s: String) -> String {
41 let ns = s as NSString
42 var out = s
43 for m in escapes.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
44 let run = m.range(at: 1)
45 out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2))
46 }
47 return out
48 }
49
50 /// `#+LINK: key template` lines of a file.
51 public static func abbreviations(in text: String) -> [String: String] {
52 var result: [String: String] = [:]
53 let regex = try! NSRegularExpression(pattern: "^[ \\t]*#\\+LINK:[ \\t]+(\\S+)[ \\t]+(.*?)[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
54 let ns = text as NSString
55 for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) where result[ns.substring(with: m.range(at: 1))] == nil {
56 result[ns.substring(with: m.range(at: 1))] = ns.substring(with: m.range(at: 2))
57 }
58 return result
59 }
60
61 /// `org-link-expand-abbrev` for templates with `%s`, `%h`, or a plain prefix.
62 static func expandAbbreviation(_ link: String, _ abbreviations: [String: String]) -> String {
63 guard !abbreviations.isEmpty else { return link }
64 let regex = try! NSRegularExpression(pattern: "^([^:]*)(::?(.*))?$")
65 let ns = link as NSString
66 guard let m = regex.firstMatch(in: link, range: NSRange(location: 0, length: ns.length)),
67 let template = abbreviations[ns.substring(with: m.range(at: 1))] else { return link }
68 let tag = m.range(at: 2).location == NSNotFound ? "" : ns.substring(with: m.range(at: 3))
69 if template.contains("%s") {
70 return template.replacingOccurrences(of: "%s", with: tag, options: [], range: template.range(of: "%s"))
71 }
72 if template.contains("%h") {
73 let hex = tag.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&=+?#"))) ?? tag
74 return template.replacingOccurrences(of: "%h", with: hex, options: [], range: template.range(of: "%h"))
75 }
76 return template + tag
77 }
78
79 /// A bracket link's inside (`[[` to `]]` or `][`), as `org-element-link-parser` reads it.
80 public static func parse(bracket inside: String, abbreviations: [String: String] = [:]) -> OrgLink {
81 let joined = inside.contains("\n") ? inside.replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: " ", options: .regularExpression) : inside
82 let raw = expandAbbreviation(unescape(joined), abbreviations)
83 let ns = raw as NSString
84 var type: String
85 var path: String
86 if raw.hasPrefix("/") || raw.hasPrefix("~") || raw.hasPrefix("./") || raw.hasPrefix("../") {
87 type = "file"
88 path = raw
89 } else if let m = typesPattern.firstMatch(in: raw, range: NSRange(location: 0, length: ns.length)) {
90 type = ns.substring(with: m.range(at: 1))
91 path = ns.substring(from: NSMaxRange(m.range))
92 } else if raw.hasPrefix("("), raw.hasSuffix(")"), raw.count >= 2 {
93 type = "coderef"
94 path = String(raw.dropFirst().dropLast())
95 } else if raw.hasPrefix("#") {
96 type = "custom-id"
97 path = String(raw.dropFirst())
98 } else {
99 type = "fuzzy"
100 path = raw
101 }
102 return fileParts(type: type, path: path, raw: raw)
103 }
104
105 /// A plain or angle link: `type:path` as written.
106 public static func parse(plain: String) -> OrgLink {
107 let ns = plain as NSString
108 guard let m = typesPattern.firstMatch(in: plain, range: NSRange(location: 0, length: ns.length)) else {
109 return OrgLink(type: "fuzzy", path: plain, raw: plain)
110 }
111 let path = ns.substring(from: NSMaxRange(m.range)).replacingOccurrences(of: "[ \\t]*\\n[ \\t]*", with: "", options: .regularExpression)
112 return fileParts(type: ns.substring(with: m.range(at: 1)), path: path, raw: plain)
113 }
114
115 /// `file` and `file+app` links keep their `::search` apart.
116 static func fileParts(type: String, path: String, raw: String) -> OrgLink {
117 guard type == "file" || type.hasPrefix("file+") else { return OrgLink(type: type, path: path, raw: raw) }
118 var path = path
119 var search: String?
120 if let range = path.range(of: "::(.*)$", options: .regularExpression) {
121 search = String(path[range].dropFirst(2))
122 path.removeSubrange(range)
123 }
124 path = path.replacingOccurrences(of: "^///*([A-Za-z]:)?/", with: "$1/", options: .regularExpression)
125 return OrgLink(type: "file", path: path, searchOption: search, raw: raw)
126 }
127
128 /// The link at `offset`: the link node holding it, read with the file's abbreviations.
129 public static func link(at offset: Int, text: String, tree: OrgTree) -> (link: OrgLink, range: Range<Int>)? {
130 var found: SyntaxNode?
131 func walk(_ node: SyntaxNode) {
132 for child in node.children where child.range.lowerBound <= offset && offset < child.range.upperBound
133 || (child.range.upperBound == offset && child.kind == .link) {
134 if child.kind == .link { found = child }
135 walk(child)
136 }
137 }
138 walk(tree.root)
139 guard let node = found else { return nil }
140 let whole = node.text
141 var link: OrgLink
142 if whole.hasPrefix("[["), let path = node.linkPath {
143 link = parse(bracket: path, abbreviations: abbreviations(in: tree.settings.setupKeywords + text))
144 } else if whole.hasPrefix("<") && whole.hasSuffix(">") {
145 link = parse(plain: String(whole.dropFirst().dropLast()))
146 } else if tree.settings.radioTargets.contains(where: { words($0) == words(whole) }) {
147 link = OrgLink(type: "radio", path: whole, raw: whole)
148 } else {
149 link = parse(plain: whole)
150 }
151 if link.type == "attachment" { link.position = node.range.lowerBound }
152 return (link, node.range)
153 }
154
155 /// Words without case, as radio links match their targets.
156 static func words(_ s: String) -> [String] { s.lowercased().split(whereSeparator: \.isWhitespace).map(String.init) }
157
158 /// `org-link--search-radio-target`: the `<<<target>>>` a radio link's text names.
159 public static func searchRadio(_ target: String, tree: OrgTree) -> SearchResult {
160 var found: Int?
161 func walk(_ node: SyntaxNode) {
162 for child in node.children where found == nil {
163 if child.kind == .radioTarget, words(String(child.text.dropFirst(3).dropLast(3))) == words(target) {
164 found = child.range.lowerBound
165 }
166 walk(child)
167 }
168 }
169 walk(tree.root)
170 return found.map { .found($0) } ?? .failed("No match for radio target: \(target)")
171 }
172
173 /// The file `org-attach-follow` opens for an `attachment` link: in the entry's attachment
174 /// folder (`OrgAttach.directory`) when it exists, else relative to the file's folder, as
175 /// `org-attach-expand` has it. Nil without a folder to start from.
176 public static func attachmentFile(_ link: OrgLink, tree: OrgTree, path: String?, idDir: String = "data/", inherit: Bool? = nil, isDirectory: (String) -> Bool) -> OrgLink? {
177 guard let path else { return nil }
178 let folder = (path as NSString).deletingLastPathComponent
179 let dir = OrgAttach.directory(tree: tree, at: link.position ?? 0, path: path, idDir: idDir, inherit: inherit, isDirectory: isDirectory) ?? folder
180 var file = link.path
181 var search: String?
182 if let range = file.range(of: "::") {
183 search = String(file[range.upperBound...])
184 file = String(file[..<range.lowerBound])
185 }
186 return OrgLink(type: "file", path: OrgAttach.expand(file, in: dir), searchOption: search, raw: link.raw)
187 }
188
189 // MARK: - Searching a file
190
191 public enum SearchResult: Sendable, Equatable {
192 case found(Int)
193 case failed(String)
194 /// `/regexp/`: `org-occur`'s sparse tree for the regular expression.
195 case occur(String)
196 }
197
198 /// The regular expression of a `[[/regexp/]]` link or a `file:…::/regexp/` search.
199 public static func regexpSearch(_ link: OrgLink) -> String? {
200 let s = link.type == "fuzzy" ? link.path : link.type == "file" ? (link.searchOption ?? "") : ""
201 guard s.count >= 2, s.hasPrefix("/"), s.hasSuffix("/") else { return nil }
202 return String(s.dropFirst().dropLast())
203 }
204
205 /// `org-link-search` in an org file: a `#custom-id`, a `<<target>>`, a `#+NAME:`, or a
206 /// heading with these words (`*` asks for a heading only).
207 public static func search(_ s: String, text: String, tree: OrgTree) -> SearchResult {
208 guard s.contains(where: { !$0.isWhitespace }) else { return .failed("Invalid search string \"\(s)\"") }
209 let ns = text as NSString
210 let all = NSRange(location: 0, length: ns.length)
211 let normalized = s.replacingOccurrences(of: "\\n[ \\t]*", with: " ", options: .regularExpression)
212 let starred = normalized.hasPrefix("*")
213 let words = (starred ? String(s.dropFirst()) : s).split(whereSeparator: \.isWhitespace).map(String.init)
214 let model = DocumentModel(tree: tree)
215
216 if normalized.hasPrefix("#") {
217 let id = String(normalized.dropFirst())
218 for heading in model.headings where heading.properties.contains(where: { $0.key.uppercased() == "CUSTOM_ID" && $0.value == id }) {
219 return .found(heading.headingRange.lowerBound)
220 }
221 return .failed("No match for custom ID: \(id)")
222 }
223 if normalized.hasPrefix("("), normalized.hasSuffix(")") {
224 let name = String(normalized.dropFirst().dropLast())
225 return Coderef.search(name, text: text, tree: tree).map(SearchResult.found) ?? .failed("No match for coderef: \(name)")
226 }
227 if normalized.count >= 2, normalized.hasPrefix("/"), normalized.hasSuffix("/") {
228 return .occur(String(s.dropFirst().dropLast()))
229 }
230 let quoted = words.map(NSRegularExpression.escapedPattern(for:))
231 if !starred {
232 // A dedicated target, not part of a radio target.
233 let target = try! NSRegularExpression(pattern: "(?<!<)<<" + quoted.joined(separator: "(?:[ \\t\\n]+)") + ">>(?!>)", options: .caseInsensitive)
234 if let m = target.firstMatch(in: text, range: all) { return .found(m.range.location) }
235 let name = try! NSRegularExpression(pattern: "^[ \\t]*#\\+NAME: +" + quoted.joined(separator: "[ \\t]+") + "[ \\t]*$", options: [.anchorsMatchLines, .caseInsensitive])
236 if let m = name.firstMatch(in: text, range: all) { return .found(ns.lineRange(for: m.range).location) }
237 }
238 let upper = words.map { $0.uppercased() }
239 for heading in model.headings {
240 let title = normalizedTitle(heading.title)
241 if title.split(whereSeparator: \.isWhitespace).map({ $0.uppercased() }) == upper {
242 return .found(heading.headingRange.lowerBound)
243 }
244 }
245 return .failed("No match for fuzzy expression: \(normalized)")
246 }
247
248 /// `org-link--normalize-string` of a heading title: statistics cookies and runs of space go.
249 static func normalizedTitle(_ title: String) -> String {
250 var t = title
251 if t == "COMMENT" { t = "" } else if t.hasPrefix("COMMENT ") { t = String(t.dropFirst(8)) }
252 t = t.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression)
253 t = t.replacingOccurrences(of: "[ \\t]+", with: " ", options: .regularExpression)
254 return t.trimmingCharacters(in: .whitespaces)
255 }
256}
257
258/// `org-open-at-point` on a link or a timestamp (C-c C-o).
259public struct OpenLinkAtPoint: OrgCommand {
260 public init() {}
261 public var id: String { "org.link.open" }
262 public var title: String { "Open Link" }
263 public func applies(in context: EditContext) -> Bool {
264 Links.link(at: context.caret, text: context.text, tree: context.tree) != nil
265 || Links.timestampDays(at: context.caret, text: context.text) != nil
266 }
267 public func run(in context: EditContext) -> CommandStep {
268 if let found = Links.link(at: context.caret, text: context.text, tree: context.tree) {
269 return .external(.openLink(found.link))
270 }
271 if let days = Links.timestampDays(at: context.caret, text: context.text) {
272 return .external(.agenda(start: days.start, days: days.count))
273 }
274 return .failed("No link to follow here")
275 }
276}
277
278extension Links {
279 /// An `elisp:` link's form evaluated in `Elisp`: `org-link--open-elisp`'s message, the
280 /// error's, or why it needs Emacs.
281 public static func evaluateElisp(_ form: String) -> String {
282 let lisp = Elisp()
283 lisp.standardTime()
284 EmacsBuffer.defineLookups(lisp)
285 lisp.unboundUnsupported = true
286 do {
287 let value = try lisp.eval(try LispReader.readFirst(form).sexp)
288 if Elisp.containsClosure(value) { return "This link uses Emacs Lisp that runs only in Emacs." }
289 return "\(form) => \(try Elisp.format([.string("%s"), value]))"
290 } catch is Elisp.Unsupported {
291 return "This link uses Emacs Lisp that runs only in Emacs."
292 } catch {
293 return "\(error)"
294 }
295 }
296}
297
298extension Links {
299 /// `org-at-date-range-p` with INACTIVE-OK: the range starting at one of the two brackets
300 /// back from `offset` that reaches it.
301 static func dateRange(at offset: Int, text ns: NSString) -> [Range<Int>?]? {
302 let stamp = "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?)[\\]>]"
303 let regex = try! NSRegularExpression(pattern: stamp + "--?-?" + stamp)
304 func char(_ i: Int) -> unichar? { i >= 0 && i < ns.length ? ns.character(at: i) : nil }
305 let brackets: Set<unichar> = [91, 60]
306 var p = offset
307 for _ in 0..<2 {
308 while let c = char(p - 1), !brackets.contains(c), c != 10, c != 13 { p -= 1 }
309 while let c = char(p - 1), brackets.contains(c) { p -= 1 }
310 if let m = regex.firstMatch(in: ns as String, options: .anchored, range: NSRange(location: p, length: ns.length - p)),
311 NSMaxRange(m.range) >= offset {
312 return (0..<m.numberOfRanges).map { i in m.range(at: i).location == NSNotFound ? nil : m.range(at: i).location..<NSMaxRange(m.range(at: i)) }
313 }
314 }
315 return nil
316 }
317
318 /// `org-follow-timestamp-link`: the agenda's first day and length for the date range or
319 /// timestamp at `offset`. Point just past a timestamp isn't on it.
320 public static func timestampDays(at offset: Int, text: String) -> (start: Int, count: Int)? {
321 let buffer = EmacsBuffer(text, point: offset)
322 func day(_ match: [Range<Int>?], _ group: Int) -> Int? {
323 guard let range = match[group] else { return nil }
324 let parts = buffer.substring(range.lowerBound, range.upperBound).prefix(10).split(separator: "-").compactMap { Int($0) }
325 return parts.count == 3 ? Days.absolute(year: parts[0], month: parts[1], day: parts[2]) : nil
326 }
327 if let range = dateRange(at: offset, text: text as NSString), let first = day(range, 1), let last = day(range, 2) {
328 return (first, last - first + 1)
329 }
330 if let (part, match) = buffer.atTimestamp(), part != .after, let first = day(match, 1) {
331 return (first, 1)
332 }
333 return nil
334 }
335}