Sha256: 5a030b02076413cc591067edbc4ed82055865fd61838fba4e5a982e1f92c52b3

Contents?: true

Size: 1.03 KB

Versions: 11

Compression:

Stored size: 1.03 KB

Contents

begin
  require "linguist"
rescue LoadError => _
  abort "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 = Pygments::Lexer[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
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
html-pipeline-1.11.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.10.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.9.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.8.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.7.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.6.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.5.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.4.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.3.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.1.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-1.0.0 lib/html/pipeline/syntax_highlight_filter.rb