语法高亮工具Pygments

天天写代码, 天天看代码,没有颜色的代码看久了自然会眼花,于是各种高亮工具诞生了。基本上每个IDE都集成了代码语法高亮着色器,在Web应用里面,代码着色可以在用户端用JavaScript实现也可以在服务器端实现,PHP实现的着色工具最多,可惜俺不会,找啊找啊找到了这款神奇的代码语法着色器Pygments,支持很多语言(有一多半语言我都只听说过),俺够用了,而且是Python写的,方便偶在GAE里面折腾。
官方地址:http://pygments.org/

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code.

偶继续折腾GAE
“main.py”

#!/usr/bin/env python
 
import wsgiref.handlers
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
 
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
 
class MainHandler(webapp.RequestHandler):
  def get(self):
	template_values = {
        }
	path = os.path.join(os.path.dirname(__file__), 'index.html')
	self.response.out.write(template.render(path, template_values))
  def post(self):
	code = self.request.get('content')
	template_values = {
            'codehtml': highlight(code, PythonLexer(), HtmlFormatter(linenos='inline',linenospecial=5)),
            'style':HtmlFormatter().get_style_defs('.highlight')
            }
	path = os.path.join(os.path.dirname(__file__), 'index.html')
	self.response.out.write(template.render(path, template_values))
 
def main():
  application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)
 
 
if __name__ == '__main__':
  main()

模板文件“index.html”


  
    
{{ codehtml }}

-EOF-