Syntax highlighting the code in your clipboard

 

Some months back here on Gamefromscratch.com we switched to using a product called Highlight for all our syntax highlighting needs.  It has worked out pretty well with one major exception.  On the Mac, there is no GUI interface. 

 

My typical workflow is:

Copy whatever code example I want to share to clipboard.

Paste into Highlight app.

Select language.

Select paste back to clipboard.

Paste into blogging software.

 

As you may be able to guess I do A LOT of code samples.  You generally only see all the end results, not all the screw ups and revisions I make on my end.  Simply put, this is an operation I perform daily and any time savings would certainly be felt.  On the Mac however, there is only a command line interface, making the process a bit more annoying. 

 

For Mac syntax highlighting the workflow went:

Copy the code I want into a temporary text file.

Look up the command for highlight, convert convert the temp file into a different temp file.

Open the temp file up in a RTF friendly reader like Word.

Paste the code example over to my blog software.

 

As you may be able to guess, this process is a heck of a lot slower, so generally I just stick to windows when doing code highlighting work, even when developing on a Mac, I do the blog post editing on Windows.  Not a great solution.

 

Turns out, well, I’m a bit of an idiot.  Now all I do is open a terminal and type:

pbpaste|highlight –syntax cpp -O rtf|pbcopy

 

And done!

 

The above line will paste the contents of the clipboard to stdout, highlight in turn reads STDIN then marks it up as cpp in RTF format and dumps it back to standard out, which then get’s piped back to the clipboard.

 

This one line of script would literally have saved me dozens of hours.

 

Now I need to figure out how to do the same thing from a Command Prompt on Windows.  I don’t have access to a Windows laptop currently, but I imagine it might be possible using clip.exe.  Otherwise I have no doubt I can pull it off with powershell.

 

So, if you ever find yourself with a clipboard full of source code you want to syntax highlight, this is the fastest way I’ve found yet.

 

Ok… now back to the regularly scheduled broadcast!


Scroll to Top