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 <code 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



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 9

def call
  doc.search('code').each do |node|
    next unless lang = node['class']
    lexer = Pygments::Lexer[lang]

    if lexer
      text = node.inner_text

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

      node.child.replace(html)
    else
      node.remove_attribute 'class'
    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, options: { nowrap: true, startinline: true })
rescue Timeout::Error
  nil
end