cocoaautocompletesubclassnstextviewfieldeditor

Cocoa: Stopping the field editor from auto-completing on space key


I have a custom view with several NSTextField controls for which I want to supply custom auto-completions and I have successfully implemented all that using the NSTextFieldDelegate Protocol. The auto-completions are full names or place names, depending on which text field is being edited.

The issue is that the auto-completions almost always contain a space character and so if the user is typing something that matches a suggestion, but doesn't want to accept that suggestion, the field editor will accept the suggestion when user presses the space key. I want the field editor to accept the suggestion using the tab key only.

I understand that this will involve subclassing NSTextView to provide a custom field editor, and this is documented by Apple as being the acceptable way, however it's not clear to me what methods I need to override and what the overridden methods need to do, in order to get me what I want.

Can anyone suggest how this is achieved?


Solution

  • I admit that I'd been fumbling with this question for quite some time earlier, before I discovered an acceptable answer via Google-fu. The magic code, blatantly stolen from the original answerer:

    @interface MLFieldEditor : NSTextView @end
    
    @implementation MLFieldEditor
    
    
    -  (void)insertCompletion:(NSString *)word forPartialWordRange:(NSRange)charRange movement:(NSInteger)movement isFinal:(BOOL)flag {
        // suppress completion if user types a space
        if (movement == NSRightTextMovement) return;
    
        // show full replacements
        if (charRange.location != 0) {
            charRange.length += charRange.location;
            charRange.location = 0;
        }
    
        [super insertCompletion:word forPartialWordRange:charRange movement:movement isFinal:flag];
    
        if (movement == NSReturnTextMovement)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:MLSearchFieldAutocompleted object:self userInfo:nil];
        } }
    
    @end
    

    (Additional reference)