Sources/OrgCore/Links/OrgProtocol.swift
cmc org-roam: aliases, refs, excludes, chooser tags, template choice, capture buffer
ed22b081d6 2 hours ago109 lines · 6055 bytes
11 symbols in this file
1import Foundation
2
3// `org-protocol://` URLs (Org 9.8.7's org-protocol.el): `capture` and `store-link`, in the
4// new `?key=value` form and the old `:/a/b/c` form.
5
6public enum OrgProtocol {
7 public enum Request: Sendable, Equatable {
8 /// `org-protocol-capture`: the template key (nil for the template list) and the link
9 /// properties `org-link-store-props` sets (`type`, `link`, `description`,
10 /// `annotation`, `initial`), absent when nil.
11 case capture(template: String?, properties: [String: String])
12 /// `org-protocol-store-link`: the link and its title.
13 case storeLink(url: String, title: String?)
14 /// org-roam-protocol's `roam-ref`: the node with a ref, made with a ref template when
15 /// there's none.
16 case roamRef(ref: String, title: String?, body: String?, template: String?)
17 /// org-roam-protocol's `roam-node`: the node with an ID.
18 case roamNode(id: String)
19 }
20
21 public static func parse(_ url: String) -> Request? {
22 guard let protocolMatch = url.firstMatch(of: /^org-protocol:\/+/) else { return nil }
23 let rest = url[protocolMatch.range.upperBound...]
24 // org-roam-protocol's handlers take the new `?key=value` form only.
25 for name in ["roam-ref", "roam-node"] {
26 guard rest.hasPrefix(name), let separator = rest.dropFirst(name.count).firstMatch(of: /^\/*\?/) else { continue }
27 let parts = query(String(rest.dropFirst(name.count)[separator.range.upperBound...]))
28 func value(_ key: String) -> String? { parts.first { $0.0 == key }?.1 ?? nil }
29 if name == "roam-node" { return value("node").map { .roamNode(id: $0) } }
30 guard let ref = value("ref"), !ref.isEmpty else { return nil }
31 return .roamRef(ref: ref, title: value("title"), body: value("body"), template: value("template").flatMap { $0.isEmpty ? nil : $0 })
32 }
33 for name in ["store-link", "capture"] {
34 guard rest.hasPrefix(name), let separator = rest.dropFirst(name.count).firstMatch(of: /^(:\/+|\/*\?)/) else { continue }
35 let info = String(rest.dropFirst(name.count)[separator.range.upperBound...])
36 let newStyle = !separator.output.1.hasPrefix(":")
37 let parts: [(String, String?)] = newStyle ? query(info) : []
38 let old = newStyle ? [] : split(info)
39 func value(_ key: String) -> String? { parts.first { $0.0 == key }?.1 ?? nil }
40 if name == "store-link" {
41 let order = assign(old, ["url", "title"])
42 let link = newStyle ? value("url") : order["url"] ?? nil
43 return .storeLink(url: sanitize(link ?? ""), title: newStyle ? value("title") : order["title"] ?? nil)
44 }
45 var fields: [String: String?] = [:]
46 if newStyle {
47 for key in ["template", "url", "title", "body"] { fields[key] = value(key) }
48 } else {
49 fields = assign(old, old.first?.count == 1 ? ["template", "url", "title", "body"] : ["url", "title", "body"])
50 }
51 let link = (fields["url"] ?? nil).map(sanitize)
52 let title = (fields["title"] ?? nil) ?? ""
53 var properties: [String: String] = ["description": title, "initial": (fields["body"] ?? nil) ?? ""]
54 if let link {
55 properties["link"] = link
56 properties["annotation"] = Links.makeString(link, title.contains { !$0.isWhitespace } ? title : link)
57 if let type = link.firstMatch(of: /^([a-z]+):/) { properties["type"] = String(type.1) }
58 } else {
59 properties["annotation"] = title
60 }
61 return .capture(template: (fields["template"] ?? nil).flatMap { $0.isEmpty ? nil : $0 }, properties: properties)
62 }
63 return nil
64 }
65
66 /// An `org-protocol://capture?…` link, as bookmarklets build them, with every value
67 /// percent-encoded so `+`, `&` and `=` survive `parse`.
68 public static func captureURL(template: String?, url: String?, title: String, body: String) -> String {
69 let fields: [(String, String?)] = [("template", template), ("url", url), ("title", title), ("body", body)]
70 return "org-protocol://capture?" + fields.compactMap { key, value in
71 value.map { key + "=" + ($0.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? $0) }
72 }.joined(separator: "&")
73 }
74
75 /// `org-protocol-convert-query-to-plist` and `org-link-decode`: `+` is a space; a value
76 /// ends at its second `=`.
77 static func query(_ info: String) -> [(String, String?)] {
78 info.replacingOccurrences(of: "+", with: " ").components(separatedBy: "&").map { pair in
79 let c = pair.components(separatedBy: "=")
80 return (c[0], c.count > 1 ? decode(c[1]) : nil)
81 }
82 }
83
84 /// `org-protocol-split-data` with `org-protocol-data-separator`, each part decoded.
85 static func split(_ info: String) -> [String] {
86 info.split(separator: /\/+|\?/, omittingEmptySubsequences: false).map { decode(String($0)) }
87 }
88
89 /// `org-protocol-assign-parameters`: values in order, then the rest as key, value.
90 static func assign(_ data: [String], _ order: [String]) -> [String: String?] {
91 var result: [String: String?] = [:]
92 var data = data[...]
93 for key in order { result[key] = data.popFirst() }
94 while let key = data.popFirst() { result[key] = data.popFirst() }
95 return result
96 }
97
98 /// `org-link-decode`: `%XX` sequences as UTF-8.
99 static func decode(_ s: String) -> String {
100 s.removingPercentEncoding ?? s
101 }
102
103 /// `org-protocol-sanitize-uri`: `scheme:/a/b` back to `scheme://a/b`.
104 static func sanitize(_ uri: String) -> String {
105 guard uri.firstMatch(of: /^[a-z]+:\//) != nil else { return uri }
106 let parts = uri.split(separator: /\/+/, omittingEmptySubsequences: false)
107 return parts[0] + "//" + parts.dropFirst().joined(separator: "/")
108 }
109}