@@ -75,7 +75,12 @@ public struct DirectiveCompletionItem: Sendable, Equatable {
7575 subtitle : completion . subtitle ,
7676 detail : nil ,
7777 insertion : snippet . replacingOccurrences ( of : " | " , with : " " ) ,
78- caretOffset : caret . map { snippet . distance ( from : snippet . startIndex , to : $0 ) } ,
78+ // In UTF-16 units, not Characters: `caretOffset` is added onto an
79+ // NSRange location (`applyDirectiveCompletion`), which counts
80+ // UTF-16 code units. A Character count lands the caret wrong —
81+ // possibly mid-surrogate — for a snippet carrying any character
82+ // outside the BMP before the `|` marker.
83+ caretOffset : caret . map { snippet . utf16 . distance ( from : snippet . utf16 . startIndex , to : $0 ) } ,
7984 symbolName : completion . symbolName
8085 )
8186 }
@@ -194,15 +199,43 @@ enum DirectiveCompletionScanner {
194199 let nameRange = NSRange ( location : markerIndex + 1 , length : cursor - ( markerIndex + 1 ) )
195200 let name = ns . substring ( with : nameRange )
196201
197- // Still inside the name: complete the directive name itself.
202+ // Still inside the name: complete the directive name itself. The name
203+ // run above only looked at characters BEFORE the caret, so a pick
204+ // made with the caret in the middle of an existing name (`@fo|nt`)
205+ // would otherwise replace only the typed prefix and leave the rest
206+ // of the identifier dangling after the inserted snippet. Extend the
207+ // replacement to the end of the name token too.
198208 if cursor == caret {
199- let candidates = nameCandidates ( prefix : name , marker : marker , directives : directives , settings : settings )
209+ // A bare marker (`Ping @|`) offers no context: every registered
210+ // directive would otherwise match, which captures Enter for
211+ // "confirm" in ordinary prose whenever a marker precedes it —
212+ // the boundary rule keeps an email address safe, but a marker
213+ // after a plain space is not. Wait for at least one typed
214+ // character before showing anything.
215+ guard ! name . isEmpty else { return nil }
216+
217+ var nameEnd = caret
218+ while nameEnd < ns . length , isNameChar ( ns . character ( at : nameEnd ) ) { nameEnd += 1 }
219+
220+ // An exact, finished match — the typed name matches a directive
221+ // that needs nothing more (no required parameters) — is a
222+ // completed call, not something still being typed. Keeping the
223+ // context open here captures Enter as "confirm" instead of a
224+ // newline break for a self-contained call like `@pagebreak`.
225+ if nameEnd == caret ,
226+ let entry = table [ name ] ,
227+ let matched = directives . first ( where : { $0 . id == entry . id } ) ,
228+ matched . syntax . parameters . allSatisfy ( { ! $0 . isRequired } ) {
229+ return nil
230+ }
231+
232+ let candidates = nameCandidates ( prefix : name , table : table , directives : directives )
200233 guard ! candidates . isEmpty else { return nil }
201234 return DirectiveCompletionContext (
202235 kind : . name ,
203236 marker : Character ( UnicodeScalar ( marker ) ?? " @ " ) ,
204237 prefix : name ,
205- replacementRange : NSRange ( location : markerIndex , length : caret - markerIndex ) ,
238+ replacementRange : NSRange ( location : markerIndex , length : nameEnd - markerIndex ) ,
206239 directiveID : nil ,
207240 candidates : candidates
208241 )
@@ -301,6 +334,10 @@ enum DirectiveCompletionScanner {
301334 valueStart += 1
302335 }
303336 let prefix = ns . substring ( with : NSRange ( location : valueStart , length : caret - valueStart ) )
337+ // The value may continue past the caret (`@glyph(sta|r)`); a pick
338+ // there must replace the whole token or it leaves the tail dangling
339+ // behind the inserted candidate. Find where the value actually ends.
340+ let valueEnd = max ( caret , valueTokenEnd ( in : ns , from : valueStart ) )
304341
305342 // Resolve which parameter this is.
306343 let schema = directive . syntax . parameters
@@ -320,28 +357,62 @@ enum DirectiveCompletionScanner {
320357 kind : . argument ( label : label , index : argumentIndex ) ,
321358 marker : Character ( UnicodeScalar ( marker ) ?? " @ " ) ,
322359 prefix : prefix ,
323- replacementRange : NSRange ( location : valueStart , length : caret - valueStart ) ,
360+ replacementRange : NSRange ( location : valueStart , length : valueEnd - valueStart ) ,
324361 directiveID : directive . id ,
325362 candidates : candidates
326363 )
327364 }
328365
366+ /// Scan forward from `start` to find the end of the current argument
367+ /// value — the first unescaped, unquoted `,` or `)` at depth 0, a line
368+ /// break, or the end of the string. Mirrors the quote/depth tracking the
369+ /// backward scan in `argumentContext` already does, just forward.
370+ private static func valueTokenEnd ( in ns : NSString , from start : Int ) -> Int {
371+ var index = start
372+ var depth = 0
373+ var inQuote = false
374+ while index < ns . length {
375+ let c = ns . character ( at : index )
376+ if c == 0x0A || c == 0x0D { return index }
377+ if c == quote , ! isEscaped ( index , ns ) {
378+ inQuote . toggle ( )
379+ index += 1
380+ continue
381+ }
382+ if ! inQuote , ! isEscaped ( index , ns ) {
383+ if c == lparen { depth += 1 }
384+ if c == rparen {
385+ if depth == 0 { return index }
386+ depth -= 1
387+ }
388+ if c == comma , depth == 0 { return index }
389+ }
390+ index += 1
391+ }
392+ return ns . length
393+ }
394+
329395 // MARK: Name candidates
330396
331397 /// Registry-filtered directive names. The engine owns this ranking, so a
332398 /// newly registered directive shows up with no embedder change.
399+ ///
400+ /// Candidates come from `table` — the registry's winning entries for
401+ /// this marker — not the raw configured `directives` list. The registry
402+ /// drops a directive with an empty name and resolves a duplicate name by
403+ /// "first registration wins"; sourcing candidates from the unfiltered
404+ /// list could offer a name the parser will never actually recognize.
333405 private static func nameCandidates (
334406 prefix : String ,
335- marker : unichar ,
336- directives : [ any MarkdownDirective ] ,
337- settings : DirectiveRegistrySettings
407+ table : [ String : DirectiveRegistry . Entry ] ,
408+ directives : [ any MarkdownDirective ]
338409 ) -> [ DirectiveCompletionItem ] {
339410 let needle = prefix . lowercased ( )
340- let defaultMarker = settings . defaultMarker
341- return directives
411+ let registered = table . values . compactMap { entry in
412+ directives . first { $0 . id == entry . id }
413+ }
414+ return registered
342415 . filter { directive in
343- let own = directive . syntax . marker ?? defaultMarker
344- guard Array ( String ( own ) . utf16 ) . first == marker else { return false }
345416 guard ! needle . isEmpty else { return true }
346417 if directive . syntax . name . lowercased ( ) . hasPrefix ( needle ) { return true }
347418 return directive . completion . keywords . contains { $0 . lowercased ( ) . hasPrefix ( needle ) }
0 commit comments