Class: HTML::Pipeline::SyntaxHighlightFilterPatch
- Inherits:
-
Filter
- Object
- Filter
- HTML::Pipeline::SyntaxHighlightFilterPatch
- Defined in:
- lib/html/pipeline/syntax_hightlight_filter.rb
Overview
HTML Filter that syntax highlights code blocks wrapped in <pre lang=“…”>.
Instance Method Summary collapse
- #call ⇒ Object
- #highlight_with_timeout_handling(text, lang) ⇒ Object
-
#initialize(*args) ⇒ SyntaxHighlightFilterPatch
constructor
A new instance of SyntaxHighlightFilterPatch.
- #lexer_for(lang) ⇒ Object
Constructor Details
#initialize(*args) ⇒ SyntaxHighlightFilterPatch
Returns a new instance of SyntaxHighlightFilterPatch.
7 8 9 10 |
# File 'lib/html/pipeline/syntax_hightlight_filter.rb', line 7 def initialize(*args) super(*args) @formatter = Rouge::Formatters::HTML.new end |
Instance Method Details
#call ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/html/pipeline/syntax_hightlight_filter.rb', line 12 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
32 33 34 35 36 |
# File 'lib/html/pipeline/syntax_hightlight_filter.rb', line 32 def highlight_with_timeout_handling(text, lang) Rouge.highlight(text, lang, @formatter) rescue Timeout::Error => _ nil end |
#lexer_for(lang) ⇒ Object
38 39 40 |
# File 'lib/html/pipeline/syntax_hightlight_filter.rb', line 38 def lexer_for(lang) Rouge::Lexer.find(lang) end |