Commit ed22b081d6
Verified · cmc
Changed files (37)
- Sources/OrgApp/CaptureModel.swift +14 −10
- Sources/OrgApp/CommandTitles.swift +1
- Sources/OrgApp/DenoteSequenceActions.swift +1 −1
- Sources/OrgApp/EmacsImport.swift +69 −3
- Sources/OrgApp/EmacsImportSections.swift +1 −1
- Sources/OrgApp/LinkFollow.swift +11 −1
- Sources/OrgApp/RoamActions.swift +130 −62
- Sources/OrgApp/RoamCapture.swift added +189
- Sources/OrgApp/RoamNode.swift +1 −15
- Sources/OrgCore/Capture/RoamTarget.swift added +41
- Sources/OrgCore/Keymap/PresetDoom.swift +4
- Sources/OrgCore/Links/Links.swift +3 −2
- Sources/OrgCore/Links/OrgProtocol.swift +14
- Sources/OrgEditorAppKit/EditorCommands.swift +1
- Sources/OrgIndex/FileRecord.swift +14 −3
- Sources/OrgIndex/IndexStore.swift +56 −16
- Sources/OrgIndex/RoamProperties.swift added +86
- Sources/Orgstar/CaptureView.swift +27 −4
- Sources/Orgstar/ContentView.swift +5
- Sources/Orgstar/OrgstarApp.swift +17
- Sources/OrgstarMobile/CaptureScreen.swift +10 −3
- Sources/OrgstarMobile/EditorScreen.swift +4 −2
- Sources/OrgstarMobile/FoldersScreen.swift +2 −1
- Sources/OrgstarMobile/OrgstarMobileApp.swift +9
- Tests/OrgAppTests/DailiesTests.swift +5 −3
- Tests/OrgAppTests/EmacsImportTests.swift +33
- Tests/OrgAppTests/RoamCaptureTests.swift added +277
- Tests/OrgAppTests/RoamNodeTests.swift −13
- Tests/OrgAppTests/RoamOracleTests.swift added +222
- Tests/OrgCoreTests/OrgProtocolTests.swift +11
- docs/manual/guide/03-keys.org +2 −1
- docs/manual/guide/08-capture.org +1 −1
- docs/manual/guide/09-links.org +63 −7
- docs/manual/guide/13-configuration.org +2 −1
- docs/manual/guide/14-ios.org +1 −1
- docs/manual/guide/15-alongside-emacs.org +1 −1
- l10n/Localizable.xcstrings +70
Sources/OrgApp/CaptureModel.swift +14 −10 · view
| @@ -46,7 +46,7 @@ public enum CaptureTemplates { | ||
| 46 | 46 | var templates: [CaptureTemplate] = [] |
| 47 | 47 | var groups: [CaptureGroup] = [] |
| 48 | 48 | var problems: [String] = [] |
| 49 | for table in tables where !(table.name.isEmpty && table.values.isEmpty) { | |
| 49 | for table in tables where !(table.name.isEmpty && table.values.isEmpty) && RoamTemplate.Set(rawValue: table.name) == nil { | |
| 50 | 50 | guard table.name == "template", table.isArrayElement else { |
| 51 | 51 | problems.append("capture.toml line \(table.line): expected [[template]]") |
| 52 | 52 | continue |
| @@ -86,19 +86,23 @@ public enum CaptureTemplates { | ||
| 86 | 86 | } else { |
| 87 | 87 | target = .file(file) |
| 88 | 88 | } |
| 89 | func flag(_ name: String) -> Bool { values[name]?.bool ?? false } | |
| 90 | func lines(_ name: String) -> Int? { values[name]?.integer } | |
| 91 | let options = CaptureTemplate.Options( | |
| 92 | prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"), | |
| 93 | emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"), | |
| 94 | jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"), | |
| 95 | tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote") | |
| 96 | ) | |
| 97 | templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options)) | |
| 89 | templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options(values))) | |
| 98 | 90 | } |
| 99 | 91 | return (templates.isEmpty ? defaults : templates, templates.isEmpty ? [] : groups, problems) |
| 100 | 92 | } |
| 101 | 93 | |
| 94 | /// A table's template properties beyond the target. | |
| 95 | nonisolated static func options(_ values: [String: TOML.Value]) -> CaptureTemplate.Options { | |
| 96 | func flag(_ name: String) -> Bool { values[name]?.bool ?? false } | |
| 97 | func lines(_ name: String) -> Int? { values[name]?.integer } | |
| 98 | return CaptureTemplate.Options( | |
| 99 | prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"), | |
| 100 | emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"), | |
| 101 | jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"), | |
| 102 | tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote") | |
| 103 | ) | |
| 104 | } | |
| 105 | ||
| 102 | 106 | /// What `org-capture` lists after the keys typed so far: the groups and templates one key |
| 103 | 107 | /// longer, in the templates' order. A template with no group for its prefix is listed |
| 104 | 108 | /// too, so that it can be reached. |
Sources/OrgApp/CommandTitles.swift +1 · view
| @@ -112,6 +112,7 @@ enum CommandTitles { | ||
| 112 | 112 | String(localized: "Find Node…", comment: "Command title"), |
| 113 | 113 | String(localized: "Find Note in Silo…", comment: "Command title"), |
| 114 | 114 | String(localized: "Find Previous", comment: "Command title"), |
| 115 | String(localized: "Find Ref…", comment: "Command title"), | |
| 115 | 116 | String(localized: "Find Sequence Relatives…", comment: "Command title"), |
| 116 | 117 | String(localized: "Find and Replace", comment: "Command title"), |
| 117 | 118 | String(localized: "Footnote Action", comment: "Command title"), |
Sources/OrgApp/DenoteSequenceActions.swift +1 −1 · view
| @@ -43,7 +43,7 @@ extension RoamActions { | ||
| 43 | 43 | let known: [IndexStore.Node] |
| 44 | 44 | do { known = try nodes() } catch { return show(error.localizedDescription) } |
| 45 | 45 | createDenote(title.trimmingCharacters(in: .whitespaces), known: known, signature: signature) { choice in |
| 46 | if case .created(let path, _, _) = choice { open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) } | |
| 46 | if case .created(let path, let offset, _, _) = choice { open(path, offset) } | |
| 47 | 47 | } |
| 48 | 48 | } |
| 49 | 49 | } |
Sources/OrgApp/EmacsImport.swift +69 −3 · view
| @@ -13,6 +13,9 @@ public struct EmacsImport: Sendable { | ||
| 13 | 13 | case folder(String) |
| 14 | 14 | /// A `[[template]]` table for capture.toml. |
| 15 | 15 | case capture(key: String, toml: String) |
| 16 | /// A `[[roam-template]]`, `[[roam-dailies-template]]` or `[[roam-ref-template]]` table | |
| 17 | /// for capture.toml, by its table name. | |
| 18 | case roamTemplate(set: String, key: String, toml: String) | |
| 16 | 19 | /// A `[[bind]]` table for keymap.toml. |
| 17 | 20 | case binding(keys: String, command: String, mode: String?) |
| 18 | 21 | /// An `[org-structure-template-alist]` entry for config.toml. |
| @@ -628,15 +631,22 @@ public struct EmacsImport: Sendable { | ||
| 628 | 631 | guard let dir = value.string else { return note("not a string") } |
| 629 | 632 | add(name, .string(dir)) |
| 630 | 633 | case "org-roam-dailies-capture-templates": |
| 631 | // The first template's entry and its `(file+head NAME HEAD)` target. | |
| 632 | guard let first = value.elements?.first?.elements, first.count >= 4, let entry = first[3].string, | |
| 634 | // One template with a `(file+head NAME HEAD)` target: the settings; otherwise each | |
| 635 | // template as a table. | |
| 636 | let templates = value.elements ?? [] | |
| 637 | guard templates.count == 1, let first = templates[0].elements, first.count >= 4, let entry = first[3].string, | |
| 633 | 638 | let at = first.firstIndex(of: .symbol(":target")), at + 1 < first.count, let target = first[at + 1].elements, |
| 634 | 639 | target.count == 3, target[0].symbol == "file+head", let file = target[1].string, let head = target[2].string else { |
| 635 | return note("not a template with a (file+head NAME HEAD) target") | |
| 640 | for template in templates { roamTemplate(template, set: .dailies, variable: name, source: source, id: id) } | |
| 641 | return | |
| 636 | 642 | } |
| 637 | 643 | add("org-roam-dailies-file", .string(file)) |
| 638 | 644 | add("org-roam-dailies-head", .string(head)) |
| 639 | 645 | add("org-roam-dailies-entry", .string(entry)) |
| 646 | case "org-roam-capture-templates": | |
| 647 | for template in value.elements ?? [] { roamTemplate(template, set: .node, variable: name, source: source, id: id) } | |
| 648 | case "org-roam-capture-ref-templates": | |
| 649 | for template in value.elements ?? [] { roamTemplate(template, set: .ref, variable: name, source: source, id: id) } | |
| 640 | 650 | case "org-attach-id-dir": |
| 641 | 651 | guard let dir = value.string else { return note("not a string") } |
| 642 | 652 | add(name, .string(dir)) |
| @@ -1055,6 +1065,56 @@ public struct EmacsImport: Sendable { | ||
| 1055 | 1065 | items.append(Item(id: id(), name: "capture \"\(key)\" \(name)", summary: "capture template \"\(key)\"", source: source, change: .capture(key: key, toml: toml))) |
| 1056 | 1066 | } |
| 1057 | 1067 | |
| 1068 | /// An org-roam capture template, `(KEY NAME TYPE TEMPLATE :target TARGET …)`, as a table: | |
| 1069 | /// targets `file`, `file+head`, `file+olp` and `file+head+olp` (`:if-new` too, as org-roam | |
| 1070 | /// 2.0 named it). | |
| 1071 | mutating func roamTemplate(_ entry: Sexp, set: RoamTemplate.Set, variable: String, source: String, id: () -> Int) { | |
| 1072 | func quoted(_ s: String) -> String { UserConfig.format(.string(s)) } | |
| 1073 | guard let parts = entry.elements, parts.count >= 4, let key = parts[0].string, let type = parts[2].symbol, let template = parts[3].string else { | |
| 1074 | unsupported.append(Note(id: id(), name: variable, reason: "a template that isn't (KEY NAME TYPE \"TEMPLATE\" …)", source: source)) | |
| 1075 | return | |
| 1076 | } | |
| 1077 | let name = "\(variable) \"\(key)\"" | |
| 1078 | guard ["entry", "item", "checkitem", "plain", "table-line"].contains(type) else { | |
| 1079 | unsupported.append(Note(id: id(), name: name, reason: "\(type) templates aren't supported", source: source)) | |
| 1080 | return | |
| 1081 | } | |
| 1082 | var properties: [String: Sexp] = [:] | |
| 1083 | let rest = Array(parts.dropFirst(4)) | |
| 1084 | for i in stride(from: 0, to: rest.count - 1, by: 2) { if let name = rest[i].symbol { properties[name] = rest[i + 1] } } | |
| 1085 | var toml = "[[\(set.rawValue)]]\nkey = \(quoted(key))\nname = \(quoted(parts[1].string ?? key))\ntype = \(quoted(type))\n" | |
| 1086 | let target = (properties[":target"] ?? properties[":if-new"])?.elements ?? [] | |
| 1087 | let olp = target.last?.elements.flatMap { list in list.allSatisfy { $0.string != nil } ? list.compactMap(\.string).joined(separator: "/") : nil } | |
| 1088 | switch (target.first?.symbol, target.count) { | |
| 1089 | case ("file", 2) where target[1].string != nil: | |
| 1090 | toml += "file = \(quoted(target[1].string!))\n" | |
| 1091 | case ("file+head", 3) where target[1].string != nil && target[2].string != nil: | |
| 1092 | toml += "file = \(quoted(target[1].string!))\nhead = \(quoted(target[2].string!))\n" | |
| 1093 | case ("file+olp", 3) where target[1].string != nil && olp != nil: | |
| 1094 | toml += "file = \(quoted(target[1].string!))\nolp = \(quoted(olp!))\n" | |
| 1095 | case ("file+head+olp", 4) where target[1].string != nil && target[2].string != nil && olp != nil: | |
| 1096 | toml += "file = \(quoted(target[1].string!))\nhead = \(quoted(target[2].string!))\nolp = \(quoted(olp!))\n" | |
| 1097 | default: | |
| 1098 | let kind = target.first?.symbol.map { "target \($0) isn't supported" } ?? "no :target" | |
| 1099 | unsupported.append(Note(id: id(), name: name, reason: kind, source: source)) | |
| 1100 | return | |
| 1101 | } | |
| 1102 | for flag in ["prepend", "immediate-finish", "jump-to-captured"] { | |
| 1103 | if let value = properties[":" + flag], value.symbol != "nil" { toml += "\(flag) = true\n" } | |
| 1104 | } | |
| 1105 | for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] { | |
| 1106 | if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" } | |
| 1107 | } | |
| 1108 | // The capture window shows the template's text whether or not it's narrowed. | |
| 1109 | let known = [":target", ":if-new", ":unnarrowed", ":prepend", ":immediate-finish", ":jump-to-captured", ":empty-lines", ":empty-lines-before", ":empty-lines-after"] | |
| 1110 | let ignored = properties.keys.filter { !known.contains($0) } | |
| 1111 | if !ignored.isEmpty { | |
| 1112 | unsupported.append(Note(id: id(), name: name, reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source)) | |
| 1113 | } | |
| 1114 | toml += "template = \(quoted(template))\n" | |
| 1115 | items.append(Item(id: id(), name: name, summary: "\(set.rawValue) \"\(key)\"", source: source, change: .roamTemplate(set: set.rawValue, key: key, toml: toml))) | |
| 1116 | } | |
| 1117 | ||
| 1058 | 1118 | /// Emacs commands and the Orgstar commands that do the same. |
| 1059 | 1119 | static let commands: [String: String] = [ |
| 1060 | 1120 | "org-todo": "org.todo.cycle", "org-shiftright": "org.todo.next", "org-shiftleft": "org.todo.previous", "org-priority-up": "org.priority.up", "org-priority-down": "org.priority.down", |
| @@ -1228,6 +1288,12 @@ extension EmacsImport { | ||
| 1228 | 1288 | addedCapture += "\n" + toml |
| 1229 | 1289 | if toml.contains("\ntemplate = ") { templates += 1 } |
| 1230 | 1290 | } |
| 1291 | var roamKeys = Set((try? TOML.parse(capture))?.compactMap { table in table.values["key"]?.string.map { table.name + " " + $0 } } ?? []) | |
| 1292 | for item in items { | |
| 1293 | guard case .roamTemplate(let set, let key, let toml) = item.change, roamKeys.insert(set + " " + key).inserted else { continue } | |
| 1294 | addedCapture += "\n" + toml | |
| 1295 | templates += 1 | |
| 1296 | } | |
| 1231 | 1297 | if !addedCapture.isEmpty { |
| 1232 | 1298 | capture += (capture.isEmpty ? "# Capture templates. Imported from Emacs.\n" : "\n# Imported from Emacs.\n") + addedCapture |
| 1233 | 1299 | if !write(capture, to: captureFile) { templates = 0 } |
Sources/OrgApp/EmacsImportSections.swift +1 −1 · view
| @@ -6,7 +6,7 @@ extension EmacsImport { | ||
| 6 | 6 | [ |
| 7 | 7 | (String(localized: "Settings", bundle: .main), items.filter { if case .setting = $0.change { true } else { false } }), |
| 8 | 8 | (String(localized: "Folders", bundle: .main), folders ? items.filter { if case .folder = $0.change { true } else { false } } : []), |
| 9 | (String(localized: "Capture Templates", bundle: .main), items.filter { if case .capture = $0.change { true } else { false } }), | |
| 9 | (String(localized: "Capture Templates", bundle: .main), items.filter { if case .capture = $0.change { true } else if case .roamTemplate = $0.change { true } else { false } }), | |
| 10 | 10 | (String(localized: "Key Bindings", bundle: .main), items.filter { if case .binding = $0.change { true } else { false } }), |
| 11 | 11 | (String(localized: "Structure Templates", bundle: .main), items.filter { if case .structureTemplate = $0.change { true } else { false } }), |
| 12 | 12 | (String(localized: "Denote Templates", bundle: .main), items.filter { if case .denoteTemplate = $0.change { true } else { false } }), |
Sources/OrgApp/LinkFollow.swift +11 −1 · view
| @@ -16,7 +16,7 @@ public enum LinkFollow: Equatable, Sendable { | ||
| 16 | 16 | |
| 17 | 17 | extension DocumentSession { |
| 18 | 18 | /// Follows a link as `org-link-open` does: files open as buffers (with a `::` search), |
| 19 | /// `id:` and `denote:` links through the index, internal and radio links in the current file, | |
| 19 | /// `id:`, `roam:` and `denote:` links through the index, internal and radio links in the current file, | |
| 20 | 20 | /// `attachment:` links in their entry's attachment folder, and web and mail links go to |
| 21 | 21 | /// their apps. |
| 22 | 22 | public func follow(_ link: OrgLink, workspace: WorkspaceModel?, isText: (String) -> Bool) -> LinkFollow { |
| @@ -33,6 +33,16 @@ extension DocumentSession { | ||
| 33 | 33 | } |
| 34 | 34 | show(location) |
| 35 | 35 | return .shown |
| 36 | case "roam": | |
| 37 | // `org-roam-link-follow-link`: the node with the title or alias. | |
| 38 | guard let workspace, let nodes = try? workspace.nodes(overlay: workspace.overlay(openDocuments), denote: false) else { | |
| 39 | return .message("Can't read the index") | |
| 40 | } | |
| 41 | let matches = nodes.filter { $0.title == link.path || $0.aliases.contains(link.path) } | |
| 42 | guard let node = matches.first else { return .message("No node has the title or alias \(link.path)") } | |
| 43 | guard Set(matches.map(\.id)).count == 1 else { return .message("Multiple nodes exist with title or alias \"\(link.path)\"") } | |
| 44 | show(node.location) | |
| 45 | return .shown | |
| 36 | 46 | case "denote": |
| 37 | 47 | let paths = ((try? workspace?.index.files()) ?? []).map(\.path) |
| 38 | 48 | if let query = Denote.query(link.path) { |
Sources/OrgApp/RoamActions.swift +130 −62 · view
| @@ -24,6 +24,11 @@ public struct RoamActions { | ||
| 24 | 24 | /// In the Mac sandbox, asks for access to folders outside the sidebar's that new notes go |
| 25 | 25 | /// in. False when one is still out of reach. |
| 26 | 26 | public var reachFolders: ([String]) -> Bool = { _ in true } |
| 27 | /// Shows the capture window for an org-roam capture. Without it, the first template is | |
| 28 | /// filed at once and its file opened there. | |
| 29 | public var capture: ((RoamCapture) -> Void)? | |
| 30 | /// org-roam's capture templates, from capture.toml. | |
| 31 | public var templates: (RoamTemplate.Set) -> (templates: [RoamTemplate], problems: [String]) = { RoamTemplate.load($0) } | |
| 27 | 32 | |
| 28 | 33 | public init( |
| 29 | 34 | session: DocumentSession, roots: @escaping () -> [String], nodes: @escaping () throws -> [IndexStore.Node], show: @escaping (String) -> Void, |
| @@ -92,10 +97,12 @@ public struct RoamActions { | ||
| 92 | 97 | case "app.node.find": |
| 93 | 98 | chooseNode("Node: ") { choice in |
| 94 | 99 | switch choice { |
| 95 | case .existing(let node): open(node.location.path, node.location.start) | |
| 96 | case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) | |
| 100 | case .existing(let node, _): open(node.location.path, node.location.start) | |
| 101 | case .created(let path, let offset, _, _): open(path, offset) | |
| 97 | 102 | } |
| 98 | 103 | } |
| 104 | case "app.node.find-ref": | |
| 105 | findRef() | |
| 99 | 106 | case "app.node.silo-find", "app.node.silo-create": |
| 100 | 107 | // denote-silo: a folder of `denote-silo-directories` in place of `denote-directory`. |
| 101 | 108 | let silos = DenoteNote.silos(roots: roots()) |
| @@ -104,8 +111,8 @@ public struct RoamActions { | ||
| 104 | 111 | guard let answer, let silo = silos.first(where: { DenoteNote.abbreviated($0) == answer }) else { return } |
| 105 | 112 | let opened: (NodeChoice) -> Void = { choice in |
| 106 | 113 | switch choice { |
| 107 | case .existing(let node): open(node.location.path, node.location.start) | |
| 108 | case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) | |
| 114 | case .existing(let node, _): open(node.location.path, node.location.start) | |
| 115 | case .created(let path, _, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) | |
| 109 | 116 | } |
| 110 | 117 | } |
| 111 | 118 | guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) } |
| @@ -117,8 +124,8 @@ public struct RoamActions { | ||
| 117 | 124 | case "app.node.insert": |
| 118 | 125 | chooseNode("Node: ") { choice in |
| 119 | 126 | switch choice { |
| 120 | case .existing(let node): insertLink(linkType + node.id, node.title) | |
| 121 | case .created(_, let id, let title): insertLink(linkType + id, title) | |
| 127 | case .existing(let node, let title): insertLink(linkType + node.id, title) | |
| 128 | case .created(_, _, let id, let title): insertLink(linkType + id, title) | |
| 122 | 129 | } |
| 123 | 130 | } |
| 124 | 131 | default: |
| @@ -126,89 +133,150 @@ public struct RoamActions { | ||
| 126 | 133 | } |
| 127 | 134 | } |
| 128 | 135 | |
| 129 | /// `org-roam-dailies-goto-*`: the day's file, made if missing. | |
| 130 | func goto(_ day: Date) { | |
| 131 | guard let dailies else { return show("No folder for daily notes") } | |
| 132 | guard reachFolders([dailies.directory]) else { return } | |
| 133 | do { | |
| 134 | let (path, created) = try dailies.ensure(day) | |
| 135 | if created { refresh() } | |
| 136 | open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) | |
| 137 | } catch { | |
| 138 | show("Can't make the daily note: \(error.localizedDescription)") | |
| 136 | /// The daily-note templates: `[[roam-dailies-template]]`, or one from the | |
| 137 | /// `org-roam-dailies-…` settings; for a Denote journal, one for the day's entry. | |
| 138 | private func dailyTemplates(_ dailies: Dailies, _ day: Date) -> [RoamTemplate] { | |
| 139 | if dailies.journal != nil { | |
| 140 | return [RoamTemplate(key: "d", name: "default", kind: .entry, template: dailies.entry, file: dailies.path(for: day), head: dailies.newText(day, id: ""))] | |
| 139 | 141 | } |
| 142 | let (templates, problems) = self.templates(.dailies) | |
| 143 | if let problem = problems.first { show(problem) } | |
| 144 | return templates | |
| 140 | 145 | } |
| 141 | 146 | |
| 142 | /// `org-roam-dailies-capture-*`: the entry template filed at the end of the day's file, | |
| 143 | /// which opens with the caret at `%?`. | |
| 144 | func capture(_ day: Date) { | |
| 147 | /// `org-roam-dailies-goto-*`: the day's file, made if missing. With templates aimed at | |
| 148 | /// different files, asks which. | |
| 149 | func goto(_ day: Date) { | |
| 145 | 150 | guard let dailies else { return show("No folder for daily notes") } |
| 146 | 151 | guard reachFolders([dailies.directory]) else { return } |
| 147 | let context = CaptureContext(now: day, file: session.path ?? "", userName: NSFullUserName()) | |
| 148 | let questions = Capture.questions(dailies.entry, context: context) | |
| 149 | func ask(_ answers: [String]) { | |
| 150 | guard answers.count < questions.count else { return file(answers) } | |
| 151 | let question = questions[answers.count] | |
| 152 | self.ask(Prompt(key: "q\(answers.count)", message: question.prompt + ": ", initial: question.defaultValue, requireMatch: false)) { answer in | |
| 153 | if let answer { ask(answers + [answer]) } | |
| 152 | let templates = dailyTemplates(dailies, day) | |
| 153 | func go(_ template: RoamTemplate) { | |
| 154 | var dailies = dailies | |
| 155 | if dailies.journal == nil { | |
| 156 | dailies.file = template.file | |
| 157 | dailies.head = template.head | |
| 154 | 158 | } |
| 155 | } | |
| 156 | func file(_ answers: [String]) { | |
| 157 | 159 | do { |
| 158 | 160 | let (path, created) = try dailies.ensure(day) |
| 159 | 161 | if created { refresh() } |
| 160 | guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") } | |
| 161 | let filled: (text: String, cursor: Int) | |
| 162 | switch Capture.fill(dailies.entry, context: context, answers: answers) { | |
| 163 | case .success(let result): filled = result | |
| 164 | case .failure(.message(let message)): return show(message) | |
| 165 | } | |
| 166 | let template = CaptureTemplate(key: "d", name: "daily", target: .file(path), template: dailies.entry) | |
| 167 | switch Capture.placement(filled.text, template: template, in: text, now: day) { | |
| 168 | case .failure(.message(let message)): show(message) | |
| 169 | case .success(let placed): | |
| 170 | if case .failed(let message) = session.perform(ReplaceText(old: text, new: placed.text), path: path, at: 0, expect: nil) { return show(message) } | |
| 171 | open(path, placed.start + filled.cursor) | |
| 172 | } | |
| 162 | open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) | |
| 173 | 163 | } catch { |
| 174 | 164 | show("Can't make the daily note: \(error.localizedDescription)") |
| 175 | 165 | } |
| 176 | 166 | } |
| 177 | ask([]) | |
| 167 | guard Set(templates.map(\.file)).count > 1 else { return go(templates[0]) } | |
| 168 | chooseTemplate(templates) { go($0) } | |
| 169 | } | |
| 170 | ||
| 171 | /// `org-capture`'s template menu, for a command that files nothing. | |
| 172 | private func chooseTemplate(_ templates: [RoamTemplate], _ then: @escaping (RoamTemplate) -> Void) { | |
| 173 | let labels = templates.map { "[\($0.key)] \($0.name)" } | |
| 174 | ask(Prompt(key: "template", message: "Template: ", choices: labels)) { answer in | |
| 175 | guard let answer, let index = labels.firstIndex(of: answer) else { return } | |
| 176 | then(templates[index]) | |
| 177 | } | |
| 178 | } | |
| 179 | ||
| 180 | /// `org-roam-dailies-capture-*`: the capture window with the daily-note templates; the | |
| 181 | /// entry goes at the end of the day's file, made with its head when it's new. | |
| 182 | func capture(_ day: Date) { | |
| 183 | guard let dailies else { return show("No folder for daily notes") } | |
| 184 | guard reachFolders([dailies.directory]) else { return } | |
| 185 | start(RoamCapture(dailyTemplates(dailies, day), title: "", directory: dailies.directory, now: day, ids: dailies.journal == nil, | |
| 186 | session: session, refresh: refresh) { _, _, _ in }) | |
| 187 | } | |
| 188 | ||
| 189 | /// Shows the capture window, or without one, files the first template at once and opens | |
| 190 | /// what it filed. | |
| 191 | func start(_ roam: RoamCapture) { | |
| 192 | if let capture { return capture(roam) } | |
| 193 | switch roam.fileFirst() { | |
| 194 | case .success(let entry): open(entry.path, entry.offset) | |
| 195 | case .failure(let error): show(error.message) | |
| 196 | } | |
| 178 | 197 | } |
| 179 | 198 | |
| 180 | 199 | enum NodeChoice { |
| 181 | case existing(IndexStore.Node) | |
| 182 | case created(path: String, id: String, title: String) | |
| 200 | /// A node, by the title or alias chosen. | |
| 201 | case existing(IndexStore.Node, title: String) | |
| 202 | /// A new node, with where its text went. | |
| 203 | case created(path: String, offset: Int, id: String, title: String) | |
| 183 | 204 | } |
| 184 | 205 | |
| 185 | /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A | |
| 186 | /// title no node has makes a node with it, as org-roam's default capture template does; | |
| 187 | /// with Denote, `denote` asks for its keywords and makes the note. | |
| 206 | /// `org-roam-node-read--completions`: a candidate for each node's title and each of its | |
| 207 | /// aliases, with its file's name when names repeat, and its tags after it as Doom's | |
| 208 | /// `org-roam-node-display-template` shows them. | |
| 209 | nonisolated static func candidates(_ nodes: [IndexStore.Node]) -> [(label: String, node: IndexStore.Node, title: String)] { | |
| 210 | let names = nodes.flatMap { node in ([node.title] + node.aliases).map { (node: node, name: $0) } } | |
| 211 | let counts = Dictionary(names.map { ($0.name, 1) }, uniquingKeysWith: +) | |
| 212 | return names.map { node, name in | |
| 213 | var label = counts[name, default: 0] > 1 ? "\(name) (\((node.location.path as NSString).lastPathComponent))" : name | |
| 214 | if !node.tags.isEmpty { label += " " + node.tags.map { "#" + $0 }.joined(separator: " ") } | |
| 215 | return (label, node, name) | |
| 216 | } | |
| 217 | } | |
| 218 | ||
| 219 | /// `org-roam-node-read`: a node by its title or an alias. A title no node has goes to the | |
| 220 | /// capture window with `[[roam-template]]`'s templates, as `org-roam-capture-` does, and | |
| 221 | /// once filed makes the node; with Denote, `denote` asks for its keywords and makes the note. | |
| 188 | 222 | private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) { |
| 189 | 223 | let known: [IndexStore.Node] |
| 190 | 224 | do { known = try nodes() } catch { return show(error.localizedDescription) } |
| 191 | 225 | let all = silo.map { silo in known.filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? known |
| 192 | let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +) | |
| 193 | let labels = all.map { node in | |
| 194 | counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title | |
| 195 | } | |
| 196 | ask(Prompt(key: "node", message: message, choices: labels, requireMatch: false)) { answer in | |
| 226 | let candidates = Self.candidates(all) | |
| 227 | ask(Prompt(key: "node", message: message, choices: candidates.map(\.label), requireMatch: false)) { answer in | |
| 197 | 228 | guard let answer else { return } |
| 198 | if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) } | |
| 229 | if let chosen = candidates.first(where: { $0.label == answer }) ?? candidates.first(where: { $0.title == answer }) { | |
| 230 | return then(.existing(chosen.node, title: chosen.title)) | |
| 231 | } | |
| 199 | 232 | let title = answer.trimmingCharacters(in: .whitespaces) |
| 200 | 233 | guard !title.isEmpty else { return } |
| 201 | 234 | if denote || silo != nil { return createDenote(title, known: all, silo: silo, then) } |
| 202 | 235 | guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") } |
| 203 | 236 | guard reachFolders([folder]) else { return } |
| 204 | do { | |
| 205 | let node = try RoamNode.create(title: title, in: folder) | |
| 206 | refresh() | |
| 207 | show("Created \((node.path as NSString).lastPathComponent)") | |
| 208 | then(.created(path: node.path, id: node.id, title: title)) | |
| 209 | } catch { | |
| 210 | show("Can't make the node: \(error)") | |
| 211 | } | |
| 237 | let (templates, problems) = self.templates(.node) | |
| 238 | if let problem = problems.first { show(problem) } | |
| 239 | start(RoamCapture(templates, title: title, directory: folder, session: session, refresh: refresh) { path, offset, id in | |
| 240 | then(.created(path: path, offset: offset, id: id, title: title)) | |
| 241 | }) | |
| 242 | } | |
| 243 | } | |
| 244 | ||
| 245 | /// `org-roam-ref-find`: a node by one of its `ROAM_REFS`, shown with its title. | |
| 246 | private func findRef() { | |
| 247 | let known: [IndexStore.Node] | |
| 248 | do { known = try nodes() } catch { return show(error.localizedDescription) } | |
| 249 | let refs = known.flatMap { node in node.refs.map { (label: "\($0) \(node.title)", node: node) } } | |
| 250 | guard !refs.isEmpty else { return show("No node has refs") } | |
| 251 | ask(Prompt(key: "ref", message: "Ref: ", choices: refs.map(\.label))) { answer in | |
| 252 | guard let answer, let chosen = refs.first(where: { $0.label == answer }) else { return } | |
| 253 | open(chosen.node.location.path, chosen.node.location.start) | |
| 254 | } | |
| 255 | } | |
| 256 | ||
| 257 | /// org-roam-protocol's `roam-ref`: the node with the ref, else the capture window with | |
| 258 | /// `[[roam-ref-template]]`'s templates (only the one keyed `template` when given) for a new | |
| 259 | /// node with the ref in its `ROAM_REFS`; and `roam-node`: the node with the ID. | |
| 260 | public func follow(_ request: OrgProtocol.Request) { | |
| 261 | let known: [IndexStore.Node] | |
| 262 | do { known = try nodes() } catch { return show(error.localizedDescription) } | |
| 263 | switch request { | |
| 264 | case .roamNode(let id): | |
| 265 | guard let node = known.first(where: { $0.id == id }) else { return show("No node has the ID \(id)") } | |
| 266 | open(node.location.path, node.location.start) | |
| 267 | case .roamRef(let ref, let title, let body, let key): | |
| 268 | if let node = known.first(where: { $0.refs.contains(ref) }) { return open(node.location.path, node.location.start) } | |
| 269 | guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") } | |
| 270 | guard reachFolders([folder]) else { return } | |
| 271 | let (all, problems) = self.templates(.ref) | |
| 272 | if let problem = problems.first { show(problem) } | |
| 273 | let templates = key.map { key in all.filter { $0.key == key } } ?? all | |
| 274 | guard !templates.isEmpty else { return show("No roam-ref template \"\(key ?? "")\"") } | |
| 275 | let quoted = ref.contains(where: \.isWhitespace) ? "\"" + ref.replacingOccurrences(of: "\"", with: "\\\"") + "\"" : ref | |
| 276 | start(RoamCapture(templates, title: title ?? ref, directory: folder, fields: ["ref": ref, "body": body ?? ""], properties: [("ROAM_REFS", quoted)], | |
| 277 | session: session, refresh: refresh) { path, offset, _ in open(path, offset) }) | |
| 278 | default: | |
| 279 | break | |
| 212 | 280 | } |
| 213 | 281 | } |
| 214 | 282 | |
| @@ -254,7 +322,7 @@ public struct RoamActions { | ||
| 254 | 322 | now: answers.date ?? Date(), signature: answers.signature, template: answers.template) |
| 255 | 323 | refresh() |
| 256 | 324 | show("Created \((note.path as NSString).lastPathComponent)") |
| 257 | then(.created(path: note.path, id: note.id, title: title)) | |
| 325 | then(.created(path: note.path, offset: (session.text(of: note.path).map { ($0 as NSString).length }) ?? 0, id: note.id, title: title)) | |
| 258 | 326 | } catch { |
| 259 | 327 | show("Can't make the note: \(error)") |
| 260 | 328 | } |
Sources/OrgApp/RoamCapture.swift added +189 · view
| @@ -0,0 +1,189 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | ||
| 4 | /// An org-roam capture template, from `capture.toml`: | |
| 5 | /// | |
| 6 | /// ```toml | |
| 7 | /// [[roam-template]] # org-roam-capture-templates | |
| 8 | /// key = "d" | |
| 9 | /// name = "default" | |
| 10 | /// type = "plain" # as for [[template]]; plain unless set | |
| 11 | /// template = "%?" | |
| 12 | /// file = "%<%Y%m%d%H%M%S>-${slug}.org" | |
| 13 | /// head = "#+title: ${title}\n" | |
| 14 | /// olp = "Projects/Active" # file+head+olp; the headings are made when missing | |
| 15 | /// ``` | |
| 16 | /// | |
| 17 | /// `[[roam-dailies-template]]` (`org-roam-dailies-capture-templates`) is the same, an `entry` | |
| 18 | /// unless set, with `file` in the daily-notes folder; `[[roam-ref-template]]` | |
| 19 | /// (`org-roam-capture-ref-templates`) is for org-protocol's `roam-ref`. `${title}`, `${slug}` | |
| 20 | /// and `${id}` fill in the node's title, slug and ID, and for a ref, `${ref}` and `${body}`. | |
| 21 | /// The other properties of `[[template]]` apply. | |
| 22 | public struct RoamTemplate: Sendable, Equatable { | |
| 23 | public enum Set: String, Sendable { | |
| 24 | case node = "roam-template", dailies = "roam-dailies-template", ref = "roam-ref-template" | |
| 25 | } | |
| 26 | ||
| 27 | public var key: String | |
| 28 | public var name: String | |
| 29 | public var kind: CaptureTemplate.Kind | |
| 30 | public var template: String | |
| 31 | public var file: String | |
| 32 | public var head: String | |
| 33 | public var olp: [String] | |
| 34 | public var options: CaptureTemplate.Options | |
| 35 | ||
| 36 | public init(key: String, name: String, kind: CaptureTemplate.Kind, template: String, file: String, head: String, olp: [String] = [], | |
| 37 | options: CaptureTemplate.Options = CaptureTemplate.Options()) { | |
| 38 | self.key = key | |
| 39 | self.name = name | |
| 40 | self.kind = kind | |
| 41 | self.template = template | |
| 42 | self.file = file | |
| 43 | self.head = head | |
| 44 | self.olp = olp | |
| 45 | self.options = options | |
| 46 | } | |
| 47 | ||
| 48 | /// org-roam's defaults; for daily notes, the `org-roam-dailies-…` settings. | |
| 49 | public static func defaults(_ set: Set, defaults: UserDefaults = .standard) -> [RoamTemplate] { | |
| 50 | switch set { | |
| 51 | case .node: [RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "%<%Y%m%d%H%M%S>-${slug}.org", head: "#+title: ${title}\n")] | |
| 52 | case .dailies: [RoamTemplate(key: "d", name: "default", kind: .entry, template: OrgPreferences.dailiesEntry(defaults), | |
| 53 | file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults))] | |
| 54 | case .ref: [RoamTemplate(key: "r", name: "ref", kind: .plain, template: "%?", file: "${slug}.org", head: "#+title: ${title}")] | |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | /// The set's templates in `capture.toml`, or the defaults when it has none, and what was | |
| 59 | /// wrong with the tables left out. | |
| 60 | public static func load(_ set: Set, userFile: URL = UserConfig.file("capture.toml"), defaults: UserDefaults = .standard) -> (templates: [RoamTemplate], problems: [String]) { | |
| 61 | guard let text = try? String(contentsOf: userFile, encoding: .utf8), let tables = try? TOML.parse(text) else { return (Self.defaults(set, defaults: defaults), []) } | |
| 62 | var templates: [RoamTemplate] = [], problems: [String] = [] | |
| 63 | let fallback = Self.defaults(set, defaults: defaults)[0] | |
| 64 | for table in tables where table.name == set.rawValue { | |
| 65 | let values = table.values | |
| 66 | guard let key = values["key"]?.string, !key.isEmpty, let body = values["template"]?.string else { | |
| 67 | problems.append("capture.toml line \(table.line): a [[\(set.rawValue)]] needs key and template") | |
| 68 | continue | |
| 69 | } | |
| 70 | guard let kind = CaptureTemplate.Kind(rawValue: values["type"]?.string ?? fallback.kind.rawValue) else { | |
| 71 | problems.append("capture.toml line \(table.line): unknown type") | |
| 72 | continue | |
| 73 | } | |
| 74 | templates.append(RoamTemplate( | |
| 75 | key: key, name: values["name"]?.string ?? key, kind: kind, template: body, file: values["file"]?.string ?? fallback.file, | |
| 76 | head: values["head"]?.string ?? (values["file"] == nil ? fallback.head : ""), | |
| 77 | olp: values["olp"]?.string.map { $0.split(separator: "/").map(String.init) } ?? [], options: CaptureTemplates.options(values))) | |
| 78 | } | |
| 79 | return (templates.isEmpty ? Self.defaults(set, defaults: defaults) : templates, problems) | |
| 80 | } | |
| 81 | ||
| 82 | /// `org-roam-format-template`: `${name}` for each field there is a value for. | |
| 83 | static func fill(_ text: String, _ fields: [String: String]) -> String { | |
| 84 | text.replacing(/\$\{([^}:]+)(?::[^}]*)?\}/) { match in fields[String(match.1)] ?? String(match.0) } | |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | /// An org-roam capture (`org-roam-capture-`) waiting for the capture window: the templates to | |
| 89 | /// choose from, each aimed at its file. Filing makes the file when it's new, with the head and | |
| 90 | /// an `ID`, or gives an existing one an `ID` when it has none, then places the entry as | |
| 91 | /// `org-capture` does and calls back with the node's ID. | |
| 92 | @MainActor | |
| 93 | public final class RoamCapture: Identifiable { | |
| 94 | public let templates: [CaptureTemplate] | |
| 95 | /// The date the templates' escapes use: a daily note's day, else when capture began. | |
| 96 | public let now: Date | |
| 97 | /// Each template's head, filled in, by key. | |
| 98 | let heads: [String: String] | |
| 99 | /// Put in a new file's property drawer after the ID: a ref capture's `ROAM_REFS`. | |
| 100 | let properties: [(key: String, value: String)] | |
| 101 | let session: DocumentSession | |
| 102 | let refresh: () -> Void | |
| 103 | let filed: (_ path: String, _ offset: Int, _ id: String) -> Void | |
| 104 | /// A new file's ID. | |
| 105 | let newID: String | |
| 106 | /// Whether the file gets an `ID`; not for a Denote journal entry. | |
| 107 | let ids: Bool | |
| 108 | ||
| 109 | /// `templates` filled in for a node titled `title`, their files under `directory`. | |
| 110 | public init( | |
| 111 | _ templates: [RoamTemplate], title: String, directory: String, now: Date = Date(), fields: [String: String] = [:], | |
| 112 | properties: [(key: String, value: String)] = [], ids: Bool = true, session: DocumentSession, refresh: @escaping () -> Void, | |
| 113 | newID: String = UUID().uuidString.lowercased(), filed: @escaping (_ path: String, _ offset: Int, _ id: String) -> Void | |
| 114 | ) { | |
| 115 | let fields = ["title": title, "slug": RoamNode.slug(title), "id": newID].merging(fields) { $1 } | |
| 116 | var context = CaptureContext(now: now, userName: NSFullUserName()) | |
| 117 | context.readsTemplateFiles() | |
| 118 | var heads: [String: String] = [:] | |
| 119 | self.templates = templates.map { template in | |
| 120 | let name = Dailies.expandTime(RoamTemplate.fill(template.file, fields), now).trimmingCharacters(in: .whitespaces) | |
| 121 | let path = OrgAttach.expand(name, in: directory) | |
| 122 | let head = RoamTemplate.fill(template.head, fields) | |
| 123 | if case .success(let filled) = Capture.fill(head, context: context) { heads[template.key] = filled.text } else { heads[template.key] = Dailies.expandTime(head, now) } | |
| 124 | return CaptureTemplate(key: template.key, name: template.name, kind: template.kind, | |
| 125 | target: template.olp.isEmpty ? .file(path) : .outline(file: path, path: template.olp), | |
| 126 | template: RoamTemplate.fill(template.template, fields), options: template.options) | |
| 127 | } | |
| 128 | self.now = now | |
| 129 | self.heads = heads | |
| 130 | self.properties = properties | |
| 131 | self.session = session | |
| 132 | self.refresh = refresh | |
| 133 | self.newID = newID | |
| 134 | self.ids = ids | |
| 135 | self.filed = filed | |
| 136 | } | |
| 137 | ||
| 138 | /// The template's file: `head` filled in at the top of a new file. | |
| 139 | public func isNew(_ template: CaptureTemplate) -> Bool { | |
| 140 | !session.isOpen(template.target.file) && !FileManager.default.fileExists(atPath: template.target.file) | |
| 141 | } | |
| 142 | ||
| 143 | /// Files `text`, the capture window's text, with `template`. | |
| 144 | public func file(_ text: String, with template: CaptureTemplate) -> Result<(path: String, offset: Int), CaptureError> { | |
| 145 | let path = template.target.file | |
| 146 | var olp: [String] = [] | |
| 147 | if case .outline(_, let path) = template.target { olp = path } | |
| 148 | let created = isNew(template) | |
| 149 | let id: String | |
| 150 | if created { | |
| 151 | var head = heads[template.key] ?? "" | |
| 152 | if !head.isEmpty, !head.hasSuffix("\n") { head += "\n" } | |
| 153 | let prepared = ids ? RoamTarget.prepare(head, properties: properties, olp: olp) { newID } : (text: head, id: "") | |
| 154 | do { | |
| 155 | try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true) | |
| 156 | try Data(prepared.text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting) | |
| 157 | } catch { | |
| 158 | return .failure(CaptureError(message: "Can't make \((path as NSString).lastPathComponent): \(error.localizedDescription)")) | |
| 159 | } | |
| 160 | id = prepared.id | |
| 161 | } else { | |
| 162 | guard let text = session.text(of: path) else { return .failure(CaptureError(message: "Can't read \((path as NSString).lastPathComponent)")) } | |
| 163 | let prepared = ids ? RoamTarget.prepare(text, olp: olp) { newID } : (text: text, id: "") | |
| 164 | if prepared.text != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: prepared.text), path: path, at: 0, expect: nil) { | |
| 165 | return .failure(CaptureError(message: message)) | |
| 166 | } | |
| 167 | id = prepared.id | |
| 168 | } | |
| 169 | let placed = session.capture(text, template: template, root: nil, file: path, now: now) | |
| 170 | if case .success(let entry) = placed { | |
| 171 | if created { refresh() } | |
| 172 | filed(entry.path, entry.offset, id) | |
| 173 | } | |
| 174 | return placed | |
| 175 | } | |
| 176 | ||
| 177 | /// Files the first template's text with its questions unanswered, without the capture | |
| 178 | /// window. | |
| 179 | public func fileFirst() -> Result<(path: String, offset: Int), CaptureError> { | |
| 180 | guard let template = templates.first else { return .failure(CaptureError(message: "No template")) } | |
| 181 | var context = CaptureContext(now: now, userName: NSFullUserName()) | |
| 182 | context.readsTemplateFiles() | |
| 183 | let answers = Capture.questions(template.template, context: context).map { _ in "" } | |
| 184 | switch Capture.fill(template.template, context: context, answers: answers) { | |
| 185 | case .success(let filled): return file(filled.text, with: template) | |
| 186 | case .failure(.message(let message)): return .failure(CaptureError(message: message)) | |
| 187 | } | |
| 188 | } | |
| 189 | } | |
Sources/OrgApp/RoamNode.swift +1 −15 · view
| @@ -1,9 +1,7 @@ | ||
| 1 | 1 | import Foundation |
| 2 | 2 | import OrgCore |
| 3 | 3 | |
| 4 | /// A new org-roam node from a title, as org-roam 2.3's default capture template makes it: a file | |
| 5 | /// `%<%Y%m%d%H%M%S>-${slug}.org` in `org-roam-directory`, starting `#+title: ${title}` under | |
| 6 | /// the ID drawer. | |
| 4 | /// Where new org-roam nodes go, and their slugs. | |
| 7 | 5 | public enum RoamNode { |
| 8 | 6 | /// `org-roam-directory`: the setting, else the first folder. |
| 9 | 7 | public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? { |
| @@ -30,16 +28,4 @@ public enum RoamNode { | ||
| 30 | 28 | while out.last == "_" { out.removeLast() } |
| 31 | 29 | return out.lowercased() |
| 32 | 30 | } |
| 33 | ||
| 34 | /// Makes the node's file in `folder`. Fails rather than replace a file that's there. | |
| 35 | public static func create(title: String, in folder: String, now: Date = Date(), | |
| 36 | id: () -> String = { UUID().uuidString.lowercased() }) throws -> (path: String, id: String) { | |
| 37 | let name = Dailies.expandTime("%<%Y%m%d%H%M%S>", now) + "-" + slug(title) + ".org" | |
| 38 | let path = (folder as NSString).appendingPathComponent(name) | |
| 39 | let (text, nodeID) = OrgAttach.ensuringID("#+title: \(title)\n", at: 0, newID: id) | |
| 40 | try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) | |
| 41 | guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") } | |
| 42 | try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting) | |
| 43 | return (path, nodeID) | |
| 44 | } | |
| 45 | 31 | } |
Sources/OrgCore/Capture/RoamTarget.swift added +41 · view
| @@ -0,0 +1,41 @@ | ||
| 1 | import 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. | |
| 6 | public 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 | } | |
Sources/OrgCore/Keymap/PresetDoom.swift +4 · view
| @@ -224,6 +224,10 @@ extension KeymapPreset { | ||
| 224 | 224 | command = "app.node.find" |
| 225 | 225 | mode = "normal" |
| 226 | 226 | [[bind]] |
| 227 | keys = "SPC n r F" | |
| 228 | command = "app.node.find-ref" | |
| 229 | mode = "normal" | |
| 230 | [[bind]] | |
| 227 | 231 | keys = "SPC n r i" |
| 228 | 232 | command = "app.node.insert" |
| 229 | 233 | mode = "normal" |
Sources/OrgCore/Links/Links.swift +3 −2 · view
| @@ -22,9 +22,10 @@ public struct OrgLink: Sendable, Equatable { | ||
| 22 | 22 | } |
| 23 | 23 | |
| 24 | 24 | public enum Links { |
| 25 | /// `org-link-parameters` in Emacs with Org's default modules, org-attach's and Denote's. | |
| 25 | /// `org-link-parameters` in Emacs with Org's default modules, org-attach's, Denote's and | |
| 26 | /// org-roam's. | |
| 26 | 27 | static let types = [ |
| 27 | "attachment", "id", "denote", "eww", "rmail", "mhe", "irc", "info", "gnus", "docview", "bibtex", "bbdb", "w3m", "doi", "file+sys", "file+emacs", | |
| 28 | "attachment", "id", "denote", "roam", "eww", "rmail", "mhe", "irc", "info", "gnus", "docview", "bibtex", "bbdb", "w3m", "doi", "file+sys", "file+emacs", | |
| 28 | 29 | "shell", "news", "mailto", "https", "http", "ftp", "shortdoc", "help", "file", "elisp", |
| 29 | 30 | ] |
| 30 | 31 | |
Sources/OrgCore/Links/OrgProtocol.swift +14 · view
| @@ -11,11 +11,25 @@ public enum OrgProtocol { | ||
| 11 | 11 | case capture(template: String?, properties: [String: String]) |
| 12 | 12 | /// `org-protocol-store-link`: the link and its title. |
| 13 | 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) | |
| 14 | 19 | } |
| 15 | 20 | |
| 16 | 21 | public static func parse(_ url: String) -> Request? { |
| 17 | 22 | guard let protocolMatch = url.firstMatch(of: /^org-protocol:\/+/) else { return nil } |
| 18 | 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 | } | |
| 19 | 33 | for name in ["store-link", "capture"] { |
| 20 | 34 | guard rest.hasPrefix(name), let separator = rest.dropFirst(name.count).firstMatch(of: /^(:\/+|\/*\?)/) else { continue } |
| 21 | 35 | let info = String(rest.dropFirst(name.count)[separator.range.upperBound...]) |
Sources/OrgEditorAppKit/EditorCommands.swift +1 · view
| @@ -142,6 +142,7 @@ public enum EditorCommands { | ||
| 142 | 142 | EditorCommand(id: "app.dailies.next", title: "Next Daily Note", action: .app), |
| 143 | 143 | EditorCommand(id: "app.dailies.previous", title: "Previous Daily Note", action: .app), |
| 144 | 144 | EditorCommand(id: "app.node.find", title: "Find Node…", action: .app), |
| 145 | EditorCommand(id: "app.node.find-ref", title: "Find Ref…", action: .app), | |
| 145 | 146 | EditorCommand(id: "app.node.insert", title: "Insert Node Link…", action: .app), |
| 146 | 147 | EditorCommand(id: "app.node.graph", title: "Show Node Graph", action: .app), |
| 147 | 148 | EditorCommand(id: "app.sidebar-agenda", title: "Show Agenda or Files in Sidebar", action: .app), |
Sources/OrgIndex/FileRecord.swift +14 −3 · view
| @@ -116,6 +116,10 @@ public struct FileRecord: Sendable, Equatable { | ||
| 116 | 116 | public let title: String? |
| 117 | 117 | /// The text before the first heading, searched as the file itself. |
| 118 | 118 | public let preamble: String |
| 119 | /// `#+FILETAGS`: the file node's tags. | |
| 120 | public let fileTags: [String] | |
| 121 | /// The file's own `ROAM_ALIASES`, `ROAM_REFS` and `ROAM_EXCLUDE`, as written. | |
| 122 | public let fileRoam: RoamProperties | |
| 119 | 123 | |
| 120 | 124 | public static func hash(_ bytes: [UInt8]) -> String { |
| 121 | 125 | SHA256.hash(data: Data(bytes)).map { String(format: "%02x", $0) }.joined() |
| @@ -132,7 +136,8 @@ public struct FileRecord: Sendable, Equatable { | ||
| 132 | 136 | var resolved = settings |
| 133 | 137 | resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile) |
| 134 | 138 | self.settingsVersion = Self.settingsVersion(settings, text: source.text, setupKeywords: resolved.org.setupKeywords) |
| 135 | (headings, links, fileID, title, preamble) = kind == .conflict ? ([], [], nil, nil, "") : Self.rows(source.text, settings: resolved) | |
| 139 | (headings, links, fileID, title, preamble, fileTags, fileRoam) = kind == .conflict | |
| 140 | ? ([], [], nil, nil, "", [], RoamProperties()) : Self.rows(source.text, settings: resolved) | |
| 136 | 141 | } |
| 137 | 142 | |
| 138 | 143 | /// The settings version a file's rows are built under: the index's, with the keywords of |
| @@ -169,11 +174,14 @@ public struct FileRecord: Sendable, Equatable { | ||
| 169 | 174 | fileID = nil |
| 170 | 175 | title = nil |
| 171 | 176 | preamble = "" |
| 177 | fileTags = [] | |
| 178 | fileRoam = RoamProperties() | |
| 172 | 179 | } |
| 173 | 180 | |
| 174 | 181 | public static func unreadHash(size: Int, mtime: Double) -> String { "unread:\(size):\(mtime)" } |
| 175 | 182 | |
| 176 | static func rows(_ text: String, settings: IndexSettings) -> (headings: [HeadingRecord], links: [LinkRow], fileID: String?, title: String?, preamble: String) { | |
| 183 | static func rows(_ text: String, settings: IndexSettings) | |
| 184 | -> (headings: [HeadingRecord], links: [LinkRow], fileID: String?, title: String?, preamble: String, fileTags: [String], fileRoam: RoamProperties) { | |
| 177 | 185 | let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings.org), settings: settings.semantic) |
| 178 | 186 | let utf16 = text.utf16 |
| 179 | 187 | func slice(_ range: Range<Int>) -> String { |
| @@ -215,7 +223,10 @@ public struct FileRecord: Sendable, Equatable { | ||
| 215 | 223 | let fileID = model.property("ID", of: nil)?.value.trimmingCharacters(in: .whitespaces) |
| 216 | 224 | let zeroth = model.headings.first.map { slice(0..<$0.sectionRange.lowerBound) } ?? text |
| 217 | 225 | let titles = zeroth.matches(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) } |
| 218 | return (headings, model.links.map(linkRow), fileID?.isEmpty == false ? fileID : nil, titles.isEmpty ? nil : titles.joined(separator: " "), zeroth) | |
| 226 | let roam = RoamProperties(aliases: model.property("ROAM_ALIASES", of: nil)?.value, refs: model.property("ROAM_REFS", of: nil)?.value, | |
| 227 | exclude: model.property("ROAM_EXCLUDE", of: nil)?.value) | |
| 228 | return (headings, model.links.map(linkRow), fileID?.isEmpty == false ? fileID : nil, titles.isEmpty ? nil : titles.joined(separator: " "), zeroth, | |
| 229 | model.fileTags, roam) | |
| 219 | 230 | } |
| 220 | 231 | |
| 221 | 232 | static func linkRow(_ target: String) -> LinkRow { |
Sources/OrgIndex/IndexStore.swift +56 −16 · view
| @@ -187,6 +187,16 @@ public final class IndexStore: Sendable { | ||
| 187 | 187 | UPDATE files SET settings_version = -1; |
| 188 | 188 | """) |
| 189 | 189 | } |
| 190 | migrator.registerMigration("v5") { db in | |
| 191 | // File tags and org-roam properties, for file nodes; files are read again to fill them. | |
| 192 | try db.execute(sql: """ | |
| 193 | ALTER TABLE files ADD COLUMN tags TEXT; | |
| 194 | ALTER TABLE files ADD COLUMN roam_aliases TEXT; | |
| 195 | ALTER TABLE files ADD COLUMN roam_refs TEXT; | |
| 196 | ALTER TABLE files ADD COLUMN roam_exclude TEXT; | |
| 197 | UPDATE files SET settings_version = -1; | |
| 198 | """) | |
| 199 | } | |
| 190 | 200 | return migrator |
| 191 | 201 | } |
| 192 | 202 | |
| @@ -220,11 +230,14 @@ public final class IndexStore: Sendable { | ||
| 220 | 230 | try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [record.path]) |
| 221 | 231 | try db.execute( |
| 222 | 232 | sql: """ |
| 223 | INSERT INTO files (path, root, kind, size, mtime, hash, settings_version, parsed_at, org_id, title) | |
| 224 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| 233 | INSERT INTO files (path, root, kind, size, mtime, hash, settings_version, parsed_at, org_id, title, | |
| 234 | tags, roam_aliases, roam_refs, roam_exclude) | |
| 235 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| 225 | 236 | """, |
| 226 | 237 | arguments: [record.path, record.root, record.kind.rawValue, record.size, record.mtime, record.hash, |
| 227 | record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title] | |
| 238 | record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title, | |
| 239 | record.fileTags.isEmpty ? nil : record.fileTags.joined(separator: ":"), | |
| 240 | record.fileRoam.aliases, record.fileRoam.refs, record.fileRoam.exclude] | |
| 228 | 241 | ) |
| 229 | 242 | let fileID = db.lastInsertedRowID |
| 230 | 243 | if !record.preamble.allSatisfy(\.isWhitespace) { |
| @@ -414,29 +427,52 @@ public final class IndexStore: Sendable { | ||
| 414 | 427 | public let id: String |
| 415 | 428 | public let title: String |
| 416 | 429 | public let location: HeadingLocation |
| 430 | /// `ROAM_ALIASES`: other titles the node is found by. | |
| 431 | public var aliases: [String] = [] | |
| 432 | /// `ROAM_REFS`: links and `cite:` keys the node stands for. | |
| 433 | public var refs: [String] = [] | |
| 434 | /// A file's `#+FILETAGS`; a heading's tags, inherited ones first. | |
| 435 | public var tags: [String] = [] | |
| 417 | 436 | } |
| 418 | 437 | |
| 419 | /// Every heading and file with an ID, files first, unsaved buffers' in place of their | |
| 420 | /// files'. A file's title is its `#+TITLE`, else its name without `.org`. | |
| 438 | /// Every heading and file with an ID and without `ROAM_EXCLUDE`, files first, unsaved | |
| 439 | /// buffers' in place of their files'. A file's title is its `#+TITLE`, else its name | |
| 440 | /// without `.org`. | |
| 421 | 441 | public func nodes(overlay: [String: FileRecord] = [:]) throws -> [Node] { |
| 422 | 442 | func fileTitle(_ path: String, _ title: String?) -> String { title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension } |
| 443 | func node(_ id: String, _ title: String, _ location: HeadingLocation, _ roam: RoamProperties, _ tags: [String]) -> Node? { | |
| 444 | roam.excluded ? nil : Node(id: id, title: title, location: location, aliases: roam.aliasList, refs: roam.refList, tags: tags) | |
| 445 | } | |
| 446 | func tags(_ joined: String?) -> [String] { joined?.split(separator: ":").map(String.init) ?? [] } | |
| 423 | 447 | let indexed = try database.read { db in |
| 424 | let files = try Row.fetchAll(db, sql: "SELECT path, hash, org_id, title FROM files WHERE org_id IS NOT NULL AND kind = 'org' ORDER BY path").map { row in | |
| 425 | Node(id: row["org_id"], title: fileTitle(row["path"], row["title"]), location: .file(row["path"], contentHash: row["hash"])) | |
| 448 | let files = try Row.fetchAll( | |
| 449 | db, | |
| 450 | sql: "SELECT path, hash, org_id, title, tags, roam_aliases, roam_refs, roam_exclude FROM files WHERE org_id IS NOT NULL AND kind = 'org' ORDER BY path" | |
| 451 | ).compactMap { row in | |
| 452 | node(row["org_id"], fileTitle(row["path"], row["title"]), .file(row["path"], contentHash: row["hash"]), | |
| 453 | RoamProperties(aliases: row["roam_aliases"], refs: row["roam_refs"], exclude: row["roam_exclude"]), tags(row["tags"])) | |
| 426 | 454 | } |
| 427 | 455 | let headings = try Row.fetchAll( |
| 428 | 456 | db, |
| 429 | 457 | sql: """ |
| 430 | SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.org_id | |
| 458 | SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.org_id, | |
| 459 | (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_ALIASES' AND inherited = 0) AS aliases, | |
| 460 | (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_REFS' AND inherited = 0) AS refs, | |
| 461 | (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_EXCLUDE' AND inherited = 0) AS exclude, | |
| 462 | (SELECT group_concat(tag, ':') FROM (SELECT tag FROM tags WHERE heading_id = h.id ORDER BY rowid)) AS tags | |
| 431 | 463 | FROM headings h JOIN files f ON f.id = h.file_id |
| 432 | 464 | WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal |
| 433 | 465 | """ |
| 434 | ).map { Node(id: $0["org_id"], title: $0["title"], location: location($0)) } | |
| 466 | ).compactMap { row in | |
| 467 | node(row["org_id"], row["title"], location(row), RoamProperties(aliases: row["aliases"], refs: row["refs"], exclude: row["exclude"]), tags(row["tags"])) | |
| 468 | } | |
| 435 | 469 | return files + headings |
| 436 | 470 | } |
| 437 | 471 | let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in |
| 438 | (record.fileID.map { [Node(id: $0, title: fileTitle(record.path, record.title), location: .file(record.path, contentHash: record.hash))] } ?? []) | |
| 439 | + record.headings.compactMap { heading in heading.orgID.map { Node(id: $0, title: heading.title, location: location(record, heading)) } } | |
| 472 | (record.fileID.flatMap { node($0, fileTitle(record.path, record.title), .file(record.path, contentHash: record.hash), record.fileRoam, record.fileTags) }.map { [$0] } ?? []) | |
| 473 | + record.headings.compactMap { heading in | |
| 474 | heading.orgID.flatMap { node($0, heading.title, location(record, heading), RoamProperties(heading.properties), heading.tags.map(\.name)) } | |
| 475 | } | |
| 440 | 476 | } |
| 441 | 477 | return indexed.filter { overlay[$0.location.path] == nil } + live |
| 442 | 478 | } |
| @@ -455,21 +491,25 @@ public final class IndexStore: Sendable { | ||
| 455 | 491 | return indexed.filter { overlay[$0.location.path] == nil } + live |
| 456 | 492 | } |
| 457 | 493 | |
| 458 | /// Where every heading with an ID starts and ends, subtree included, by file: the text each | |
| 459 | /// of org-roam's heading nodes covers. Unsaved buffers' in place of their files'. | |
| 494 | /// Where every heading with an ID and without `ROAM_EXCLUDE` starts and ends, subtree | |
| 495 | /// included, by file: the text each of org-roam's heading nodes covers. Unsaved buffers' in place of their files'. | |
| 460 | 496 | public func nodeSections(overlay: [String: FileRecord] = [:]) throws -> [String: [(id: String, range: Range<Int>)]] { |
| 461 | 497 | var sections: [String: [(id: String, range: Range<Int>)]] = [:] |
| 462 | 498 | try database.read { db in |
| 463 | 499 | let rows = try Row.fetchAll(db, sql: """ |
| 464 | SELECT f.path, h.org_id, h.start_offset, h.end_offset FROM headings h JOIN files f ON f.id = h.file_id | |
| 500 | SELECT f.path, h.org_id, h.start_offset, h.end_offset, | |
| 501 | (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_EXCLUDE' AND inherited = 0) AS exclude | |
| 502 | FROM headings h JOIN files f ON f.id = h.file_id | |
| 465 | 503 | WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal |
| 466 | 504 | """) |
| 467 | for row in rows where overlay[row["path"]] == nil { | |
| 505 | for row in rows where overlay[row["path"]] == nil && !RoamProperties(exclude: row["exclude"]).excluded { | |
| 468 | 506 | sections[row["path"], default: []].append((row["org_id"], (row["start_offset"] as Int)..<(row["end_offset"] as Int))) |
| 469 | 507 | } |
| 470 | 508 | } |
| 471 | 509 | for record in overlay.values { |
| 472 | sections[record.path] = record.headings.compactMap { heading in heading.orgID.map { ($0, heading.start..<heading.end) } } | |
| 510 | sections[record.path] = record.headings.compactMap { heading in | |
| 511 | RoamProperties(heading.properties).excluded ? nil : heading.orgID.map { ($0, heading.start..<heading.end) } | |
| 512 | } | |
| 473 | 513 | } |
| 474 | 514 | return sections |
| 475 | 515 | } |
Sources/OrgIndex/RoamProperties.swift added +86 · view
| @@ -0,0 +1,86 @@ | ||
| 1 | import Foundation | |
| 2 | ||
| 3 | /// A node's `ROAM_ALIASES`, `ROAM_REFS` and `ROAM_EXCLUDE` as written, read as org-roam 2.3's | |
| 4 | /// `org-roam-db-update-file` reads them. | |
| 5 | public struct RoamProperties: Sendable, Equatable { | |
| 6 | public var aliases: String? | |
| 7 | public var refs: String? | |
| 8 | public var exclude: String? | |
| 9 | ||
| 10 | public init(aliases: String? = nil, refs: String? = nil, exclude: String? = nil) { | |
| 11 | self.aliases = aliases | |
| 12 | self.refs = refs | |
| 13 | self.exclude = exclude | |
| 14 | } | |
| 15 | ||
| 16 | /// From a heading's own property rows; inherited values don't count. | |
| 17 | init(_ rows: [PropertyRow]) { | |
| 18 | func own(_ key: String) -> String? { rows.first { $0.key == key && !$0.inherited }?.value } | |
| 19 | self.init(aliases: own("ROAM_ALIASES"), refs: own("ROAM_REFS"), exclude: own("ROAM_EXCLUDE")) | |
| 20 | } | |
| 21 | ||
| 22 | /// `org-roam-db-node-p`: `(org-entry-get (point) "ROAM_EXCLUDE")` is non-nil, which any | |
| 23 | /// value but `nil` is. | |
| 24 | public var excluded: Bool { exclude.map { $0.trimmingCharacters(in: .whitespaces) != "nil" } ?? false } | |
| 25 | ||
| 26 | public var aliasList: [String] { aliases.map(Self.split) ?? [] } | |
| 27 | ||
| 28 | /// `org-roam-db-insert-refs`: `@key` and the keys of `[cite:…]` as `cite:key`, and links, | |
| 29 | /// bracketed or plain, as their targets. Anything else is skipped, as org-roam skips it | |
| 30 | /// with a warning. | |
| 31 | public var refList: [String] { | |
| 32 | var result: [String] = [] | |
| 33 | for ref in refs.map(Self.split) ?? [] { | |
| 34 | if ref.hasPrefix("@") { | |
| 35 | result.append("cite:" + ref.dropFirst()) | |
| 36 | } else if ref.hasPrefix("[cite:") { | |
| 37 | result += ref.matches(of: /@([^\s;\]]+)/).map { "cite:" + $0.1 } | |
| 38 | } else if let bracket = ref.firstMatch(of: /\[\[([^\]]+)\](?:\[[^\]]*\])?\]/) { | |
| 39 | result.append(String(bracket.1)) | |
| 40 | } else if let plain = ref.firstMatch(of: Self.plainLink) { | |
| 41 | result.append(String(plain.0)) | |
| 42 | } | |
| 43 | } | |
| 44 | return result | |
| 45 | } | |
| 46 | ||
| 47 | /// Link types `org-link-plain-re` knows without other packages loaded. | |
| 48 | nonisolated(unsafe) static let plainLink = /(?:https?|ftp|mailto|doi|file|news|shell|elisp|help|info|id|attachment|bbdb|docview|gnus|irc|rmail|w3m|eww):[^\s\[\]<>]+/ | |
| 49 | ||
| 50 | /// `split-string-and-unquote`: words separated by whitespace, a double-quoted string read as | |
| 51 | /// one, with its escapes. | |
| 52 | public static func split(_ string: String) -> [String] { | |
| 53 | var words: [String] = [] | |
| 54 | var current = "" | |
| 55 | var chars = string.makeIterator() | |
| 56 | func flush() { | |
| 57 | if !current.isEmpty { words.append(current) } | |
| 58 | current = "" | |
| 59 | } | |
| 60 | while let c = chars.next() { | |
| 61 | if c == "\"" { | |
| 62 | flush() | |
| 63 | var quoted = "" | |
| 64 | while let q = chars.next(), q != "\"" { | |
| 65 | if q == "\\", let escaped = chars.next() { | |
| 66 | switch escaped { | |
| 67 | case "n": quoted.append("\n") | |
| 68 | case "t": quoted.append("\t") | |
| 69 | case "\n": break | |
| 70 | default: quoted.append(escaped) | |
| 71 | } | |
| 72 | } else { | |
| 73 | quoted.append(q) | |
| 74 | } | |
| 75 | } | |
| 76 | words.append(quoted) | |
| 77 | } else if c.isWhitespace { | |
| 78 | flush() | |
| 79 | } else { | |
| 80 | current.append(c) | |
| 81 | } | |
| 82 | } | |
| 83 | flush() | |
| 84 | return words | |
| 85 | } | |
| 86 | } | |
Sources/Orgstar/CaptureView.swift +27 −4 · view
| @@ -33,6 +33,8 @@ struct CaptureView: View { | ||
| 33 | 33 | @State private var keys = "" |
| 34 | 34 | /// The agenda day the entry is captured for, as `Days` numbers it. |
| 35 | 35 | @State private var day: Int? |
| 36 | /// An org-roam capture: its templates in place of capture.toml's, filed through it. | |
| 37 | @State private var roam: RoamCapture? | |
| 36 | 38 | @FocusState private var focused: Bool |
| 37 | 39 | @Environment(\.dismissWindow) private var dismissWindow |
| 38 | 40 | @Environment(\.openWindow) private var openWindow |
| @@ -40,7 +42,7 @@ struct CaptureView: View { | ||
| 40 | 42 | var body: some View { |
| 41 | 43 | VStack(alignment: .leading, spacing: 12) { |
| 42 | 44 | if let template, editing { |
| 43 | Text("\(template.name) → \(Self.target(template))").font(.headline) | |
| 45 | Text("\(template.name) → \(target(template))").font(.headline) | |
| 44 | 46 | TextEditor(text: $text, selection: $selection) |
| 45 | 47 | .font(.body.monospaced()) |
| 46 | 48 | .focused($focused) |
| @@ -49,7 +51,7 @@ struct CaptureView: View { | ||
| 49 | 51 | Spacer() |
| 50 | 52 | Button("Cancel", role: .cancel) { close() } |
| 51 | 53 | .keyboardShortcut(.cancelAction) |
| 52 | if template.kind == .entry { | |
| 54 | if template.kind == .entry, roam == nil { | |
| 53 | 55 | Button("Refile…") { finish(refile: true) } |
| 54 | 56 | } |
| 55 | 57 | Button("Capture") { finish() } |
| @@ -97,7 +99,7 @@ struct CaptureView: View { | ||
| 97 | 99 | case .template(let template): |
| 98 | 100 | Text(template.name) |
| 99 | 101 | Spacer() |
| 100 | Text(Self.target(template)).foregroundStyle(.secondary).font(.caption) | |
| 102 | Text(target(template)).foregroundStyle(.secondary).font(.caption) | |
| 101 | 103 | } |
| 102 | 104 | } |
| 103 | 105 | } |
| @@ -145,6 +147,13 @@ struct CaptureView: View { | ||
| 145 | 147 | } |
| 146 | 148 | } |
| 147 | 149 | |
| 150 | /// Where the template files; for org-roam, the file's name, marked when it's new. | |
| 151 | private func target(_ template: CaptureTemplate) -> String { | |
| 152 | guard let roam else { return Self.target(template) } | |
| 153 | let name = Self.target(template) | |
| 154 | return roam.isNew(template) ? String(localized: "\(name) (new)", comment: "Capture window: an org-roam template's file that capturing makes") : name | |
| 155 | } | |
| 156 | ||
| 148 | 157 | static func target(_ template: CaptureTemplate) -> String { |
| 149 | 158 | if template.options.denote { return "a new Denote note" } |
| 150 | 159 | let file = (template.target.file as NSString).lastPathComponent |
| @@ -169,6 +178,7 @@ struct CaptureView: View { | ||
| 169 | 178 | editing = false |
| 170 | 179 | keys = "" |
| 171 | 180 | day = nil |
| 181 | roam = nil | |
| 172 | 182 | let clocked = clock.running |
| 173 | 183 | let clockFile = clocked.map { Links.abbreviate($0.path, home: OrgPaths.home) } |
| 174 | 184 | context = CaptureContext( |
| @@ -190,6 +200,16 @@ struct CaptureView: View { | ||
| 190 | 200 | private func takeRequest() { |
| 191 | 201 | guard let request = commands.captureRequest else { return } |
| 192 | 202 | commands.captureRequest = nil |
| 203 | if let roam = commands.roamCapture { | |
| 204 | commands.roamCapture = nil | |
| 205 | self.roam = roam | |
| 206 | templates = roam.templates | |
| 207 | groups = [] | |
| 208 | problem = nil | |
| 209 | context.now = roam.now | |
| 210 | if templates.count == 1 { choose(templates[0]) } | |
| 211 | return | |
| 212 | } | |
| 193 | 213 | day = request.day |
| 194 | 214 | context.initial = request.properties["initial"] ?? "" |
| 195 | 215 | context.annotation = request.properties["annotation"] ?? "" |
| @@ -254,6 +274,7 @@ struct CaptureView: View { | ||
| 254 | 274 | /// and the date tree's day. |
| 255 | 275 | private func captureDate(_ now: Date) -> Date { |
| 256 | 276 | if let treeDate { return treeDate } |
| 277 | if let roam { return roam.now } | |
| 257 | 278 | guard let day else { return now } |
| 258 | 279 | let d = Days.date(day) |
| 259 | 280 | let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now) |
| @@ -265,7 +286,9 @@ struct CaptureView: View { | ||
| 265 | 286 | let opened = context.now |
| 266 | 287 | let now = Date() |
| 267 | 288 | let placed: Result<(path: String, offset: Int), CaptureError> |
| 268 | if let denote { | |
| 289 | if let roam { | |
| 290 | placed = roam.file(text, with: template) | |
| 291 | } else if let denote { | |
| 269 | 292 | do { |
| 270 | 293 | let file = try denoteFile ?? denote.create(denoteAnswers, now: now) |
| 271 | 294 | if denoteFile == nil { Task { await workspace.refresh() } } |
Sources/Orgstar/ContentView.swift +5 · view
| @@ -954,6 +954,7 @@ struct ContentView: View { | ||
| 954 | 954 | editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end]))) |
| 955 | 955 | }, |
| 956 | 956 | refresh: { [workspace] in Task { await workspace.refresh() } }) |
| 957 | actions.capture = { [commands] in commands.capture(roam: $0) } | |
| 957 | 958 | #if APPSTORE |
| 958 | 959 | actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) } |
| 959 | 960 | #endif |
| @@ -1574,6 +1575,10 @@ struct ContentView: View { | ||
| 1574 | 1575 | case let id where id.hasPrefix("app.attach."): |
| 1575 | 1576 | guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return } |
| 1576 | 1577 | attachActions.run(id) |
| 1578 | case "app.node.protocol": | |
| 1579 | guard let request = commands.roamProtocol else { return } | |
| 1580 | commands.roamProtocol = nil | |
| 1581 | roamActions.follow(request) | |
| 1577 | 1582 | case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."): |
| 1578 | 1583 | roamActions.run(id) |
| 1579 | 1584 | default: |
Sources/Orgstar/OrgstarApp.swift +17 · view
| @@ -143,6 +143,20 @@ final class AppCommands { | ||
| 143 | 143 | var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)? |
| 144 | 144 | private var captureSerial = 0 |
| 145 | 145 | |
| 146 | /// An org-roam capture waiting for the capture window, with its templates in place of | |
| 147 | /// capture.toml's. | |
| 148 | var roamCapture: RoamCapture? | |
| 149 | /// An org-roam-protocol link waiting for the main window. | |
| 150 | var roamProtocol: OrgProtocol.Request? | |
| 151 | ||
| 152 | /// Opens the capture window on an org-roam capture. | |
| 153 | func capture(roam: RoamCapture) { | |
| 154 | captureSerial += 1 | |
| 155 | roamCapture = roam | |
| 156 | captureRequest = (nil, [:], nil, captureSerial) | |
| 157 | run("app.capture") | |
| 158 | } | |
| 159 | ||
| 146 | 160 | /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and |
| 147 | 161 | /// the entry is scheduled on it. The caller opens the capture window. |
| 148 | 162 | func capture(on day: Int) { |
| @@ -173,6 +187,9 @@ final class AppCommands { | ||
| 173 | 187 | storeLink(StoredLink(link: link, description: title)) |
| 174 | 188 | NSPasteboard.general.clearContents() |
| 175 | 189 | NSPasteboard.general.setString(link, forType: .string) |
| 190 | case .roamRef, .roamNode: | |
| 191 | roamProtocol = OrgProtocol.parse(url) | |
| 192 | run("app.node.protocol") | |
| 176 | 193 | case nil: |
| 177 | 194 | show(String(localized: "orgstar handles org-protocol capture and store-link")) |
| 178 | 195 | } |
Sources/OrgstarMobile/CaptureScreen.swift +10 −3 · view
| @@ -91,7 +91,7 @@ struct CaptureScreen: View { | ||
| 91 | 91 | .navigationBarTitleDisplayMode(.inline) |
| 92 | 92 | .toolbar { |
| 93 | 93 | ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } |
| 94 | if editing, template?.kind == .entry { | |
| 94 | if editing, template?.kind == .entry, request.roam == nil { | |
| 95 | 95 | ToolbarItem(placement: .bottomBar) { Button("Refile…") { file(refile: true) } } |
| 96 | 96 | } |
| 97 | 97 | ToolbarItem(placement: .confirmationAction) { |
| @@ -104,6 +104,11 @@ struct CaptureScreen: View { | ||
| 104 | 104 | } |
| 105 | 105 | } |
| 106 | 106 | .onAppear { |
| 107 | if let roam = request.roam { | |
| 108 | templates = roam.templates | |
| 109 | key = templates.first?.key | |
| 110 | return | |
| 111 | } | |
| 107 | 112 | let loaded = CaptureTemplates.load() |
| 108 | 113 | templates = loaded.templates |
| 109 | 114 | groups = loaded.groups |
| @@ -147,7 +152,7 @@ struct CaptureScreen: View { | ||
| 147 | 152 | static let treeQuestion = Capture.Question(prompt: "Date for tree entry", defaultValue: "", choices: [], kind: .date(withTime: false, inactive: false)) |
| 148 | 153 | |
| 149 | 154 | /// The template's date: the tree's day, the agenda day, or now. |
| 150 | private var captureDate: Date { treeDate ?? request.day.map(Self.date) ?? Date() } | |
| 155 | private var captureDate: Date { treeDate ?? request.roam?.now ?? request.day.map(Self.date) ?? Date() } | |
| 151 | 156 | |
| 152 | 157 | private func fill() { |
| 153 | 158 | guard let template else { return } |
| @@ -197,7 +202,9 @@ struct CaptureScreen: View { | ||
| 197 | 202 | guard let template else { return } |
| 198 | 203 | let now = Date() |
| 199 | 204 | let placed: Result<(path: String, offset: Int), CaptureError> |
| 200 | if let denote { | |
| 205 | if let roam = request.roam { | |
| 206 | placed = roam.file(text, with: template) | |
| 207 | } else if let denote { | |
| 201 | 208 | do { |
| 202 | 209 | let file = try denoteFile ?? denote.create(denoteAnswers, now: now) |
| 203 | 210 | if denoteFile == nil { Task { await workspace.refresh() } } |
Sources/OrgstarMobile/EditorScreen.swift +4 −2 · view
| @@ -625,7 +625,7 @@ extension EditorScreen { | ||
| 625 | 625 | |
| 626 | 626 | /// org-roam's daily notes and nodes. |
| 627 | 627 | private var roamActions: RoamActions { |
| 628 | RoamActions( | |
| 628 | var actions = RoamActions( | |
| 629 | 629 | session: session, roots: { workspace.rootPaths }, |
| 630 | 630 | nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) }, |
| 631 | 631 | show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) }, |
| @@ -642,6 +642,8 @@ extension EditorScreen { | ||
| 642 | 642 | _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end]))) |
| 643 | 643 | }, |
| 644 | 644 | refresh: { Task { await workspace.refresh() } }) |
| 645 | actions.capture = { model.captureRequest = CaptureRequest(roam: $0) } | |
| 646 | return actions | |
| 645 | 647 | } |
| 646 | 648 | |
| 647 | 649 | /// org-attach's commands for the entry at the caret. |
| @@ -1128,7 +1130,7 @@ struct CommandPalette: View { | ||
| 1128 | 1130 | ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"), |
| 1129 | 1131 | ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"), |
| 1130 | 1132 | ("app.rename-tag", "Rename Tag…"), ("app.rename-todo-keyword", "Rename TODO Keyword…"), |
| 1131 | ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"), ("app.node.graph", "Show Node Graph"), | |
| 1133 | ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.find-ref", "Find Ref…"), ("app.node.insert", "Insert Node Link…"), ("app.node.graph", "Show Node Graph"), | |
| 1132 | 1134 | ("app.node.rename-from-front-matter", "Rename Note from Front Matter"), |
| 1133 | 1135 | ("app.node.rename", "Rename Note…"), |
| 1134 | 1136 | ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"), |
Sources/OrgstarMobile/FoldersScreen.swift +2 −1 · view
| @@ -162,7 +162,8 @@ extension FoldersScreen { | ||
| 162 | 162 | /// A daily note, opened in the reader. |
| 163 | 163 | private func dailies(_ id: String) { |
| 164 | 164 | guard ProAccess.shared.allows(.roam) else { return } |
| 165 | RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { [] }, show: { workspace.lastError = $0 }, ask: { $1(nil) }, | |
| 165 | // Templates aimed at different files: the first. | |
| 166 | RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { [] }, show: { workspace.lastError = $0 }, ask: { $1($0.choices.first) }, | |
| 166 | 167 | open: { path, offset in model.openRequest = .offset(path, offset) }, insertLink: { _, _ in }, |
| 167 | 168 | refresh: { Task { await workspace.refresh() } }).run(id) |
| 168 | 169 | } |
Sources/OrgstarMobile/OrgstarMobileApp.swift +9 · view
| @@ -142,6 +142,8 @@ struct CaptureRequest: Identifiable { | ||
| 142 | 142 | var properties: [String: String] = [:] |
| 143 | 143 | /// An agenda day (a `Days` number) the entry is scheduled on. |
| 144 | 144 | var day: Int? |
| 145 | /// An org-roam capture, whose templates take the place of capture.toml's. | |
| 146 | var roam: RoamCapture? | |
| 145 | 147 | } |
| 146 | 148 | |
| 147 | 149 | extension CaptureRequest { |
| @@ -509,6 +511,13 @@ struct RootView: View { | ||
| 509 | 511 | } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) { |
| 510 | 512 | message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks) |
| 511 | 513 | UIPasteboard.general.string = link |
| 514 | } else if let request = OrgProtocol.parse(url.absoluteString), ProAccess.shared.allows(.roam) { | |
| 515 | // org-roam-protocol's `roam-ref` and `roam-node`. | |
| 516 | var actions = RoamActions(session: session, roots: { workspace.rootPaths }, nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) }, | |
| 517 | show: { message = $0 }, ask: { $1(nil) }, open: { path, offset in model.openRequest = .offset(path, offset) }, | |
| 518 | insertLink: { _, _ in }, refresh: { Task { await workspace.refresh() } }) | |
| 519 | actions.capture = { capture = CaptureRequest(roam: $0) } | |
| 520 | actions.follow(request) | |
| 512 | 521 | } else if url.scheme == "org-protocol" { |
| 513 | 522 | message = "orgstar handles org-protocol capture and store-link" |
| 514 | 523 | } |
Tests/OrgAppTests/DailiesTests.swift +5 −3 · view
| @@ -248,7 +248,7 @@ struct DailiesTests { | ||
| 248 | 248 | open: { _, _ in }, insertLink: { _, _ in }, refresh: {}) |
| 249 | 249 | actions.createDenote("Field Notes", roots: [folder.path], prompts: ["title", "signature", "subdirectory", "date", "file-type", "template", "keywords"], |
| 250 | 250 | templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in |
| 251 | if case .created(let path, _, _) = choice { created = path } | |
| 251 | if case .created(let path, _, _, _) = choice { created = path } | |
| 252 | 252 | } |
| 253 | 253 | #expect(asked == ["signature", "subdirectory", "date", "template", "keywords"]) |
| 254 | 254 | let path = try #require(created) |
| @@ -284,14 +284,16 @@ struct DailiesTests { | ||
| 284 | 284 | defer { try? FileManager.default.removeItem(at: folder) } |
| 285 | 285 | let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))) |
| 286 | 286 | var opened: (String, Int)? |
| 287 | let actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { Issue.record("\($0)") }, ask: { $1(nil) }, | |
| 287 | var actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { [] }, show: { Issue.record("\($0)") }, ask: { $1(nil) }, | |
| 288 | 288 | open: { opened = ($0, $1) }, insertLink: { _, _ in }, refresh: {}) |
| 289 | actions.templates = { (RoamTemplate.defaults($0), []) } | |
| 289 | 290 | actions.capture(Self.day) |
| 290 | 291 | let path = folder.appendingPathComponent("daily/2026-10-11.org").path |
| 291 | 292 | let text = try String(contentsOfFile: path, encoding: .utf8) |
| 292 | 293 | #expect(text.hasPrefix(":PROPERTIES:\n:ID: ")) |
| 293 | 294 | #expect(text.hasSuffix(":END:\n#+title: 2026-10-11\n* \n")) |
| 294 | #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 1) | |
| 295 | // Without a capture window, the entry is filed at once and opens where it starts. | |
| 296 | #expect(opened?.0 == path && opened?.1 == (text as NSString).length - 3) | |
| 295 | 297 | } |
| 296 | 298 | |
| 297 | 299 | /// An index that can't be read is reported, not offered as an empty list of nodes. |
Tests/OrgAppTests/EmacsImportTests.swift +33 · view
| @@ -262,6 +262,39 @@ struct EmacsImportTests { | ||
| 262 | 262 | #expect(s["org-roam-dailies-entry"] == .string("* %<%H:%M> %?")) |
| 263 | 263 | } |
| 264 | 264 | |
| 265 | /// Several daily-note templates, and org-roam's node templates, become tables in | |
| 266 | /// capture.toml beside org-capture's. | |
| 267 | @MainActor | |
| 268 | @Test func importsRoamTemplates() async throws { | |
| 269 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") | |
| 270 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) | |
| 271 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 272 | try #""" | |
| 273 | (setq org-capture-templates '(("d" "Diary" entry (file "diary.org") "* %?"))) | |
| 274 | (setq org-roam-capture-templates | |
| 275 | '(("d" "default" plain "%?" :target (file+head "%<%Y%m%d%H%M%S>-${slug}.org" "#+title: ${title}\n") :unnarrowed t) | |
| 276 | ("p" "project" entry "* ${title}" :if-new (file+head+olp "projects.org" "#+title: Projects\n" ("Active"))) | |
| 277 | ("x" "odd" plain "%?" :target (node "abc")))) | |
| 278 | (setq org-roam-dailies-capture-templates | |
| 279 | '(("d" "default" entry "* %?" :target (file+head "%<%Y-%m-%d>.org" "#+title: %<%Y-%m-%d>\n")) | |
| 280 | ("w" "work" entry "* %<%H:%M> %?" :target (file+olp "%<%Y-%m-%d>.org" ("Work")) :clock-in t))) | |
| 281 | """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8) | |
| 282 | let result = EmacsImport.scan(EmacsImport.files(in: folder)) | |
| 283 | #expect(settings(result)["org-roam-dailies-entry"] == nil) | |
| 284 | #expect(result.unsupported.map(\.name).sorted() == ["org-roam-capture-templates \"x\"", "org-roam-dailies-capture-templates \"w\""]) | |
| 285 | _ = await EmacsImport.apply(result.items, defaults: TestDefaults("orgstar-import-roam"), workspace: nil, directory: folder, writeConfig: true) | |
| 286 | let file = folder.appendingPathComponent("capture.toml") | |
| 287 | #expect(CaptureTemplates.load(userFile: file).templates.map(\.key) == ["d"]) | |
| 288 | #expect(RoamTemplate.load(.node, userFile: file).templates == [ | |
| 289 | RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "%<%Y%m%d%H%M%S>-${slug}.org", head: "#+title: ${title}\n"), | |
| 290 | RoamTemplate(key: "p", name: "project", kind: .entry, template: "* ${title}", file: "projects.org", head: "#+title: Projects\n", olp: ["Active"]), | |
| 291 | ]) | |
| 292 | #expect(RoamTemplate.load(.dailies, userFile: file).templates == [ | |
| 293 | RoamTemplate(key: "d", name: "default", kind: .entry, template: "* %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n"), | |
| 294 | RoamTemplate(key: "w", name: "work", kind: .entry, template: "* %<%H:%M> %?", file: "%<%Y-%m-%d>.org", head: "", olp: ["Work"]), | |
| 295 | ]) | |
| 296 | } | |
| 297 | ||
| 265 | 298 | @Test func readsDenote() throws { |
| 266 | 299 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") |
| 267 | 300 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
Tests/OrgAppTests/RoamCaptureTests.swift added +277 · view
| @@ -0,0 +1,277 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import OrgDocument | |
| 4 | @testable import OrgIndex | |
| 5 | import Testing | |
| 6 | @testable import OrgApp | |
| 7 | ||
| 8 | struct RoamPropertiesTests { | |
| 9 | @Test func splitsAsSplitStringAndUnquote() { | |
| 10 | #expect(RoamProperties.split(#""Alias One" two three"#) == ["Alias One", "two", "three"]) | |
| 11 | #expect(RoamProperties.split(#"a"b c"d"#) == ["a", "b c", "d"]) | |
| 12 | #expect(RoamProperties.split(#""say \"hi\"" "back\\slash""#) == [#"say "hi""#, #"back\slash"#]) | |
| 13 | #expect(RoamProperties.split(" ") == []) | |
| 14 | } | |
| 15 | ||
| 16 | @Test func readsRefsAsOrgRoamDoes() { | |
| 17 | let refs = RoamProperties(refs: #"https://example.com @key2020 [cite:@a;@b] [[https://x.org/p][Page]] junk "file:/tmp/a b.pdf""#).refList | |
| 18 | #expect(refs == ["https://example.com", "cite:key2020", "cite:a", "cite:b", "https://x.org/p", "file:/tmp/a"]) | |
| 19 | } | |
| 20 | ||
| 21 | @Test func excludeIsAnyValueButNil() { | |
| 22 | #expect(RoamProperties(exclude: "t").excluded) | |
| 23 | #expect(RoamProperties(exclude: "").excluded) | |
| 24 | #expect(!RoamProperties(exclude: "nil").excluded) | |
| 25 | #expect(!RoamProperties().excluded) | |
| 26 | } | |
| 27 | ||
| 28 | @Test func indexedNodesHaveAliasesRefsAndTagsAndLeaveExcludedOut() throws { | |
| 29 | let store = try IndexStore() | |
| 30 | let text = """ | |
| 31 | :PROPERTIES: | |
| 32 | :ID: f1 | |
| 33 | :ROAM_ALIASES: "Alias One" two | |
| 34 | :ROAM_REFS: @key | |
| 35 | :END: | |
| 36 | #+title: File One | |
| 37 | #+filetags: :alpha: | |
| 38 | * Head :beta: | |
| 39 | :PROPERTIES: | |
| 40 | :ID: h1 | |
| 41 | :ROAM_EXCLUDE: t | |
| 42 | :END: | |
| 43 | ** Child | |
| 44 | :PROPERTIES: | |
| 45 | :ID: h2 | |
| 46 | :END: | |
| 47 | ||
| 48 | """ | |
| 49 | let record = FileRecord(path: "/n/a.org", root: "/n", kind: .org, bytes: Array(text.utf8), mtime: 1, settings: IndexSettings()) | |
| 50 | try store.write(record) | |
| 51 | for nodes in [try store.nodes(), try store.nodes(overlay: ["/n/a.org": record])] { | |
| 52 | #expect(nodes.map(\.id) == ["f1", "h2"]) | |
| 53 | #expect(nodes.first?.aliases == ["Alias One", "two"]) | |
| 54 | #expect(nodes.first?.refs == ["cite:key"]) | |
| 55 | #expect(nodes.first?.tags == ["alpha"]) | |
| 56 | #expect(nodes.last?.tags == ["alpha", "beta"]) | |
| 57 | } | |
| 58 | #expect(try store.nodeSections()["/n/a.org"]?.map(\.id) == ["h2"]) | |
| 59 | } | |
| 60 | } | |
| 61 | ||
| 62 | @MainActor | |
| 63 | struct RoamCaptureTests { | |
| 64 | static var now: Date { Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 13, hour: 9, minute: 5, second: 7))! } | |
| 65 | ||
| 66 | static func folder() throws -> URL { | |
| 67 | let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath() | |
| 68 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | |
| 69 | return url | |
| 70 | } | |
| 71 | ||
| 72 | static func node(_ id: String, _ title: String, aliases: [String] = [], refs: [String] = [], tags: [String] = [], path: String? = nil) -> IndexStore.Node { | |
| 73 | IndexStore.Node(id: id, title: title, location: .file(path ?? "/n/\(id).org", contentHash: ""), aliases: aliases, refs: refs, tags: tags) | |
| 74 | } | |
| 75 | ||
| 76 | /// Actions answering each question with the next of `answers`, keeping what they did. | |
| 77 | final class Recorder { | |
| 78 | var answers: [String?] = [] | |
| 79 | var asked: [Prompt] = [] | |
| 80 | var shown: [String] = [] | |
| 81 | var opened: [(String, Int)] = [] | |
| 82 | var links: [(String, String)] = [] | |
| 83 | var captures: [RoamCapture] = [] | |
| 84 | } | |
| 85 | ||
| 86 | static func actions(_ folder: URL, nodes: [IndexStore.Node] = [], templates: [RoamTemplate.Set: [RoamTemplate]] = [:], _ recorder: Recorder) -> RoamActions { | |
| 87 | let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))) | |
| 88 | var actions = RoamActions(session: session, roots: { [folder.path] }, nodes: { nodes }, show: { recorder.shown.append($0) }, | |
| 89 | ask: { prompt, reply in | |
| 90 | recorder.asked.append(prompt) | |
| 91 | reply(recorder.answers.isEmpty ? nil : recorder.answers.removeFirst()) | |
| 92 | }, | |
| 93 | open: { recorder.opened.append(($0, $1)) }, insertLink: { recorder.links.append(($0, $1)) }, refresh: {}) | |
| 94 | actions.capture = { recorder.captures.append($0) } | |
| 95 | actions.templates = { set in (templates[set] ?? RoamTemplate.defaults(set), []) } | |
| 96 | return actions | |
| 97 | } | |
| 98 | ||
| 99 | @Test func newNodeFileFromTheDefaultTemplate() throws { | |
| 100 | let folder = try Self.folder() | |
| 101 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 102 | let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))) | |
| 103 | var filed: (String, Int, String)? | |
| 104 | let capture = RoamCapture(RoamTemplate.defaults(.node), title: "Field Notes", directory: folder.path, now: Self.now, session: session, refresh: {}, | |
| 105 | newID: "abc-123") { filed = ($0, $1, $2) } | |
| 106 | #expect(capture.templates.map(\.target) == [.file(folder.appendingPathComponent("20261013090507-field_notes.org").path)]) | |
| 107 | #expect(capture.isNew(capture.templates[0])) | |
| 108 | guard case .success(let entry) = capture.file("First line", with: capture.templates[0]) else { Issue.record("not filed"); return } | |
| 109 | let text = try String(contentsOfFile: entry.path, encoding: .utf8) | |
| 110 | #expect(text == ":PROPERTIES:\n:ID: abc-123\n:END:\n#+title: Field Notes\nFirst line\n") | |
| 111 | #expect(filed?.0 == entry.path && filed?.2 == "abc-123") | |
| 112 | } | |
| 113 | ||
| 114 | /// Find Node… with a new title shows the capture window; nothing is written until it files, | |
| 115 | /// and then the node opens. Insert Node Link… links to it only once it's filed. | |
| 116 | @Test func newNodesWaitForTheCaptureWindow() throws { | |
| 117 | let folder = try Self.folder() | |
| 118 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 119 | let recorder = Recorder() | |
| 120 | recorder.answers = ["Fresh Idea", "Fresh Idea"] | |
| 121 | let actions = Self.actions(folder, recorder) | |
| 122 | actions.run("app.node.find") | |
| 123 | #expect(recorder.captures.count == 1) | |
| 124 | #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0.hasSuffix(".org") }.isEmpty) | |
| 125 | let capture = recorder.captures[0] | |
| 126 | guard case .success(let entry) = capture.file("", with: capture.templates[0]) else { Issue.record("not filed"); return } | |
| 127 | #expect(recorder.opened.map(\.0) == [entry.path]) | |
| 128 | ||
| 129 | actions.run("app.node.insert") | |
| 130 | #expect(recorder.links.isEmpty) | |
| 131 | let second = recorder.captures[1] | |
| 132 | guard case .success = second.file("", with: second.templates[0]) else { Issue.record("not filed"); return } | |
| 133 | #expect(recorder.links.first?.1 == "Fresh Idea") | |
| 134 | #expect(recorder.links.first?.0.hasPrefix("id:") == true) | |
| 135 | } | |
| 136 | ||
| 137 | @Test func severalTemplatesAreAllOffered() throws { | |
| 138 | let folder = try Self.folder() | |
| 139 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 140 | let recorder = Recorder() | |
| 141 | recorder.answers = ["Topic"] | |
| 142 | let templates = [RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "${slug}.org", head: "#+title: ${title}\n"), | |
| 143 | RoamTemplate(key: "p", name: "person", kind: .plain, template: "* About ${title}", file: "people/${slug}.org", head: "#+title: ${title}\n")] | |
| 144 | Self.actions(folder, templates: [.node: templates], recorder).run("app.node.find") | |
| 145 | #expect(recorder.captures.first?.templates.map(\.key) == ["d", "p"]) | |
| 146 | #expect(recorder.captures.first?.templates.map(\.target.file) == [folder.path + "/topic.org", folder.path + "/people/topic.org"]) | |
| 147 | #expect(recorder.captures.first?.templates.last?.template == "* About Topic") | |
| 148 | } | |
| 149 | ||
| 150 | @Test func candidatesShowAliasesAndTags() { | |
| 151 | let nodes = [Self.node("1", "Apple", aliases: ["Malus"], tags: ["fruit", "tree"]), Self.node("2", "Pear"), Self.node("3", "Pear")] | |
| 152 | #expect(RoamActions.candidates(nodes).map(\.label) == ["Apple #fruit #tree", "Malus #fruit #tree", "Pear (2.org)", "Pear (3.org)"]) | |
| 153 | } | |
| 154 | ||
| 155 | /// An alias finds its node, and the link it inserts is described by the alias, as | |
| 156 | /// `org-roam-node-insert` does; a title typed without the tags shown still matches. | |
| 157 | @Test func aliasesFindTheirNode() throws { | |
| 158 | let folder = try Self.folder() | |
| 159 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 160 | let recorder = Recorder() | |
| 161 | recorder.answers = ["Malus #fruit", "Apple"] | |
| 162 | let actions = Self.actions(folder, nodes: [Self.node("1", "Apple", aliases: ["Malus"], tags: ["fruit"])], recorder) | |
| 163 | actions.run("app.node.insert") | |
| 164 | actions.run("app.node.find") | |
| 165 | #expect(recorder.links.map(\.1) == ["Malus"] && recorder.links.map(\.0) == ["id:1"]) | |
| 166 | #expect(recorder.opened.map(\.0) == ["/n/1.org"]) | |
| 167 | #expect(recorder.captures.isEmpty) | |
| 168 | } | |
| 169 | ||
| 170 | @Test func refsFindTheirNode() throws { | |
| 171 | let folder = try Self.folder() | |
| 172 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 173 | let recorder = Recorder() | |
| 174 | recorder.answers = ["cite:key2020 Paper"] | |
| 175 | Self.actions(folder, nodes: [Self.node("1", "Paper", refs: ["https://example.com", "cite:key2020"]), Self.node("2", "Other")], recorder).run("app.node.find-ref") | |
| 176 | #expect(recorder.asked.first?.choices == ["https://example.com Paper", "cite:key2020 Paper"]) | |
| 177 | #expect(recorder.opened.map(\.0) == ["/n/1.org"]) | |
| 178 | } | |
| 179 | ||
| 180 | /// org-protocol's `roam-ref`: the node with the ref opens; another ref makes a node with | |
| 181 | /// it in `ROAM_REFS` through the capture window. `roam-node` opens the node with the ID. | |
| 182 | @Test func protocolRefsOpenOrMakeNodes() throws { | |
| 183 | let folder = try Self.folder() | |
| 184 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 185 | let recorder = Recorder() | |
| 186 | let actions = Self.actions(folder, nodes: [Self.node("1", "Paper", refs: ["https://example.com"])], recorder) | |
| 187 | actions.follow(.roamRef(ref: "https://example.com", title: "Example", body: nil, template: nil)) | |
| 188 | actions.follow(.roamNode(id: "1")) | |
| 189 | #expect(recorder.opened.map(\.0) == ["/n/1.org", "/n/1.org"]) | |
| 190 | actions.follow(.roamRef(ref: "https://new.example/a b", title: "New Page", body: "quoted", template: nil)) | |
| 191 | let capture = try #require(recorder.captures.first) | |
| 192 | guard case .success(let entry) = capture.file("", with: capture.templates[0]) else { Issue.record("not filed"); return } | |
| 193 | let text = try String(contentsOfFile: entry.path, encoding: .utf8) | |
| 194 | #expect((entry.path as NSString).lastPathComponent == "new_page.org") | |
| 195 | #expect(text.contains(":ROAM_REFS: \"https://new.example/a b\"\n:END:\n#+title: New Page\n")) | |
| 196 | } | |
| 197 | ||
| 198 | @Test func dailyGotoAsksOnlyWhenTemplatesNameDifferentFiles() throws { | |
| 199 | let folder = try Self.folder() | |
| 200 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 201 | let same = [RoamTemplate(key: "d", name: "default", kind: .entry, template: "* %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n"), | |
| 202 | RoamTemplate(key: "t", name: "task", kind: .entry, template: "* TODO %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n")] | |
| 203 | let recorder = Recorder() | |
| 204 | Self.actions(folder, templates: [.dailies: same], recorder).goto(DailiesTests.day) | |
| 205 | #expect(recorder.asked.isEmpty && recorder.opened.map(\.0) == [folder.path + "/daily/2026-10-11.org"]) | |
| 206 | ||
| 207 | let different = [same[0], RoamTemplate(key: "w", name: "work", kind: .entry, template: "* %?", file: "work-%<%Y-%m-%d>.org", head: "#+title: Work\n")] | |
| 208 | let asking = Recorder() | |
| 209 | asking.answers = ["[w] work"] | |
| 210 | let actions = Self.actions(folder, templates: [.dailies: different], asking) | |
| 211 | actions.goto(DailiesTests.day) | |
| 212 | #expect(asking.asked.first?.choices == ["[d] default", "[w] work"]) | |
| 213 | #expect(asking.opened.map(\.0) == [folder.path + "/daily/work-2026-10-11.org"]) | |
| 214 | #expect(try String(contentsOfFile: folder.path + "/daily/work-2026-10-11.org", encoding: .utf8).hasSuffix(":END:\n#+title: Work\n")) | |
| 215 | ||
| 216 | actions.capture(DailiesTests.day) | |
| 217 | #expect(asking.captures.first?.templates.map(\.key) == ["d", "w"]) | |
| 218 | #expect(asking.captures.first?.now == DailiesTests.day) | |
| 219 | } | |
| 220 | ||
| 221 | @Test func templatesLoadFromCaptureToml() throws { | |
| 222 | let folder = try Self.folder() | |
| 223 | defer { try? FileManager.default.removeItem(at: folder) } | |
| 224 | let file = folder.appendingPathComponent("capture.toml") | |
| 225 | try #""" | |
| 226 | [[template]] | |
| 227 | key = "t" | |
| 228 | name = "Todo" | |
| 229 | file = "todo.org" | |
| 230 | template = "* TODO %?" | |
| 231 | ||
| 232 | [[roam-template]] | |
| 233 | key = "p" | |
| 234 | name = "person" | |
| 235 | template = "* Notes" | |
| 236 | file = "people/${slug}.org" | |
| 237 | head = "#+title: ${title}\n#+filetags: :person:\n" | |
| 238 | type = "entry" | |
| 239 | ||
| 240 | [[roam-template]] | |
| 241 | key = "x" | |
| 242 | ||
| 243 | [[roam-dailies-template]] | |
| 244 | key = "j" | |
| 245 | name = "journal" | |
| 246 | template = "* %<%H:%M> %?" | |
| 247 | olp = "Journal/Log" | |
| 248 | """#.write(to: file, atomically: true, encoding: .utf8) | |
| 249 | let nodes = RoamTemplate.load(.node, userFile: file) | |
| 250 | #expect(nodes.templates == [RoamTemplate(key: "p", name: "person", kind: .entry, template: "* Notes", file: "people/${slug}.org", head: "#+title: ${title}\n#+filetags: :person:\n")]) | |
| 251 | #expect(nodes.problems.count == 1) | |
| 252 | let defaults = TestDefaults("orgstar-roam-templates") | |
| 253 | let dailies = RoamTemplate.load(.dailies, userFile: file, defaults: defaults).templates | |
| 254 | #expect(dailies.map(\.olp) == [["Journal", "Log"]] && dailies.map(\.kind) == [.entry] && dailies.map(\.file) == ["%<%Y-%m-%d>.org"]) | |
| 255 | #expect(RoamTemplate.load(.ref, userFile: file).templates == RoamTemplate.defaults(.ref)) | |
| 256 | let capture = CaptureTemplates.load(userFile: file) | |
| 257 | #expect(capture.templates.map(\.key) == ["t"] && capture.problems.isEmpty) | |
| 258 | } | |
| 259 | } | |
| 260 | ||
| 261 | @MainActor | |
| 262 | struct RoamLinkTests { | |
| 263 | @Test func roamLinksFollowTitlesAndAliases() async throws { | |
| 264 | let notes = try Folder() | |
| 265 | let a = try notes.write("a.org", ":PROPERTIES:\n:ID: a1\n:ROAM_ALIASES: \"Second Name\"\n:END:\n#+title: First\n") | |
| 266 | _ = try notes.write("b.org", ":PROPERTIES:\n:ID: b1\n:END:\n#+title: Twice\n") | |
| 267 | _ = try notes.write("c.org", ":PROPERTIES:\n:ID: c1\n:END:\n#+title: Twice\n") | |
| 268 | let workspace = try WorkspaceModel(directory: nil) | |
| 269 | try await workspace.addRoot(notes.url) | |
| 270 | let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) | |
| 271 | func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) } | |
| 272 | #expect(follow("roam:Second Name") == .shown && session.path == a.path) | |
| 273 | #expect(follow("roam:First") == .shown) | |
| 274 | #expect(follow("roam:Nobody") == .message("No node has the title or alias Nobody")) | |
| 275 | #expect(follow("roam:Twice") == .message("Multiple nodes exist with title or alias \"Twice\"")) | |
| 276 | } | |
| 277 | } | |
Tests/OrgAppTests/RoamNodeTests.swift −13 · view
| @@ -29,17 +29,4 @@ struct RoamNodeTests { | ||
| 29 | 29 | let emacs = try String(contentsOf: output, encoding: .utf8).split(separator: "\n", omittingEmptySubsequences: false).map(String.init) |
| 30 | 30 | #expect(Array(emacs.prefix(titles.count)) == titles.map(RoamNode.slug)) |
| 31 | 31 | } |
| 32 | ||
| 33 | @Test func newNodeFile() throws { | |
| 34 | let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").path | |
| 35 | defer { try? FileManager.default.removeItem(atPath: folder) } | |
| 36 | let now = Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 13, hour: 9, minute: 5, second: 7))! | |
| 37 | let node = try RoamNode.create(title: "Field Notes", in: folder, now: now, id: { "abc-123" }) | |
| 38 | #expect((node.path as NSString).lastPathComponent == "20261013090507-field_notes.org") | |
| 39 | #expect(node.id == "abc-123") | |
| 40 | let text = try String(contentsOfFile: node.path, encoding: .utf8) | |
| 41 | #expect(text == ":PROPERTIES:\n:ID: abc-123\n:END:\n#+title: Field Notes\n") | |
| 42 | // The same second and title again: the file is there, so nothing is overwritten. | |
| 43 | #expect(throws: (any Error).self) { try RoamNode.create(title: "Field Notes", in: folder, now: now, id: { "other" }) } | |
| 44 | } | |
| 45 | 32 | } |
Tests/OrgAppTests/RoamOracleTests.swift added +222 · view
| @@ -0,0 +1,222 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import OrgDocument | |
| 4 | import OrgIndex | |
| 5 | import Testing | |
| 6 | @testable import OrgApp | |
| 7 | ||
| 8 | /// org-roam itself, run in Emacs, when it's installed: the load-path directories in | |
| 9 | /// `ORGSTAR_ROAM` (colon-separated), else a Doom (straight) install. | |
| 10 | enum RoamOracle { | |
| 11 | static let packages = ["org-roam", "emacsql", "magit-section", "dash", "compat", "llama", "cond-let"] | |
| 12 | ||
| 13 | static let loadPath: [String]? = { | |
| 14 | if let paths = ProcessInfo.processInfo.environment["ORGSTAR_ROAM"] { return paths.split(separator: ":").map(String.init) } | |
| 15 | let fm = FileManager.default, home = NSHomeDirectory() | |
| 16 | let roots = ["\(home)/.config/emacs/.local/straight", "\(home)/.emacs.d/.local/straight"].flatMap { root in | |
| 17 | ((try? fm.contentsOfDirectory(atPath: root)) ?? []).filter { $0.hasPrefix("build-") && !$0.hasSuffix(".el") }.sorted().reversed().map { "\(root)/\($0)" } | |
| 18 | } | |
| 19 | for root in roots { | |
| 20 | let dirs = packages.map { "\(root)/\($0)" }.filter { fm.fileExists(atPath: $0) } | |
| 21 | if dirs.first == "\(root)/org-roam", dirs.count >= 5 { return dirs } | |
| 22 | } | |
| 23 | return nil | |
| 24 | }() | |
| 25 | ||
| 26 | static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil } | |
| 27 | ||
| 28 | /// Runs `body` with org-roam loaded, `org-roam-directory` at `folder`, its database and | |
| 29 | /// `org-id-locations-file` in a folder beside it, and the database synced. | |
| 30 | static func run(_ folder: URL, _ body: String) throws -> String { | |
| 31 | let paths = loadPath!.map(\.debugDescription).joined(separator: " ") | |
| 32 | let state = folder.deletingLastPathComponent().appendingPathComponent(folder.lastPathComponent + "-state").path | |
| 33 | try FileManager.default.createDirectory(atPath: state, withIntermediateDirectories: true) | |
| 34 | return try DailiesTests.emacs(""" | |
| 35 | (progn (setq load-path (append (list \(paths)) load-path) make-backup-files nil auto-save-default nil create-lockfiles nil | |
| 36 | coding-system-for-read 'utf-8 coding-system-for-write 'utf-8 org-id-locations-file \((state + "/ids").debugDescription)) | |
| 37 | (require 'org-roam) (require 'org-roam-dailies) | |
| 38 | (setq org-roam-directory \((folder.path + "/").debugDescription) org-roam-db-location \((state + "/db.sqlite").debugDescription)) | |
| 39 | (org-roam-db-sync) | |
| 40 | \(body)) | |
| 41 | """) | |
| 42 | } | |
| 43 | ||
| 44 | static func folder() throws -> URL { | |
| 45 | let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roam-\(UUID().uuidString)").resolvingSymlinksInPath() | |
| 46 | try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | |
| 47 | return url | |
| 48 | } | |
| 49 | ||
| 50 | static func remove(_ folder: URL) { | |
| 51 | try? FileManager.default.removeItem(at: folder) | |
| 52 | try? FileManager.default.removeItem(at: folder.deletingLastPathComponent().appendingPathComponent(folder.lastPathComponent + "-state")) | |
| 53 | } | |
| 54 | ||
| 55 | /// IDs as one placeholder, since each side makes its own. | |
| 56 | static func withoutIDs(_ text: String) -> String { | |
| 57 | text.replacing(/(?m)^:ID:[ \t]+\S+$/, with: ":ID: x") | |
| 58 | } | |
| 59 | } | |
| 60 | ||
| 61 | struct RoamOracleTests { | |
| 62 | static let files: [(name: String, text: String)] = [ | |
| 63 | ("a.org", """ | |
| 64 | :PROPERTIES: | |
| 65 | :ID: f1 | |
| 66 | :ROAM_ALIASES: "Alias One" two "say \\"hi\\"" | |
| 67 | :ROAM_REFS: https://example.com @key2020 [cite:@other2021;@third] [[https://x.org/page][Page]] junk | |
| 68 | :END: | |
| 69 | #+title: File One | |
| 70 | #+filetags: :alpha:beta: | |
| 71 | * Head :gamma: | |
| 72 | :PROPERTIES: | |
| 73 | :ID: h1 | |
| 74 | :ROAM_REFS: @headkey | |
| 75 | :END: | |
| 76 | ** Deeper :delta: | |
| 77 | :PROPERTIES: | |
| 78 | :ID: h1b | |
| 79 | :ROAM_ALIASES: Deep | |
| 80 | :END: | |
| 81 | * Excl | |
| 82 | :PROPERTIES: | |
| 83 | :ID: h2 | |
| 84 | :ROAM_EXCLUDE: t | |
| 85 | :END: | |
| 86 | ** Child | |
| 87 | :PROPERTIES: | |
| 88 | :ID: h3 | |
| 89 | :END: | |
| 90 | * ExNil | |
| 91 | :PROPERTIES: | |
| 92 | :ID: h4 | |
| 93 | :ROAM_EXCLUDE: nil | |
| 94 | :END: | |
| 95 | * No ID :epsilon: | |
| 96 | ||
| 97 | """), | |
| 98 | ("b.org", """ | |
| 99 | :PROPERTIES: | |
| 100 | :ID: f2 | |
| 101 | :ROAM_EXCLUDE: t | |
| 102 | :END: | |
| 103 | #+title: Excluded file | |
| 104 | * Inside | |
| 105 | :PROPERTIES: | |
| 106 | :ID: h5 | |
| 107 | :ROAM_ALIASES: x | |
| 108 | :END: | |
| 109 | ||
| 110 | """), | |
| 111 | ("c.org", """ | |
| 112 | :PROPERTIES: | |
| 113 | :ID: f3 | |
| 114 | :END: | |
| 115 | #+title: Third | |
| 116 | * Untitled file's heading | |
| 117 | :PROPERTIES: | |
| 118 | :ID: h6 | |
| 119 | :END: | |
| 120 | ||
| 121 | """), | |
| 122 | ] | |
| 123 | ||
| 124 | /// Nodes, aliases, refs and tags as org-roam's database has them after `org-roam-db-sync`. | |
| 125 | @Test(.enabled(if: RoamOracle.enabled)) func nodesMatchOrgRoam() throws { | |
| 126 | let folder = try RoamOracle.folder() | |
| 127 | defer { RoamOracle.remove(folder) } | |
| 128 | let store = try IndexStore() | |
| 129 | for file in Self.files { | |
| 130 | let path = folder.appendingPathComponent(file.name).path | |
| 131 | try file.text.write(toFile: path, atomically: true, encoding: .utf8) | |
| 132 | try store.write(FileRecord(path: path, root: folder.path, kind: .org, bytes: Array(file.text.utf8), mtime: 1, settings: IndexSettings())) | |
| 133 | } | |
| 134 | let output = try RoamOracle.run(folder, """ | |
| 135 | (dolist (row (org-roam-db-query [:select [id title] :from nodes])) | |
| 136 | (let ((id (car row))) | |
| 137 | (princ (format "%s\\t%s\\t%s\\t%s\\t%s\\n" id (cadr row) | |
| 138 | (string-join (sort (mapcar #'car (org-roam-db-query [:select alias :from aliases :where (= node-id $s1)] id)) #'string<) "|") | |
| 139 | (string-join (sort (mapcar (lambda (r) (concat (cadr r) ":" (car r))) (org-roam-db-query [:select [ref type] :from refs :where (= node-id $s1)] id)) #'string<) "|") | |
| 140 | (string-join (sort (mapcar #'car (org-roam-db-query [:select tag :from tags :where (= node-id $s1)] id)) #'string<) "|"))))) | |
| 141 | """) | |
| 142 | let theirs = output.split(separator: "\n").map(String.init).filter { $0.contains("\t") }.sorted() | |
| 143 | let ours = try store.nodes().map { node in | |
| 144 | [node.id, node.title, node.aliases.sorted().joined(separator: "|"), node.refs.sorted().joined(separator: "|"), node.tags.sorted().joined(separator: "|")].joined(separator: "\t") | |
| 145 | }.sorted() | |
| 146 | #expect(!theirs.isEmpty) | |
| 147 | #expect(ours == theirs) | |
| 148 | } | |
| 149 | ||
| 150 | /// New nodes from `org-roam-capture-` with `:immediate-finish`: a `file+head` template | |
| 151 | /// and a `file+head+olp` one, twice, whose headings are made the first time. | |
| 152 | @MainActor | |
| 153 | @Test(.enabled(if: RoamOracle.enabled)) func captureMatchesOrgRoam() throws { | |
| 154 | let theirs = try RoamOracle.folder(), ours = try RoamOracle.folder() | |
| 155 | defer { | |
| 156 | RoamOracle.remove(theirs) | |
| 157 | RoamOracle.remove(ours) | |
| 158 | } | |
| 159 | _ = try RoamOracle.run(theirs, """ | |
| 160 | (setq org-roam-capture-templates | |
| 161 | '(("d" "default" plain "%?" :target (file+head "${slug}.org" "#+title: ${title}\\n") :unnarrowed t :immediate-finish t) | |
| 162 | ("p" "project" entry "* ${title} %?\\nbody" :target (file+head+olp "proj.org" "#+title: Projects" ("Work" "Active")) :immediate-finish t) | |
| 163 | ("e" "plain end" plain "Some ${slug} text" :target (file+head "end-${slug}.org" "#+title: ${title}") :immediate-finish t))) | |
| 164 | (org-roam-capture- :node (org-roam-node-create :title "Field Notes") :keys "d" :props '(:finalize find-file)) | |
| 165 | (org-roam-capture- :node (org-roam-node-create :title "Big Thing") :keys "p" :props '(:finalize find-file)) | |
| 166 | (org-roam-capture- :node (org-roam-node-create :title "Other Thing") :keys "p" :props '(:finalize find-file)) | |
| 167 | (org-roam-capture- :node (org-roam-node-create :title "Café Time") :keys "e" :props '(:finalize find-file)) | |
| 168 | """) | |
| 169 | let session = DocumentSession(recovery: FileRecoveryStore(directory: ours.appendingPathComponent(".r"))) | |
| 170 | let templates = [ | |
| 171 | RoamTemplate(key: "d", name: "default", kind: .plain, template: "%?", file: "${slug}.org", head: "#+title: ${title}\n"), | |
| 172 | RoamTemplate(key: "p", name: "project", kind: .entry, template: "* ${title} %?\nbody", file: "proj.org", head: "#+title: Projects", olp: ["Work", "Active"]), | |
| 173 | RoamTemplate(key: "e", name: "plain end", kind: .plain, template: "Some ${slug} text", file: "end-${slug}.org", head: "#+title: ${title}"), | |
| 174 | ] | |
| 175 | for (key, title) in [("d", "Field Notes"), ("p", "Big Thing"), ("p", "Other Thing"), ("e", "Café Time")] { | |
| 176 | let capture = RoamCapture(templates.filter { $0.key == key }, title: title, directory: ours.path, session: session, refresh: {}) { _, _, _ in } | |
| 177 | if case .failure(let error) = capture.fileFirst() { Issue.record("\(error.message)") } | |
| 178 | } | |
| 179 | for name in ["field_notes.org", "proj.org", "end-cafe_time.org"] { | |
| 180 | var expected = try String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8) | |
| 181 | let actual = try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8) | |
| 182 | // A plain template of only `%?` leaves an empty line in Emacs, which orgstar's | |
| 183 | // capture doesn't add, for org-roam or org-capture. | |
| 184 | if name == "field_notes.org", expected.hasSuffix("\n\n") { expected.removeLast() } | |
| 185 | #expect(RoamOracle.withoutIDs(actual) == RoamOracle.withoutIDs(expected), "\(name)") | |
| 186 | } | |
| 187 | } | |
| 188 | ||
| 189 | /// `org-roam-dailies-capture-date` with two templates into the same day's file, the second | |
| 190 | /// under an outline path. | |
| 191 | @MainActor | |
| 192 | @Test(.enabled(if: RoamOracle.enabled)) func dailiesCaptureMatchesOrgRoam() throws { | |
| 193 | let theirs = try RoamOracle.folder(), ours = try RoamOracle.folder() | |
| 194 | defer { | |
| 195 | RoamOracle.remove(theirs) | |
| 196 | RoamOracle.remove(ours) | |
| 197 | } | |
| 198 | let seconds = Int(DailiesTests.day.timeIntervalSince1970) | |
| 199 | try FileManager.default.createDirectory(at: theirs.appendingPathComponent("daily"), withIntermediateDirectories: true) | |
| 200 | _ = try RoamOracle.run(theirs, """ | |
| 201 | (setq org-roam-dailies-capture-templates | |
| 202 | '(("d" "default" entry "* Note %?" :target (file+head "%<%Y-%m-%d>.org" "#+title: %<%Y-%m-%d>\\n") :immediate-finish t) | |
| 203 | ("j" "journal" entry "* Entry %?" :target (file+head+olp "%<%Y-%m-%d>.org" "#+title: %<%Y-%m-%d>\\n" ("Journal")) :immediate-finish t))) | |
| 204 | (org-roam-dailies--capture (seconds-to-time \(seconds)) nil "d") | |
| 205 | (org-roam-dailies--capture (seconds-to-time \(seconds)) nil "j") | |
| 206 | (org-roam-dailies--capture (seconds-to-time \(seconds)) nil "d") | |
| 207 | """) | |
| 208 | let session = DocumentSession(recovery: FileRecoveryStore(directory: ours.appendingPathComponent(".r"))) | |
| 209 | let directory = ours.appendingPathComponent("daily").path | |
| 210 | let templates = [ | |
| 211 | RoamTemplate(key: "d", name: "default", kind: .entry, template: "* Note %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n"), | |
| 212 | RoamTemplate(key: "j", name: "journal", kind: .entry, template: "* Entry %?", file: "%<%Y-%m-%d>.org", head: "#+title: %<%Y-%m-%d>\n", olp: ["Journal"]), | |
| 213 | ] | |
| 214 | for key in ["d", "j", "d"] { | |
| 215 | let capture = RoamCapture(templates.filter { $0.key == key }, title: "", directory: directory, now: DailiesTests.day, session: session, refresh: {}) { _, _, _ in } | |
| 216 | if case .failure(let error) = capture.fileFirst() { Issue.record("\(error.message)") } | |
| 217 | } | |
| 218 | let expected = try String(contentsOf: theirs.appendingPathComponent("daily/2026-10-11.org"), encoding: .utf8) | |
| 219 | let actual = try String(contentsOf: ours.appendingPathComponent("daily/2026-10-11.org"), encoding: .utf8) | |
| 220 | #expect(RoamOracle.withoutIDs(actual) == RoamOracle.withoutIDs(expected)) | |
| 221 | } | |
| 222 | } | |
Tests/OrgCoreTests/OrgProtocolTests.swift +11 · view
| @@ -25,6 +25,8 @@ struct OrgProtocolTests { | ||
| 25 | 25 | }).joined(separator: "\n") |
| 26 | 26 | case .storeLink(let url, let title)?: |
| 27 | 27 | return "store url=\(url)\ntitle=\(title ?? "nil")" |
| 28 | case .roamRef, .roamNode: | |
| 29 | return "roam" | |
| 28 | 30 | case nil: |
| 29 | 31 | return "none" |
| 30 | 32 | } |
| @@ -61,6 +63,15 @@ struct OrgProtocolTests { | ||
| 61 | 63 | } |
| 62 | 64 | } |
| 63 | 65 | |
| 66 | /// org-roam-protocol's handlers, which read the `?key=value` form. | |
| 67 | @Test func roamProtocols() { | |
| 68 | #expect(OrgProtocol.parse("org-protocol://roam-ref?template=r&ref=https%3A%2F%2Fexample.com%2Fa&title=A+page&body=Some+text") | |
| 69 | == .roamRef(ref: "https://example.com/a", title: "A page", body: "Some text", template: "r")) | |
| 70 | #expect(OrgProtocol.parse("org-protocol://roam-ref?ref=cite%3Akey") == .roamRef(ref: "cite:key", title: nil, body: nil, template: nil)) | |
| 71 | #expect(OrgProtocol.parse("org-protocol://roam-ref?title=no+ref") == nil) | |
| 72 | #expect(OrgProtocol.parse("org-protocol://roam-node?node=5f0c-1e2a") == .roamNode(id: "5f0c-1e2a")) | |
| 73 | } | |
| 74 | ||
| 64 | 75 | @Test func captureURLRoundTrips() { |
| 65 | 76 | let url = OrgProtocol.captureURL(template: "w", url: "https://example.com/a?b=1&c=2+3", title: "Tea & cake = 100% café", body: "line one\nline+two") |
| 66 | 77 | #expect(OrgProtocol.parse(url) == .capture(template: "w", properties: [ |
docs/manual/guide/03-keys.org +2 −1 · view
| @@ -1143,7 +1143,8 @@ See [[file:09-links.org][Links]]. | ||
| 1143 | 1143 | |
| 1144 | 1144 | | Command | Emacs | Mac | Doom | What it does | |
| 1145 | 1145 | |-+-+-+-+-| |
| 1146 | | Find Node… (=app.node.find=) | =C-c n f= | — | =SPC n r f= (N) | Opens a heading or file with an ID, chosen by title (=org-roam-node-find=). | | |
| 1146 | | Find Node… (=app.node.find=) | =C-c n f= | — | =SPC n r f= (N) | Opens a heading or file with an ID, chosen by title or alias (=org-roam-node-find=). | | |
| 1147 | | Find Ref… (=app.node.find-ref=) | — | — | =SPC n r F= (N) | Opens the node with a =ROAM_REFS= link or citation key (=org-roam-ref-find=). | | |
| 1147 | 1148 | | Insert Node Link… (=app.node.insert=) | =C-c n i= | — | =SPC n r i= (N) | Inserts an =id:= link to a node (=org-roam-node-insert=). | |
| 1148 | 1149 | | Show Node Graph (=app.node.graph=) | =C-c n g= | — | =SPC n r g= (N) | Opens the graph of nodes and the links between them. | |
| 1149 | 1150 | | Go to Today's Daily Note (=app.dailies.today=) | =C-c n d d= | — | =SPC n r d t= (N) | =org-roam-dailies-goto-today=. | |
docs/manual/guide/08-capture.org +1 −1 · view
| @@ -294,7 +294,7 @@ org-protocol://store-link?url=https%3A%2F%2Fexample.com&title=Example | ||
| 294 | 294 | |
| 295 | 295 | This stores the link, so =C-c C-l= in the editor offers it (see [[file:09-links.org][Links]]), and puts the URL on the clipboard. |
| 296 | 296 | |
| 297 | Other handlers, such as =open-source=, report that orgstar handles only capture and store-link. | |
| 297 | org-roam's =roam-ref= and =roam-node= handlers work too; see [[file:09-links.org][Links]]. Other handlers, such as =open-source=, report that orgstar handles only capture and store-link. | |
| 298 | 298 | |
| 299 | 299 | ** Bookmarklets |
| 300 | 300 | |
docs/manual/guide/09-links.org +63 −7 · view
| @@ -56,6 +56,7 @@ A message in the echo area explains a link that can't be followed. | ||
| 56 | 56 | | =doi= | =[[doi:10.1000/182]]= | Opens =https://doi.org/= followed by the DOI. | |
| 57 | 57 | | =file= (also =file+sys:=, =file+emacs:=) | =[[file:notes.org::*Ideas]]= | See /File links/ below. | |
| 58 | 58 | | =id= | =[[id:6a3c…]]= | Opens the file with the heading whose =ID= property matches, and moves to the heading. | |
| 59 | | =roam= | =[[roam:Field Notes]]= | Opens the org-roam node with that title or alias; see /Nodes and daily notes/ below. | | |
| 59 | 60 | | Custom ID | =[[#setup]]= | Moves to the heading in this file whose =CUSTOM_ID= property is =setup=. | |
| 60 | 61 | | Heading | =[[*Weekly review]]= | Moves to the heading in this file with that title. | |
| 61 | 62 | | Text | =[[budget table]]= | Searches this file: a =<<budget table>>= target, then =#+NAME: budget table=, then a heading. | |
| @@ -326,18 +327,66 @@ the index, without org-roam's database. | ||
| 326 | 327 | |
| 327 | 328 | | Command | Emacs | Doom | What it does | |
| 328 | 329 | |-+-+-+-| |
| 329 | | Find Node… | =C-c n f= | =SPC n r f= | Asks for a node by title and opens it (=org-roam-node-find=). | | |
| 330 | | Insert Node Link… | =C-c n i= | =SPC n r i= | Asks for a node and inserts =[[id:…][Title]]=; with a selection, the selection is the description (=org-roam-node-insert=). | | |
| 330 | | Find Node… | =C-c n f= | =SPC n r f= | Asks for a node by title or alias and opens it (=org-roam-node-find=). | | |
| 331 | | Find Ref… | — | =SPC n r F= | Asks for one of the nodes' refs and opens its node (=org-roam-ref-find=). | | |
| 332 | | Insert Node Link… | =C-c n i= | =SPC n r i= | Asks for a node and inserts =[[id:…][Title]]=, with the alias as the description when an alias was chosen; with a selection, the selection is the description (=org-roam-node-insert=). | | |
| 331 | 333 | | Show Node Graph | =C-c n g= | =SPC n r g= | Opens the graph of nodes and their links; see /The graph/ below. | |
| 332 | 334 | | Go to Today's, Yesterday's, Tomorrow's Daily Note | =C-c n d d=, =y=, =t= | =SPC n r d t=, =y=, =m= | Opens the day's note, making it if missing (=org-roam-dailies-goto-today= and the others). | |
| 333 | 335 | | Go to Daily Note for Date… | =C-c n d c= | =SPC n r d d= | Asks for a date, then opens its note. | |
| 334 | 336 | | Capture to Today's Daily Note (and Yesterday's, Tomorrow's, for Date…) | =C-c n j=, =C-c n d n=, =C-c n d v= | =SPC n r d n=, =T=, =Y=, =M=, =D= | Files the entry template at the end of the day's note and opens it at =%?= (=org-roam-dailies-capture-today= and the others). | |
| 335 | 337 | | Next Daily Note, Previous Daily Note | =C-c n d f=, =b= | =SPC n r d f=, =b= | From a daily note, opens the next or previous one there is (=org-roam-dailies-goto-next-note=). | |
| 336 | 338 | |
| 337 | The keys are the ones org-roam's manual suggests for Emacs and Doom's. Titles that | |
| 338 | repeat show their file's name. A file node's title is its =#+TITLE=, or its name. | |
| 339 | The keys are the ones org-roam's manual suggests for Emacs and Doom's. A file node's | |
| 340 | title is its =#+TITLE=, or its name. The node properties are read as org-roam 2.3 reads them: | |
| 341 | ||
| 342 | - =ROAM_ALIASES=: other titles for the node, separated by spaces, with quotes around one | |
| 343 | that has spaces (="Alias One" two=). Each alias is listed in the chooser as a title of | |
| 344 | its own. | |
| 345 | - =ROAM_REFS=: links and citation keys the node stands for, such as | |
| 346 | =https://example.com @key2020 [cite:@key2021]=. Find Ref… lists them. | |
| 347 | - =ROAM_EXCLUDE=: with any value but =nil=, the heading or file isn't a node. It isn't | |
| 348 | inherited: the headings under an excluded one with an =ID= are still nodes. | |
| 349 | - Tags: a file node's are its =#+FILETAGS=; a heading's are its own and those it inherits. | |
| 350 | The chooser shows them after the title, as =#tag=, as Doom's chooser does, and typing a | |
| 351 | tag finds its nodes. | |
| 352 | ||
| 353 | Names that repeat show their file's name. A =[[roam:Title]]= link opens the node with that | |
| 354 | title or alias, as =org-roam-link-follow-link= does. | |
| 355 | ||
| 356 | A title that no node has opens the capture window with the =[[roam-template]]= templates | |
| 357 | from =capture.toml=, as =org-roam-capture-= does: choose one when there are several, answer | |
| 358 | its prompts, edit the text, and press Capture (=⌘Return= on the Mac) to make the node, or | |
| 359 | Cancel to make nothing. Find Node… then opens the node; Insert Node Link… links to it. Without | |
| 360 | templates, org-roam's default is used: | |
| 339 | 361 | |
| 340 | A title that no node has makes a new node, as org-roam's default capture template does: a file named =%<%Y%m%d%H%M%S>-${slug}.org= in =org-roam-directory= (the first folder unless it is set), starting with an =ID= property drawer and =#+title:= and the title. Find Node… opens it; Insert Node Link… links to it. The slug is the title in lower case, accents dropped, with everything but letters and digits as one =_=, as =org-roam-node-slugify= makes it. | |
| 362 | #+BEGIN_SRC toml | |
| 363 | [[roam-template]] | |
| 364 | key = "d" | |
| 365 | name = "default" | |
| 366 | type = "plain" # entry, item, checkitem, plain or table-line | |
| 367 | template = "%?" | |
| 368 | file = "%<%Y%m%d%H%M%S>-${slug}.org" # in org-roam-directory | |
| 369 | head = "#+title: ${title}\n" # at the top of a new file | |
| 370 | #+END_SRC | |
| 371 | ||
| 372 | =olp = "Projects/Active"= files the text under that outline path, making the headings that | |
| 373 | are missing (=file+head+olp=). A new file starts with an =ID= property drawer and the head; | |
| 374 | a file that's there gets an =ID= when it has none, and is the node. =${title}=, =${slug}= | |
| 375 | and =${id}= are the node's title, slug and =ID=; =%<…>= and the other escapes are | |
| 376 | org-capture's (see [[file:08-capture.org][Capture]]), and =immediate-finish=, =prepend= and the other | |
| 377 | template properties apply. The slug is the title in lower case, accents dropped, with | |
| 378 | everything but letters and digits as one =_=, as =org-roam-node-slugify= makes it. | |
| 379 | ||
| 380 | org-protocol's =roam-ref= opens the node whose =ROAM_REFS= has the =ref=, and otherwise | |
| 381 | makes one in the capture window with =[[roam-ref-template]]= (only the one keyed =template= | |
| 382 | when the link names one), with the ref in its =ROAM_REFS=. Without templates, org-roam's | |
| 383 | default makes =${slug}.org= with =#+title: ${title}=; =${ref}= and =${body}= are the link's | |
| 384 | =ref= and =body=. =roam-node= opens the node with the =node= ID: | |
| 385 | ||
| 386 | #+BEGIN_SRC text | |
| 387 | org-protocol://roam-ref?template=r&ref=https%3A%2F%2Fexample.com&title=Example | |
| 388 | org-protocol://roam-node?node=5f0c1e2a-… | |
| 389 | #+END_SRC | |
| 341 | 390 | |
| 342 | 391 | *The graph.* Show Node Graph, or Window ▸ Node Graph on the Mac and Commands on iOS, draws every node as a dot and every =id:= link between two nodes as a line. It is part of orgstar+. |
| 343 | 392 | |
| @@ -362,8 +411,15 @@ org-roam's default daily template does it, with an =ID= like every new org-roam | ||
| 362 | 411 | (="#+title: %<%Y-%m-%d>\n"=) and =org-roam-dailies-entry= (="* %?"=) change the file name, |
| 363 | 412 | what a new note starts with, and what capturing adds; =%<…>= formats the note's date as |
| 364 | 413 | =format-time-string= does. The entry is an org-capture template; its date escapes |
| 365 | (=%t=, =%U= and the like) use the note's day. Import from Emacs reads them from the first of | |
| 366 | =org-roam-dailies-capture-templates=. See [[file:13-configuration.org][Configuration]]. | |
| 414 | (=%t=, =%U= and the like) use the note's day. See [[file:13-configuration.org][Configuration]]. | |
| 415 | ||
| 416 | For several daily templates, =[[roam-dailies-template]]= tables in =capture.toml= take the | |
| 417 | place of those three settings, as =org-roam-dailies-capture-templates= does. They have the | |
| 418 | keys of =[[roam-template]]=; =type= is =entry= unless set, and =file= is in the daily-notes | |
| 419 | folder. Capturing opens the capture window with them: choose one, edit the entry, and Capture | |
| 420 | files it in the day's note, making the note with the template's head when it's new. The go-to | |
| 421 | commands ask which template only when the templates name different files. Import from Emacs | |
| 422 | reads one =(file+head NAME HEAD)= template into the three settings, and several into tables. | |
| 367 | 423 | |
| 368 | 424 | ** Denote |
| 369 | 425 | |
docs/manual/guide/13-configuration.org +2 −1 · view
| @@ -833,7 +833,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, = | ||
| 833 | 833 | | =denote-sequence-scheme=, =denote-journal-interval= | The same key | |
| 834 | 834 | | =denote-templates= | =[denote-templates]=: entries whose text is a string or =concat= of strings; a function is listed as unsupported | |
| 835 | 835 | | =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats | |
| 836 | | =org-roam-dailies-capture-templates= | =org-roam-dailies-file=, =-head= and =-entry=, from the first template's =(file+head NAME HEAD)= target and template | | |
| 836 | | =org-roam-dailies-capture-templates= | =org-roam-dailies-file=, =-head= and =-entry=, from one template with a =(file+head NAME HEAD)= target; several as =[[roam-dailies-template]]= tables in =capture.toml= | | |
| 837 | | =org-roam-capture-templates=, =org-roam-capture-ref-templates= | =[[roam-template]]= and =[[roam-ref-template]]= tables in =capture.toml=, for =file=, =file+head=, =file+olp= and =file+head+olp= targets | | |
| 837 | 838 | | =org-timer-format=, =org-timer-default-timer= | The same keys; a number becomes a string | |
| 838 | 839 | | =org-attach-id-dir= | The same key, when the value is a string or an =expand-file-name= form | |
| 839 | 840 | | =org-attach-use-inheritance= | =selective=, or =t= / =nil= as ="t"= / ="nil"= | |
docs/manual/guide/14-ios.org +1 −1 · view
| @@ -190,7 +190,7 @@ Cancel answers nothing, as =C-g= does. | ||
| 190 | 190 | |
| 191 | 191 | =C-c '= on a block, and =C-c `= on a table field, open the text in a sheet of its own; Save puts it back. A src block's code is colored as its language, as in the editor. |
| 192 | 192 | |
| 193 | Show Backlinks in Commands lists the links to the heading at the caret and to the file; the daily note commands, Find Node…, Insert Node Link… and Show Node Graph, all in Commands, work with org-roam-style notes, and the Folders tab's calendar menu opens today's, yesterday's and tomorrow's note. See [[file:09-links.org][Links]]. | |
| 193 | Show Backlinks in Commands lists the links to the heading at the caret and to the file; the daily note commands, Find Node…, Find Ref…, Insert Node Link… and Show Node Graph, all in Commands, work with org-roam-style notes, and the Folders tab's calendar menu opens today's, yesterday's and tomorrow's note. A new node and a daily-note capture open the capture sheet, whose Template picker lists the org-roam templates. See [[file:09-links.org][Links]]. | |
| 194 | 194 | |
| 195 | 195 | Incremental Search is in Commands, and on =C-s= and =C-r= with a hardware keyboard; see [[file:02-the-editor.org][The editor]]. =auto-fill-mode= works as on the Mac. |
| 196 | 196 | |
docs/manual/guide/15-alongside-emacs.org +1 −1 · view
| @@ -292,7 +292,7 @@ Other: | ||
| 292 | 292 | - Keyboard macros (see [[file:03-keys.org][Keys and commands]]): the prefix argument counts macros only; =C-u= before another command does nothing and says so. =C-u C-x (= and =C-u <f3>= (append to the last macro), the macro ring (=C-x C-k C-n=, =C-x C-k C-p=), the counter commands other than =<f3>= (=C-x C-k C-c=, =C-x C-k C-f=), =C-x C-k e= (editing a macro), =C-x C-k b= (binding a key), =C-x C-k r= (running on each line of the region) and =C-x q= (query) aren't supported. A named macro is saved in =macros.toml= rather than written with =insert-kbd-macro=. Commands run from a menu or the palette while recording aren't recorded; Emacs records =M-x= and its answer. |
| 293 | 293 | - The agenda's text search (see [[file:07-agenda.org][The agenda]]) covers the agenda files only: =org-agenda-text-search-extra-files= and =org-agenda-search-view-max-outline-level= aren't supported. It runs from the view menu rather than the dispatcher's =s= and =S=, and the search view's =[=, =]=, ={= and =}= keys, which add words and regexps to the search, aren't supported. |
| 294 | 294 | - In regexps, =\<=, =\>= and =\b= use Org's word syntax but don't find a word boundary where the script changes between two word characters, as Emacs does (for example between an emoji and a letter). |
| 295 | - org-roam: nodes come from orgstar's index, not org-roam's database, so =ROAM_ALIASES=, =ROAM_REFS=, =ROAM_EXCLUDE=, and node tags in the chooser aren't supported; the graph is orgstar's own (see [[file:09-links.org][Links]]), not org-roam-ui's. Insert Node Link… and Find Node… make a new node from a title that isn't found with org-roam's default template only, and file it at once rather than in a capture buffer. Daily notes use the first of =org-roam-dailies-capture-templates=, without choosing among several, and the date prompt prefers future dates, where org-roam prefers past ones. Capturing to a daily note files the entry at once rather than in a capture buffer. | |
| 295 | - org-roam: nodes come from orgstar's index, not org-roam's database; the graph is orgstar's own (see [[file:09-links.org][Links]]), not org-roam-ui's. Templates are tables in =capture.toml= rather than Lisp: targets other than =file=, =file+head=, =file+olp= and =file+head+olp= (such as =node=), function templates and =${…}= fields other than =title=, =slug=, =id= and a ref's =ref= and =body= aren't supported, and the capture window shows only the template's text, as if every template were narrowed. When an outline path's heading appears twice, the last is used where org-roam reports an error. A template of only =%?= doesn't leave the empty line Emacs leaves. The go-to daily-note commands ask for a template only when the templates name different files. Cancelling a capture makes nothing, so there's no question about deleting the new file. =roam:= links aren't rewritten to =id:= links when followed (=org-roam-link-auto-replace=), and one to a title no node has reports it rather than making the node. =roam-ref= with an existing node opens it rather than capturing into it. Refs aren't listed as backlinks (reflinks), and =org-roam-node-display-template= isn't read: the chooser shows title and tags. The daily date prompt prefers future dates, where org-roam prefers past ones. | |
| 296 | 296 | - org-timer: =org-timer-display= is always the mode line. The timer's =C-u= forms are separate commands bound to =C-u C-c C-x 0=, =C-u C-u C-c C-x 0= and =C-u C-c C-x ,=; Set Countdown Timer… has no prefix-argument forms. |
| 297 | 297 | - Radio lists are Org 9.8's =#+ATTR_ORG: :radio= checkbox lists. The =#+ORGLST= radio lists of Org 9.1 and earlier, removed in Org 9.2, aren't supported, nor is =org-list-checkbox-radio-mode=. |
| 298 | 298 | - org-attach: =org-attach-method= is always =cp= for Attach File… (the other methods have their own commands), =org-attach-auto-tag= is always =ATTACH=, =org-attach-preferred-new-method= is always =id=, and =org-attach-id-to-path-function-list= is Org's default. The dispatcher's =b=, =O= and =F= keys and =org-attach-archive-delete= aren't supported. Delete All Attachments… asks once and deletes the folder with what's in it. |
l10n/Localizable.xcstrings +70 · view
| @@ -87,6 +87,41 @@ | ||
| 87 | 87 | } |
| 88 | 88 | } |
| 89 | 89 | }, |
| 90 | "%@ (new)": { | |
| 91 | "comment": "Capture window: an org-roam template's file that capturing makes", | |
| 92 | "localizations": { | |
| 93 | "de": { | |
| 94 | "stringUnit": { | |
| 95 | "state": "translated", | |
| 96 | "value": "%@ (neu)" | |
| 97 | } | |
| 98 | }, | |
| 99 | "es": { | |
| 100 | "stringUnit": { | |
| 101 | "state": "translated", | |
| 102 | "value": "%@ (nuevo)" | |
| 103 | } | |
| 104 | }, | |
| 105 | "fr": { | |
| 106 | "stringUnit": { | |
| 107 | "state": "translated", | |
| 108 | "value": "%@ (nouveau)" | |
| 109 | } | |
| 110 | }, | |
| 111 | "ja": { | |
| 112 | "stringUnit": { | |
| 113 | "state": "translated", | |
| 114 | "value": "%@(新規)" | |
| 115 | } | |
| 116 | }, | |
| 117 | "pt-BR": { | |
| 118 | "stringUnit": { | |
| 119 | "state": "translated", | |
| 120 | "value": "%@ (novo)" | |
| 121 | } | |
| 122 | } | |
| 123 | } | |
| 124 | }, | |
| 90 | 125 | "%@ (orgstar+)": { |
| 91 | 126 | "localizations": { |
| 92 | 127 | "de": { |
| @@ -19377,6 +19412,41 @@ | ||
| 19377 | 19412 | } |
| 19378 | 19413 | } |
| 19379 | 19414 | }, |
| 19415 | "Find Ref…": { | |
| 19416 | "comment": "Command title", | |
| 19417 | "localizations": { | |
| 19418 | "de": { | |
| 19419 | "stringUnit": { | |
| 19420 | "state": "translated", | |
| 19421 | "value": "Referenz suchen …" | |
| 19422 | } | |
| 19423 | }, | |
| 19424 | "es": { | |
| 19425 | "stringUnit": { | |
| 19426 | "state": "translated", | |
| 19427 | "value": "Buscar referencia…" | |
| 19428 | } | |
| 19429 | }, | |
| 19430 | "fr": { | |
| 19431 | "stringUnit": { | |
| 19432 | "state": "translated", | |
| 19433 | "value": "Rechercher une référence…" | |
| 19434 | } | |
| 19435 | }, | |
| 19436 | "ja": { | |
| 19437 | "stringUnit": { | |
| 19438 | "state": "translated", | |
| 19439 | "value": "参照を検索…" | |
| 19440 | } | |
| 19441 | }, | |
| 19442 | "pt-BR": { | |
| 19443 | "stringUnit": { | |
| 19444 | "state": "translated", | |
| 19445 | "value": "Buscar Referência…" | |
| 19446 | } | |
| 19447 | } | |
| 19448 | } | |
| 19449 | }, | |
| 19380 | 19450 | "Find Sequence Relatives…": { |
| 19381 | 19451 | "comment": "Command title", |
| 19382 | 19452 | "localizations": { |