0

I have a subclasses NSTextView and I would like to modify user input (based on a preference) to replace tabs with spaces. So far I've modified the insertTab method to be something like this:

- (void) insertTab: (id) sender
{
    if(shouldInsertSpaces) {
        [self insertText: @"    "];
        return;
    }

    [super insertTab: sender];
}

But I also want to replace spaces during a paste event. One solution I thought of was to modify the NSTextStorage replaceCharacter:with: method, but I found this replaces text if I load data into the textview. Specifically I only want to modify text the user is entering manually.

A solution found here suggests modifying the pasteboard, but I do not want to do that as I don't want to mess up the users pasteboard should they want to paste somewhere else. Does anyone have any other suggestions as to how I can go about doing this?

Community
  • 1
  • 1
Niki
  • 3
  • 1

1 Answers1

1

As mentioned in the other question, look at readSelectionFromPasteboard:type:. Override it and replace the pasteboard. For example:

- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type {
    id data = [pboard dataForType:type];
    NSDictionary *dictionary = nil;
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithRTF:data documentAttributes:&dictionary];
    for (;;) {
        NSRange range = [[text string] rangeOfString:@"\t"];
        if (range.location == NSNotFound)
            break;
        [text replaceCharactersInRange:range withString:@"    "];
    }
    data = [text RTFFromRange:NSMakeRange(0, text.length) documentAttributes:dictionary];
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:@"MyNoTabsPasteBoard"];
    [pasteboard clearContents];
    [pasteboard declareTypes:@[type] owner:self];
    [pasteboard setData:data forType:type];
    return [super readSelectionFromPasteboard:pasteboard type:type];
}
Willeke
  • 14,578
  • 4
  • 19
  • 47