11import AppKit
2+ import MarkdownEngine
23
34struct SlashCommand : Identifiable {
45 let id : String
@@ -14,7 +15,9 @@ final class SlashCommandHandler {
1415 private var popup : SlashCommandPopup ?
1516 private var triggerLocation : Int ?
1617 private var keyMonitor : Any ?
17- /// Most-recently-known cursor document position (updated every content change).
18+ private weak var textView : NSTextView ?
19+ private var lastObservedContent : String ?
20+ /// Most-recently-known cursor document position in UTF-16 units.
1821 private var lastCursorPos : Int = 0
1922
2023 var isActive : Bool {
@@ -69,30 +72,58 @@ final class SlashCommandHandler {
6972 ]
7073 }
7174
72- // MARK: - Content Change (called from MarkdownEditorView.onChange)
75+ // MARK: - Text Mutation
7376
74- func contentDidChange ( content : String , cursorPos : Int ) {
75- lastCursorPos = cursorPos
77+ /// Tracks a completed native edit using the same UTF-16 coordinates as NSTextView.
78+ func textDidMutate ( _ mutation : MarkdownTextMutation , in textView : NSTextView ) {
79+ let currentContent = textView . string
80+ lastObservedContent = currentContent
81+ let content = currentContent as NSString
82+ let selection = textView . selectedRange ( )
83+ guard selection . length == 0 , selection . location <= content . length else {
84+ dismiss ( )
85+ return
86+ }
87+
88+ self . textView = textView
89+ let previousCursorPos = lastCursorPos
90+ lastCursorPos = selection . location
7691
7792 guard let triggerLoc = triggerLocation else {
78- checkForSlashTrigger ( content : content )
93+ checkForSlashTrigger ( after : mutation , content : content )
7994 return
8095 }
8196
82- if lastCursorPos <= triggerLoc {
97+ // An active query occupies the UTF-16 range after the slash through the
98+ // previous caret. Edits before the slash or outside that query invalidate
99+ // the session rather than trying to shift a stale replacement range.
100+ let queryStart = triggerLoc + 1
101+ guard previousCursorPos >= queryStart ,
102+ mutation . range . location >= queryStart ,
103+ NSMaxRange ( mutation . range ) <= previousCursorPos ,
104+ mutation . range . location + mutation . replacement . utf16 . count == lastCursorPos ,
105+ lastCursorPos > triggerLoc ,
106+ lastCursorPos <= content . length
107+ else {
83108 dismiss ( )
84109 return
85110 }
86111
87- let start = content . index ( content . startIndex , offsetBy : min ( triggerLoc + 1 , content . count ) )
88- let end = content . index ( content . startIndex , offsetBy : min ( lastCursorPos , content . count ) )
89- if start < end {
90- updateFilter ( String ( content [ start ..< end ] ) . lowercased ( ) )
91- } else {
112+ let queryRange = NSRange ( location : queryStart , length : lastCursorPos - queryStart )
113+ if queryRange . length == 0 {
92114 popup ? . updateCommands ( Self . commands )
115+ } else {
116+ updateFilter ( content . substring ( with : queryRange ) . lowercased ( ) )
93117 }
94118 }
95119
120+ /// Dismisses an active session when the binding changes without a matching
121+ /// exact native mutation, such as an IME batch or programmatic replacement.
122+ func contentDidSynchronize ( _ content : String ) {
123+ guard isActive , content != lastObservedContent else { return }
124+ dismiss ( )
125+ }
126+
96127 // MARK: - Keyboard Forwarding
97128
98129 func handleArrowDown ( ) -> Bool {
@@ -116,27 +147,36 @@ final class SlashCommandHandler {
116147 popup ? . close ( )
117148 popup = nil
118149 triggerLocation = nil
150+ textView = nil
151+ lastObservedContent = nil
119152 }
120153
121154 // MARK: - Private
122155
123- private func checkForSlashTrigger ( content : String ) {
156+ private func checkForSlashTrigger ( after mutation : MarkdownTextMutation , content : NSString ) {
124157 let pos = lastCursorPos
125- guard pos > 0 , pos <= content . count else { return }
126- let idx = content . index ( content . startIndex , offsetBy : pos - 1 )
127- guard content [ idx ] == " / " else { return }
158+ let replacementLength = mutation . replacement . utf16 . count
159+ guard pos > 0 ,
160+ pos <= content . length ,
161+ mutation . range . location + replacementLength == pos ,
162+ content . character ( at : pos - 1 ) == 0x2F
163+ else { return }
164+
128165 if pos > 1 {
129- let prevIdx = content . index ( before : idx )
130- let prev = content [ prevIdx ]
131- guard prev == " \n " || prev == " " || prev == " \t " else { return }
166+ switch content . character ( at : pos - 2 ) {
167+ case 0x0A , 0x20 , 0x09 : break // newline, space, tab
168+ default : return
169+ }
132170 }
133171 triggerLocation = pos - 1
134- showPopup ( )
172+ guard let textView else {
173+ triggerLocation = nil
174+ return
175+ }
176+ showPopup ( in : textView )
135177 }
136178
137- private func showPopup ( ) {
138- guard let textView = NSApp . keyWindow ? . firstResponder as? NSTextView else { return }
139-
179+ private func showPopup ( in textView : NSTextView ) {
140180 // firstRect(forCharacterRange:) returns a screen-coordinate rect for the
141181 // character at the cursor — use the bottom-left corner as the popup origin.
142182 var actualRange = NSRange ( )
@@ -179,12 +219,11 @@ final class SlashCommandHandler {
179219 // MARK: - Execution
180220
181221 private func executeCommand ( _ command : SlashCommand ) {
182- guard let triggerLoc = triggerLocation else { return }
222+ guard let triggerLoc = triggerLocation , let textView else { return }
183223 let to = lastCursorPos
184- // Dismiss before inserting — clears triggerLocation so the resulting
185- // contentDidChange doesn't accidentally re-trigger slash detection .
224+ // Dismiss before inserting so the resulting mutation cannot extend the
225+ // completed slash-command session .
186226 dismiss ( )
187- guard let textView = NSApp . keyWindow ? . firstResponder as? NSTextView else { return }
188227 let replaceRange = NSRange ( location : triggerLoc , length : to - triggerLoc )
189228 textView . insertText ( command . insertion , replacementRange : replaceRange )
190229 if let offset = command . cursorOffset {
0 commit comments