Class: Glim::LiquidTags::HighlightBlock

Inherits:
Liquid::Block
  • Object
show all
Defined in:
lib/liquid_ext.rb

Instance Method Summary collapse

Constructor Details

#initialize(tag_name, markup, tokens) ⇒ HighlightBlock

Returns a new instance of HighlightBlock.



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/liquid_ext.rb', line 168

def initialize(tag_name, markup, tokens)
  super

  if markup =~ /^([a-zA-Z0-9.+#_-]+)((\s+\w+(=(\w+|"[^"]*"))?)*)\s*$/
    @language, @options = $1, $2.scan(/(\w+)(?:=(?:(\w+)|"([^"]*)"))?/).map do |key, value, list|
      [ key.to_sym, list ? list.split : (value || true) ]
    end.to_h
  else
    @language, @options = nil, {}
    $log.error("Unable to parse highlight tag: #{markup}") unless markup.strip.empty?
  end

  begin
    require 'rouge'
  rescue LoadError => e
    $log.warn("Unable to load the rouge gem required by the highlight tag: #{e}")
  end
end

Instance Method Details

#render(context) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/liquid_ext.rb', line 187

def render(context)
  source = super.to_s.gsub(/\A[\r\n]+|[\r\n]+\z/, '')

  if defined?(Rouge)
    rouge_options = {
      :line_numbers => @options[:linenos] == true ? 'inline' : @options[:linenos],
      :wrap         => false,
      :css_class    => 'highlight',
      :gutter_class => 'gutter',
      :code_class   => 'code'
    }.merge(@options)

    lexer     = Rouge::Lexer.find_fancy(@language, source) || Rouge::Lexers::PlainText
    formatter = Rouge::Formatters::HTMLLegacy.new(rouge_options)
    source    = formatter.format(lexer.lex(source))

    $log.warn("No language specified in highlight tag. Will use #{lexer.class.name} to parse the code.") if @language.nil?
  end

  code_attributes = @language ? " class=\"language-#{@language.tr('+', '-')}\" data-lang=\"#{@language}\"" : ""
  "<figure class=\"highlight\"><pre><code#{code_attributes}>#{source.chomp}</code></pre></figure>"
end