Skip to content

Commit bdf8a2c

Browse files
Add find & replace: replaceCurrent / replaceAll bus handlers (#93)
Extends the existing display-coordinate find with two bus notifications: `replaceCurrent` (replace the focused match, re-highlight, keep the index on the next occurrence) and `replaceAll` (replace every match in one undo step, back-to-front so ranges stay valid). Both edit the engine's own text with proper shouldChangeText/didChangeText undo registration and report the remaining count via `findResults`. Shared `findMatches` helper extracted from `handleFindQuery`. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 809c41b commit bdf8a2c

3 files changed

Lines changed: 113 additions & 16 deletions

File tree

‎Sources/MarkdownEngine/Services/MarkdownEditorServices.swift‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,17 @@ public struct MarkdownEditorBus: Sendable {
244244
/// Posted by the engine in response to `findQuery` with `userInfo["count"] as? Int`
245245
/// (number of matches in the displayed text), so the host can show "x of y".
246246
public var findResults: Notification.Name?
247+
/// Posted by the host UI to replace the current find match. Expected
248+
/// `userInfo["query"] as? String`, `userInfo["replacement"] as? String`,
249+
/// optional `userInfo["currentIndex"] as? Int`. The engine edits its own
250+
/// displayed text (with undo), re-highlights the remaining matches, and
251+
/// posts `findResults` with the new count.
252+
public var replaceCurrent: Notification.Name?
253+
/// Posted by the host UI to replace every find match in one undo step.
254+
/// Expected `userInfo["query"] as? String`, `userInfo["replacement"] as? String`.
255+
/// The engine posts `findResults` with the count still matching afterward
256+
/// (non-zero only if the replacement itself contains the query).
257+
public var replaceAll: Notification.Name?
247258

248259
public init(
249260
applyBoldRequest: Notification.Name? = nil,
@@ -265,7 +276,9 @@ public struct MarkdownEditorBus: Sendable {
265276
findScrollToRange: Notification.Name? = nil,
266277
findClearHighlights: Notification.Name? = nil,
267278
findQuery: Notification.Name? = nil,
268-
findResults: Notification.Name? = nil
279+
findResults: Notification.Name? = nil,
280+
replaceCurrent: Notification.Name? = nil,
281+
replaceAll: Notification.Name? = nil
269282
) {
270283
self.applyBoldRequest = applyBoldRequest
271284
self.applyItalicRequest = applyItalicRequest
@@ -287,6 +300,8 @@ public struct MarkdownEditorBus: Sendable {
287300
self.findClearHighlights = findClearHighlights
288301
self.findQuery = findQuery
289302
self.findResults = findResults
303+
self.replaceCurrent = replaceCurrent
304+
self.replaceAll = replaceAll
290305
}
291306

292307
public static let `default` = MarkdownEditorBus()

‎Sources/MarkdownEngine/TextView/Coordinator/NativeTextViewCoordinator+Find.swift‎

Lines changed: 87 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,26 +34,98 @@ extension NativeTextViewCoordinator {
3434
let query = info["query"] as? String else { return }
3535
let requestedIndex = info["currentIndex"] as? Int ?? 0
3636

37-
var allRanges: [NSRange] = []
38-
if !query.isEmpty {
39-
let haystack = tv.string as NSString
40-
let opts: NSString.CompareOptions = [.caseInsensitive, .diacriticInsensitive]
41-
var searchStart = 0
42-
while searchStart < haystack.length {
43-
let scope = NSRange(location: searchStart, length: haystack.length - searchStart)
44-
let found = haystack.range(of: query, options: opts, range: scope)
45-
if found.location == NSNotFound { break }
46-
allRanges.append(found)
47-
searchStart = found.location + max(found.length, 1)
48-
}
49-
}
50-
37+
let allRanges = findMatches(of: query, in: tv.string as NSString)
5138
let currentIndex = allRanges.isEmpty ? 0 : min(max(requestedIndex, 0), allRanges.count - 1)
5239
renderFindMatches(allRanges, currentIndex: currentIndex)
40+
postFindResults(count: allRanges.count)
41+
}
5342

43+
/// All ranges of `query` in `haystack` (display coordinates), case- and
44+
/// diacritic-insensitive. Shared by find and replace.
45+
func findMatches(of query: String, in haystack: NSString) -> [NSRange] {
46+
guard !query.isEmpty else { return [] }
47+
var ranges: [NSRange] = []
48+
let opts: NSString.CompareOptions = [.caseInsensitive, .diacriticInsensitive]
49+
var searchStart = 0
50+
while searchStart < haystack.length {
51+
let scope = NSRange(location: searchStart, length: haystack.length - searchStart)
52+
let found = haystack.range(of: query, options: opts, range: scope)
53+
if found.location == NSNotFound { break }
54+
ranges.append(found)
55+
searchStart = found.location + max(found.length, 1)
56+
}
57+
return ranges
58+
}
59+
60+
private func postFindResults(count: Int) {
5461
if let resultsName = configuration.services.bus.findResults {
55-
NotificationCenter.default.post(name: resultsName, object: nil, userInfo: ["count": allRanges.count])
62+
NotificationCenter.default.post(name: resultsName, object: nil, userInfo: ["count": count])
63+
}
64+
}
65+
66+
/// Replace the current find match with the replacement string (one undo
67+
/// step), then re-highlight and report the remaining match count.
68+
@objc func handleReplaceCurrent(_ notification: Notification) {
69+
guard let tv = textView, tv.isEditable,
70+
let info = notification.userInfo,
71+
let query = info["query"] as? String, !query.isEmpty,
72+
let replacement = info["replacement"] as? String else { return }
73+
let requestedIndex = info["currentIndex"] as? Int ?? 0
74+
75+
let matches = findMatches(of: query, in: tv.string as NSString)
76+
guard !matches.isEmpty else { postFindResults(count: 0); return }
77+
let idx = min(max(requestedIndex, 0), matches.count - 1)
78+
let target = matches[idx]
79+
guard NSMaxRange(target) <= (tv.string as NSString).length else { return }
80+
81+
tv.breakUndoCoalescing()
82+
isProgrammaticEdit = true
83+
defer { isProgrammaticEdit = false }
84+
guard tv.shouldChangeText(in: target, replacementString: replacement) else { return }
85+
tv.textStorage?.replaceCharacters(in: target, with: replacement)
86+
tv.didChangeText()
87+
tv.undoManager?.setActionName("Replace")
88+
tv.breakUndoCoalescing()
89+
90+
// Re-find on the edited text; keep the index so focus lands on the next
91+
// occurrence (or clamps to the last remaining one).
92+
let updated = findMatches(of: query, in: tv.string as NSString)
93+
let nextIndex = updated.isEmpty ? 0 : min(idx, updated.count - 1)
94+
renderFindMatches(updated, currentIndex: nextIndex)
95+
postFindResults(count: updated.count)
96+
}
97+
98+
/// Replace every find match in a single undo step, then re-highlight.
99+
@objc func handleReplaceAll(_ notification: Notification) {
100+
guard let tv = textView, tv.isEditable,
101+
let info = notification.userInfo,
102+
let query = info["query"] as? String, !query.isEmpty,
103+
let replacement = info["replacement"] as? String else { return }
104+
105+
let matches = findMatches(of: query, in: tv.string as NSString)
106+
guard !matches.isEmpty else { postFindResults(count: 0); return }
107+
108+
// Group as one undo; edit back-to-front so earlier ranges stay valid.
109+
let orderedRanges = matches.reversed().map { NSValue(range: $0) }
110+
let replacements = Array(repeating: replacement, count: matches.count)
111+
112+
tv.breakUndoCoalescing()
113+
isProgrammaticEdit = true
114+
defer { isProgrammaticEdit = false }
115+
guard tv.shouldChangeText(inRanges: orderedRanges, replacementStrings: replacements) else { return }
116+
tv.textStorage?.beginEditing()
117+
for match in matches.reversed() {
118+
tv.textStorage?.replaceCharacters(in: match, with: replacement)
56119
}
120+
tv.textStorage?.endEditing()
121+
tv.didChangeText()
122+
tv.undoManager?.setActionName("Replace All")
123+
tv.breakUndoCoalescing()
124+
125+
// Usually zero remain; non-zero only if the replacement contains the query.
126+
let remaining = findMatches(of: query, in: tv.string as NSString)
127+
renderFindMatches(remaining, currentIndex: 0)
128+
postFindResults(count: remaining.count)
57129
}
58130

59131
/// Highlight all matches (current one stronger) and scroll the current match into view.

‎Sources/MarkdownEngine/TextView/Coordinator/NativeTextViewCoordinator.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,16 @@ public final class NativeTextViewCoordinator: NSObject, NSTextViewDelegate {
295295
self?.handleFindQuery(notification)
296296
})
297297
}
298+
if let name = bus.replaceCurrent {
299+
busObservers.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] notification in
300+
self?.handleReplaceCurrent(notification)
301+
})
302+
}
303+
if let name = bus.replaceAll {
304+
busObservers.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] notification in
305+
self?.handleReplaceAll(notification)
306+
})
307+
}
298308
}
299309

300310
// Find-in-document highlight handlers live in

0 commit comments

Comments
 (0)