-->

2013年2月4日星期一

使用prettify对代码进行语法高亮设置

prettify是google提供的一款源代码语法高亮着色器,主页见 https://code.google.com/p/google-code-prettify/ 。只要在blogger模板里加几行代码,就可以实现在发表文章时候的代码语法高亮,并且提供若干种模板供使用。

prettify提供了css和js供下载,可放于自己的服务器,下载地址为 https://code.google.com/p/google-code-prettify/downloads/list ,另外也可以使用google code服务器上的代码。

打开blogger模板编辑,在<head>与</head>之间添加如下语句:

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

修改<body>为<body onload='prettyPrint()'>并保存模板。

在文章发布页面,HTML编辑模式,将想要高亮的源代码的前后作如下修改即可
<pre class="prettyprint">...</pre>

使用prettify不必指定代码语言的种类,它会自动做出判断,但是如果仍然想要指定的话,仅需这样
<pre class="prettyprint lang-html">...</pre>

语法类型通过class中的lang-*来指定,prettify能够自动识别的语言包括"bsh","c","cc","cpp","cs","csh","cyc","cv","htm","html","java","js","m","mxml","perl","pl","pm","py","rb","sh","xhtml","xml"和"xsl"。

还可以为代码增加行号,可以使用linenums的class,另外如果第一行不是从1开始的话,只需要指定行号即可,举例如下:
<pre class="prettyprint linenums:4"
>// This is line 4.
foo();
bar();
baz();
boo();
far();
faz();
<pre>
上面的例子显示为

  1. // This is line 4.
  2. foo();
  3. bar();
  4. baz();
  5. boo();
  6. far();
  7. faz();

prettify提供的其他几个颜色主题的css为
https://code.google.com/p/google-code-prettify/source/browse/trunk/styles/desert.css
https://code.google.com/p/google-code-prettify/source/browse/trunk/styles/sunburst.css
https://code.google.com/p/google-code-prettify/source/browse/trunk/styles/sons-of-obsidian.css