Sha256: 4c6501f0c04ad31aa41dac7f453287849d0f20b5f4cf0e4a85bf8ec68a5243de

Contents?: true

Size: 1.16 KB

Versions: 5

Compression:

Stored size: 1.16 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 = lexer_for(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

      def lexer_for(lang)
        (Linguist::Language[lang] && Linguist::Language[lang].lexer) || Pygments::Lexer[lang]
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
html-pipeline-2.2.2 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.2.1 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.2.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.1.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-2.0 lib/html/pipeline/syntax_highlight_filter.rb