代码改变世界

使用dp.SyntaxHighlighter显示高亮语法

2008-05-24 17:03  Jaypei  阅读(1874)  评论(0编辑  收藏  举报
放置代码

把代码放置在<pre>或<textarea>标签中,设置代码attribute和class,例如:
<pre name="code" class="c-sharp">
... some code here ...
</pre>

或者
<textarea name="code" class="c#" cols="60" rows="10">
... some code here ...
</textarea>

语言别名参考如下:
Language Aliases
C++ cpp, c, c++
C# c#, c-sharp, csharp
CSS css
Delphi delphi, pascal
Java java
Java Script js, jscript, javascript
PHP php
Python py, python
Ruby rb, ruby, rails, ror
Sql sql
VB vb, vb.net
XML/HTML xml, html, xhtml, xslt


扩展设置 

可通过一些选项配置代码块。使用冒号分割参数,例如:
<pre name="code" class="html:collapse">
... some code here ...
</pre>
配置选项如下:
nogutter Will display no gutter.
nocontrols Will display no controls at the top.
collapse Will collapse the block by default.
firstline[value] Will begin line count at value. Default value is 1.
showcolumns Will show row columns in the first line.


让它工作

最后,使用Javascript完成渲染工作:
<link type="text/css" rel="stylesheet" href="css/SyntaxHighlighter.css"></link>
<script language="javascript" src="js/shCore.js"></script>
<script language="javascript" src="js/shBrushCSharp.js"></script>
<script language="javascript" src="js/shBrushXml.js"></script>
<script language="javascript">
dp.SyntaxHighlighter.ClipboardSwf 
= '/flash/clipboard.swf';
dp.SyntaxHighlighter.HighlightAll(
'code');
</script>
dp.SyntaxHighlighter是一个全局方法,负责在web页面寻找所有代码块并转换成高亮代码块。
function dp.SyntaxHighlighter.HighlightAll(name, [showGutter], [showControls], [collapseAll], [firstLine], [showColumns])

name required Name of <pre> and <textarea> elements to use.
showGutter optional Turns gutter on or off on all processed code blocks.
showControls optional Turns controls on or off on all processed <pre>.
collapseAll optional Turns collapse on or off on all processed <pre>. If showControls is false or switched, this value will be ignored.
firstLine optional Allows to specify the first line where line numbering starts. This is usefull if you want to illustrate where the code block is located relative to the file.
showColumns optional Will show row columns in the first line.


Blogger模式

Blogger有一个"坏习惯",习惯用"<br />" 换行。V1.5.1增加新功能Blogger模式解决此问题:
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll(
'code');
如上,在HighlightAll()之前调用BloggerMode()就可以了。


参考地址:
http://code.google.com/p/syntaxhighlighter/wiki/Usage
下载地址:
http://code.google.com/p/syntaxhighlighter/downloads/list