Sha256: f91511927a212bce387c6754e76ca01121e41a427a3ff10e82d7a8ffaa6580ab

Contents?: true

Size: 831 Bytes

Versions: 3

Compression:

Stored size: 831 Bytes

Contents

begin
  require 'linguist'
rescue LoadError
  raise LoadError, "You need to install 'github-linguist' before using the 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|
          next unless lang = node['lang']
          next unless lexer = Pygments::Lexer[lang]
          text = node.inner_text

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

          node.replace(html)
        end
        doc
      end

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
html-pipeline-0.2.1 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-0.2.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-0.1.0 lib/html/pipeline/syntax_highlight_filter.rb