Thursday, September 25, 2008

Copying and Pasting Formatted Code in Blogger

I often see some nice HTML code on a web page and want to use it in Blogger.

<span><a href="http://www.blogger.com">Get your own blog!</a></span>

If you copy the above text, you will also copy the formatting that comes with it. To use it - as HTML - paste it into the Edit Html tab of a new Blogger post.

Or, paste it into something like Notepad or UltraEdit first, then copy and paste it from there - Notepad and UltraEdit are examples of text editors that ignore formatting information when you paste text into them. You can do the same with Word too: in Word 2003 and before, you select   Edit | Paste Special | Unformatted Text.

If you copy and paste it straight from the web page into the Compose tab of a new Blogger post, it will look as it did on the web page (or close to - some more complicated formatting might be ignored or not copied in its entirety).

But if you then click on the Edit Html tab, you will see that what you actually have is the code you wanted - formatted to look as it did on the page you copied it from. I.e. it might work to display the formatted code, but it won't work as HTML code itself.

As an author of blog posts, this is generally unavoidable even if you use no extra formatting! This is because the software e.g. Blogger, will automatically wrap text in formatting HTML of its own. For example, consider the below very plain piece of html.

<span><a href="http://www.blogger.com">Get your own blog!</a></span>

Copy that in compose mode (not HTML), and the line above becomes this:

&lt;span&gt;&lt;a href="http://www.blogger.com"&gt;Get your own blog!&lt;/a&gt;&lt;/span&gt;

No formatting at all: I used the HTML entities for < and > to avoid the code being evaluated as HTML, but there is no PRE, B I tags etc. Copy and paste this into the Compose tab of a new Blogger post and then look at the Edit Html tab - you will still see extra SPANs and other things, because Blogger is formatting all of my text.

Also see my other post, Bogger: Convert Line Breaks Setting for an idea about some other difficulties with posting code in Blogger - and a few alternatives for how to post code.

Thanks to Nithin for asking posting code in Blogger.