Sha256: 2a4688ea9f9cf4a224f276bb39cdca7a5e4cb357fbd6c5a368584591533dc660

Contents?: true

Size: 1.2 KB

Versions: 8

Compression:

Stored size: 1.2 KB

Contents

begin
  require "linguist"
rescue LoadError => _
  raise HTML::Pipeline::MissingDependencyError, "Missing dependency 'github-linguist' for SyntaxHighlightFilter. See README.md for details."
end

module HTML
  class Pipeline
    # HTML Filter that syntax highlights code blocks wrapped
    # in <pre lang="...">.
    class SyntaxHighlightFilter < Filter
      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

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

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

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
html-pipeline-2.7.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.6.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.5.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.4.2 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.4.1 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.4.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.3.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.2.4 lib/html/pipeline/syntax_highlight_filter.rb