# stdlib require 'cgi' module Rouge module Formatters # Transforms a token stream into HTML output. class HTML < Formatter tag 'html' # @option opts :css_class # A css class to be used for the generated
tag. def initialize(opts={}) @css_class = opts[:css_class] || 'highlight' @line_numbers = opts.fetch(:line_numbers) { false } end # @yield the html output. def stream(tokens, &b) if @line_numbers stream_tableized(tokens, &b) else stream_untableized(tokens, &b) end end def stream_untableized(tokens, &b) yield "" tokens.each do |tok, val| span(tok, val, &b) end yield '' end def stream_tableized(tokens, &b) num_lines = 0 code = '' tokens.each do |tok, val| num_lines += val.scan(/\n/).size span(tok, val) { |str| code << str } end # add an extra line number for non-newline-terminated strings num_lines += 1 if code[-1] != "\n" # generate a string of newline-separated line numbers for the gutter numbers = num_lines.times.map do |x| %<#{x+1}> end.join yield "" yield "
' yield numbers yield ' | ' yield '' yield code yield ' | ' yield '