Commit 3751eb7330

3751eb733020e3cdc9832f98bc6720b65a1f2ecb

parent: 8239baf5aa

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 21:37 UTC

iOS: Find in the editor and reader toolbars

Both open the system find bar. The editor selects the result shown and
unfolds it; the reader marks the results and unfolds and scrolls to the
one shown.

Ref #222

Layout: unified · split

Changed files (5)
Sources/OrgstarMobile/EditorScreen.swift +3 · view
@@ -133,6 +133,9 @@ struct EditorScreen: View {
133 if pane?.conflict != nil { 133 if pane?.conflict != nil {
134 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict } 134 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
135 } 135 }
136 Button("Find", systemImage: "magnifyingglass") {
137 textView?.interactions.lazy.compactMap { $0 as? UIFindInteraction }.first?.presentFindNavigator(showingReplace: false)
138 }
136 // Redo on a long press, as the system's back buttons offer history. 139 // Redo on a long press, as the system's back buttons offer history.
137 Menu { 140 Menu {
138 Button("Redo", systemImage: "arrow.uturn.forward") { editor?.run("edit.redo") } 141 Button("Redo", systemImage: "arrow.uturn.forward") { editor?.run("edit.redo") }
Sources/OrgstarMobile/MobileEditor.swift +3 · view
@@ -193,6 +193,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
193 return handleKey(key) 193 return handleKey(key)
194 } 194 }
195 view.onLayout = { [weak self] in self?.viewResized() } 195 view.onLayout = { [weak self] in self?.viewResized() }
196 let find = EditorFind(view: view) { [weak self] in self?.unfold(around: $0) }
197 view.find = find
198 view.addInteraction(UIFindInteraction(sessionDelegate: find))
196 view.onFiles = { [weak self, weak view] files in 199 view.onFiles = { [weak self, weak view] files in
197 guard let self, let onFiles else { return false } 200 guard let self, let onFiles else { return false }
198 if let view { focus(view) } 201 if let view { focus(view) }
Sources/OrgstarMobile/MobileFragments.swift +77 · view
@@ -44,6 +44,8 @@ final class KeyedTextView: UITextView {
44 private var handled: Set<UIKeyboardHIDUsage>? 44 private var handled: Set<UIKeyboardHIDUsage>?
45 /// Called after each layout pass, as the view's size settles. 45 /// Called after each layout pass, as the view's size settles.
46 var onLayout: (() -> Void)? 46 var onLayout: (() -> Void)?
47 /// The find bar's session, which opens folded text before a result shows.
48 var find: EditorFind?
47 /// The text container's width while lines are truncated. 49 /// The text container's width while lines are truncated.
48 static let truncatedWidth: CGFloat = 100_000 50 static let truncatedWidth: CGFloat = 100_000
49 /// The widest the text runs, centred in a wider view; 0 for the view's width. 51 /// The widest the text runs, centred in a wider view; 0 for the view's width.
@@ -111,6 +113,81 @@ final class KeyedTextView: UITextView {
111 } 113 }
112} 114}
113 115
116/// The editor's find: the file's text searched, folded text opened before a result shows, and that result selected.
117final class EditorFind: NSObject, @preconcurrency UITextSearching, UIFindInteractionDelegate {
118 nonisolated(unsafe) private weak var view: UITextView?
119 private let found: (Int) -> Void
120
121 init(view: UITextView, found: @escaping (Int) -> Void) {
122 self.view = view
123 self.found = found
124 }
125
126 func findInteraction(_ interaction: UIFindInteraction, sessionFor view: UIView) -> UIFindSession? {
127 UITextSearchingFindSession(searchableObject: self)
128 }
129
130 var selectedTextRange: UITextRange? { view?.selectedTextRange }
131
132 func compare(_ foundRange: UITextRange, toRange: UITextRange, document: AnyHashable??) -> ComparisonResult {
133 view?.compare(foundRange, toRange: toRange, document: document) ?? .orderedSame
134 }
135
136 nonisolated func performTextSearch(queryString: String, options: UITextSearchOptions, resultAggregator: UITextSearchAggregator<AnyHashable?>) {
137 // The aggregator takes results from any thread; the view's ranges are made on the main thread.
138 nonisolated(unsafe) let aggregator = resultAggregator
139 let search = {
140 MainActor.assumeIsolated {
141 guard let view = self.view else { return }
142 for found in Self.matches(of: queryString, in: view.textStorage.string as NSString, options: options) {
143 guard let start = view.position(from: view.beginningOfDocument, offset: found.lowerBound),
144 let end = view.position(from: start, offset: found.count),
145 let range = view.textRange(from: start, to: end) else { continue }
146 aggregator.foundRange(range, searchString: queryString, document: nil)
147 }
148 }
149 aggregator.finishedSearching()
150 }
151 if Thread.isMainThread { search() } else { DispatchQueue.main.sync(execute: search) }
152 }
153
154 /// Where `query` is in `text`, as the find bar's options ask: case, and matching a word's
155 /// start or a whole word.
156 nonisolated static func matches(of query: String, in text: NSString, options: UITextSearchOptions) -> [Range<Int>] {
157 func isWord(_ index: Int) -> Bool {
158 guard index >= 0, index < text.length, let scalar = Unicode.Scalar(text.character(at: index)) else { return false }
159 return CharacterSet.alphanumerics.contains(scalar)
160 }
161 var matches: [Range<Int>] = []
162 var from = 0
163 while from < text.length {
164 let found = text.range(of: query, options: options.stringCompareOptions, range: NSRange(location: from, length: text.length - from))
165 guard found.location != NSNotFound, found.length > 0 else { break }
166 from = NSMaxRange(found)
167 switch options.wordMatchMethod {
168 case .startsWith: if isWord(found.location - 1) { continue }
169 case .fullWord: if isWord(found.location - 1) || isWord(NSMaxRange(found)) { continue }
170 default: break
171 }
172 matches.append(found.location..<NSMaxRange(found))
173 }
174 return matches
175 }
176
177 func decorate(foundTextRange: UITextRange, document: AnyHashable??, usingStyle style: UITextSearchFoundTextStyle) {
178 guard let view else { return }
179 view.decorate(foundTextRange: foundTextRange, document: document, usingStyle: style)
180 guard style == .highlighted else { return }
181 let start = view.offset(from: view.beginningOfDocument, to: foundTextRange.start)
182 found(start)
183 // The result shown is selected, as the Mac's find selects it.
184 view.selectedTextRange = foundTextRange
185 view.scrollRangeToVisible(NSRange(location: start, length: view.offset(from: foundTextRange.start, to: foundTextRange.end)))
186 }
187
188 func clearAllDecoratedFoundText() { view?.clearAllDecoratedFoundText() }
189}
190
114extension NSAttributedString.Key { 191extension NSAttributedString.Key {
115 /// The character an entity shows as, on the entity's last character. 192 /// The character an entity shows as, on the entity's last character.
116 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay") 193 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
Sources/OrgstarMobile/ReaderScreen.swift +149 · view
@@ -43,6 +43,12 @@ struct ReaderScreen: View {
43 @State private var previewed: URL? 43 @State private var previewed: URL?
44 /// The pane the reader shows its file in, closed with the reader. 44 /// The pane the reader shows its file in, closed with the reader.
45 @State private var holder = PaneHolder() 45 @State private var holder = PaneHolder()
46 /// The system find bar over the file's text, shown each time `findRequest` changes.
47 @State private var find = ReaderFind()
48 @State private var findRequest = 0
49 /// Find's results, true for the one shown, and the offset to scroll to.
50 @State private var found: [Range<Int>: Bool] = [:]
51 @State private var findTarget: Int?
46 @Environment(\.openURL) private var openURL 52 @Environment(\.openURL) private var openURL
47 @Environment(MobileModel.self) private var model 53 @Environment(MobileModel.self) private var model
48 54
@@ -103,11 +109,21 @@ struct ReaderScreen: View {
103 guard let offset = pane?.revealRequest?.offset else { return } 109 guard let offset = pane?.revealRequest?.offset else { return }
104 reveal(offset, proxy) 110 reveal(offset, proxy)
105 } 111 }
112 .onChange(of: findTarget) {
113 guard let offset = findTarget else { return }
114 findTarget = nil
115 showFound(offset, proxy)
116 }
106 } 117 }
107 .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent) 118 .navigationTitle(((shownPath ?? "") as NSString).lastPathComponent)
108 .navigationBarTitleDisplayMode(.inline) 119 .navigationBarTitleDisplayMode(.inline)
109 .toolbar { 120 .toolbar {
110 ToolbarItemGroup(placement: .primaryAction) { 121 ToolbarItemGroup(placement: .primaryAction) {
122 Button("Find", systemImage: "magnifyingglass") {
123 find.text = (document?.tree.text ?? "") as NSString
124 findRequest += 1
125 }
126 .disabled(document == nil)
111 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty) 127 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
112 if let path = shownPath { 128 if let path = shownPath {
113 if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } } 129 if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } }
@@ -119,6 +135,7 @@ struct ReaderScreen: View {
119 .sheet(isPresented: $showingOutline) { outlineSheet } 135 .sheet(isPresented: $showingOutline) { outlineSheet }
120 .message($message) 136 .message($message)
121 .environment(\.openURL, OpenURLAction { url in follow(url) }) 137 .environment(\.openURL, OpenURLAction { url in follow(url) })
138 .background { FindHost(find: find, request: findRequest) }
122 .onAppear(perform: open) 139 .onAppear(perform: open)
123 .onChange(of: pane?.path) { loadFolds() } 140 .onChange(of: pane?.path) { loadFolds() }
124 .onChange(of: pane?.editVersion) { loadFolds() } 141 .onChange(of: pane?.editVersion) { loadFolds() }
@@ -325,11 +342,45 @@ struct ReaderScreen: View {
325 } 342 }
326 part.font = Font(font as CTFont) 343 part.font = Font(font as CTFont)
327 part.foregroundColor = Color(uiColor: color) 344 part.foregroundColor = Color(uiColor: color)
345 if !found.isEmpty { markFound(&part, segment) }
328 result += part 346 result += part
329 } 347 }
330 return result 348 return result
331 } 349 }
332 350
351 /// Find's results in a segment's text: exactly where the segment shows the file as written,
352 /// otherwise the whole segment.
353 private func markFound(_ part: inout AttributedString, _ segment: ReadingText.Segment) {
354 let length = (segment.text as NSString).length
355 let span = segment.offset..<(segment.offset + length)
356 let source = (document?.tree.text ?? "") as NSString
357 let asWritten = span.upperBound <= source.length && source.substring(with: NSRange(span)) == segment.text
358 for (range, shown) in found where range.overlaps(span) || (span.isEmpty && range.contains(span.lowerBound)) {
359 let color = Color(uiColor: shown ? .systemYellow : .systemYellow.withAlphaComponent(0.35))
360 guard asWritten else {
361 part.backgroundColor = color
362 continue
363 }
364 let text = segment.text
365 func index(_ offset: Int) -> AttributedString.Index {
366 let utf16 = text.utf16.index(text.startIndex, offsetBy: min(max(0, offset - span.lowerBound), length))
367 return part.index(part.startIndex, offsetByCharacters: text.distance(from: text.startIndex, to: utf16))
368 }
369 let lower = index(range.lowerBound), upper = index(range.upperBound)
370 if lower < upper { part[lower..<upper].backgroundColor = color }
371 }
372 }
373
374 /// Unfolds the way to a find result, its heading and a drawer it's in, and scrolls to its heading.
375 private func showFound(_ offset: Int, _ proxy: ScrollViewProxy) {
376 folded.removeAll { $0.contains(offset) }
377 // Before the first heading, the text shows already.
378 guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return }
379 fold.folds.remove(outline[index].start)
380 fold.bodyFolds.remove(outline[index].start)
381 reveal(offset, proxy)
382 }
383
333 /// How deep a role's text usually nests: elements, then objects, then their parts. 384 /// How deep a role's text usually nests: elements, then objects, then their parts.
334 private static func depth(_ role: StyleRole) -> Int { 385 private static func depth(_ role: StyleRole) -> Int {
335 switch role { 386 switch role {
@@ -343,6 +394,8 @@ struct ReaderScreen: View {
343 // MARK: - Actions 394 // MARK: - Actions
344 395
345 private func open() { 396 private func open() {
397 find.onChange = { found = $0 }
398 find.onShow = { findTarget = $0 }
346 let pane = holder.pane ?? { 399 let pane = holder.pane ?? {
347 let made = session.makePane() 400 let made = session.makePane()
348 holder.pane = made 401 holder.pane = made
@@ -438,6 +491,102 @@ struct ReaderScreen: View {
438 } 491 }
439} 492}
440 493
494/// The reader's find, for the system find bar: it searches the file as written and tells the
495/// reader which results to mark and which one to show.
496@MainActor
497final class ReaderFind: NSObject, @preconcurrency UITextSearching, UIFindInteractionDelegate {
498 /// The file's text, set when the find bar opens.
499 nonisolated(unsafe) var text: NSString = ""
500 /// Each result marked, true for the one shown.
501 var onChange: ([Range<Int>: Bool]) -> Void = { _ in }
502 /// The result to show, by its offset.
503 var onShow: (Int) -> Void = { _ in }
504 private var marked: [Range<Int>: Bool] = [:]
505
506 final class Position: UITextPosition {
507 let offset: Int
508 init(_ offset: Int) { self.offset = offset }
509 }
510
511 final class TextRange: UITextRange {
512 let range: Range<Int>
513 init(_ range: Range<Int>) { self.range = range }
514 override var start: UITextPosition { Position(range.lowerBound) }
515 override var end: UITextPosition { Position(range.upperBound) }
516 override var isEmpty: Bool { range.isEmpty }
517 }
518
519 func findInteraction(_ interaction: UIFindInteraction, sessionFor view: UIView) -> UIFindSession? {
520 UITextSearchingFindSession(searchableObject: self)
521 }
522
523 var selectedTextRange: UITextRange? { nil }
524
525 func compare(_ foundRange: UITextRange, toRange: UITextRange, document: AnyHashable??) -> ComparisonResult {
526 let a = (foundRange as? TextRange)?.range.lowerBound ?? 0, b = (toRange as? TextRange)?.range.lowerBound ?? 0
527 return a < b ? .orderedAscending : a > b ? .orderedDescending : .orderedSame
528 }
529
530 /// May be called off the main thread; reads only `text`, an immutable string.
531 nonisolated func performTextSearch(queryString: String, options: UITextSearchOptions, resultAggregator: UITextSearchAggregator<AnyHashable?>) {
532 for found in EditorFind.matches(of: queryString, in: text, options: options) {
533 resultAggregator.foundRange(TextRange(found), searchString: queryString, document: nil)
534 }
535 resultAggregator.finishedSearching()
536 }
537
538 func decorate(foundTextRange: UITextRange, document: AnyHashable??, usingStyle style: UITextSearchFoundTextStyle) {
539 guard let range = (foundTextRange as? TextRange)?.range else { return }
540 switch style {
541 case .normal: marked[range] = nil
542 case .highlighted:
543 marked[range] = true
544 onShow(range.lowerBound)
545 default: marked[range] = false
546 }
547 onChange(marked)
548 }
549
550 func clearAllDecoratedFoundText() {
551 marked = [:]
552 onChange(marked)
553 }
554
555 func scrollRangeToVisible(_ range: UITextRange, inDocument: AnyHashable??) {
556 if let range = (range as? TextRange)?.range { onShow(range.lowerBound) }
557 }
558}
559
560/// Holds the find interaction for a SwiftUI screen, and shows its find bar when `request` changes.
561private struct FindHost: UIViewRepresentable {
562 let find: ReaderFind
563 let request: Int
564
565 /// The find bar shows for the first responder's interaction.
566 final class Host: UIView {
567 override var canBecomeFirstResponder: Bool { true }
568 }
569
570 func makeUIView(context: Context) -> Host {
571 let view = Host()
572 view.addInteraction(UIFindInteraction(sessionDelegate: find))
573 return view
574 }
575
576 func updateUIView(_ view: Host, context: Context) {
577 guard request != context.coordinator.shown else { return }
578 context.coordinator.shown = request
579 view.becomeFirstResponder()
580 view.interactions.lazy.compactMap { $0 as? UIFindInteraction }.first?.presentFindNavigator(showingReplace: false)
581 }
582
583 func makeCoordinator() -> Coordinator { Coordinator() }
584
585 final class Coordinator {
586 var shown = 0
587 }
588}
589
441private extension AttributedString { 590private extension AttributedString {
442 /// Without the final newline, which `Text` would show as an empty line. 591 /// Without the final newline, which `Text` would show as an empty line.
443 func trimmingTrailingNewlines() -> AttributedString { 592 func trimmingTrailingNewlines() -> AttributedString {
docs/manual/guide/14-ios.org +3 −1 · view
@@ -40,7 +40,8 @@ Tap a file in Folders or Search, or Open in File in an agenda entry's sheet, to
40- Text is styled as in the editor, in the theme's colours, font, size, line spacing and heading sizes, on the theme's background: TODO keywords, priorities, tags, emphasis, code, timestamps, links, and the code in src blocks. Text can be selected and copied. 40- Text is styled as in the editor, in the theme's colours, font, size, line spacing and heading sizes, on the theme's background: TODO keywords, priorities, tags, emphasis, code, timestamps, links, and the code in src blocks. Text can be selected and copied.
41- The reader follows the editor's display settings (see Themes and display below): Show Markup, hidden emphasis markers, pretty entities, indentation, leading stars, inline images and truncated lines. Tables show at full width, without narrowed columns. 41- The reader follows the editor's display settings (see Themes and display below): Show Markup, hidden emphasis markers, pretty entities, indentation, leading stars, inline images and truncated lines. Tables show at full width, without narrowed columns.
42- Tap a link to follow it. Links to headings and files in your folders open in the reader; links to other files, such as an attached PDF or image, open in Quick Look; web links open in the browser. 42- Tap a link to follow it. Links to headings and files in your folders open in the reader; links to other files, such as an attached PDF or image, open in Quick Look; web links open in the browser.
43- The toolbar has Outline (a list of headings to jump to), Export, and Edit (the pencil). 43- The toolbar has Find, Outline (a list of headings to jump to), Export, and Edit (the pencil).
44- Find opens the system find bar over the file's text. Results are marked, and the one shown is unfolded and scrolled to.
44 45
45* The editor 46* The editor
46 47
@@ -51,6 +52,7 @@ The editor folds headings, drawers and blocks (tap a fold's =…= to open it, an
51The toolbar has: 52The toolbar has:
52 53
53- Conflict :: shown while the file and your edits conflict; opens the conflict sheet. 54- Conflict :: shown while the file and your edits conflict; opens the conflict sheet.
55- Find :: the system find bar. The result shown is selected, and opened when it is in folded text.
54- Undo :: touch and hold it for Redo. 56- Undo :: touch and hold it for Redo.
55- More :: Commands, Clock In, Show Markup, Recent Entries, Export, Sync Conflict Copies, and Recovered Versions. 57- More :: Commands, Clock In, Show Markup, Recent Entries, Export, Sync Conflict Copies, and Recovered Versions.
56 58
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form