summaryrefslogtreecommitdiff
path: root/lib/asciidoctor/pdf/ext/pygments.rb
blob: 14bb4907c048efa9570ef83e21b0c6eaeec9561e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# frozen_string_literal: true

module Pygments
  module Ext
    module BlockStyles
      BlockSelectorRx = /^\.highlight *\{([^}]+?)\}/
      HighlightBackgroundColorRx = /^\.highlight +\.hll +{ *background(?:-color)?: *#(\h{6})/
      ColorPropertiesRx = /(?:^|;) *(background(?:-color)?|color): *#?(\h{6}) *(?=$|;)/

      @cache = ::Hash.new do |cache, key|
        styles = {}
        if BlockSelectorRx =~ (css = ::Pygments.css '.highlight', style: key)
          $1.scan ColorPropertiesRx do |pname, pval|
            case pname
            when 'background', 'background-color'
              styles[:background_color] = pval
            when 'color'
              styles[:font_color] = pval
            end
          end
        end
        styles[:highlight_background_color] = $1 if HighlightBackgroundColorRx =~ css
        @cache = cache.merge key => styles
        styles
      end

      def self.available? style
        (@available ||= ::Pygments.styles.to_set).include? style
      end

      def self.for style
        @cache[style]
      end
    end
  end
end