I've been playing with a script that takes the selected text in Chrome and looks it up in Google, offering the four top choices, and then pasting the relevant link. It is pasted in different formats depending on which page is currently open in Chrome - DokuWiki format with DokuWiki open, HTML with normal websites, and I want rich text for my WordPress WYSIWYG editor.
I tried to use pbpaste -Prefer rtf
to see what a rich-text link with no other styling looked like on the pasteboard, but it still outputs plain text. After saving a file in Text Edit, and experimenting, I came up with the following
text = %q|{\rtf1{\field{\*\fldinst{HYPERLINK "URL"}}{\fldrslt TEXT}}}|
text.gsub!("URL", url)
text.gsub!("TEXT", stext)
(I had to use the gsub
, because somehow when using %Q
and #{}
to insert the variables, the string didn't work)
This works, however, when I paste it, there is an additional lineshift before and after the link. What would the string look like to avoid this?
From the shell the clean solution is this:
URL="http://www.google.com/"
NAME="Click here for Google"
echo "<a href='$URL'>$NAME</a>" | textutil -stdin -format html -convert rtf -stdout | pbcopy
So, use the textutil
command to convert correct html .. into rtf...
ruby variant:
url = 'http://www.google.com'
name = 'click here'
system("echo '<a href=\"#{url}\">#{name}</a>' | textutil -stdin -format html -convert rtf -stdout | pbcopy")
so, when you run the above without pbcopy part, you'll get:
{\rtf1\ansi\ansicpg1250\cocoartf1038\cocoasubrtf350
{\fonttbl\f0\froman\fcharset0 Times-Roman;}
{\colortbl;\red255\green255\blue255;\red0\green0\blue238;}
\deftab720
\pard\pardeftab720\ql\qnatural
{\field{\*\fldinst{HYPERLINK "http://www.google.com/"}}{\fldrslt
\f0\fs24 \cf2 \ul \ulc2 click here}}}
EDIT: removed -Prefer based on mklement comment
One way of doing this is using MacRuby, which is able to directly access the pasteboard through the Cocoa framework, rather than using the command line tool, which gives you more options.
For example, you can use this function to paste in HTML code, including hyperlinks, which will function correctly inserted into TextEdit or a WordPress editing box:
framework 'Cocoa'
def pbcopy(string)
pasteBoard = NSPasteboard.generalPasteboard
pasteBoard.declareTypes([NSHTMLPboardType], owner: nil)
pasteBoard.setString(string, forType: NSHTMLPboardType)
end
This works much better than the command-line pbcopy, in that it definitively avoids adding white-space, and also avoids having to send RTF for rich text, where HTML is much easier to generate programmatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With