List Injection for PRE Tags

A suggestion

How to present, how to print a source listing? Can we replace a pre-formatted source listing with a well-formed ordered list?

In a css-d thread (in reference to a wsg thread), I suggested to inject an ordered list via Javascript. This would allow to automatically build a pretty source listing from a pre-listing without painful handcoding. We could copy our listing into a pre-section, and the script would "pretty-print" an ordered list to the screen. Without Javascript, the user gets the preformatted content just like before.

It makes sense to put a source listing in an ol and the tabulator as a class for li and the line code in code (see this demonstration by Simon Willison).

  1. <ol class="csshtml">
  2. <li class="t0"><code> ... </code></li>
  3. <li class="t1"><code> ... </code></li>
  4. <li class="t0"><code> ... </code></li>
  5. </ol>

The advantage is the ability to style without the limitations of current pre implementations (see the threads for more information). We have control over an ol-list (line-numbers, highlighting lines on hover, indenting, wrapping). One can write rules for media print and for media screen, projection.

Solution in Javascript

blog entry of the chocolate medal winning script

Choan C. Gálvez coded a Javascript injection.

LIPT demonstration page

Choan's script in action.

Known solutions in PHP


A known PHP solution by Dunstan Orchard.

textpattern forum

Johan Nilsson's implementation as a plugin for the Textpattern CMS.


Post your comments and solutions to

Philippe Wittenbergh says: "The one problem with the JS solution (which works nicely, on my side, thanks Choan) is when one wants to copy the code snipped - you copy it as a list, in FF, Safari. Like this (copy from Choan's example): # function doListings() { ..."

Roger Johansson says: "I see two problems: 1. User agents with JavaScript off get the default pre styling which may cause very long lines and horizontal scrolling. 2. The script will not work in documents served as application/xhtml+xml [javascriptWithXML]. Running the script on the server instead would take care of both those problems."

Choan C. Gálvez blogged about his (almost?) definitive version of the script and says: "Now it works in documents served as application/xhtml+xml following the recommendation by Roger Johansson."

Created, and last updated:
Jun. 23th, 2005
Feb. 19th, 2006
Ingo Chao