3
votes

I have a NSTextView, where the user can paste plain text into.

When the users has "foo" in the pasteboard I would like "bar" to be pasted. In other words, a user goes to, say, a web browser, selects "foo", cmd+c, switches to my NSTextView, cmd+v and "bar" appears at insertion point.

Please, does anyone know how to approach this?

Edit: is it possible to somehow use readSelectionFromPasteboard:type: for this? I just don't know what to put in the method body of my overridden textview..?

1
Is it a very specific text replacement function? - Dan F
That determines the complexity of the answer - Dan F
@DanF: it just replaces string "foo" with string "bar". Plain text. - Ecir Hana

1 Answers

8
votes

Try this. Subclass your text view, and override paste: this way:

@implementation RDTextView

-(void)paste:(id)sender {
    NSPasteboard *pb = [NSPasteboard generalPasteboard];
    NSString *pbItem = [pb readObjectsForClasses: @[[NSString class],[NSAttributedString class]] options:nil].lastObject;
    if ([pbItem isKindOfClass:[NSAttributedString class]]) 
        pbItem = [(NSAttributedString *)pbItem string];

    if ([pbItem isEqualToString:@"foo"]) {
        [self insertText:@"bar"];
    }else{
        [super paste:sender];
    }
}

@end