Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextView paste: how to paste "bar" instead when "foo" is pasted?

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..?

like image 522
Ecir Hana Avatar asked Oct 28 '25 04:10

Ecir Hana


1 Answers

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
like image 101
rdelmar Avatar answered Oct 29 '25 21:10

rdelmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!