Sources/OrgCore/Links/LinkStore.swift

345 lines · 19182 bytes

  1import Foundation
  2
  3/// An entry of `org-stored-links`.
  4public struct StoredLink: Sendable, Equatable, Codable {
  5    public let link: String
  6    public let description: String?
  7
  8    public init(link: String, description: String?) {
  9        self.link = link
 10        self.description = description
 11    }
 12
 13    /// `org-link--add-to-stored-links`: puts `link` first in `links` and says what happened.
 14    public static func add(_ link: StoredLink, to links: inout [StoredLink]) -> String {
 15        if links.first == link { return "This link has already been stored" }
 16        let moved = links.contains(link)
 17        links.removeAll { $0 == link }
 18        links.insert(link, at: 0)
 19        return (moved ? "Link moved to front: " : "Stored: ") + (link.description ?? link.link)
 20    }
 21}
 22
 23extension Links {
 24    /// `org-store-link` in an org file, with `org-link-context-for-files` t: a file link to
 25    /// `path` with a search string for the target, named element, heading or line at the
 26    /// caret (the selection when there is one). `path` is as `abbreviate-file-name` gives it.
 27    public static func store(in context: EditContext, path: String) -> StoredLink {
 28        let link = "file:" + path
 29        guard let target = targetAtCaret(context) else {
 30            guard let (search, description, _) = preciseTarget(context) else { return StoredLink(link: link, description: nil) }
 31            return StoredLink(link: link + "::" + search, description: description.map(displayFormat))
 32        }
 33        return StoredLink(link: link + "::" + target, description: nil)
 34    }
 35
 36    /// `org-id-store-link` after `org-id-get-create`: an `id:` link to the entry at the caret,
 37    /// described by its title, or before the first heading by `#+TITLE` or the file name.
 38    public static func storeID(in context: EditContext, fileName: String) -> StoredLink? {
 39        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
 40        buffer.backToHeadingOrPointMin()
 41        guard let id = buffer.entryID() else { return nil }
 42        let link = "id:" + id
 43        // With `org-id-link-use-context`, a target after the entry's start narrows the link.
 44        if let (search, description, position) = preciseTarget(context), position > buffer.point {
 45            return StoredLink(link: link + "::" + search, description: description)
 46        }
 47        if buffer.beforeFirstHeading { return StoredLink(link: link, description: buffer.keyword("TITLE") ?? fileName) }
 48        guard let match = buffer.lookingAt(buffer.complexHeadingPattern), let all = match[0] else { return StoredLink(link: link, description: link) }
 49        let title = match[4] ?? all
 50        return StoredLink(link: link, description: buffer.substring(title.lowerBound, title.upperBound))
 51    }
 52
 53    /// `denote-link-ol-store` with `denote-org-store-link-to-heading` nil: a `denote:` link to
 54    /// the note at `path`, to the entry at the caret when it has a CUSTOM_ID, described by the
 55    /// note's title. Nil when the file name has no identifier.
 56    public static func storeDenote(in context: EditContext, path: String) -> StoredLink? {
 57        guard let id = Denote.identifier(ofFile: path) else { return nil }
 58        let title = Denote.frontMatter(of: context.text).title ?? Denote.name(ofFile: path).title?.replacingOccurrences(of: "-", with: " ") ?? ""
 59        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
 60        buffer.backToHeadingOrPointMin()
 61        let custom = buffer.beforeFirstHeading ? nil : buffer.entryProperty("CUSTOM_ID")
 62        return StoredLink(link: "denote:" + id + (custom.map { "::#" + $0 } ?? ""), description: title)
 63    }
 64
 65    /// A `<<target>>` on the caret's line that the caret touches, as `org-in-regexp` finds it.
 66    static func targetAtCaret(_ context: EditContext) -> String? {
 67        let ns = context.text as NSString
 68        let line = ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0))
 69        var end = NSMaxRange(line)
 70        if end > line.location, ns.character(at: end - 1) == 10 { end -= 1 }
 71        let regex = try! NSRegularExpression(pattern: "[^<]<<([^<>]+)>>[^>]")
 72        var from = line.location
 73        while from < end, let m = regex.firstMatch(in: context.text, range: NSRange(from..<end)), m.range.location <= context.caret {
 74            if NSMaxRange(m.range) >= context.caret { return ns.substring(with: m.range(at: 1)) }
 75            from = m.range.location + 1
 76        }
 77        return nil
 78    }
 79
 80    /// `org-link-precise-link-target`: the search string and description for the caret, and
 81    /// where the search matches.
 82    static func preciseTarget(_ context: EditContext) -> (String, String?, Int)? {
 83        let ns = context.text as NSString
 84        let result: (String, String?, Int)
 85        if let range = context.selection.first, !range.isEmpty {
 86            result = (normalize(ns.substring(with: NSRange(range)), context: true), nil, range.lowerBound)
 87        } else if let (name, start) = namedElement(at: context.caret, in: context.tree) {
 88            result = (name, name, start)
 89        } else if let heading = DocumentModel(tree: context.tree).headings.last(where: { $0.headingRange.lowerBound <= context.caret }) {
 90            let title = normalizedTitle(heading.title)
 91            let customID = heading.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value
 92            result = (customID.map { "#" + $0 } ?? "*" + title, title, heading.headingRange.lowerBound)
 93        } else {
 94            let line = ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0))
 95            result = (normalize(ns.substring(with: line).trimmingCharacters(in: .newlines), context: true), nil, line.location)
 96        }
 97        return result.0.contains(where: { !$0.isWhitespace }) ? result : nil
 98    }
 99
100    /// The `#+NAME` of the element at `offset`, and where the element starts (its first
101    /// affiliated keyword).
102    static func namedElement(at offset: Int, in tree: OrgTree) -> (String, Int)? {
103        let containers: Set<SyntaxKind> = [.document, .zerothSection, .section, .plainList, .item, .drawer, .footnoteDefinition]
104        var node = tree.root
105        while true {
106            let children = node.children
107            guard let index = children.firstIndex(where: { $0.range.contains(offset) || ($0.range.upperBound == offset && offset == tree.root.range.upperBound) }) else { return nil }
108            var element = index
109            while element < children.count, children[element].kind == .affiliatedKeyword { element += 1 }
110            if element > index, element == children.count || children[element - 1].range.upperBound != children[element].range.lowerBound { return nil }
111            if element == index, containers.contains(children[index].kind) {
112                node = children[index]
113                continue
114            }
115            var first = element
116            while first > 0, children[first - 1].kind == .affiliatedKeyword, children[first - 1].range.upperBound == children[first].range.lowerBound { first -= 1 }
117            for keyword in children[first..<element].reversed() {
118                if let range = keyword.text.range(of: "^[ \\t]*#\\+NAME:[ \\t]*(.*?)[ \\t]*\\n?$", options: [.regularExpression, .caseInsensitive]) {
119                    let value = keyword.text[range].replacingOccurrences(of: "^[ \\t]*#\\+[Nn][Aa][Mm][Ee]:[ \\t]*|[ \\t]*\\n?$", with: "", options: .regularExpression)
120                    if !value.isEmpty { return (value, children[first].range.lowerBound) }
121                }
122            }
123            return nil
124        }
125    }
126
127    /// `org-link--normalize-string`: statistics cookies and runs of blanks become one space;
128    /// with `context`, enclosing parentheses and leading `#` and `*` go too.
129    static func normalize(_ s: String, context: Bool) -> String {
130        var t = s.replacingOccurrences(of: "\\[[0-9]*(%|/[0-9]*)\\]", with: " ", options: .regularExpression)
131        t = t.replacingOccurrences(of: "[ \\t]+", with: " ", options: .regularExpression)
132        t = t.trimmingCharacters(in: .whitespacesAndNewlines)
133        guard context else { return t }
134        while true {
135            if t.hasPrefix("("), t.hasSuffix(")"), t.count >= 2 {
136                t = String(t.dropFirst().dropLast()).trimmingCharacters(in: .whitespacesAndNewlines)
137            } else if let range = t.range(of: "^[#*]+[ \\t]*", options: .regularExpression) {
138                t.removeSubrange(range)
139            } else {
140                return t
141            }
142        }
143    }
144
145    static let bracketLink = try! NSRegularExpression(pattern: "\\[\\[((?:[^\\]\\[\\\\]|\\\\(?:\\\\\\\\)*[\\]\\[]|\\\\+[^\\]\\[])+)\\](?:\\[((?:.|\\n)+?)\\])?\\]")
146
147    /// `org-link-display-format`: bracket links become their descriptions.
148    static func displayFormat(_ s: String) -> String {
149        let ns = s as NSString
150        var out = s
151        for m in bracketLink.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() {
152            let group = m.range(at: 2).location != NSNotFound ? m.range(at: 2) : m.range(at: 1)
153            out = (out as NSString).replacingCharacters(in: m.range, with: ns.substring(with: group))
154        }
155        return out
156    }
157
158    /// `org-link-escape`.
159    static func escape(_ link: String) -> String {
160        let regex = try! NSRegularExpression(pattern: "(\\\\*)([\\[\\]]|$)")
161        let ns = link as NSString
162        var out = link
163        for m in regex.matches(in: link, range: NSRange(location: 0, length: ns.length)).reversed() {
164            let run = ns.substring(with: m.range(at: 1))
165            out = (out as NSString).replacingCharacters(in: m.range(at: 1), with: run + run + (m.range(at: 2).length > 0 ? "\\" : ""))
166        }
167        return out
168    }
169
170    /// `org-link-make-string`.
171    public static func makeString(_ link: String, _ description: String?) -> String {
172        let zeroWidthSpace = "\u{200B}"
173        let description = description.flatMap { d -> String? in
174            guard d.contains(where: { !$0.isWhitespace }) else { return nil }
175            return d.trimmingCharacters(in: .whitespacesAndNewlines)
176                .replacingOccurrences(of: "\\]$", with: "]" + zeroWidthSpace, options: .regularExpression)
177                .replacingOccurrences(of: "\\]\\]", with: "]" + zeroWidthSpace + "]", options: .regularExpression)
178        }
179        return "[[" + escape(link) + "]" + (description.map { "[" + $0 + "]" } ?? "") + "]"
180    }
181
182    /// `expand-file-name` of `path` in `directory`, with `~` for `home`.
183    static func expand(_ path: String, directory: String?, home: String) -> String {
184        var p = path
185        if p == "~" || p.hasPrefix("~/") { p = home + p.dropFirst() }
186        if !p.hasPrefix("/"), let directory { p = (directory as NSString).appendingPathComponent(p) }
187        return (p as NSString).standardizingPath
188    }
189
190    /// `abbreviate-file-name`: `~` for the home folder.
191    public static func abbreviate(_ path: String, home: String) -> String {
192        if path == home { return "~" }
193        return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
194    }
195
196    /// `org-link-make-string-for-buffer` before its description prompt: the link a buffer
197    /// visiting `file` gets, and the description to offer.
198    static func forBuffer(_ link: String, description: String?, file: String?, home: String) -> (link: String, description: String?) {
199        var link = link
200        var description = description
201        if link.hasPrefix("<"), link.hasSuffix(">"), typesPattern.firstMatch(in: String(link.dropFirst()), range: NSRange(location: 0, length: (link as NSString).length - 1)) != nil {
202            link = String(link.dropFirst().dropLast())
203        }
204        let directory = file.map { ($0 as NSString).deletingLastPathComponent }
205        if let file, let range = link.range(of: "^file:(.+?)::", options: .regularExpression) {
206            let path = String(link[range].dropFirst(5).dropLast(2))
207            if expand(path, directory: directory, home: home) == expand(file, directory: nil, home: home) {
208                link = String(link[range.upperBound...])
209            }
210        }
211        if let prefix = ["file:", "docview:"].first(where: link.hasPrefix) {
212            var rest = String(link.dropFirst(prefix.count))
213            var search: String?
214            if let range = rest.range(of: "::(.*)$", options: .regularExpression) {
215                search = String(rest[range].dropFirst(2))
216                rest.removeSubrange(range)
217            }
218            let original = rest.contains(where: { !$0.isWhitespace }) ? rest : file ?? ""
219            let expanded = expand(original, directory: directory, home: home)
220            let base = directory.map { expand($0, directory: nil, home: home) + "/" }
221            let path = base.map(expanded.hasPrefix) == true ? String(expanded.dropFirst(base!.count)) : abbreviate(expanded, home: home)
222            link = prefix + path + (search.map { "::" + $0 } ?? "")
223            if description == original { description = path }
224        }
225        return (link, description)
226    }
227}
228
229/// `org-insert-link` (C-c C-l): asks for a link, offering stored links and link types, and a
230/// description; on a link, edits it.
231public struct InsertLink: OrgCommand {
232    /// `org-stored-links`, most recent first.
233    public let stored: [StoredLink]
234    /// The file the buffer visits.
235    public let file: String?
236    public let home: String
237
238    public init(stored: [StoredLink] = [], file: String? = nil, home: String = OrgPaths.home) {
239        self.stored = stored
240        self.file = file
241        self.home = home
242    }
243
244    public var id: String { "org.link.insert" }
245    public var title: String { "Insert Link" }
246    public func applies(in context: EditContext) -> Bool { true }
247
248    public func run(in context: EditContext) -> CommandStep {
249        let ns = context.text as NSString
250        var remove: Range<Int>?
251        var description: String?
252        if let range = context.selection.first, !range.isEmpty {
253            remove = range
254            description = ns.substring(with: NSRange(range))
255        }
256        var link: String
257        if let found = Links.link(at: context.caret, text: context.text, tree: context.tree) {
258            let whole = ns.substring(with: NSRange(found.range))
259            remove = found.range
260            let initial: String
261            if whole.hasPrefix("[[") {
262                let inside = whole.dropFirst(2).dropLast(1)
263                let split = inside.range(of: "][")
264                initial = Links.unescape(String(split.map { inside[..<$0.lowerBound] } ?? inside.dropLast()))
265                description = split.map { String(inside[$0.upperBound...].dropLast()) }
266            } else {
267                initial = whole.hasPrefix("<") && whole.hasSuffix(">") ? String(whole.dropFirst().dropLast()) : whole
268            }
269            guard let answer = context.answers["link"] else { return .prompt(Prompt(key: "link", message: "Link:", initial: initial)) }
270            link = answer
271        } else {
272            let prefixes = Array(Links.abbreviations(in: context.tree.settings.setupKeywords + context.text).keys).sorted() + Links.types
273            guard let answer = context.answers["link"] else {
274                let message = stored.first.map { "Insert link (default \($0.link)):" } ?? "Insert link:"
275                let choices = stored.map(\.link) + stored.compactMap(\.description) + prefixes.map { $0 + ":" }
276                return .prompt(Prompt(key: "link", message: message, choices: choices, requireMatch: false))
277            }
278            link = answer.isEmpty ? stored.first?.link ?? "" : answer
279            guard link.contains(where: { !$0.isWhitespace }) else { return .failed("No link selected") }
280            if let byDescription = stored.last(where: { $0.description == link }) { link = byDescription.link }
281            let type = link.hasSuffix(":") ? String(link.dropLast()) : link
282            if prefixes.contains(type) {
283                guard let special = context.answers["special"] else {
284                    return .prompt(Prompt(key: "special", message: "Link (no completion support):", initial: type + ":"))
285                }
286                link = special
287            }
288            description = description ?? stored.first { $0.link == link }?.description
289        }
290        let used = link
291        let prepared = Links.forBuffer(link, description: description, file: file, home: home)
292        guard let typed = context.answers["description"] else {
293            return .prompt(Prompt(key: "description", message: "Description:", initial: prepared.description ?? ""))
294        }
295        let text = Links.makeString(prepared.link, typed)
296        let at = remove ?? context.caret..<context.caret
297        let end = at.lowerBound + (text as NSString).length
298        let effects: [Effect] = stored.contains { $0.link == used } ? [.storedLinkUsed(used)] : []
299        return .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: at, replacement: text)], selection: [end..<end], effects: effects))
300    }
301}
302
303/// `org-id-get-create`: gives the entry an `ID` property unless it has one.
304public struct CreateID: OrgCommand {
305    let newID: @Sendable () -> String
306
307    public init(newID: @escaping @Sendable () -> String = { UUID().uuidString.lowercased() }) {
308        self.newID = newID
309    }
310
311    public var id: String { "org.id.create" }
312    public var title: String { "Create ID" }
313    public func applies(in context: EditContext) -> Bool { true }
314    public func run(in context: EditContext) -> CommandStep {
315        commitBuffer(context) { buffer in
316            buffer.saveExcursion {
317                buffer.backToHeadingOrPointMin()
318                if buffer.entryID() == nil { buffer.entryPut("ID", newID()) }
319            }
320        }
321    }
322}
323
324extension EmacsBuffer {
325    /// The entry's own `ID` when it has non-blank one, from point at its heading (or the
326    /// start of the file).
327    func entryID() -> String? { entryProperty("ID") }
328
329    /// A property in the drawer of the entry at point, or before the first heading, the file's.
330    func entryProperty(_ name: String) -> String? {
331        saveExcursion {
332            if beforeFirstHeading {
333                while bolp, lookingAt("^[ \\t]*#[ \\t]") != nil || lookingAt("^[ \\t]*#$") != nil { if forwardLine(1) != 0 { break } }
334            } else {
335                forwardLine(1)
336                if lookingAt(planningPattern) != nil { forwardLine(1) }
337            }
338            guard let drawer = looking(Self.propertyDrawerPattern, caseInsensitive: true) else { return nil }
339            let body = substring(drawer[0]!.lowerBound, drawer[0]!.upperBound)
340            let key = NSRegularExpression.escapedPattern(for: name)
341            guard let range = body.range(of: "(?m)^[ \\t]*:\(key):[ \\t]+(\\S.*?)[ \\t]*$", options: [.regularExpression, .caseInsensitive]) else { return nil }
342            return body[range].replacingOccurrences(of: "^[ \\t]*:\(key):[ \\t]+|[ \\t]+$", with: "", options: [.regularExpression, .caseInsensitive])
343        }
344    }
345}