Skip to content

Commit 9b25347

Browse files
committed
Add replaceCharacters(in:with:) that takes NSAttributedString
Add an overload of replaceCharacters that accepts an NSAttributedString instead of just a plain String. This allows preserving text attributes when replacing text via text finder, which is needed for rich text find and replace.
1 parent 2daca7c commit 9b25347

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

Sources/STTextViewAppKit/STTextFinderClient.swift

+15
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ final class STTextFinderClient: NSObject, NSTextFinderClient {
4545
return result
4646
}
4747

48+
func replaceCharacters(in range: NSRange, with string: NSAttributedString) {
49+
guard let textContentManager = textView?.textLayoutManager.textContentManager,
50+
let textRange = NSTextRange(range, in: textContentManager),
51+
let textView = textView
52+
else {
53+
return
54+
}
55+
56+
if textView.shouldChangeText(in: textRange, replacementString: string.string) {
57+
// let typingAttributes = textView.typingAttributes(at: textRange.location)
58+
let attributedString = NSAttributedString(attributedString: string)
59+
textView.replaceCharacters(in: textRange, with: attributedString, allowsTypingCoalescing: false)
60+
}
61+
}
62+
4863
func replaceCharacters(in range: NSRange, with string: String) {
4964
guard let textContentManager = textView?.textLayoutManager.textContentManager,
5065
let textRange = NSTextRange(range, in: textContentManager),

Sources/STTextViewAppKit/STTextView.swift

+4
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,10 @@ import AVFoundation
13231323
textFinderClient.replaceCharacters(in: range, with: string)
13241324
}
13251325

1326+
public func replaceCharacters(in range: NSRange, with string: NSAttributedString) {
1327+
textFinderClient.replaceCharacters(in: range, with: string)
1328+
}
1329+
13261330
public func replaceCharacters(in range: NSTextRange, with string: String) {
13271331
replaceCharacters(in: range, with: string, useTypingAttributes: true, allowsTypingCoalescing: false)
13281332
}

0 commit comments

Comments
 (0)