
// NCTextViewAdditions.m
//
// Written by Norbert Heger <bertl@hal.kph.tuwien.ac.at>
// Copyright (c)1997
//
// This file is distributed under the terms of the
// GNU General Public License.

#import "NCTextViewAdditions.h"
#import "NCCompletionDictionary.h"
#import "NCStringAdditions.h"
#import "NCCompletionWindow.h"
#import "NCRuntimeHacks.h"

@implementation NSTextView (NCTextViewAdditions)

- (void)performWindowHack
{
    NSWindow *window = [self window];
    Class class = [NCCompletionWindow class];

    if ([window class] == [NSWindow class]) {
        [window setClass:class];
    }
    if ([window class] == class) {
        NSEvent *event = [NSApp currentEvent];
        [class setCompletionKeyCode:[event keyCode] modifierFlags:[event modifierFlags]];
    }
}

- (BOOL)selectFieldInRange:(NSRange)aRange
{
    NSString *string = [[self textStorage] string];
    NSRange fieldRange = [string rangeFromString:@"«" toString:@"»" range:aRange];

    if (fieldRange.length != 0) {
        [self setSelectedRange:fieldRange];
        return YES;
    }
    return NO;
}

- (void)selectNextField:(id)sender
{
    NSString *string = [[self textStorage] string];
    NSRange selectedRange = [self selectedRange];
    unsigned int location = selectedRange.location + selectedRange.length;
    NSRange searchRange = NSMakeRange(location, [string length] - location);

    if (![self selectFieldInRange:searchRange]) {
        searchRange = NSMakeRange(0, selectedRange.location);
        if (![self selectFieldInRange:searchRange]) { NSBeep(); }
    }
}

- (void)completeUsingDictionary:(id)sender
{
	NSRange selectedRange = [self selectedRange];

    [self performWindowHack];

    if (selectedRange.location > 0 && selectedRange.length == 0) {
	    NSTextStorage *storage = [self textStorage];
        NSRange keyRange = [storage doubleClickAtIndex:selectedRange.location - 1];
        NSString *key, *result;

        if (keyRange.location + keyRange.length > selectedRange.location) {
            keyRange.length = selectedRange.location - keyRange.location;
        }
        key = [[storage string] substringWithRange:keyRange];
        result = [[NCCompletionDictionary dictionary] objectForKey:key];
        
        if (result != nil) {
            [storage replaceCharactersInRange:keyRange withString:result];
            [self selectFieldInRange:NSMakeRange(keyRange.location, [result length])];
            return; // success
        }
    }
    if ([self respondsToSelector:@selector(complete:)]) { [self complete:nil]; }
    else { NSBeep(); }
}

@end
