Commit 9e9d587ae8
Verified · cmc
Layout: unified · split
Sources/OrgApp/WorkspaceModel.swift +7 −3
| @@ -19,6 +19,8 @@ public final class WorkspaceModel { | ||
| 19 | 19 | public var lastError: String? |
| 20 | 20 | /// Bumped when an indexed file changes on disk, with its path. |
| 21 | 21 | public private(set) var changedFile: (path: String, version: Int)? |
| 22 | /// Bumped when the index may hold other rows: after a reconcile, or a root's removal. | |
| 23 | public private(set) var indexVersion = 0 | |
| 22 | 24 | |
| 23 | 25 | public let index: IndexStore |
| 24 | 26 | /// A change (other TODO keywords) reindexes the files it affects. |
| @@ -279,6 +281,7 @@ public final class WorkspaceModel { | ||
| 279 | 281 | guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil } |
| 280 | 282 | return FileEntry(path: file.path, root: root, kind: file.kind) |
| 281 | 283 | } |
| 284 | indexVersion += 1 | |
| 282 | 285 | } |
| 283 | 286 | |
| 284 | 287 | /// Reconciles the paths a batch of file events named, or whole roots when events were lost. |
| @@ -441,11 +444,12 @@ public final class WorkspaceModel { | ||
| 441 | 444 | } |
| 442 | 445 | |
| 443 | 446 | /// Headings with links to `target`, the target heading's own links left out, each with |
| 444 | /// the line its link is on as its snippet. | |
| 445 | public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] { | |
| 447 | /// the line its link is on as its snippet. Reads every link in the index, so call it off | |
| 448 | /// the main actor; a cancelled task gets what was found so far. | |
| 449 | public nonisolated func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] { | |
| 446 | 450 | var seen = Set<HeadingLocation>() |
| 447 | 451 | return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in |
| 448 | guard !(link.source.path == target.path && link.source.start == start), | |
| 452 | guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start), | |
| 449 | 453 | Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil } |
| 450 | 454 | var source = link.source |
| 451 | 455 | if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) { |
Sources/OrgCore/Links/Backlinks.swift +7 −3
| @@ -19,6 +19,11 @@ public enum Backlinks { | ||
| 19 | 19 | } |
| 20 | 20 | } |
| 21 | 21 | |
| 22 | /// A link type and its colon. | |
| 23 | nonisolated(unsafe) private static let typePrefix = /^[a-zA-Z][-a-zA-Z0-9+]*:/ | |
| 24 | /// A bracket link: what it links to, and its description. | |
| 25 | nonisolated(unsafe) private static let bracketLink = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/ | |
| 26 | ||
| 22 | 27 | /// Whether `link`, written in the file at `source`, leads to `target`. |
| 23 | 28 | public static func links(_ link: String, from source: String, to target: Target, home: String = OrgPaths.home) -> Bool { |
| 24 | 29 | let link = Links.unescape(link) |
| @@ -42,7 +47,7 @@ public enum Backlinks { | ||
| 42 | 47 | let parts = link.components(separatedBy: "::") |
| 43 | 48 | path = parts[0] |
| 44 | 49 | search = parts.dropFirst().joined(separator: "::") |
| 45 | } else if link.firstMatch(of: /^[a-zA-Z][-a-zA-Z0-9+]*:/) != nil { | |
| 50 | } else if link.firstMatch(of: typePrefix) != nil { | |
| 46 | 51 | return false |
| 47 | 52 | } else { |
| 48 | 53 | // Within the file. |
| @@ -66,13 +71,12 @@ public enum Backlinks { | ||
| 66 | 71 | /// description, else what they link to), and the range of that link in the line. A line |
| 67 | 72 | /// longer than `width` keeps the part around the link. |
| 68 | 73 | public static func context(in body: String, link: String, width: Int = 160) -> (text: String, link: Range<Int>)? { |
| 69 | let pattern = /\[\[((?:[^\]\\]|\\.)+)\](?:\[([^\]]*)\])?\]/ | |
| 70 | 74 | for line in body.split(whereSeparator: \.isNewline) { |
| 71 | 75 | guard line.contains("[[" + link + "]") else { continue } |
| 72 | 76 | var text = "" |
| 73 | 77 | var found: Range<Int>? |
| 74 | 78 | var rest = Substring(line) |
| 75 | while let match = rest.firstMatch(of: pattern) { | |
| 79 | while let match = rest.firstMatch(of: bracketLink) { | |
| 76 | 80 | text += rest[..<match.range.lowerBound] |
| 77 | 81 | let shown = match.2.map(String.init) ?? String(match.1) |
| 78 | 82 | let start = text.utf16.count |
Sources/OrgCore/Links/Links.swift +4 −2
| @@ -33,12 +33,14 @@ public enum Links { | ||
| 33 | 33 | pattern: "^(" + types.sorted { $0.count > $1.count }.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|") + "):" |
| 34 | 34 | ) |
| 35 | 35 | |
| 36 | /// Runs of backslashes before a bracket or the end. | |
| 37 | private static let escapes = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])") | |
| 38 | ||
| 36 | 39 | /// `org-link-unescape`: halves each run of backslashes before a bracket or the end. |
| 37 | 40 | static func unescape(_ s: String) -> String { |
| 38 | let regex = try! NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])") | |
| 39 | 41 | let ns = s as NSString |
| 40 | 42 | var out = s |
| 41 | for m in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() { | |
| 43 | for m in escapes.matches(in: s, range: NSRange(location: 0, length: ns.length)).reversed() { | |
| 42 | 44 | let run = m.range(at: 1) |
| 43 | 45 | out = (out as NSString).replacingCharacters(in: run, with: String(repeating: "\\", count: run.length / 2)) |
| 44 | 46 | } |
Sources/Orgstar/BacklinksPane.swift +17 −11
| @@ -21,7 +21,8 @@ struct BacklinksPane: View { | ||
| 21 | 21 | private struct Key: Equatable { |
| 22 | 22 | var path: String? |
| 23 | 23 | var heading: Int? |
| 24 | var version: Int | |
| 24 | var title: String? | |
| 25 | var index: Int | |
| 25 | 26 | } |
| 26 | 27 | |
| 27 | 28 | var body: some View { |
| @@ -32,7 +33,7 @@ struct BacklinksPane: View { | ||
| 32 | 33 | Section("Links to this file") { rows(toFile) } |
| 33 | 34 | } |
| 34 | 35 | .themedListBackground(theme.color("sidebar-background", in: colorScheme)) |
| 35 | .task(id: Key(path: session.path, heading: heading?.start, version: session.editVersion)) { refresh() } | |
| 36 | .task(id: Key(path: session.path, heading: heading?.start, title: heading?.title, index: workspace.indexVersion)) { await refresh() } | |
| 36 | 37 | } |
| 37 | 38 | |
| 38 | 39 | @ViewBuilder |
| @@ -56,23 +57,28 @@ struct BacklinksPane: View { | ||
| 56 | 57 | } |
| 57 | 58 | } |
| 58 | 59 | |
| 59 | private func refresh() { | |
| 60 | private func refresh() async { | |
| 60 | 61 | guard let path = session.path else { |
| 61 | 62 | toHeading = [] |
| 62 | 63 | toFile = [] |
| 63 | 64 | return |
| 64 | 65 | } |
| 65 | 66 | let overlay = workspace.overlay(session.openDocuments) |
| 67 | let found = await Self.backlinks(in: workspace, path: path, tree: session.document?.tree, heading: heading?.start, overlay: overlay) | |
| 68 | guard !Task.isCancelled else { return } | |
| 69 | (toFile, toHeading) = found | |
| 70 | } | |
| 71 | ||
| 72 | @concurrent | |
| 73 | private nonisolated static func backlinks( | |
| 74 | in workspace: WorkspaceModel, path: String, tree: OrgTree?, heading: Int?, overlay: [String: FileRecord] | |
| 75 | ) async -> (toFile: [HeadingLocation], toHeading: [HeadingLocation]) { | |
| 76 | let model = tree.map { DocumentModel(tree: $0) } | |
| 66 | 77 | // The file's own ID, as an org-roam file node. |
| 67 | let fileID = session.document.map { DocumentModel(tree: $0.tree).property("ID", of: nil)?.value } | |
| 68 | toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: fileID ?? nil), overlay: overlay) | |
| 69 | guard let heading, let tree = session.document?.tree, | |
| 70 | let info = DocumentModel(tree: tree).headings.first(where: { $0.headingRange.lowerBound == heading.start }) else { | |
| 71 | toHeading = [] | |
| 72 | return | |
| 73 | } | |
| 78 | let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model?.property("ID", of: nil)?.value), overlay: overlay) | |
| 79 | guard let heading, let info = model?.headings.first(where: { $0.headingRange.lowerBound == heading }) else { return (toFile, []) } | |
| 74 | 80 | let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value |
| 75 | 81 | let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID) |
| 76 | toHeading = workspace.backlinks(to: target, excluding: heading.start, overlay: overlay) | |
| 82 | return (toFile, workspace.backlinks(to: target, excluding: heading, overlay: overlay)) | |
| 77 | 83 | } |
| 78 | 84 | } |
Sources/OrgstarMobile/BacklinksScreen.swift +15 −6
| @@ -28,7 +28,7 @@ struct BacklinksScreen: View { | ||
| 28 | 28 | .navigationBarTitleDisplayMode(.inline) |
| 29 | 29 | .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } } |
| 30 | 30 | } |
| 31 | .task { refresh() } | |
| 31 | .task { await refresh() } | |
| 32 | 32 | } |
| 33 | 33 | |
| 34 | 34 | @ViewBuilder |
| @@ -52,15 +52,24 @@ struct BacklinksScreen: View { | ||
| 52 | 52 | } |
| 53 | 53 | } |
| 54 | 54 | |
| 55 | private func refresh() { | |
| 55 | private func refresh() async { | |
| 56 | 56 | let overlay = workspace.overlay(session.openDocuments) |
| 57 | 57 | guard let document = session.openDocuments.first(where: { $0.path == path })?.document else { return } |
| 58 | let model = DocumentModel(tree: document.tree) | |
| 59 | toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay) | |
| 60 | guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return heading = nil } | |
| 58 | let found = await Self.backlinks(in: workspace, path: path, tree: document.tree, caret: caret, overlay: overlay) | |
| 59 | guard !Task.isCancelled else { return } | |
| 60 | (toFile, heading) = found | |
| 61 | } | |
| 62 | ||
| 63 | @concurrent | |
| 64 | private nonisolated static func backlinks( | |
| 65 | in workspace: WorkspaceModel, path: String, tree: OrgTree, caret: Int, overlay: [String: FileRecord] | |
| 66 | ) async -> (toFile: [HeadingLocation], heading: (title: String, links: [HeadingLocation])?) { | |
| 67 | let model = DocumentModel(tree: tree) | |
| 68 | let toFile = workspace.backlinks(to: Backlinks.Target(path: path, id: model.property("ID", of: nil)?.value), overlay: overlay) | |
| 69 | guard let info = model.headings.last(where: { $0.headingRange.lowerBound <= caret }) else { return (toFile, nil) } | |
| 61 | 70 | let customID = info.properties.last { $0.key.uppercased() == "CUSTOM_ID" }?.value |
| 62 | 71 | let target = Backlinks.Target(path: path, title: info.title, id: info.id, customID: customID) |
| 63 | heading = (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay)) | |
| 72 | return (toFile, (info.title, workspace.backlinks(to: target, excluding: info.headingRange.lowerBound, overlay: overlay))) | |
| 64 | 73 | } |
| 65 | 74 | } |
| 66 | 75 | #endif |
Tests/OrgAppTests/AppTests.swift +2
| @@ -149,6 +149,8 @@ struct WorkspaceModelTests { | ||
| 149 | 149 | #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"]) |
| 150 | 150 | #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"]) |
| 151 | 151 | #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"]) |
| 152 | // Off the main actor, as the panes ask. | |
| 153 | #expect(await Task.detached { model.backlinks(to: sink).map(\.title) }.value == ["Plumbing", "Other", "c.org"]) | |
| 152 | 154 | // Each with the line its link is on, the link as it reads. |
| 153 | 155 | #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."]) |
| 154 | 156 | #expect(model.backlinks(to: sink).first?.snippet?.matches == [0..<8]) |
Tests/OrgCoreTests/BacklinkTests.swift +19
| @@ -24,6 +24,25 @@ struct BacklinkTests { | ||
| 24 | 24 | #expect(!links("*Fix the sink", from: "/notes/b.org", to: heading)) |
| 25 | 25 | } |
| 26 | 26 | |
| 27 | /// The patterns are compiled once, not for each link: testing the links takes less time | |
| 28 | /// than compiling them that often would. | |
| 29 | @Test func testsManyLinksWithoutCompilingPatterns() throws { | |
| 30 | let links = (0..<20_000).map { ["id:abc-\($0)", "file:a.org::*Fix the sink", "https://example.org/\($0)", "Fix the sink"][$0 % 4] } | |
| 31 | let clock = ContinuousClock() | |
| 32 | let compiling = try clock.measure { | |
| 33 | for index in links.indices { | |
| 34 | _ = try NSRegularExpression(pattern: "(\\\\+)(?=$|[\\[\\]])") | |
| 35 | if index % 2 == 0 { _ = try Regex("^[a-zA-Z][-a-zA-Z0-9+]*:") } | |
| 36 | } | |
| 37 | } | |
| 38 | var hits = 0 | |
| 39 | let testing = clock.measure { | |
| 40 | for link in links where Backlinks.links(link, from: "/notes/b.org", to: heading, home: "/home") { hits += 1 } | |
| 41 | } | |
| 42 | #expect(hits == 5_000) | |
| 43 | #expect(testing < compiling / 2, "\(testing) against \(compiling)") | |
| 44 | } | |
| 45 | ||
| 27 | 46 | @Test func followsDenoteLinks() { |
| 28 | 47 | let file = Backlinks.Target(path: "/notes/20261119T120000--a-note__kw.org") |
| 29 | 48 | let heading = Backlinks.Target(path: file.path, title: "Inside", customID: "in") |