Saturday, January 3, 2015

How to Add Syntax-Highlighted Code Snippets to Blog Posts

I was looking for a quick, ultra-lightweight way to add code snippets to blog posts. My requirements were:
  1. The tool must not require me to embed a third-party widget into my blog post. That rules out Github Gists.
  2. The tool must not require me to make changes to my main blog template, especially not changes that load any additional files. That rules out SyntaxHighlighter.
Now, don't get me wrong, Gists and SyntaxHighlighter are both awesome tools that I like to use for other purposes.

I found a tool called by Alexander Kojevnikov which met the above criteria. It's pretty awesome:
Now, adding code blocks to blog posts is easy:
  1. Paste your source code into the left box
  2. Click Highlight!
  3. Copy the generated HTML/CSS code into the HTML for your blog post. (For example, if you're on Blogger, click HTML next to Compose and then paste the code into its place.)
  4. Preview and edit to make sure that the in-between whitespace looks decent.
As a bonus, it's open source, and it's powered by Flask and Pygments, two other nice open-source Python packages.