/* MyTextView.m created by ovidiu on Sat 29-Mar-1997 */

#import <AppKit/AppKit.h>
#import "MyTextView.h"
#import "Preferences.h"
#import "LineAndCharacterRange.h"

@implementation MyTextView

- (NSString*)linesContainingSelection:(NSRange*)linesRange
{
    NSString* string = [[[self layoutManager] textStorage] string];
    int length = [string length];
    NSRange range = [[[self layoutManager] firstTextView] selectedRange];
    NSRange beginningOfLine, endOfLine;
    NSRange finalRange;

    beginningOfLine = [string rangeOfString:@"\n"
                                    options:NSBackwardsSearch
                                      range:NSMakeRange(0, range.location)];
    if (!beginningOfLine.length)
        beginningOfLine.location = 0;
    else
        beginningOfLine.location++;

    endOfLine = [string rangeOfString:@"\n" options:0 range:NSMakeRange(range.location + range.length, length - range.location - range.length)];
    if (!endOfLine.length)
        endOfLine.location = length;
    else
        endOfLine.location++;

    finalRange.location = beginningOfLine.location;
    finalRange.length = endOfLine.location - beginningOfLine.location;
    if (linesRange)
        *linesRange = finalRange;
    return [string substringWithRange:finalRange];
}

- (void)insertText:(NSString*)aString
{
    id lineRangeViewer = [LineAndCharacterRange sharedInstance];
    unichar c = [aString characterAtIndex:0];

    if (c == 0x0192) // Alt-f
        [self moveWordForward:nil];
    else if (c == 0x2211) // Alt-b
        [self moveWordBackward:nil];
    else if (c == 0x007f) // Alt-Backspace
        [self deleteWordBackward:nil];
    else if (c == 0x0394) // Alt-d
        [self deleteWordForward:nil];
    else
        [super insertText:aString];

    if ([lineRangeViewer autoupdate])
        [lineRangeViewer updateInfo];
}

- (void)doCommandBySelector:(SEL)aSelector
{
    id lineRangeViewer = [LineAndCharacterRange sharedInstance];

    [super doCommandBySelector:aSelector];
    if ([lineRangeViewer autoupdate])
        [lineRangeViewer updateInfo];
}

@end
