Class: HTML::Pipeline::SyntaxHighlightFilter

Inherits:
Filter
  • Object
show all
Defined in:
lib/html/pipeline/syntax_highlight_filter.rb

Overview

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

Instance Attribute Summary

Attributes inherited from Filter

#context, #result

Instance Method Summary collapse

Methods inherited from Filter

#base_url, call, #current_user, #doc, #has_ancestor?, #html, #needs, #parse_html, #repository, to_document, to_html, #validate

Constructor Details

#initialize(*args) ⇒ SyntaxHighlightFilter


10
11
12
13
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 10

def initialize(*args)
  super(*args)
  @formatter = Rouge::Formatters::HTML.new
end

Instance Method Details

#callObject


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 15

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) ⇒ Object


35
36
37
38
39
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 35

def highlight_with_timeout_handling(text, lang)
  Rouge.highlight(text, lang, @formatter)
rescue Timeout::Error => _
  nil
end

#lexer_for(lang) ⇒ Object


41
42
43
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 41

def lexer_for(lang)
  Rouge::Lexer.find(lang)
end