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, #initialize, #needs, #parse_html, #repository, to_document, to_html, #validate

Constructor Details

This class inherits a constructor from HTML::Pipeline::Filter

Instance Method Details

#callObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 8

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(lexer, text)
    next if html.nil?

    if (node = node.replace(html).first)
      klass = node["class"]
      klass = [klass, "highlight-#{lang}"].compact.join " "

      node["class"] = klass
    end
  end
  doc
end

#highlight_with_timeout_handling(lexer, text) ⇒ Object



28
29
30
31
32
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 28

def highlight_with_timeout_handling(lexer, text)
  lexer.highlight(text)
rescue Timeout::Error => boom
  nil
end

#lexer_for(lang) ⇒ Object



34
35
36
# File 'lib/html/pipeline/syntax_highlight_filter.rb', line 34

def lexer_for(lang)
  (Linguist::Language[lang] && Linguist::Language[lang].lexer) || Pygments::Lexer[lang]
end