Class: Jekyll::HighlightBlock

Inherits:
Liquid::Block
  • Object
show all
Includes:
Liquid::StandardFilters
Defined in:
lib/jekyll/tags/highlight.rb

Constant Summary collapse

SYNTAX =

we need a language, but the linenos argument is optional.

/(\w+)\s?(:?linenos)?\s?/

Instance Method Summary collapse

Constructor Details

#initialize(tag_name, markup, tokens) ⇒ HighlightBlock

Returns a new instance of HighlightBlock.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/jekyll/tags/highlight.rb', line 9

def initialize(tag_name, markup, tokens)
  super
  if markup =~ SYNTAX
    @lang = $1
    if defined? $2
      # additional options to pass to Albino.
      @options = { 'O' => 'linenos=inline' }
    else
      @options = {}
    end
  else
    raise SyntaxError.new("Syntax Error in 'highlight' - Valid syntax: highlight <lang> [linenos]")
  end
end

Instance Method Details

#render(context) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/jekyll/tags/highlight.rb', line 24

def render(context)
  if context.registers[:site].pygments
    render_pygments(context, super.to_s)
  else
    render_codehighlighter(context, super.to_s)
  end
end

#render_codehighlighter(context, code) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/jekyll/tags/highlight.rb', line 54

def render_codehighlighter(context, code)
#The div is required because RDiscount blows ass
  <<-HTML
<div>
  <pre>
<code class='#{@lang}'>#{h(code).strip}</code>
  </pre>
</div>
  HTML
end

#render_pygments(context, code) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/jekyll/tags/highlight.rb', line 32

def render_pygments(context, code)
  if cache_dir = context.registers[:site].pygments_cache
    path = File.join(cache_dir, "#{@lang}-#{Digest::MD5.hexdigest(code)}.html")
    if File.exist?(path)
      highlighted_code = File.read(path)
    else
      highlighted_code = Albino.new(code, @lang).to_s(@options)
      File.open(path, 'w') {|f| f.print(highlighted_code) }
    end
  else
    highlighted_code = Albino.new(code, @lang).to_s(@options)
  end
    
  if context["content_type"] == :markdown
    return "\n" + highlighted_code + "\n"
  elsif context["content_type"] == :textile
    return "<notextile>" + highlighted_code + "</notextile>"
  else
    return highlighted_code
  end
end