Swift Syntax Highlighting Workaround for Blogging

Since Swift was announced less than one week ago, we as a community can’t reasonably expect syntax rules to be pulled into popular highlighting libraries like Pygments yet (though it’s certainly already in the works). You’ll notice in our most recent post, Unit Testing in Swift, that we successfully applied syntax highlighting to our code samples. How did we do it without manually applying styles? Read on:

Step 1. Copy from Xcode

The first thing to do is simply copy the code from Xcode. Highlight what you need and copy it.

Step 2. Export via TextEdit

Next, simply paste into TextEdit.app. Then, you need to save the document somewhere, choosing the File Format of “Web Page (.html)”.

Step 3. Grab the Relevant CSS and HTML

Finally, open the saved file in your favorite HTML editor (vim, of course), and extract the <style> and <body> blocks. Insert them as needed into your blogging platform.

Potential Pitfall

If you find yourself pasting multiple code blocks into an article, you’ll realize you only need the style block to be included once. Be careful, though, since each time you perform this workflow, the CSS will only include what you need. Therefore, if you rely on the initially generated CSS to be sufficient, it might not include the styles for syntax that is found only in later blocks of code.


Category: Development
Tags: Swift, Tutorial