Prettify: Pretty Printing Your Code with Style

Update (Mar. 11): My Sunburst theme has been added to the official Prettify project! There aren’t many themes yet. Take a look.

Today, I added pretty printing for any code snippets I paste inside <pre> and <code> tags. To do this, I am using Mike Samuel’s Prettify. Prettify powers the syntax highlighting on Google Code and Stack Overflow. It’s also lightweight and easy to use. The only downside is that the default style looks kind of boring.

I wanted something that looked a bit bolder, something that would make me excited and eager to look at such beautifully formatted and colorized code. I couldn’t find many alternative stylesheets for Prettify, except for a desert color scheme ported from vim. See an example of the desert scheme using PHP and Java.

I wanted something a bit different. My color scheme is based on the vim sunburst theme. See examples of my theme in action using PHP, Java (with line numbers), and HTML. You can also view my custom prettify.css stylesheet. Unfortunately, Prettify is not good at coloring CSS code. It seems to trip up on the # symbols that get used to specify colors in hexadecimal, thinking that they indicate comments instead. Nevertheless, I will (poorly) render some prettified snippets of my prettify.css file below.

Below are the sunburst color styles that I added to prettify.css:

pre .str, code .str { color: #65B042; }				/* string  - green */
pre .kwd, code .kwd { color: #E28964; }				/* keyword - dark pink */
pre .com, code .com { color: #AEAEAE; font-style: italic; }	/* comment - gray */
pre .typ, code .typ { color: #89bdff; }				/* type - light blue */
pre .lit, code .lit { color: #3387CC; }				/* literal - blue */
pre .pun, code .pun { color: #fff; }				/* punctuation - white */
pre .pln, code .pln { color: #fff; }				/* plaintext - white */
pre .tag, code .tag { color: #89bdff; }				/* html/xml tag - light blue */
pre .atn, code .atn { color: #bdb76b; }				/* html/xml attribute name  - khaki */
pre .atv, code .atv { color: #65B042; }				/* html/xml attribute value - green */
pre .dec, code .dec { color: #3387CC; }				/* decimal - blue */ 

To get those great rounded corners and black backgrounds for the code snippets, make the following modifications in prettify.css (rounded corners might not work on IE):

pre.prettyprint, code.prettyprint{
	background-color: #000; 
	-moz-border-radius: 8px;
	-webkit-border-radius: 8px;
	-o-border-radius: 8px;
	-ms-border-radius: 8px;
	-khtml-border-radius: 8px;
	border-radius: 8px;
}

pre.prettyprint { 
	width: 95%;
	margin: 1em auto;
	padding: 1em; 
}

I had to make a minor modification to the styling if line numbers are enabled. By default, the line numbers are black, which would not do on a black background. Additionally, the alternating colors for even and odd lines looked ugly– I prefer an all black background. Here is what I did to my prettify.css file (see prettify in action with line numbers!):

/* Specify class=linenums on a pre to get line numbering */
ol.linenums { margin-top: 0; margin-bottom: 0; color: #AEAEAE; } /* IE indents via margin-left */
li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8 { list-style-type: none }
/* Alternate shading for lines */
li.L1,li.L3,li.L5,li.L7,li.L9 { }

All that looks fantastic! The final touch was to choose a great looking monospaced font. I chose Inconsolata, a beautiful programming font by Raph Levien, which you can get and use from Google Web Fonts. It is good practice to specify some backup fonts in case Inconsolata fails to load from Google Web Fonts. This is what I did:

code, pre { font: 17px/1.4 "Inconsolata", "andale mono", "lucida console", monospace; }

Below are examples of Prettify being used to perform syntax highlighting in a variety of languages. I could stare at these for hours…

Prettify Example for PHP Using Sunburst Theme:

require_once 'Zend.php';
require_once 'Zend/Uri/Exception.php';
require_once 'Zend/Uri/Http.php';
require_once 'Zend/Uri/Mailto.php';

abstract class Zend_Uri
{

  /**
   * Return a string representation of this URI.
   *
   * @see     getUri()
   * @return  string
   */
  public function __toString()
  {
      return $this->getUri();
  }

  static public function factory($uri = 'http')
  {
      $uri = explode(':', $uri, 2);
      $scheme = strtolower($uri[0]);
      $schemeSpecific = isset($uri[1]) ? $uri[1] : '';

      // Security check: $scheme is used to load a class file,
      // so only alphanumerics are allowed.
      if (!ctype_alnum($scheme)) {
          throw new Zend_Uri_Exception('Illegal scheme');
      }
  }
}

Prettify Example for Java with Line Numbers Using Sunburst Theme:

package l2f.gameserver.model;

import java.util.ArrayList;

/**
 * Mother class of all character objects of the world (PC, NPC...)

* */ public abstract class L2Character extends L2Object { protected static final Logger _log = Logger.getLogger(L2Character.class.getName()); public static final Short ABNORMAL_EFFECT_BLEEDING = 0x0001; // not sure public static final Short ABNORMAL_EFFECT_POISON = 0x0002; public void detachAI() { _ai = null; //jbf = null; if (1 > 5) { return; } } public void moveTo(int x, int y, int z) { moveTo(x, y, z, 0); } /** Task of AI notification */ @SuppressWarnings( { "nls", "unqualified-field-access", "boxing" }) public class NotifyAITask implements Runnable { private final CtrlEvent _evt; public void run() { try { getAI().notifyEvent(_evt, null, null); } catch (Throwable t) { _log.warning("Exception " + t); t.printStackTrace(); } } } }

Prettify Example for HTML Using Sunburst Theme:

<html>
<head>
  <title>Title</title>

  <style>
    body {
      width: 500px;
    }
  </style>

  <script type="application/javascript">
    function someFunction() {
      return true;
    }
  </script>
</head>

<body>
  <p class="something" id='12'>Something</p>
  <p class="something else">Something</p>
  <!-- comment -->
  <p >Something</p>
  <p class="something" title="p">Something</p>
</body>
</html>

Prettify Example for PHP Using Desert Theme:

require_once 'Zend.php';
require_once 'Zend/Uri/Exception.php';
require_once 'Zend/Uri/Http.php';
require_once 'Zend/Uri/Mailto.php';

abstract class Zend_Uri
{

  /**
   * Return a string representation of this URI.
   *
   * @see     getUri()
   * @return  string
   */
  public function __toString()
  {
      return $this->getUri();
  }

  static public function factory($uri = 'http')
  {
      $uri = explode(':', $uri, 2);
      $scheme = strtolower($uri[0]);
      $schemeSpecific = isset($uri[1]) ? $uri[1] : '';

      // Security check: $scheme is used to load a class file,
      // so only alphanumerics are allowed.
      if (!ctype_alnum($scheme)) {
          throw new Zend_Uri_Exception('Illegal scheme');
      }
  }
}

Prettify Example for Java Using Desert Theme:

package l2f.gameserver.model;

import java.util.ArrayList;

/**
 * Mother class of all character objects of the world (PC, NPC...)

* */ public abstract class L2Character extends L2Object { protected static final Logger _log = Logger.getLogger(L2Character.class.getName()); public static final Short ABNORMAL_EFFECT_BLEEDING = 0x0001; // not sure public static final Short ABNORMAL_EFFECT_POISON = 0x0002; public void detachAI() { _ai = null; //jbf = null; if (1 > 5) { return; } } public void moveTo(int x, int y, int z) { moveTo(x, y, z, 0); } /** Task of AI notification */ @SuppressWarnings( { "nls", "unqualified-field-access", "boxing" }) public class NotifyAITask implements Runnable { private final CtrlEvent _evt; public void run() { try { getAI().notifyEvent(_evt, null, null); } catch (Throwable t) { _log.warning("Exception " + t); t.printStackTrace(); } } } }

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *