You can load the Prettify script to highlight code in your web pages.
It adds styles to code snippets so that token boundaries stand out and your readers can get the gist of your code without having to mentally perform a left-to-right parse.
Marking code sections
The prettyprinter looks for
<xmp> elements with the
prettyprint class, and adds
<span>s to colorize keywords, strings,
comments, and other token types.
<pre class="prettyprint"> source code here </pre>
If you're using Markdown or some other HTML generator that does not add classes, you can alternatively ask the prettifier to target your code by preceding it with a processing instruction thus:
<?prettify?> <pre class="prettyprint"> code here </pre>
This will load the entire system and schedule the prettifier to run on page load. There are a variety of additional options you can specify (as CGI arguments) to configure the runner.
|autorun=(true, false)||true||run automatically on page load|
|lang=...||none||Loads the language handler for the given language which is usually the file extension for source files for that language. See the index of language handlers. If specified multiple times (
|skin=...||none||See the skin gallery. If specified multiple times, the first one to successfully load is used.|
The above specifies the
lang parameter to also load the CSS language
extension and the
skin parameter to load the
Serving your own JS & CSS
You can download the scripts and styles and serve them yourself. Make sure to include both the script and a stylesheet:
Then run the
PR.prettyPrint() function once your page has finished loading.
One way to do this is via the
onload handler thus:
The prettifier only adds
classes; it does not specify exact colors or fonts,
so you can swap in a different stylesheet to change the way code is
The easiest way to create your own stylesheet is by starting with one from the style gallery and tweaking it.
You can use CSS
@media rules to specify styles that work well with printers
(for example, dark text on a white background) when someone tries to print it.
Prettify makes a best effort to guess the language but works best with C-like and HTML-like languages. For others, there are special language handlers that are chosen based on language hints.
For example, set the
lang-scm hint to specify that the code is Scheme code:
<pre class="prettyprint lang-scm">(friends 'of '(parentheses))</pre>
It can also be specified as:
<?prettify lang=scm?> <pre>(friends 'of '(parentheses))</pre>
<pre class="prettyprint linenums"> Many lines of code </pre>
linenums class in the above code tells the prettyprinter to insert an
<ol> element and
<li> elements around each line so that you get line
Most stylesheets then hide the line numbers except for every fifth line.
linenums:40 makes line numbering start at line 40 if you're
excerpting a larger chunk of code. The following also works:
<?prettify linenums=40?> <pre>lots of code</pre>