class HTML::Pipeline::SyntaxHighlightFilter

HTML Filter that syntax highlights code blocks wrapped in <pre lang=“…”>.

Public Class Methods

new(*args) click to toggle source
Calls superclass method HTML::Pipeline::Filter::new
# File lib/html/pipeline_plus/syntax_highlight_filter.rb, line 8
def initialize(*args)
  super(*args)
  @formatter = Rouge::Formatters::HTML.new
end

Public Instance Methods

call() click to toggle source
# File lib/html/pipeline_plus/syntax_highlight_filter.rb, line 13
def call
  doc.search('pre').each do |node|
    default = context[:highlight] && context[:highlight].to_s
    next unless lang = node['lang'] || default
    next unless lexer = lexer_for(lang)
    text = node.inner_text

    html = highlight_with_timeout_handling(text, lang)
    next if html.nil?

    node.inner_html = html
    klass = node['class']
    scope = context[:scope] || "highlight-#{lang}"
    klass = [klass, scope].compact.join ' '

    node['class'] = klass
  end
  doc
end
highlight_with_timeout_handling(text, lang) click to toggle source
# File lib/html/pipeline_plus/syntax_highlight_filter.rb, line 33
def highlight_with_timeout_handling(text, lang)
  Rouge.highlight(text, lang, @formatter)
rescue Timeout::Error => _
  nil
end
lexer_for(lang) click to toggle source
# File lib/html/pipeline_plus/syntax_highlight_filter.rb, line 39
def lexer_for(lang)
  Rouge::Lexer.find(lang)
end