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.

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] [linenos:false] [start:#] [mark:#,#-#]
code snippet
```

Basic options

  • [language] - Used by the syntax highlighter. Passing 'plain' disables highlighting. (Supported languages.)
  • [title] - Add a figcaption to your code block.
  • [url] - Download or reference link for your code.
  • [Link text] - Text for the link, defaults to 'link'.

Additional options:

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

  • start:# - Line numbers begin at # (useful for using snippets to reference longer code).
  • 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. Here's an example without setting the language.

$ git clone git@github.com:imathis/octopress.git # fork octopress

The source:

```
$ git clone git@github.com:imathis/octopress.git # fork octopress
```

2. This example uses syntax highlighting and a code link.

Discover if a number is primelink
class Fixnum
def prime?
('1' * self) !~ /^1?$|^(11+?)\1+$/
end
end

The source:

``` 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
```

3. This example uses a custom starting line number and marks lines 52 and 54 through 55.

Coffeescript Tricks
# Given an alphabet:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
# Iterate over part of the alphabet:
console.log letter for letter in alphabet[4..8]

The source:

``` coffeescript Coffeescript Tricks start:51 mark:52,54-55
# Given an alphabet:
alphabet = 'abcdefghijklmnopqrstuvwxyz'

# Iterate over part of the alphabet:
console.log letter for letter in alphabet[4..8]
```

Other ways to embed code snippets

You might also like to embed code from a file or embed GitHub gists.

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

If you want syntax highlighting (for a supported language), specify the filename (with extension):

{% gist 4321346 gistfile1.diff %}

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 initially developed by Brandon Tilly for Jekyll blogs.

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 [start:#] [end:#] [range:#-#] [mark:#,#-#] [linenos:false] %}

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.

Including part of a file

3. Embed a file starting from a specific line.

test.jsview raw
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 start:10 %} 

4. Embed a file ending at a specific line.

test.jsview raw
/**
sample javascript from xui
*/
var undefined,
xui,
window = this,
string = new String('string'),
document = window.document,
simpleExpr = /^#?([\w-]+)$/,

The source:

{% include_code test.js end:10 %}

5. Display only the lines in a specific range.

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

The source:

{% include_code test.js range:5-16 %}

Other ways to embed code snippets

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

Inline Code Blocks

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

Syntax

{% codeblock [lang:language] [title] [url] [link text] [start:#] [mark:#,#-#] [linenos:false] %}
code snippet
{% endcodeblock %}

Basic options

  • [lang:language] - Choose a language for the syntax highlighter. Passing 'plain' disables highlighting. (Supported languages.)
  • [title] - Add a figcaption to your code block.
  • [url] - Download or reference link for your code.
  • [link text] - Text for the link, defaults to 'link'.

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. Here's an example without setting the language.

Awesome code snippet

The source:

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

2. This example uses syntax highlighting.

[rectangle setX: 10 y: 10 width: 20 height: 20];

The source:

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

3. Including a file extension in the title can also trigger highlighting.

Time to be Awesome - awesome.rb
puts "Awesome!" unless lame

The source:

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

4. Add an optional URL for downloading or linking to a source.

Javascript Array Syntaxlink
var arr1 = new Array(arrayLength);
var arr2 = new Array(element0, element1, ..., elementN);

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

5. This example uses a custom starting line number and marks lines 52 and 54 through 55.

Coffeescript Tricks
# Given an alphabet:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
# Iterate over part of the alphabet:
console.log letter for letter in alphabet[4..8]

The source:

{% codeblock Coffeescript Tricks lang:coffeescript start:51 mark:51,54-55 %}
# Given an alphabet:
alphabet = 'abcdefghijklmnopqrstuvwxyz'

# Iterate over part of the alphabet:
console.log letter for letter in alphabet[4..8]
{% endcodeblock %}

Other ways to embed code snippets

You might also like to use back tick code blocks, embed code from a file, or embed GitHub gists.

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.

Spaces vs. Tabs

If you use tabs, there is an issue where the first level indentation is shorter than the rest. The cause is currently unknown since lots of text processors are involved. To fix, use spaces. You'll be happier anyway.

Also, see Blogging with Plugins and The Octopress plugins page