Sources/OrgCore/Capture/RoamTarget.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgCore/Capture/RoamTarget.swift

41 lines · 2071 bytes

2 symbols in this file
 1import Foundation
 2
 3/// org-roam 2.3's capture targets (`org-roam-capture--setup-target-location`): a file that
 4/// gets an `ID` at its top when it has none, and with `file+head+olp`, the headings of the
 5/// outline path, made when missing.
 6public enum RoamTarget {
 7    /// `text` with the file's `ID` (`org-id-get-create` at the top), `properties` put after it
 8    /// as `org-entry-put` puts them, and the headings of `olp` that are missing
 9    /// (`org-roam-capture-find-or-create-olp`). The text and the file's ID.
10    public static func prepare(
11        _ text: String, properties: [(key: String, value: String)] = [], olp: [String] = [],
12        newID: () -> String = { UUID().uuidString.lowercased() }
13    ) -> (text: String, id: String) {
14        let (withID, id) = OrgAttach.ensuringID(text, at: 0, newID: newID)
15        let buffer = EmacsBuffer(withID, point: 0)
16        for property in properties { buffer.entryPut(property.key, property.value) }
17        var start = 0, end = buffer.length, level = 0
18        for title in olp {
19            buffer.point = start
20            let pattern = "^(\\*+)[ \\t]+(?:[A-Z]+[ \\t]+)?(?:\\[#.\\][ \\t]*)?" + NSRegularExpression.escapedPattern(for: title) + "(?:[ \\t]+:[\\w@#%:]+:)?[ \\t]*$"
21            var found: Int?
22            while let match = buffer.searchForward(pattern, bound: end, caseInsensitive: false) {
23                if match[1]!.count == level + 1 { found = buffer.lineStart(match[0]!.lowerBound) }
24                buffer.point = match[0]!.upperBound
25            }
26            if found == nil {
27                buffer.point = end
28                if !buffer.bolp { buffer.insert("\n") }
29                found = buffer.point
30                buffer.insert(String(repeating: "*", count: level + 1) + " " + title + "\n")
31            }
32            level += 1
33            start = found!
34            end = buffer.saveExcursion { () -> Int in
35                Capture.endOfSubtree(buffer, heading: start)
36                return buffer.point
37            }
38        }
39        return (buffer.text as String, id)
40    }
41}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form