FEB 8, 2012


emphasize.js is a tiny javascript that does code syntax highlighting. It only loads at the end of the document so it doesn’t delay page loading. Right now it only supports Objective-C but as it’s open-source, feel free to contribute by adding your favorite language to it.

- (void)queryDidReceiveNotification:(NSNotification *)notification {
    NSArray *results = [self.metadataQuery results];
    for(NSMetadataItem *item in results) {
        NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
        NSNumber *filesize = [item valueForAttribute:NSMetadataItemFSSizeKey]; 
        NSDate *updated = [item valueForAttribute:NSMetadataItemFSContentChangeDateKey];
        NSLog(@"%@ (%@ bytes, updated %@)", filename, filesize, updated);


emphasize.js consists of 2 files: emphasize.js (which does the syntax highlighting) and emphasize.css (where you can customize your color theme). Place these files anywhere you want, and place the following right before the </body> tag in every page where you’ll need it:

<script type="text/javascript">
  var _emphasize = _emphasize || [];
  (function() {
    var t   = document.createElement('script');
    t.type  = 'text/javascript';
    t.async = true;    = 'emphasize';
    t.src = 'emphasize.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(t, s);

This project is still in its early days and will probably receive significant changes in the coming weeks, so you might want to link directly to the github version of emphasize.js. To do so, replace emphasize.js in t.src with:

Once that’s done make sure you import emphasize.css in your header:

<link rel="stylesheet" href="emphasize.css">

To syntax highlight a block of code (usually encapsulated within a <pre> or <code> tag), just give it the emphasize class followed by the language (right now only obj-c is supported):

<pre class="emphasize obj-c">

Change the colors in your local copy of emphasize.css.

About emphasize.js

I did this small project because I think Gist does a pretty bad job at syntax-highlighting Objective-C code. Plus, if you come to have more than a few of these within a single page, the “brought to you by Gist”s can get annoying. So I felt like this was a great opportunity for me to get my hands dirty with javascript and regex and make a really simple and yet effective syntax highlighting engine.

The code detection isn’t perfect and won’t adapt to every Cocoa dev’s coding style, but as with most of my open source projects, I released this first version because it fulfilled my own needs. Hopefully some of you will like it enough to perfect the detection and/or add your favorite language to it.