27

I'm looking for a way to automatically format and color code I write in an HTML document. I know wikipedia does it, for example on the page: http://en.wikipedia.org/wiki/Nested_function

I'm sure there are libraries out there to do this, but I can't for the life of me, find one. Does anyone have any suggestions?

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
B T
  • 57,525
  • 34
  • 189
  • 207

3 Answers3

44

Have a look at the Prettify JavaScript library. It's the one generally used by people (it's the one being used here on SO, for example.)

You would use it like this:

In your <head> element:

<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>

In your <body> element:

<body onload="prettyPrint()">
  <!-- any HTML you like here... -->
  <pre class="prettyprint">
def say_hi():
    print("Hello World!")
  </pre>
  <!-- any HTML you like here... -->
</body>

That's for simple use of the library. If you're using other JavaScript on your page I would recommend other methods for enabling the Prettify library (i.e., don't use the onload attribute of the <body> element.) For example, if you're using jQuery, I wrote this jQuery plugin that I usually use to syntax highlight certain elements:

// Extend jQuery functionality to support prettify as a prettify() method.
jQuery.fn.prettify = function () { this.html(prettyPrintOne(this.html())); };

Used like this:

$('#my-code-element').prettify();
NilsB
  • 1,154
  • 1
  • 16
  • 42
Blixt
  • 49,547
  • 13
  • 120
  • 153
11

This is an old question, but as it came up first in Google for me, I thought I'd add another option. While Prettify is still a serviceable option, it's showing its age a bit. A newer library I ran across is Prism, and it seems to work rather well. It's more semantic and gives finer-grained control over how to format your code. It also supports plugins and its themes look nicer out of the box than Prettify's.

Brian Moeskau
  • 20,103
  • 8
  • 71
  • 73
6

I think a simpler and powerful solution are highlight.js. It support 169 languages at this time and 77 code styles (like Solarized dark and light). Some more:

  • automatic language detection
  • multi-language code highlighting
  • available for node.js
  • works with any markup
  • compatible with any js framework

Quick setup:

1 - In HTML head:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

2 - In your HTML content

<pre>
   <code class="html">
      <p>This is your HMTL sample</p>
      <p>You can use classes like "html", "php", "css", "javascript" too..</p>
   </code>
</pre>

You can check the languages and styles here.

Tiago Gouvêa
  • 15,036
  • 4
  • 75
  • 81