Sha256: 381d5812ade64ed9684447b032113d1cc3de184724052c74950461c52afeed75

Contents?: true

Size: 795 Bytes

Versions: 2

Compression:

Stored size: 795 Bytes

Contents

require 'pygments'

module HTML
  class Pipeline

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

      def highlight_with_timeout_handling(lexer, text)
        lexer.highlight(text, options: { nowrap: true })
      rescue Timeout::Error
        nil
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
html-pipeline-linuxfr-0.14.16 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.15 lib/html/pipeline/syntax_highlight_filter.rb