[telepathy-doc/master] Syntax highlighting of inline examples via python-pygments

Davyd Madeley davyd at madeley.id.au
Wed Apr 1 23:23:36 PDT 2009


---
 docs/book/insert-examples.py  |   19 +++++++++++++++++--
 docs/book/xslt/db2html.xsl.in |    8 ++++++++
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/docs/book/insert-examples.py b/docs/book/insert-examples.py
index fdf8b94..e336112 100755
--- a/docs/book/insert-examples.py
+++ b/docs/book/insert-examples.py
@@ -18,6 +18,13 @@ import os.path
 import re
 from lxml import etree
 
+try:
+	import pygments
+	import pygments.lexers
+	import pygments.formatters
+except ImportError:
+	print >> sys.stderr, "WARNING: install python-pygments for syntax highlighting"
+
 doc = etree.parse (sys.stdin)
 examplesdir = sys.argv[1]
 
@@ -77,11 +84,19 @@ for example in examples:
 			trim = min ([ leading_space(s) for s in lines if s != "" ])
 
 			contents = '\n'.join (map (lambda s: s[trim:], lines))
-
 	else:
 		print >> sys.stderr, "Including file `%s'..." % filename
 
-	etree.SubElement (example, 'programlisting').text = etree.CDATA (contents)
+	if pygments:
+		# syntax highlighting
+		lexer = pygments.lexers.get_lexer_for_filename (filename)
+		contents = pygments.highlight (contents, lexer,
+					pygments.formatters.HtmlFormatter(noclasses=True))
+	contents = "<embedhtml>%s</embedhtml>" % contents
+	# print >> sys.stderr, contents
+	# sys.exit(-1)
+
+	etree.SubElement (example, 'programlisting').append (etree.XML (contents))
 	p = etree.SubElement (example, 'para')
 	xmlname = re.sub (r'/', '.', nicename)
 	etree.SubElement (p, 'link', linkend='appendix.source-code.%s' % xmlname).text = "Complete Source Code"
diff --git a/docs/book/xslt/db2html.xsl.in b/docs/book/xslt/db2html.xsl.in
index 7a3229a..2b27e9a 100644
--- a/docs/book/xslt/db2html.xsl.in
+++ b/docs/book/xslt/db2html.xsl.in
@@ -18,6 +18,14 @@
 
   <xsl:import href="@PARENT_STYLESHEET@"/>
 
+  <!-- this template matches the hack tag <embedhtml> and copies its
+       contents verbatim into the output document.
+       This allows us to embed XHTML directly into the output, e.g. from
+       a syntax highlighter -->
+  <xsl:template match="embedhtml">
+   <xsl:copy-of select="./*"/>
+  </xsl:template>
+
   <!-- the header to put at the top of every page -->
   <xsl:template name="tp.page_header">
    <div id="header" style="margin-bottom:1ex;">
-- 
1.5.6.5




More information about the telepathy-commits mailing list