Find Node creates a node from a new title; backlinks show the linking line !342

merged merged by cmc on 2026-10-14 04:39 UTC · krz/orgstar:roam-nodes into main

13 files changed, +239 −17

Layout: unified · split

Sources/OrgApp/RoamActions.swift +34 −8
@@ -73,9 +73,19 @@ public struct RoamActions {
7373 show("\(error)")
7474 }
7575 case "app.node.find":
76 chooseNode("Node: ") { node in open(node.location.path, node.location.start) }
76 chooseNode("Node: ") { choice in
77 switch choice {
78 case .existing(let node): open(node.location.path, node.location.start)
79 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
80 }
81 }
7782 case "app.node.insert":
78 chooseNode("Node: ") { node in insertLink("id:" + node.id, node.title) }
83 chooseNode("Node: ") { choice in
84 switch choice {
85 case .existing(let node): insertLink("id:" + node.id, node.title)
86 case .created(_, let id, let title): insertLink("id:" + id, title)
87 }
88 }
7989 default:
8090 show("Unknown command \(id)")
8191 }
@@ -130,17 +140,33 @@ public struct RoamActions {
130140 ask([])
131141 }
132142
133 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat.
134 private func chooseNode(_ message: String, _ then: @escaping (IndexStore.Node) -> Void) {
143 enum NodeChoice {
144 case existing(IndexStore.Node)
145 case created(path: String, id: String, title: String)
146 }
147
148 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A
149 /// title no node has makes a node with it, as org-roam's default capture template does.
150 private func chooseNode(_ message: String, _ then: @escaping (NodeChoice) -> Void) {
135151 let all = nodes()
136 guard !all.isEmpty else { return show("No headings or files have IDs") }
137152 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
138153 let labels = all.map { node in
139154 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
140155 }
141 ask(Prompt(key: "node", message: message, choices: labels)) { answer in
142 guard let answer, let index = labels.firstIndex(of: answer) else { return }
143 then(all[index])
156 ask(Prompt(key: "node", message: message, choices: labels, requireMatch: false)) { answer in
157 guard let answer else { return }
158 if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
159 let title = answer.trimmingCharacters(in: .whitespaces)
160 guard !title.isEmpty else { return }
161 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
162 do {
163 let node = try RoamNode.create(title: title, in: folder)
164 refresh()
165 show("Created \((node.path as NSString).lastPathComponent)")
166 then(.created(path: node.path, id: node.id, title: title))
167 } catch {
168 show("Can't make the node: \(error)")
169 }
144170 }
145171 }
146172}
Sources/OrgApp/RoamNode.swift added +45
@@ -0,0 +1,45 @@
1import Foundation
2import OrgCore
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.
7public enum RoamNode {
8 /// `org-roam-directory`: the setting, else the first folder.
9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
10 let roam = OrgPreferences.roamDirectory(defaults)
11 return roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory())
12 }
13
14 /// `org-roam-node-slugify`: without the combining marks org-roam drops, everything but
15 /// letters and digits as one `_`, none at either end, lower case.
16 public static func slug(_ title: String) -> String {
17 let trimmed: Set<UInt32> = [0x300, 0x301, 0x302, 0x303, 0x304, 0x306, 0x307, 0x308, 0x309, 0x30A, 0x30B, 0x30C,
18 0x31B, 0x323, 0x324, 0x325, 0x327, 0x32D, 0x32E, 0x330, 0x331]
19 let decomposed = title.decomposedStringWithCanonicalMapping.unicodeScalars.filter { !trimmed.contains($0.value) }
20 let composed = String(String.UnicodeScalarView(decomposed)).precomposedStringWithCanonicalMapping
21 var out = ""
22 for character in composed {
23 if character.isLetter || character.isNumber {
24 out.append(character)
25 } else if out.last != "_" {
26 out.append("_")
27 }
28 }
29 while out.first == "_" { out.removeFirst() }
30 while out.last == "_" { out.removeLast() }
31 return out.lowercased()
32 }
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}
Sources/OrgApp/WorkspaceModel.swift +7 −2
@@ -358,13 +358,18 @@ public final class WorkspaceModel {
358358 FileTreeNode.build(root: path, files: files, downloading: downloading.sorted())
359359 }
360360
361 /// Headings with links to `target`, the target heading's own links left out.
361 /// Headings with links to `target`, the target heading's own links left out, each with
362 /// the line its link is on as its snippet.
362363 public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
363364 var seen = Set<HeadingLocation>()
364365 return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in
365366 guard !(link.source.path == target.path && link.source.start == start),
366367 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
367 return link.source
368 var source = link.source
369 if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) {
370 source.snippet = Snippet(text: context.text, matches: [context.link])
371 }
372 return source
368373 }
369374 }
370375
Sources/OrgCore/Links/Backlinks.swift +37
@@ -55,4 +55,41 @@ public enum Backlinks {
5555 let wanted = search.hasPrefix("*") ? String(search.dropFirst()) : search
5656 return Links.normalizedTitle(wanted) == Links.normalizedTitle(title)
5757 }
58
59 /// The line of `body` with the link to `link` in it, links shown as they read (their
60 /// description, else what they link to), and the range of that link in the line. A line
61 /// longer than `width` keeps the part around the link.
62 public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? {
63 let pattern = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/
64 for line in body.split(whereSeparator: \.isNewline) {
65 guard line.contains("[[" + link + "]") else { continue }
66 var text = ""
67 var found: Range<Int>?
68 var rest = Substring(line)
69 while let match = rest.firstMatch(of: pattern) {
70 text += rest[..<match.range.lowerBound]
71 let shown = match.2.map(String.init) ?? String(match.1)
72 let start = text.utf16.count
73 text += shown
74 if found == nil, match.1 == link { found = start..<text.utf16.count }
75 rest = rest[match.range.upperBound...]
76 }
77 text += rest
78 guard var range = found else { continue }
79 // Trim, then cut to `width` around the link.
80 let leading = text.prefix { $0.isWhitespace }.utf16.count
81 text = text.trimmingCharacters(in: .whitespaces)
82 range = (range.lowerBound - leading)..<(range.upperBound - leading)
83 let ns = text as NSString
84 if ns.length > width {
85 let start = max(0, min(range.lowerBound - width / 3, ns.length - width))
86 let end = min(ns.length, start + width)
87 let lead = start > 0 ? "…" : "", trail = end < ns.length ? "…" : ""
88 text = lead + ns.substring(with: NSRange(location: start, length: end - start)) + trail
89 range = (range.lowerBound - start + lead.utf16.count)..<(range.upperBound - start + lead.utf16.count)
90 }
91 return (text, range)
92 }
93 return nil
94 }
5895}
Sources/OrgIndex/IndexStore.swift +33 −2
@@ -20,14 +20,25 @@ public struct IndexedHeading: Sendable, Hashable {
2020}
2121
2222public struct HeadingLocation: Sendable, Hashable {
23 /// Locations are equal by where they are; the snippet is for showing them.
24 public static func == (a: HeadingLocation, b: HeadingLocation) -> Bool {
25 a.path == b.path && a.ordinal == b.ordinal && a.title == b.title && a.start == b.start && a.contentHash == b.contentHash
26 }
27
28 public func hash(into hasher: inout Hasher) {
29 hasher.combine(path)
30 hasher.combine(ordinal)
31 hasher.combine(start)
32 }
33
2334 public let path: String
2435 /// `fileOrdinal` for the file itself, before its first heading.
2536 public let ordinal: Int
2637 public let title: String
2738 public let start: Int
2839 public let contentHash: String
29 /// The text around the match, for search results whose match is in the text.
30 public internal(set) var snippet: Snippet?
40 /// The text around the match: a search's words, or a backlink's link.
41 public var snippet: Snippet?
3142
3243 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
3344 self.path = path
@@ -456,6 +467,26 @@ public final class IndexStore: Sendable {
456467 return indexed.filter { overlay[$0.source.path] == nil } + live
457468 }
458469
470 /// The text under a heading, or before a file's first heading, that a location from
471 /// `links` or `search` stands for.
472 public func text(of location: HeadingLocation, overlay: [String: FileRecord] = [:]) throws -> String? {
473 if let record = overlay[location.path] {
474 if location.ordinal == HeadingLocation.fileOrdinal { return record.preamble }
475 return record.headings.first { $0.ordinal == location.ordinal }?.body
476 }
477 return try database.read { db in
478 if location.ordinal == HeadingLocation.fileOrdinal {
479 return try String.fetchOne(db, sql: """
480 SELECT files_fts.body FROM files_fts JOIN files f ON f.id = files_fts.rowid WHERE f.path = ?
481 """, arguments: [location.path])
482 }
483 return try String.fetchOne(db, sql: """
484 SELECT headings_fts.body FROM headings_fts JOIN headings h ON h.id = headings_fts.rowid
485 JOIN files f ON f.id = h.file_id WHERE f.path = ? AND h.ordinal = ?
486 """, arguments: [location.path, location.ordinal])
487 }
488 }
489
459490 /// IDs used by more than one heading.
460491 public func duplicateIDs(overlay: [String: FileRecord] = [:]) throws -> [String: [HeadingLocation]] {
461492 let indexed = try database.read { db in
Sources/OrgIndex/Snippet.swift +5
@@ -7,6 +7,11 @@ public struct Snippet: Sendable, Hashable {
77 /// The matched words, as UTF-16 ranges of `text`.
88 public let matches: [Range<Int>]
99
10 public init(text: String, matches: [Range<Int>]) {
11 self.text = text
12 self.matches = matches
13 }
14
1015 /// The passage of `text` around the first word starting with one of `prefixes`, compared
1116 /// without case or diacritics as the full-text index compares them; nil when none does.
1217 public init?(text: String, prefixes: [String], width: Int = 160) {
Sources/Orgstar/BacklinksPane.swift +4 −1
@@ -45,7 +45,10 @@ struct BacklinksPane: View {
4545 } label: {
4646 VStack(alignment: .leading, spacing: 2) {
4747 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
48 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
48 if let snippet = location.snippet {
49 Text(snippet.attributed).font(.callout).foregroundStyle(.secondary).lineLimit(3)
50 }
51 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
4952 }
5053 }
5154 .buttonStyle(.plain)
Sources/OrgstarMobile/BacklinksScreen.swift +4 −1
@@ -43,7 +43,10 @@ struct BacklinksScreen: View {
4343 } label: {
4444 VStack(alignment: .leading, spacing: 2) {
4545 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1).foregroundStyle(.primary)
46 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
46 if let snippet = location.snippet {
47 Text(snippet.attributed).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
48 }
49 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
4750 }
4851 }
4952 }
Tests/OrgAppTests/AppTests.swift +3
@@ -118,6 +118,9 @@ struct WorkspaceModelTests {
118118 #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
119119 #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
120120 #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
121 // Each with the line its link is on, the link as it reads.
122 #expect(model.backlinks(to: sink).map { $0.snippet?.text } == ["the sink and file:a.org", "file:a.org::#sink https://x.org", "About file:a.org::*Sink and file:a.org."])
123 #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
121124 let fromC = try #require(model.backlinks(to: sink).last)
122125 #expect(fromC == .file(c, contentHash: fromC.contentHash))
123126 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
Tests/OrgAppTests/RoamNodeTests.swift added +45
@@ -0,0 +1,45 @@
1import Foundation
2import Testing
3@testable import OrgApp
4
5struct RoamNodeTests {
6 /// `org-roam-node-slugify` from org-roam 2.3, run in Emacs. Titles and slugs go through
7 /// UTF-8 files: Emacs decodes its command line by the locale.
8 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
9 func slugsMatchOrgRoam() throws {
10 let titles = ["Hello World", "Café au lait", " Spaces and__underscores ", "C++ & Rust!", "Привет мир", "日本語のノート", "naïve résumé", "x", "---", "Ångström 2026"]
11 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-slug-\(UUID().uuidString)")
12 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
13 defer { try? FileManager.default.removeItem(at: folder) }
14 let input = folder.appendingPathComponent("titles.txt"), output = folder.appendingPathComponent("slugs.txt")
15 try titles.joined(separator: "\n").write(to: input, atomically: true, encoding: .utf8)
16 let form = """
17 (progn (require 'ucs-normalize) (require 'seq) (require 'subr-x)
18 (let* ((coding-system-for-read 'utf-8) (coding-system-for-write 'utf-8)
19 (slug-trim-chars '(#x300 #x301 #x302 #x303 #x304 #x306 #x307 #x308 #x309 #x30A #x30B #x30C #x31B #x323 #x324 #x325 #x327 #x32D #x32E #x330 #x331))
20 (titles (split-string (with-temp-buffer (insert-file-contents "\(input.path)") (buffer-string)) "\n")))
21 (with-temp-file "\(output.path)"
22 (dolist (title titles)
23 (insert (thread-last title (ucs-normalize-NFD-string) (seq-remove (lambda (char) (memq char slug-trim-chars)))
24 (apply #'string) (ucs-normalize-NFC-string) (replace-regexp-in-string "[^[:alnum:]]" "_")
25 (replace-regexp-in-string "__*" "_") (replace-regexp-in-string "^_" "") (replace-regexp-in-string "_$" "") (downcase))
26 "\n")))))
27 """
28 _ = try DailiesTests.emacs(form)
29 let emacs = try String(contentsOf: output, encoding: .utf8).split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
30 #expect(Array(emacs.prefix(titles.count)) == titles.map(RoamNode.slug))
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}
Tests/OrgCoreTests/BacklinkTests.swift +16
@@ -1,3 +1,4 @@
1import Foundation
12import Testing
23@testable import OrgCore
34
@@ -22,4 +23,19 @@ struct BacklinkTests {
2223 #expect(links("Fix the sink", from: "/notes/a.org", to: heading))
2324 #expect(!links("*Fix the sink", from: "/notes/b.org", to: heading))
2425 }
26
27 @Test func contextLineShowsLinksAsTheyRead() throws {
28 let body = ":PROPERTIES:\n:ID: x\n:END:\nFirst line.\nSee [[id:s-1][the sink]] and [[file:a.org]] today.\n"
29 let context = try #require(Backlinks.context(in: body, link: "id:s-1"))
30 #expect(context.text == "See the sink and file:a.org today.")
31 #expect((context.text as NSString).substring(with: NSRange(context.link)) == "the sink")
32 let plain = try #require(Backlinks.context(in: "Read [[file:a.org::*Sink]].\n", link: "file:a.org::*Sink"))
33 #expect(plain.text == "Read file:a.org::*Sink." && plain.link == 5..<22)
34 #expect(Backlinks.context(in: "nothing here\n", link: "id:zz") == nil)
35 // A long line keeps the part around the link.
36 let long = String(repeating: "word ", count: 60) + "[[id:q][target]]" + String(repeating: " more", count: 60)
37 let cut = try #require(Backlinks.context(in: long, link: "id:q"))
38 #expect(cut.text.utf16.count < 200 && cut.text.hasPrefix("…") && cut.text.hasSuffix("…"))
39 #expect((cut.text as NSString).substring(with: NSRange(cut.link)) == "target")
40 }
2541}
docs/manual/guide/09-links.org +5 −2
@@ -269,8 +269,9 @@ has two sections:
269269- *Links to* the heading at the caret, named after that heading.
270270- *Links to this file*.
271271
272Each row shows the linking heading and its file name; a link in the text before a
273file's first heading is listed under the file's name. Click a row to open it. The
272Each row shows the linking heading, the line the link is on with links shown as they read
273and this one in bold, and the file name; a link in the text before a file's first heading is
274listed under the file's name. Click a row to open it. The
274275pane is shown by default, orgstar remembers whether it is shown, and it updates as
275276you move the caret and edit.
276277
@@ -305,6 +306,8 @@ the index, without org-roam's database.
305306The keys are the ones org-roam's manual suggests for Emacs and Doom's. Titles that
306307repeat show their file's name. A file node's title is its =#+TITLE=, or its name.
307308
309A 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.
310
308311Daily notes are in =org-roam-dailies-directory= (=daily/=) under =org-roam-directory=,
309312which is the first sidebar folder unless set. A new note is named and started as
310313org-roam's default daily template does it, with an =ID= like every new org-roam file:
docs/manual/guide/15-alongside-emacs.org +1 −1
@@ -248,7 +248,7 @@ Other:
248248- =auto-fill-mode= fills on a typed space only, not on =RET=.
249249- 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.
250250- 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).
251- org-roam: nodes come from orgstar's index, not org-roam's database, so =ROAM_ALIASES=, =ROAM_REFS=, =ROAM_EXCLUDE=, node tags in the chooser and the graph aren't supported. Insert Node Link… and Find Node… don't make new nodes from a title that isn't found. 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.
251- org-roam: nodes come from orgstar's index, not org-roam's database, so =ROAM_ALIASES=, =ROAM_REFS=, =ROAM_EXCLUDE=, node tags in the chooser and the graph aren't supported. 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.
252252- 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.
253253- 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=.
254254- 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.