使用google-code-prettify在页面上显示代码

tools @ 22 March 2007, “No Comments”

为了能够在blog里显示代码,一直没有找到理想的解决方案,因为没能满足以下三个要求:

  1. 能够根据语法高亮或者着色;
  2. 不在代码里添加内嵌的css代码;
  3. 没有副作用(比如第二点,在代码里直接插入渲染的代码,要修改可能就比较麻烦),包括增加服务器的压力;

今天找到一个满意的方案:google-code-prettify,很好地满足了前面三个要求,使用方法很简单

当然,如果在RSS阅读器里看代码,是看不到语法着色的(这是第二个要求的代价);如果浏览器关掉了Javascript,也看不到(这是第三个要求的代价)。

例子:

PHP:


require_once 'Url/PathVars.class.php';
...
require_once 'View/SearchPage.class.php';

class Controller_Dispatcher
{
	public static function handle_request($url)
	{
		$pv = new Url_PathVars('/');
		
		// TODO:this is ugly, got to change it
		if (substr(strtolower($pv->fragment), 0, 8) == '/search?')
		{
			self::handle_search_request($pv);
			return;
		}
		switch ( strtolower($pv->fetchByIndex(0)) )
		{
			case '':
				self::handle_default_home_request($pv);
				break;
			case 'people':
				self::handle_people_scope_request($pv);
				break;
		...
	}
}

Javascript:

window.addEventListener(
		"load", 
		function() 
		{
			twsstopper = new TWSStopper(window);
			window.twsstopper = twsstopper;
			twsstopper.startUp(window);

		    var appcontent = window.document.getElementById("appcontent");
		    if (appcontent) 
			{
    		    if (!appcontent.TimeWastingSiteStopper) 
				{
        		    appcontent.TimeWastingSiteStopper = true;
	            	appcontent.addEventListener("DOMContentLoaded", twsstopper.onAction, false);
    	    	}
			}
		}, 
		false);

bash:

cd $TMP_DIR

if [ -f "chrome.manifest" ]; then
  echo "Preprocessing chrome.manifest..."
  # You think this is scary?
  #s/^(content\s+\S*\s+)(\S*\/)$/\1jar:chrome\/$APP_NAME\.jar!\/\2/
  #s/^(skin|locale)(\s+\S*\s+\S*\s+)(.*\/)$/\1\2jar:chrome\/$APP_NAME\.jar!\/\3/
  #
  # Then try this! (Same, but with characters escaped for bash :)
  sed -i -r s/^\(content\\s+\\S*\\s+\)\(\\S*\\/\)\\s*$/\\1jar:chrome\\/$APP_NAME\\.jar!\\/\\2/ chrome.manifest
  sed -i -r s/^\(skin\|locale\)\(\\s+\\S*\\s+\\S*\\s+\)\(.*\\/\)\\s*$/\\1\\2jar:chrome\\/$APP_NAME\\.jar!\\/\\3/ chrome.manifest

  # (it simply adds jar:chrome/whatever.jar!/ at appropriate positions of chrome.manifest)
fi

BAT?:

xcopy build\skin build\chrome\skin /i /e
...
rmdir /s /q build\locale
rmdir /s /q build\skin
 
cd build\chrome
7z a -tzip "%x%.jar" * -r -mx=0
cd ..\..

Leave a Reply