css.rb
70 lines
| 1.6 KiB
| text/x-ruby
|
RubyLexer
|
r638 | module CodeRay | ||
module Encoders | ||||
class HTML | ||||
class CSS | ||||
attr :stylesheet | ||||
def CSS.load_stylesheet style = nil | ||||
CodeRay::Styles[style] | ||||
end | ||||
def initialize style = :default | ||||
@classes = Hash.new | ||||
style = CSS.load_stylesheet style | ||||
@stylesheet = [ | ||||
style::CSS_MAIN_STYLES, | ||||
style::TOKEN_COLORS.gsub(/^(?!$)/, '.CodeRay ') | ||||
].join("\n") | ||||
parse style::TOKEN_COLORS | ||||
end | ||||
def [] *styles | ||||
cl = @classes[styles.first] | ||||
return '' unless cl | ||||
style = '' | ||||
1.upto(styles.size) do |offset| | ||||
break if style = cl[styles[offset .. -1]] | ||||
end | ||||
|
r3478 | # warn 'Style not found: %p' % [styles] if style.empty? | ||
|
r638 | return style | ||
end | ||||
private | ||||
CSS_CLASS_PATTERN = / | ||||
|
r3478 | ( # $1 = selectors | ||
(?: | ||||
(?: \s* \. [-\w]+ )+ | ||||
\s* ,? | ||||
)+ | ||||
) | ||||
|
r638 | \s* \{ \s* | ||
( [^\}]+ )? # $2 = style | ||||
\s* \} \s* | ||||
| | ||||
( . ) # $3 = error | ||||
/mx | ||||
def parse stylesheet | ||||
|
r3478 | stylesheet.scan CSS_CLASS_PATTERN do |selectors, style, error| | ||
|
r638 | raise "CSS parse error: '#{error.inspect}' not recognized" if error | ||
|
r3478 | for selector in selectors.split(',') | ||
classes = selector.scan(/[-\w]+/) | ||||
cl = classes.pop | ||||
@classes[cl] ||= Hash.new | ||||
@classes[cl][classes] = style.to_s.strip.delete(' ').chomp(';') | ||||
end | ||||
|
r638 | end | ||
end | ||||
end | ||||
end | ||||
end | ||||
end | ||||
if $0 == __FILE__ | ||||
require 'pp' | ||||
pp CodeRay::Encoders::HTML::CSS.new | ||||
end | ||||