fe8150d7 |
# Title: Simple Code Blocks for Jekyll
# Author: Brandon Mathis http://brandonmathis.com
# Description: Write codeblocks with semantic HTML5 <figure> and <figcaption> elements and optional syntax highlighting — all with a simple, intuitive interface.
#
# Syntax: {% codeblock [title] [url] [link text] %}
#
# For syntax highlighting, put a file extension somewhere in the title. examples:
# {% codeblock file.sh %}
# {% codeblock Time to be Awesome! (awesome.rb) %}
#
# Example:
#
# {% codeblock Got pain? painreleif.sh http://site.com/painreleief.sh Download it! %}
# $ rm -rf ~/PAIN
# {% endcodeblock %}
#
# Output:
#
# <figure role=code>
# <figcaption><span>Got pain? painrelief.sh</span> <a href="http://site.com/painrelief.sh">Download it!</a>
# <div class="highlight"><pre><code class="sh">
# -- nicely escaped highlighted code --
# </code></pre></div>
# </figure>
#
# Example 2 (no syntax highlighting):
#
# {% codeblock %}
# <sarcasm>Ooooh, sarcasm... How original!</sarcasm>
# {% endcodeblock %}
#
# <figure role=code> |
e17bb6eb |
# <pre><code><sarcasm> Ooooh, sarcasm... How original!</sarcasm></code></pre> |
fe8150d7 |
# </figure>
#
module Jekyll
class CodeBlock < Liquid::Block
CaptionUrlTitle = /(\S[\S\s]*)\s+(https?:\/\/)(\S+)\s+(.+)/i
CaptionUrl = /(\S[\S\s]*)\s+(https?:\/\/)(\S+)/i
Caption = /(\S[\S\s]*)/
def initialize(tag_name, markup, tokens)
@title = nil
@caption = nil
@highlight = true
if markup =~ CaptionUrlTitle
@file = $1 |
6f646e72 |
@caption = "<figcaption><span>#{$1}</span><a href='#{$2 + $3}'>#{$4}</a></figcaption>" |
fe8150d7 |
elsif markup =~ CaptionUrl
@file = $1 |
6f646e72 |
@caption = "<figcaption><span>#{$1}</span><a href='#{$2 + $3}'>link</a></figcaption>" |
fe8150d7 |
elsif markup =~ Caption
@file = $1
@caption = "<figcaption><span>#{$1}</span></figcaption>\n"
end
if @file =~ /\S[\S\s]*\.(\w+)/
@filetype = $1
end
super
end
def render(context)
output = super
code = super.join |
6f646e72 |
source = "<div><figure role=code>" |
fe8150d7 |
source += @caption if @caption
if @filetype |
6f646e72 |
source += "{% highlight #{@filetype} %}\n" + code + "\n{% endhighlight %}</figure></div>" |
fe8150d7 |
else |
ae51fe85 |
source += "<pre><code>" + code.lstrip.rstrip.gsub(/</,'<') + "</code></pre></figure></div>" |
fe8150d7 |
end
partial = Liquid::Template.parse(source)
context.stack do
partial.render(context)
end
end
end
end
Liquid::Template.register_tag('codeblock', Jekyll::CodeBlock) |