Publish code samples in Blogger

Publishing the code samples in Blogger has always been a pain in the ***: the quoting of angle brackets doesn't work very well unless you do it manually, the leading whitespaces get lost (more so if you use spell checker), the line breaks are sometimes lost as well ... Finally I gave up and wrote a small PERL script that takes your code on standard input (usually supplied as a file name in the command line) and leaves the Blogger-ready markup on the clipboard, ready to be inserted in your post:
use strict;
use Win32::Clipboard;

our $lcnt = 0;
our $result = "" ;
our $CLIP = Win32::Clipboard();

while (<>) {
  if (/\n/) { chop; }
  $_ =~ s/\&/&amp;/gi;
  $_ =~ s/\</&lt;/gi;
  $_ =~ s/\>/&gt;/gi;
  while (/^\s/) { $_ =~ s/^(\s*)\s/$1&nbsp;/gi; }
  $result .= ($lcnt == 0 ? "<pre class='code'>" : "\n") ;
  $result .= $_;
  $lcnt ++;
$result .= "</pre>";
$CLIP -> Empty();
$CLIP -> Set($result);
print "Result is on the clipboard";

If you're not fluent in PERL, don't even try to understand what it does ... it works :)


Dave Haynes said...

Check out one of our posts at Develocity on the same subject:

Ivan Pepelnjak said...

Thanks for the tip. If I ever decide to install Windows Live Writer (not likely, as I'm moving more and more toward Linux/OpenSource world), I'll definitely use your technique.

Alejandro R. said...

Hello Ivan,

I thought you might be interested on a post I just wrote about posting code samples on Blogger.


Ivan Pepelnjak said...

Looks great. Thanks for the link!

Post a Comment