Swift Syntax Highlighting with Jekyll

Permalink ∞

I just spend a few hours trying to find out how to embed swift snippets in my blog posts. I use Jekyll for this site, which already comes with Pygments for syntax highlighting. So adding a code block with some Swift code, already worked. The result looked something like this:


As a webdeveloper I always used TextMate (or later Sublime Text) with the Twilight theme. I ported that to Xcode when I got into iOS development and have been using it there ever since. Xcode highlights the code like this:


Shouldn't be too complicated, right? Get into the CSS file, adjust a few things. Well here is how that turned out:


Seems like the Pygments swift highlighter that you get with Jekyll is kind of old. It only detects a couple of keywords but not even all of them. The Jekyll configuration did point me to the Rouge highlighter.

So I did a gem install rouge and added the following to my _config.yml:

highlighter: rouge

And here we go, much better:

public func hello(name: String) -> String {
  return "Hello \(name)"


Here's an more complex example:

/// just some class that doesn't do much
public class SwiftHighlightExample {
  private let exampleNumber: NSNumber

  public init(intValue: Int) {
    exampleNumber = intValue as NSNumber

  public var stringValue: String {
    return exampleNumber.stringValue

  public func printNumber() {
    println("Number: \(self.numberAsString)")

let example = SwiftHighlightExample(intValue: 5)

While this example doesn't do anything meaningful, it should at least demonstrate the highlighting. It is not perfect and I had to add a few css hacks, to achieve some of the details that the highlighter wouldn't support otherwise. Still, unlike Xcode the highlighter can only guess if something is a class name, a function name or what ever.

You can have a look at css here in case you are interested. Feel free to steal it.