Friday, June 24, 2011

posting source code with styling and syntax color on blogger blogspot

Finally gotten around to looking up how to format source code nicely in blogs. ref: http://www.southernspeakers.net/2010/12/adding-syntaxhighlighter-to-blogger.html
Test code:
main() {
  int i = 123;
  printf("tst test";)
}
I've adjusted the instructions to use the new in version 3 feature of dynamic / auto loading of syntax descriptor files. To set up blogger / blogspot to show source code syntax highlighting and line numbering, open Dashboard, Design. Edit HTML, add the following code before "</head>"
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCoreMDUltra.css' rel='stylesheet' type='text/css'/>
<!-- other themes:
shThemeDefault.css
shCore.css
-->

<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js' type='text/javascript'/>

<script language='javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.defaults['auto-links'] = false; 
</script>
And after the section:
<b:section class='main' id='main' showaddelement='no'>
<b:widget id='Blog1' locked='true' title='Blog Posts' type='Blog'/>
</b:section>
Add the code:
<script type='text/javascript'>
SyntaxHighlighter.autoloader(
 'py python http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js',
  'java    http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js',
  'js    http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJs.js',
  'css    http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js',
  'text plain http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js',
  'xml    http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js',
  'cpp Cpp     http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js'
);
SyntaxHighlighter.all()
</script>

To use, wrap your CODE with, <pre class="brush:xml">CODE</pre>, for xml and html. For other languages, replace xml with the language type, such as: cpp, java, js, plain.

You'll also need to html encode the text; two web hosted html encoders: http://www.string-functions.com/htmldecode.aspx http://www.elliotswan.com/postable/ (no adverts, but only does encoding, no decoding)

No comments:

Post a Comment