Octopress

A blogging framework for hackers.

Sharing Code Snippets

« Previous, Blogging Basics

Sharing code is important, and blogging about it should be easy and beautiful. That’s why Octopress is packed with features to make blogging your code a breeze. Though Jekyll comes with support for Pygments syntax highlighting, Octopress makes it way better. Here’s how.

  • A Sass port of Solarized syntax highlighting created specifically for Octopress.
  • Gist code embedding - by Brandon Tilly.
  • Insert code snippets from your filesystem with a download link.
  • Easy inline code blocks with <figure> and <figcaption> and optional download links.
  • Pygments caching - a Jekyll community plugin.
  • Table based line numbers added with javascript.

Solarized Highlighting

Solarized has a beautiful syntax highlighting color scheme, but reproducing it requires a highly sophisticated highlighting engine. Pygments (the highlighter Jekyll uses) processes code snippets into styleable HTML, but it isn’t nearly as powerful as the highlighting engine in Vim for example. In order to port Solarized theme to octopress, I processed its test files with Pygments and styled the output with Sass while comparing them to the Vim rendered versions.

Check out the test page to see the results.

Backtick Code Blocks

With the backtick_codeblock filter you can use Github’s lovely back tick syntax highlighting blocks. Simply start a line with three back ticks followed by a space and the language you’re using.

Syntax

``` [language] [title] [url] [link text]
code snippet
```

Example (plain)

```
$ sudo make me a sandwich
```
1
$ sudo make me a sandwich

Example With Syntax Highlighting a Caption and Link

``` ruby Discover if a number is prime http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/ Source Article
class Fixnum
  def prime?
    ('1' * self) !~ /^1?$|^(11+?)\1+$/
  end
end
```
Discover if a number is prime Source Article
1
2
3
4
5
class Fixnum
  def prime?
    ('1' * self) !~ /^1?$|^(11+?)\1+$/
  end
end

Gist Embedding

All you need is the gist’s id and you can easily embed it in your page. This actually downloads a cache of the gist and embeds it in a <noscript> tag for RSS readers and search engines, while still using Github’s javascript gist embed code for browsers.

Syntax

{% gist gist_id [filename] %}

Example

{% gist 996818 %}

If you have a gist with multiple files, you can include files one at a time by adding the name after the gist id.

{% gist 1059334 svg_bullets.rb %}
{% gist 1059334 usage.scss %}

This plugin was developed by Brandon Tilly but I have fixed some bugs and made some improvements to it for Octopress.

Include Code Snippets

Import files on your filesystem into any blog post as embedded code snippets with syntax highlighting and a download link. In the _config.yml you can set your code_dir but the default is source/downloads/code. Simply put a file anywhere under that directory and use the following tag to embed it in a post.

Syntax

{% include_code [title] [lang:language] path/to/file %}

Example 1

This includes a file from source/downloads/code/test.js.

{% include_code test.js %}
(test.js) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
sample javascript from xui
*/

var undefined,
    xui,
    window     = this,
    string     = new String('string'),
    document   = window.document,
    simpleExpr = /^#?([\w-]+)$/,
    idExpr     = /^#/,
    tagExpr    = /<([\w:]+)/,
    slice      = function (e) { return [].slice.call(e, 0); };
    try { var a = slice(document.documentElement.childNodes)[0].nodeType; }
    catch(e){ slice = function (e) { var ret=[]; for (var i=0; e[i]; i++)
        ret.push(e[i]); return ret; }; }

window.x$ = window.xui = xui = function(q, context) {
    return new xui.fn.find(q, context);
};

Example 2

By default the <figcaption> will be the filename, but you can add a title before the filepath if you like.

{% include_code Add to_fraction for floats ruby/test.rb %}

This includes a file from source/downloads/code/ruby/test.rb.

Add to_fraction for floats (test.rb) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Float
  def number_decimal_places
    self.to_s.length-2
  end
  def to_fraction
    higher = 10**self.number_decimal_places
    lower = self*higher
    gcden = greatest_common_divisor(higher, lower)

    return (lower/gcden).round, (higher/gcden).round
  end

private
  def greatest_common_divisor(a, b)
     while a%b != 0
       a,b = b.round,(a%b).round
     end
     return b
  end
end

Example 3 (Force Highlighting)

Pygments supports many languages, but doesn’t recognize some file extensions. Add lang:your_language to force highlighting if the filename doesn’t work.

{% include_code test.coffee lang:coffeescript %}
(test.coffee) download
1
2
3
4
5
6
7
8
fibonacci = (n) ->
  if n <= 2
    n
  else
    arguments.callee(n - 2) + arguments.callee(n - 1)

for x in [1..10]
  console.log "#{x} : #{fibonacci(x)}"

Inline Code Blocks

With this plugin you can write blocks of code directly in your posts and optionally add titles and links.

Syntax

{% codeblock [title] [lang:language] [url] [link text] %}
code snippet
{% endcodeblock %}

Example 1

{% codeblock %}
Awesome code snippet
{% endcodeblock %}
1
Awesome code snippet

Example 2

You can also add syntax highlighting like this.

{% codeblock lang:objc %}
[rectangle setX: 10 y: 10 width: 20 height: 20];
{% endcodeblock %}
1
[rectangle setX: 10 y: 10 width: 20 height: 20];

Example 3

Including a file extension in the title enables highlighting

{% codeblock Time to be Awesome - awesome.rb %}
puts "Awesome!" unless lame
{% endcodeblock %}
Time to be Awesome - awesome.rb
1
puts "Awesome!" unless lame

Example 4 (Force Highlighting)

Pygments supports many languages, but doesn’t recognize some file extensions. Add lang:your_language to force highlighting if the filename doesn’t work.

{% codeblock Here's an example .rvmrc file. lang:ruby %}
rvm ruby-1.8.6 # ZOMG, seriously? We still use this version?
{% endcodeblock %}
Here’s an example .rvmrc file.
1
rvm ruby-1.8.6 # ZOMG, seriously? We still use this version?

Example 5

Add an optional URL to enable downloading or linking to source.

{% codeblock Javascript Array Syntax lang:js http://j.mp/pPUUmW MDN Documentation %}
var arr1 = new Array(arrayLength);
var arr2 = new Array(element0, element1, ..., elementN);
{% endcodeblock %}
Javascript Array Syntax MDN Documentation
1
2
var arr1 = new Array(arrayLength);
var arr2 = new Array(element0, element1, ..., elementN);

The last argument link_text is optional. You may want to link to a source for download file, or documentation on some other site.

Also, see Blogging with Plugins and The Octopress plugins page