Sha256: aa4aea76ea7c5480d6ccc5ae250b982c2fb3e761ac8506a118a756594d731ef7

Contents?: true

Size: 814 Bytes

Versions: 22

Compression:

Stored size: 814 Bytes

Contents

require 'pygments'

module HTML
  class Pipeline

    # HTML Filter that syntax highlights code blocks wrapped
    # in <code 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, startinline: true })
      rescue Timeout::Error
        nil
      end
    end

  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
html-pipeline-linuxfr-0.15.7 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.6 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.5 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.4 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.3 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.30 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.2 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.1 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.29 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.15.0 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.28 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.27 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.26 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.25 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.24 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.23 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.22 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.21 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.20 lib/html/pipeline/syntax_highlight_filter.rb
html-pipeline-linuxfr-0.14.19 lib/html/pipeline/syntax_highlight_filter.rb