Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a rich text link for pbcopy

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?

like image 797
Stian Håklev Avatar asked May 23 '11 09:05

Stian Håklev


Video Answer


2 Answers

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

like image 148
jm666 Avatar answered Sep 23 '22 18:09

jm666


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.

like image 32
Stian Håklev Avatar answered Sep 23 '22 18:09

Stian Håklev