88import Foundation
99import AppKit
1010
11- extension TextSelectionManager : NSTextStorageDelegate {
12- public func textStorage(
13- _ textStorage: NSTextStorage ,
14- didProcessEditing editedMask: NSTextStorageEditActions ,
15- range editedRange: NSRange ,
16- changeInLength delta: Int
17- ) {
18- guard editedMask. contains ( . editedCharacters) else { return }
19-
11+ extension TextSelectionManager {
12+ public func didReplaceCharacters( in range: NSRange , replacementLength: Int ) {
13+ let delta = replacementLength == 0 ? - range. length : replacementLength
2014 for textSelection in self . textSelections {
21- // If the text selection is ahead of the edited range, move it back by the range's length
22- if textSelection. range. location > editedRange . max {
23- textSelection . range . location += delta
15+ if textSelection . range. location > range. max {
16+ textSelection. range. location = max ( 0 , textSelection . range . location + delta )
17+
2418 textSelection. range. length = 0
25- } else if textSelection. range. intersection ( editedRange) != nil {
26- textSelection. range. location = editedRange. max
19+ } else if textSelection. range. intersection ( range) != nil
20+ || textSelection. range == range
21+ || ( textSelection. range. isEmpty && textSelection. range. location == range. max) {
22+ if replacementLength > 0 {
23+ textSelection. range. location = range. location + replacementLength
24+ } else {
25+ textSelection. range. location = range. location
26+ }
2727 textSelection. range. length = 0
2828 } else {
2929 textSelection. range. length = 0
@@ -39,8 +39,6 @@ extension TextSelectionManager: NSTextStorageDelegate {
3939 allRanges. insert ( selection. range)
4040 }
4141 }
42-
43- notifyAfterEdit ( )
4442 }
4543
4644 func notifyAfterEdit( ) {
0 commit comments