Tuesday, September 13, 2011

Syntax Highlighting in Blogger

Simplest way: use google-code-prettify. Add the following to just before the tag in the site template.

<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" rel="stylesheet" type="text/css"></link>
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" type="text/javascript"></script>

Also in the site template, add the following attribute to the <body> element.

<body onload="prettyPrint()">

To use in a post, wrap the code in <pre> tags marked with the class "prettyprint".

<pre class="prettyprint">
*** CODE GOES HERE ***
</pre>

More options:
  • Host the prettify files elsewhere, like sites.google.com or a public folder on dropbox.
  • To display line numbers, add the class "linenums" (or "linenums:{row}", where {row} is the starting row).
  • Override the detected language type with the "lang-{syntax}" class.
  • Try some different style templates.
  • Add "white-space: nowrap; overflow: auto" to the "ol.linenums" css to get scroll bars on long content.
  • Add the following css to hide the blogger nav bar: #navbar-iframe {display: none !important;}
Here's an excerpt from my template near the </head> tag:

...
  
	#navbar-iframe {display: none !important;}
	]]>
    </b:template-skin>
	
	<link href='http://dl.dropbox.com/u/11517241/google-code-prettify/src/prettify.css' rel='stylesheet' type='text/css'/>
	<script src='http://dl.dropbox.com/u/11517241/google-code-prettify/src/prettify.js' type='text/javascript'>  </script>

  </head>

  <body expr:class='&quot;loading&quot; + data:blog.mobileClass' onload='prettyPrint()'>
  
  ...

No comments:

Post a Comment