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 %}

Basic options

  • [title] - Add a custom figcaption to your code block (defaults to filename).
  • lang:language - Force the syntax highlighter to use this language. By default the file extension is used for highlighing, but not all extensions are known by Pygments.

Additional options:

These options don't depend on any previous option and order does not matter.

  • start:# - Render a snippet from the file beginning at the specified line.
  • end:# - Render a snippet from the file ending at the specified line.
  • range:#-# - Render a specified range of lines from a file (a shortcut for start:# end:#).
  • mark:#,#-# - Mark one or more lines of code with the class name "marked". Accepts one number, numbers separated by commas, and number ranges. Example mark:1,5-8 will mark lines 1,5,6,7,8. Note: If you've changed the beginning line number be sure these match rendered line numbers
  • linenos:false - Do not add line numbers to highlighted code.

Examples

1. This code snipped was included from source/downloads/code/test.js.

test.jsview raw
/**
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);
};

The source:

{% include_code test.js %}

2. Setting a custom caption.

Add to_fraction for floats (test.rb)view raw
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

The source:

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

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

Other ways to embed code snippets

You might also like to use back tick code blocks or embed GitHub gists.