Sha256: 45f1ad7011096b776bd37cca2bae1b96d4544978fdee581fa7ad8ff9d1c59128

Contents?: true

Size: 707 Bytes

Versions: 13

Compression:

Stored size: 707 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']
          next unless lexer = Pygments::Lexer[lang]
          text = node.inner_text

          html = highlight_with_timeout_handling(lexer, text)
          next if html.nil?

          node.child.replace(html)
        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

13 entries across 13 versions & 1 rubygems

Version Path
html-pipeline-linuxfr-0.14.11 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.10 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.9 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.8 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.7 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.6 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.5 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.4 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.3 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.2 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.1 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.0.14 lib/html/pipeline/syntax_highlight_filter.rb