Stupid Mac::Glue Tricks: Clipboard Cleaning

pudge on 2006-07-12T05:35:59

I hate that the Mac likes to put styled text on the clipboard and use it everywhere. Like when I am in Safari, I ctrl-click a link and select "Copy Link," and I get styled text of the link text that is hyperlinked. I do not want that. I want the link. So I have to paste it into Safari or BBEdit, then select it and copy it again, so I can paste it into iChat without being retarded.

And I don't care if you like it that way! I don't.

So I figured I'd use this simple AppleScript:

set the clipboard to (the clipboard as string) as string


It seemed to work, except that it still carried some text style information in it. I have no idea why. So I tried the equivalent Perl version:

#!/usr/bin/perl
use Mac::Glue ':all';
my $glue = new Mac::Glue 'Finder';
$glue->set_the_clipboard_to($glue->the_clipboard(as => 'string'));


That works. Why?

The returned Apple event does not return merely the text, but a record containing text and some default style information. The Mac::Glue version knows you want the text and sucks that part out, but the AppleScript version keeps the style information for you. Once I figured this part out, it was a matter of duplicating that behavior in AppleScript (I could leave it in perl, but the perl version can take a couple of seconds, and I'll be putting this in the Script Menu and calling it regularly to clean my clipboard).

So here's the final version, which first converts the returned clipboard value to a record, then extracts the key containing the text:
set the clipboard to «class ktxt» of ((the clipboard as string) as record)


Easier

Matts on 2006-07-12T13:03:44

It's cool, but there's a much easier way:
$ pbpaste | pbcopy

Re:Easier

pudge on 2006-07-12T15:50:33

That's not easier for this purpose, which is to just run a script while I am in the GUI. That would execute more slowly than the AppleScript version, if I put it in Script Menu. It's less characters, though!

Re:Easier

Matts on 2006-07-12T15:57:54

Fair enough. I figure most people with OS X don't know about pbcopy/pbpaste - two of the most useful tools on a mac IMHO.