Octopress

A blogging framework for hackers.

Include Code

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)}"