Sha256: 71c6c629763093dba40c23e814e1eff0cd2a72a2bb4f31d925d90dd73d2c638e

Contents?: true

Size: 794 Bytes

Versions: 3

Compression:

Stored size: 794 Bytes

Contents

require 'pygments'

module HTML
  class Pipeline

    # HTML Filter that syntax highlights code blocks wrapped
    # in <pre 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

3 entries across 3 versions & 1 rubygems

Version Path
html-pipeline-linuxfr-0.14.14 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.13 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.12 lib/html/pipeline/syntax_highlight_filter.rb