Class: Rouge::Formatters::HTML

Inherits:
Rouge::Formatter show all
Defined in:
lib/rouge/formatters/html.rb

Overview

Transforms a token stream into HTML output.

Constant Summary

Constants inherited from Rouge::Formatter

Rouge::Formatter::REGISTRY

Instance Method Summary collapse

Methods inherited from Rouge::Formatter

find, format, #format, #render, tag

Constructor Details

#initialize(opts = {}) ⇒ HTML

A css class to be used for the generated <pre> tag.

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :css_class (Object)


12
13
14
15
# File 'lib/rouge/formatters/html.rb', line 12

def initialize(opts={})
  @css_class = opts[:css_class] || 'highlight'
  @line_numbers = opts.fetch(:line_numbers) { false }
end

Instance Method Details

#stream(tokens) { ... } ⇒ Object

Yields:

  • the html output.



18
19
20
21
22
23
24
# File 'lib/rouge/formatters/html.rb', line 18

def stream(tokens, &b)
  if @line_numbers
    stream_tableized(tokens, &b)
  else
    stream_untableized(tokens, &b)
  end
end

#stream_tableized(tokens) {|"<pre class=#{@css_class.inspect}>"| ... } ⇒ Object

Yields:

  • ("<pre class=#{@css_class.inspect}>")


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rouge/formatters/html.rb', line 34

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|
    %<<div class="lineno">#{x+1}</div>>
  end.join

  yield "<pre class=#{@css_class.inspect}>"
  yield "<table><tbody><tr>"

  # the "gl" class applies the style for Generic.Lineno
  yield '<td class="gutter gl">'
  yield numbers
  yield '</td>'

  yield '<td class="code">'
  yield code
  yield '</td>'

  yield '</tr></tbody></table>'
  yield '</pre>'
end

#stream_untableized(tokens) {|"<pre class=#{@css_class.inspect}>"| ... } ⇒ Object

Yields:

  • ("<pre class=#{@css_class.inspect}>")


26
27
28
29
30
31
32
# File 'lib/rouge/formatters/html.rb', line 26

def stream_untableized(tokens, &b)
  yield "<pre class=#{@css_class.inspect}>"
  tokens.each do |tok, val|
    span(tok, val, &b)
  end
  yield '</pre>'
end