admonition.rb 965 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10
# encoding: utf-8

# Adapted from the admonition code on http://nanoc.ws/
class AdmonitionFilter < Nanoc::Filter

  identifier :admonition

  BOOSTRAP_MAPPING = {
    'tip'     => 'info',
    'note'    => 'info',
Julius Volz's avatar
Julius Volz committed
11
    'caution' => 'warning',
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
    'todo'    => 'info',
  }

  def run(content, params = {})
    # `#dup` is necessary because `.fragment` modifies the incoming string. Ew!
    # See https://github.com/sparklemotion/nokogiri/issues/1077
    doc = Nokogiri::HTML.fragment(content.dup)
    doc.css('p').each do |para|
      content = para.inner_html
      next if content !~ /\A(TIP|NOTE|CAUTION|TODO): (.*)\Z/m
      new_content = generate($1.downcase, $2)
      para.replace(new_content)
    end
    doc.to_s
  end

  def generate(kind, content)
    %[<div class="admonition-wrapper #{kind}">] +
    %[<div class="admonition alert alert-#{BOOSTRAP_MAPPING[kind]}">] +
31
    "<strong>#{kind.upcase}:</strong> " +
32 33 34 35 36
    content +
    %[</div></div>]
  end

end