Faster reader, fewer redraws !199

merged merged by cmc on 2026-10-10 04:43 UTC · krz/orgstar:reader-responsiveness into main

11 files changed, +239 −64

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +44 −9
@@ -9,6 +9,8 @@ import OrgPresentation
99@MainActor
1010public final class AgendaSourceCache {
1111 var entries: [String: (mtime: Date, size: Int, defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
12 /// Open buffers' sources, kept while their text is the same.
13 var open: [String: (defaults: OrgSettings, blocking: Bool, source: AgendaSource)] = [:]
1214
1315 public init() {}
1416}
@@ -101,11 +103,12 @@ public final class AgendaModel {
101103 return (days, list, events)
102104 }.value
103105 guard id == generation else { return }
104 days = result.0
105 list = result.1
106 events = result.2
107 self.today = today
108 self.calendar = calendar
106 // Unchanged results leave the views alone: a new value redraws the whole list.
107 if days != result.0 { days = result.0 }
108 if list != result.1 { list = result.1 }
109 if events != result.2 { events = result.2 }
110 if self.today != today { self.today = today }
111 if self.calendar != calendar { self.calendar = calendar }
109112 isComputing = false
110113 }
111114
@@ -131,7 +134,15 @@ public final class AgendaModel {
131134 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
132135 for path in files {
133136 if let text = open[path] {
134 reads.append((path, nil, .distantPast, -1, text))
137 // The same text parsed before, as the buffer or as the file on disk.
138 func reusable(_ source: AgendaSource?, _ parsedWith: OrgSettings?, _ parsedBlocking: Bool?) -> AgendaSource? {
139 guard let source, parsedWith == defaults, parsedBlocking == blocking, !source.readsSetupFiles, source.text == text else { return nil }
140 return source
141 }
142 let fromOpen = cache.open[path]
143 let fromDisk = cache.entries[path]
144 let cached = reusable(fromOpen?.source, fromOpen?.defaults, fromOpen?.blocking) ?? reusable(fromDisk?.source, fromDisk?.defaults, fromDisk?.blocking)
145 reads.append((path, cached, .distantPast, -1, text))
135146 continue
136147 }
137148 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
@@ -147,7 +158,7 @@ public final class AgendaModel {
147158 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
148159 for read in reads {
149160 if let cached = read.cached {
150 sources.append((read.path, read.mtime, read.size, cached, true))
161 sources.append((read.path, read.mtime, read.size, cached, read.text == nil))
151162 } else if let text = read.text {
152163 sources.append((read.path, read.mtime, read.size, AgendaSource(path: read.path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: read.path, read: OrgSettings.readFile), checksBlocking: blocking), false))
153164 } else if let data = FileManager.default.contents(atPath: read.path) {
@@ -157,8 +168,12 @@ public final class AgendaModel {
157168 }
158169 return sources
159170 }.value
160 for source in loaded where source.fromDisk {
161 cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
171 for source in loaded {
172 if source.fromDisk {
173 cache.entries[source.path] = (source.mtime, source.size, defaults, blocking, source.source)
174 } else {
175 cache.open[source.path] = (defaults, blocking, source.source)
176 }
162177 }
163178 return loaded.map(\.source)
164179 }
@@ -169,6 +184,26 @@ public final class AgendaModel {
169184 AgendaRows.groups(days, events: events, today: today, showAllDates: showAllDates, calendar: calendar, keep: keep)
170185 }
171186
187 /// `groups` with `filter`, kept while the days, events and arguments are the same, as
188 /// views ask on every redraw.
189 public func groups(showAllDates: Bool, filter: AgendaFilter) -> [AgendaDayGroup] {
190 let key = GroupsKey(days: days, events: events, today: today, showAllDates: showAllDates, filter: filter)
191 if let groupsMemo, groupsMemo.key == key { return groupsMemo.groups }
192 let groups = groups(showAllDates: showAllDates, keep: filter.keeps)
193 groupsMemo = (key, groups)
194 return groups
195 }
196
197 private struct GroupsKey: Equatable {
198 let days: [AgendaDay]
199 let events: [AgendaEvent]
200 let today: Int
201 let showAllDates: Bool
202 let filter: AgendaFilter
203 }
204
205 @ObservationIgnored private var groupsMemo: (key: GroupsKey, groups: [AgendaDayGroup])?
206
172207 nonisolated static func date(_ day: Int, calendar: Calendar) -> Date {
173208 let d = Days.date(day)
174209 return calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
Sources/OrgCore/Agenda/AgendaSource.swift +1 −1
@@ -109,7 +109,7 @@ public struct AgendaSource: Sendable {
109109 /// Each keyword's first done keyword in the first sequence that has it.
110110 let firstDone: [String: String]
111111 /// The file's text, for the search view.
112 let text: String
112 public let text: String
113113 let priorities: Priorities
114114
115115 /// `checksBlocking` false leaves every heading unblocked, for when neither enforce
Sources/OrgCore/Syntax/SyntaxNode.swift +25 −1
@@ -1,3 +1,5 @@
1import Foundation
2
13/// A view of a green node at an absolute offset, with a parent link. Created on demand.
24public final class SyntaxNode: Sendable {
35 public let green: GreenNode
@@ -112,7 +114,29 @@ public struct SyntaxToken: Sendable, Equatable {
112114public struct OrgTree: Sendable {
113115 public let green: GreenNode
114116 public let settings: OrgSettings
117 private let textCache = TextCache()
118
119 public init(green: GreenNode, settings: OrgSettings) {
120 self.green = green
121 self.settings = settings
122 }
115123
116124 public var root: SyntaxNode { SyntaxNode(green: green, offset: 0, parent: nil) }
117 public var text: String { green.text }
125 /// Built from the tree on first use, then kept: views read it once per heading.
126 public var text: String { textCache.text(of: green) }
127}
128
129/// An `OrgTree`'s text, built once.
130private final class TextCache: @unchecked Sendable {
131 private let lock = NSLock()
132 private var text: String?
133
134 func text(of green: GreenNode) -> String {
135 lock.withLock {
136 if let text { return text }
137 let built = green.text
138 text = built
139 return built
140 }
141 }
118142}
Sources/OrgCore/Syntax/Wrappers.swift +16 −12
@@ -1,3 +1,5 @@
1import Foundation
2
13/// Drawers and blocks, the elements org folds on their own (`org-fold-hide-drawer-toggle`,
24/// `org-fold-hide-block-toggle`).
35public struct Wrapper: Sendable, Equatable {
@@ -21,18 +23,19 @@ public enum Wrappers {
2123 }
2224 }
2325
24 static func wrapper(_ node: SyntaxNode) -> Wrapper? {
26 /// `text` is the document's, read in place rather than copying the node's text.
27 static func wrapper(_ node: SyntaxNode, in text: NSString) -> Wrapper? {
2528 guard let kind = kind(node.kind) else { return nil }
26 let units = Array(node.text.utf16)
29 let start = node.range.lowerBound
2730 // Blank lines after the element belong to it in the tree, not to the fold.
28 var end = units.count
29 while end > 0, [9, 10, 13, 32].contains(units[end - 1]) { end -= 1 }
30 guard let firstNewline = units.firstIndex(of: 10), firstNewline < end else { return nil }
31 var end = node.range.upperBound
32 while end > start, [9, 10, 13, 32].contains(text.character(at: end - 1)) { end -= 1 }
33 let firstNewline = text.range(of: "\n", options: .literal, range: NSRange(start..<end)).location
34 guard firstNewline != NSNotFound else { return nil }
3135 var closeStart = end
32 while closeStart > 0, units[closeStart - 1] != 10 { closeStart -= 1 }
33 let hiddenEnd = end < units.count ? end + 1 : end
34 return Wrapper(kind: kind, start: node.range.lowerBound, closeLine: node.range.lowerBound + closeStart,
35 hidden: (node.range.lowerBound + firstNewline + 1)..<(node.range.lowerBound + hiddenEnd))
36 while closeStart > start, text.character(at: closeStart - 1) != 10 { closeStart -= 1 }
37 let hiddenEnd = end < node.range.upperBound ? end + 1 : end
38 return Wrapper(kind: kind, start: start, closeLine: closeStart, hidden: (firstNewline + 1)..<hiddenEnd)
3639 }
3740
3841 /// Elements a drawer or block can sit in.
@@ -41,9 +44,10 @@ public enum Wrappers {
4144 /// Every drawer and block, in document order, nested ones included.
4245 public static func all(_ tree: OrgTree) -> [Wrapper] {
4346 var result: [Wrapper] = []
47 let text = tree.text as NSString
4448 func walk(_ node: SyntaxNode) {
4549 for child in node.children {
46 if let wrapper = wrapper(child) { result.append(wrapper) }
50 if let wrapper = wrapper(child, in: text) { result.append(wrapper) }
4751 if containers.contains(child.kind) { walk(child) }
4852 }
4953 }
@@ -55,7 +59,7 @@ public enum Wrappers {
5559 public static func starting(at offset: Int, in tree: OrgTree) -> Wrapper? {
5660 var node = tree.root
5761 while let child = node.child(containing: offset) {
58 if child.range.lowerBound == offset, let wrapper = wrapper(child) { return wrapper }
62 if child.range.lowerBound == offset, let wrapper = wrapper(child, in: tree.text as NSString) { return wrapper }
5963 node = child
6064 }
6165 return nil
@@ -67,7 +71,7 @@ public enum Wrappers {
6771 var node = tree.root
6872 var found: Wrapper?
6973 while let child = node.child(containing: offset) {
70 if let wrapper = wrapper(child), offset < wrapper.hidden.lowerBound || (wrapper.closeLine..<wrapper.hidden.upperBound).contains(offset) {
74 if let wrapper = wrapper(child, in: tree.text as NSString), offset < wrapper.hidden.lowerBound || (wrapper.closeLine..<wrapper.hidden.upperBound).contains(offset) {
7175 found = wrapper
7276 }
7377 node = child
Sources/OrgPresentation/Presentation.swift +13
@@ -1,4 +1,5 @@
11import OrgCore
2import os
23
34/// What a range of text is, for styling. Platform adapters map roles to attributes.
45public enum StyleRole: Hashable, Sendable {
@@ -208,7 +209,19 @@ public enum Presentation {
208209 }
209210
210211 /// Blocks and fixed-width areas, drawn on a shaded band the width of the view. Sorted.
212 /// The last tree's are kept: the reader asks once per section.
211213 public static func shadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
214 shadedBlocksCache.withLock { last in
215 if let last, last.green === tree.green { return last.ranges }
216 let ranges = computeShadedBlocks(tree)
217 last = (tree.green, ranges)
218 return ranges
219 }
220 }
221
222 private static let shadedBlocksCache = OSAllocatedUnfairLock<(green: GreenNode, ranges: [Range<Int>])?>(initialState: nil)
223
224 private static func computeShadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
212225 var ranges: [Range<Int>] = []
213226 func walk(_ node: SyntaxNode) {
214227 for child in node.children {
Sources/OrgPresentation/ReadingText.swift +38 −11
@@ -35,7 +35,6 @@ public enum ReadingText {
3535 /// `folded` are drawers' and blocks' hidden ranges (`Wrapper.hidden`).
3636 public static func segments(_ tree: OrgTree, in range: Range<Int>, folded: [Range<Int>] = [], display: Display = Display()) -> [Segment] {
3737 let text = tree.text as NSString
38 let runs = Presentation.styles(tree, in: range, highlighter: display.highlighter)
3938 // A fold hides from the end of the opening line through the closing line, so the
4039 // marker sits on the opening line.
4140 let folds = folded.compactMap { r -> Range<Int>? in
@@ -43,17 +42,28 @@ public enum ReadingText {
4342 let end = r.upperBound > r.lowerBound && r.upperBound <= text.length && text.character(at: r.upperBound - 1) == 10 ? r.upperBound - 1 : r.upperBound
4443 return (r.lowerBound - 1)..<min(end, range.upperBound)
4544 }
45 // Styled only where shown: a folded drawer can hold most of a section.
46 var visible: [Range<Int>] = []
47 var from = range.lowerBound
48 for fold in folds.sorted(by: { $0.lowerBound < $1.lowerBound }) where fold.upperBound > from {
49 if fold.lowerBound > from { visible.append(from..<fold.lowerBound) }
50 from = fold.upperBound
51 }
52 if from < range.upperBound || visible.isEmpty { visible.append(from..<max(from, range.upperBound)) }
53 let runs = visible.flatMap { Presentation.styles(tree, in: $0, highlighter: display.highlighter) }
4654 var hidden = runs.filter { !display.showMarkup && Presentation.hidesWithMarkup($0.role, options: display.options) }.map(\.range) + folds
4755 // `org-pretty-entities`: an entity's last character shows its character, the rest hidden.
4856 var replaced: [Int: String] = [:]
4957 var scripts: [(range: Range<Int>, superscript: Bool)] = []
5058 if !display.showMarkup, display.options.prettyEntities {
5159 let blocks = Presentation.shadedBlocks(tree)
52 let pretty = Presentation.prettyRuns(
53 text, in: range, revealedLine: nil, inBlock: { offset in blocks.contains { $0.contains(offset) } },
54 scriptExclusions: runs.filter { Presentation.excludesScripts($0.role) }.map(\.range),
55 subSuperscriptsNeedBraces: display.options.subSuperscriptsNeedBraces
56 )
60 let exclusions = runs.filter { Presentation.excludesScripts($0.role) }.map(\.range)
61 let pretty = visible.flatMap { part in
62 Presentation.prettyRuns(
63 text, in: part, revealedLine: nil, inBlock: { offset in blocks.contains { $0.contains(offset) } },
64 scriptExclusions: exclusions, subSuperscriptsNeedBraces: display.options.subSuperscriptsNeedBraces
65 )
66 }
5767 for (lineStart, run) in pretty {
5868 switch run {
5969 case .entity(let r, let shown):
@@ -83,14 +93,31 @@ public enum ReadingText {
8393 segments.append(segment)
8494 }
8595 }
86 for (a, b) in zip(points, points.dropFirst()) where a < b {
87 if folds.contains(where: { $0.lowerBound == a }) {
96 // What covers each interval between consecutive points, marked range by range rather
97 // than tested interval by interval, which grows with the square of a long section.
98 let intervals = max(points.count - 1, 0)
99 var position: [Int: Int] = [:]
100 for (k, point) in points.enumerated() { position[point] = k }
101 func covered(_ r: Range<Int>) -> Range<Int> {
102 let lo = position[max(range.lowerBound, min(range.upperBound, r.lowerBound))]!
103 let hi = position[max(range.lowerBound, min(range.upperBound, r.upperBound))]!
104 return lo..<max(lo, hi)
105 }
106 var rolesAt = [Set<StyleRole>](repeating: [], count: intervals)
107 for run in runs { for k in covered(run.range) { rolesAt[k].insert(run.role) } }
108 var hiddenAt = [Bool](repeating: false, count: intervals)
109 for r in hidden { for k in covered(r) { hiddenAt[k] = true } }
110 var scriptAt = [Bool?](repeating: nil, count: intervals)
111 for script in scripts { for k in covered(script.range) where scriptAt[k] == nil { scriptAt[k] = script.superscript } }
112 let foldStarts = Set(folds.map(\.lowerBound))
113 for (k, (a, b)) in zip(points, points.dropFirst()).enumerated() {
114 if foldStarts.contains(a) {
88115 segments.append(Segment(text: "…", roles: [.metadata], link: nil, offset: a))
89116 }
90 if hidden.contains(where: { $0.lowerBound <= a && b <= $0.upperBound }) { continue }
91 let roles = Set(runs.filter { $0.range.lowerBound <= a && b <= $0.range.upperBound }.map(\.role))
117 if hiddenAt[k] { continue }
118 let roles = rolesAt[k]
92119 let link = roles.contains(.link) ? Links.link(at: a, text: tree.text, tree: tree)?.link : nil
93 let superscript = scripts.first { $0.range.lowerBound <= a && b <= $0.range.upperBound }?.superscript
120 let superscript = scriptAt[k]
94121 let shown = replaced[a] ?? text.substring(with: NSRange(location: a, length: b - a))
95122 let segment = Segment(text: shown, roles: roles, link: link, offset: a, superscript: superscript)
96123 if replaced[a] != nil { segments.append(segment) } else { append(segment) }
Sources/Orgstar/AgendaView.swift +1 −1
@@ -159,7 +159,7 @@ struct AgendaView: View {
159159 }
160160
161161 private var groups: [AgendaDayGroup] {
162 isAgenda ? agenda.groups(showAllDates: showAllDates, keep: filter.keeps) : []
162 isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : []
163163 }
164164
165165 private var listRows: [AgendaRow] {
Sources/OrgstarMobile/AgendaScreen.swift +31 −10
@@ -8,7 +8,7 @@ import SwiftUI
88/// The agenda over the workspace's agenda files: the day/week view, the TODO list, tag and
99/// property matches, text search and the views in `views.toml`, with Org's filters and the
1010/// agenda's actions on each entry.
11struct AgendaScreen: View {
11struct AgendaScreen: View, Equatable {
1212 let workspace: WorkspaceModel
1313 let session: DocumentSession
1414 @Bindable var agenda: AgendaModel
@@ -67,6 +67,11 @@ struct AgendaScreen: View {
6767 var logMode: Bool
6868 }
6969
70 /// The same models: the root redrawing for navigation leaves the list alone.
71 nonisolated static func == (a: Self, b: Self) -> Bool {
72 a.workspace === b.workspace && a.session === b.session && a.agenda === b.agenda && a.scheduler === b.scheduler
73 }
74
7075 private var isDark: Bool { colorScheme == .dark }
7176 private var theme: ThemeSpec { model.theme }
7277
@@ -76,7 +81,7 @@ struct AgendaScreen: View {
7681 if workspace.rootPaths.isEmpty {
7782 } else if case .agenda = agenda.mode {
7883 let _ = model.settingsVersion
79 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), keep: filter.keeps) }) { group in
84 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter) }) { group in
8085 Section {
8186 day(group)
8287 } header: {
@@ -203,14 +208,30 @@ struct AgendaScreen: View {
203208 guard OrgPreferences.calendarEvents(), !CalendarEvents.isAuthorized else { return }
204209 if await model.calendarEvents.requestAccess() { tick += 1 }
205210 }
206 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
207 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
208 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) {
209 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
210 try? await Task.sleep(for: .milliseconds(150))
211 guard !Task.isCancelled else { return }
212 agenda.options.logMode = logMode
213 await agenda.refresh(open: session.openTexts)
211 .background { Refresher(workspace: workspace, session: session, agenda: agenda, model: model, tick: tick, logMode: logMode) }
212 }
213
214 /// Refreshes the agenda when files, edits or settings change. Its own view, so that what it
215 /// watches redraws only it, not the whole list.
216 private struct Refresher: View {
217 let workspace: WorkspaceModel
218 let session: DocumentSession
219 let agenda: AgendaModel
220 let model: MobileModel
221 let tick: Int
222 let logMode: Bool
223
224 var body: some View {
225 Color.clear
226 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
227 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
228 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) {
229 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
230 try? await Task.sleep(for: .milliseconds(150))
231 guard !Task.isCancelled else { return }
232 agenda.options.logMode = logMode
233 await agenda.refresh(open: session.openTexts)
234 }
214235 }
215236 }
216237
Sources/OrgstarMobile/OrgstarMobileApp.swift +33 −15
@@ -99,6 +99,37 @@ struct RootView: View {
9999
100100 private var session: DocumentSession { model.session }
101101
102 /// Reminders, widgets and Spotlight following the files. Its own view, so that edits redraw
103 /// only it, not the tabs.
104 private struct BackgroundWork: View {
105 let model: MobileModel
106 let workspace: WorkspaceModel
107 let agenda: AgendaModel
108 let active: Bool
109 let hour: Int
110
111 private var session: DocumentSession { model.session }
112
113 var body: some View {
114 Color.clear
115 // Reminders follow the files, the settings, coming back to the app and the hour.
116 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
117 settings: model.settingsVersion, active: active, hour: hour)) {
118 guard active else { return }
119 try? await Task.sleep(for: .seconds(1))
120 // After the agenda's refresh, whose parsed files these share.
121 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
122 guard !Task.isCancelled else { return }
123 await model.updateReminders()
124 await model.updateWidgets()
125 }
126 // Spotlight follows the files and saved edits.
127 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
128 await model.spotlight.update(workspace.files)
129 }
130 }
131 }
132
102133 private struct SpotlightKey: Equatable {
103134 var files: Int
104135 var changed: Int?
@@ -119,6 +150,7 @@ struct RootView: View {
119150 Tab("Agenda", systemImage: "calendar", value: .agenda) {
120151 NavigationStack(path: $agendaPath) {
121152 AgendaScreen(workspace: workspace, session: session, agenda: agenda, scheduler: model.scheduler)
153 .equatable()
122154 .toolbar { captureButton }
123155 .readerDestination(workspace: workspace, session: session)
124156 }
@@ -197,21 +229,7 @@ struct RootView: View {
197229 hour += 1
198230 }
199231 }
200 // Reminders follow the files, the settings, coming back to the app and the hour.
201 .task(id: ReminderKey(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
202 settings: model.settingsVersion, active: scenePhase == .active, hour: hour)) {
203 guard scenePhase == .active else { return }
204 try? await Task.sleep(for: .seconds(1))
205 // After the agenda's refresh, whose parsed files these share.
206 while agenda.isComputing, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(100)) }
207 guard !Task.isCancelled else { return }
208 await model.updateReminders()
209 await model.updateWidgets()
210 }
211 // Spotlight follows the files and saved edits.
212 .task(id: SpotlightKey(files: workspace.files.count, changed: workspace.changedFile?.version, saved: session.dirtyPaths.count)) {
213 await model.spotlight.update(workspace.files)
214 }
232 .background { BackgroundWork(model: model, workspace: workspace, agenda: agenda, active: scenePhase == .active, hour: hour) }
215233 .onContinueUserActivity(CSSearchableItemActionType) { activity in
216234 if let path = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String { model.openRequest = .file(path) }
217235 }
Sources/OrgstarMobile/ReaderScreen.swift +22 −4
@@ -38,6 +38,21 @@ struct ReaderScreen: View {
3838
3939 private var outline: [OutlineEntry] { session.outline }
4040
41 /// The file this reader shows. Readers lower in the stack stay alive while the session
42 /// shows another file, and draw nothing then.
43 private var path: String {
44 switch route {
45 case .file(let path), .offset(let path, _): path
46 case .heading(let location): location.path
47 }
48 }
49
50 /// The session shows this reader's file; it opens files by their resolved paths.
51 private var showsOwnFile: Bool {
52 guard let current = session.path else { return false }
53 return current == path || current == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
54 }
55
4156 var body: some View {
4257 let _ = session.editVersion
4358 // Read again when settings or the Dynamic Type size change.
@@ -47,11 +62,14 @@ struct ReaderScreen: View {
4762 ScrollViewReader { proxy in
4863 ScrollView(truncated ? [.vertical, .horizontal] : .vertical) {
4964 LazyVStack(alignment: .leading, spacing: 8) {
50 if let tree = session.document?.tree {
51 let preambleEnd = outline.first?.start ?? (tree.text as NSString).length
65 if let tree = session.document?.tree, showsOwnFile {
66 let length = (tree.text as NSString).length
67 let preambleEnd = min(outline.first?.start ?? length, length)
5268 if preambleEnd > 0 { textView(tree, 0..<preambleEnd, theme) }
5369 ForEach(Array(outline.enumerated()), id: \.element.start) { index, entry in
54 if isShown(index) {
70 // While another file opens, rows can update with the last file's
71 // entries for a moment; those don't fit this text.
72 if index < outline.count, outline[index] == entry, entry.end <= length, isShown(index) {
5573 heading(tree, entry, theme).id(entry.start)
5674 if !fold.folds.contains(entry.start), !fold.bodyFolds.contains(entry.start) {
5775 let body = bodyRange(index, tree)
@@ -293,7 +311,7 @@ struct ReaderScreen: View {
293311 /// The file's startup display, as the editor opens it; its heading folds are kept while
294312 /// the same file is open.
295313 private func loadFolds() {
296 guard let tree = session.document?.tree else { return }
314 guard let tree = session.document?.tree, showsOwnFile else { return }
297315 let display = Presentation.startupDisplay(tree, options: session.options)
298316 startup = display
299317 folded = display.wrappers.map(\.hidden)
Tests/OrgAppTests/AppTests.swift +15
@@ -524,6 +524,21 @@ enum StateBufferCaret {
524524
525525@MainActor
526526struct AgendaModelTests {
527 @Test func openBuffersFollowTheirText() async throws {
528 let notes = try Folder()
529 let file = try notes.write("a.org", "* TODO One\n")
530 let model = try WorkspaceModel(directory: nil)
531 try await model.addRoot(notes.url)
532 let agenda = AgendaModel(workspace: model)
533 agenda.mode = .todo(keywords: nil)
534 for text in ["* TODO One\n", "* TODO Two\n", "* TODO One\n", "* TODO Two\n"] {
535 await agenda.refresh(open: [file.path: text])
536 #expect(agenda.list.map(\.text) == [String(text.dropFirst(2).dropLast())])
537 }
538 await agenda.refresh(open: [:])
539 #expect(agenda.list.map(\.text) == ["TODO One"])
540 }
541
527542 @Test func entriesKnowTheirDoneKeyword() async throws {
528543 let notes = try Folder()
529544 try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")