Pretty Code (BYOSP Part 10)

Tuesday, March 6, 2012

It's always been difficult to have nicely formatted source code in a PowerPoint slide, but with HTML it's fairly easy to paste code into a pre block.

<pre>
  <code>
  var start = function () {
      assignSlideIdentifiers();
      setFirstVisibleSlide();

      $(window).bind("keydown", onKeyDown)
               .bind("hashchange", hashChange);
  };
  </code>
</pre>

Of course there is no syntax highlighting, but that's easy to rectify with google-code-prettify, a JavaScript library to provide syntax highlighting for web pages. The library supports JavaScript, C#, CSS, HTML, Ruby, and a host of other languages.

Once the prettify CSS and script is in place, all that is needed is a little kick start to prettify the code before the slide show starts. The library looks for a class of prettyprint before it jumps into action, so the startup code adds the class to code elements by default.

$(function () {
    $("code").addClass("prettyprint");
    prettyPrint();
    p5.start();
});

 

The library figures out the code you are using by sniffing for keywords and lexing with regular expressions (the source is a regex showcase). There are CSS classes you can apply if the library guesses the wrong language.

Wrapping Up

I promised to end this series after 10 posts, but I've already had requests to continue and add more features. Perhaps we'll continue after a break. This was a fun little exercise and was actually my second iteration of making an HTML 5 slide presenter.

Here are links to the previous posts: Part 1, Part 2, Part 3, Part 4, Part 5, Part 6, Part 7, Part 8, Part 9.

And here is a list of the libraries / frameworks being used:

- jQuery

- Modernizr

- google-code-prettify

- Underscore

- Sylvester

- Zoomooz

For all the code, see github.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!