class HTMLPipeline::NodeFilter::SyntaxHighlightFilter
HTML Filter
that syntax highlights text inside code blocks.
Context options:
:highlight => String represents the language to pick lexer. Defaults to empty string. :scope => String represents the class attribute adds to pre element after. Defaults to "highlight highlight-css" if highlights a css code block.
This filter does not write any additional information to the context hash.
Constants
- SELECTOR
Public Class Methods
new(context: {}, result: {})
click to toggle source
Calls superclass method
HTMLPipeline::NodeFilter::new
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 17 def initialize(context: {}, result: {}) super # TODO: test the optionality of this @formatter = context[:formatter] || Rouge::Formatters::HTML.new end
Public Instance Methods
handle_element(element)
click to toggle source
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 29 def handle_element(element) default = context[:highlight]&.to_s @lang = element["lang"] || default scope = context.fetch(:scope, "highlight") element["class"] = "#{scope} #{scope}-#{@lang}" if include_lang? end
handle_text_chunk(text)
click to toggle source
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 38 def handle_text_chunk(text) return if @lang.nil? return if (lexer = lexer_for(@lang)).nil? content = text.to_s text.replace(highlight_with_timeout_handling(content, lexer), as: :html) end
highlight_with_timeout_handling(text, lexer)
click to toggle source
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 47 def highlight_with_timeout_handling(text, lexer) Rouge.highlight(text, lexer, @formatter) rescue Timeout::Error => _e text end
include_lang?()
click to toggle source
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 57 def include_lang? !@lang.nil? && !@lang.empty? end
lexer_for(lang)
click to toggle source
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 53 def lexer_for(lang) Rouge::Lexer.find(lang) end
selector()
click to toggle source
# File lib/html_pipeline/node_filter/syntax_highlight_filter.rb, line 25 def selector SELECTOR end