Module: MaRuKu::Out::HTML

Included in:
MDElement
Defined in:
lib/maruku/output/to_html.rb,
lib/maruku.rb,
lib/maruku/ext/div.rb,
lib/maruku/ext/math/to_html.rb,
lib/maruku/ext/math/mathml_engines/none.rb,
lib/maruku/ext/math/mathml_engines/ritex.rb,
lib/maruku/ext/math/mathml_engines/blahtex.rb,
lib/maruku/ext/math/mathml_engines/itex2mml.rb

Overview

This module groups all functions related to HTML export.

Defined Under Namespace

Classes: HTMLElement, PNG

Constant Summary collapse

Xhtml11_mathml2_svg11 =
'<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"
    "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">
'
HTML4Attributes =

begin maruku_doc

Attribute: style Scope: element Output: HTML

It is copied as a standard HTML attribute.

end

{}

Instance Method Summary collapse

Instance Method Details

#add_class_to(el, cl) ⇒ Object



627
628
629
630
631
632
633
634
# File 'lib/maruku/output/to_html.rb', line 627

def add_class_to(el, cl)
  el['class'] =
    if already = el['class']
      already + " " + cl
    else
      cl
    end
end

#add_css_to(head) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/maruku/output/to_html.rb', line 223

def add_css_to(head)
  if css_list = self.attributes[:css]
    css_list.split.each do |css|
      # <link type="text/css" rel="stylesheet" href="..." />
      link = xelem('link')
      link['type'] = 'text/css'
      link['rel'] = 'stylesheet'
      link['href'] = css
      head << link << xml_newline
    end
  end
end

#add_ws(e) ⇒ Object



675
676
677
# File 'lib/maruku/output/to_html.rb', line 675

def add_ws(e)
  [xml_newline, e, xml_newline]
end

#adjust_png(png, use_depth) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/maruku/ext/math/to_html.rb', line 79

def adjust_png(png, use_depth)
  src = png.src

  height_in_px = png.height
  depth_in_px = png.depth
  height_in_ex = height_in_px / pixels_per_ex
  depth_in_ex = depth_in_px / pixels_per_ex
  total_height_in_ex = height_in_ex + depth_in_ex
  style = ""
  style << "vertical-align: -#{depth_in_ex}ex;" if use_depth
  style << "height: #{total_height_in_ex}ex;"

  img = xelem('img')
  img['src'] = src
  img['style'] = style
  img['alt'] = "$#{self.math.strip}$"
  img['class'] = 'maruku-png'
  img
end

#array_to_html(array) ⇒ Object



868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/maruku/output/to_html.rb', line 868

def array_to_html(array)
  e = []
  array.each do |c|
    if c.kind_of?(String)
      e << xtext(c)
    else
      if c.kind_of?(HTMLElement)
        e << c
        next
      end

      method = c.kind_of?(MaRuKu::MDElement) ? "to_html_#{c.node_type}" : "to_html"
      next unless c.respond_to?(method)

      h = c.send(method)

      unless h
        raise "Nil html created by method  #{method}:\n#{h.inspect}\n" +
          " for object #{c.inspect[0,300]}"
      end

      if h.kind_of? Array
        e.concat h
      else
        e << h
      end
    end
  end
  e
end

#children_to_htmlObject

Convert each child to html



864
865
866
# File 'lib/maruku/output/to_html.rb', line 864

def children_to_html
  array_to_html(@children)
end

#convert_to_mathml_blahtex(kind, tex) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/maruku/ext/math/mathml_engines/blahtex.rb', line 59

def convert_to_mathml_blahtex(kind, tex)
  result = run_blahtex(tex, %w[--mathml])

  doc = REXML::Document.new(result)
  mathml = doc.get_elements('//markup').to_a.first
  unless mathml
    maruku_error "Blahtex error: \n#{doc}"
    return nil
  end

  mathml.name = 'math'
  mathml.attributes['xmlns'] = "http://www.w3.org/1998/Math/MathML"
  mathml.attributes['display'] = (kind == :inline) ? :inline : :block

  MaRuKu::HTMLFragment.new(mathml.to_s)
rescue => e
  maruku_error "Error: #{e}"
  nil
end

#convert_to_mathml_itex2mml(kind, tex) ⇒ Object



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
# File 'lib/maruku/ext/math/mathml_engines/itex2mml.rb', line 2

def convert_to_mathml_itex2mml(kind, tex)
  return if $already_warned_itex2mml
  begin
    require 'itextomml'
  rescue LoadError => e
    maruku_error "Could not load package 'itex2mml'.\nPlease install it." unless $already_warned_itex2mml
    $already_warned_itex2mml = true
    return nil
  end

  begin
    require 'instiki_stringsupport'
  rescue LoadError
    require 'itex_stringsupport'
  end

  parser = Itex2MML::Parser.new
  mathml =
    case kind
    when :equation
      parser.block_filter(tex)
    when :inline
      parser.inline_filter(tex)
    else
      maruku_error "Unknown itex2mml kind: #{kind}"
      return
    end

  MaRuKu::HTMLFragment.new(mathml.to_utf8)
rescue => e
  maruku_error "Invalid MathML TeX: \n#{tex.gsub(/^/, 'tex>')}\n\n #{e.inspect}"
  nil
end

#convert_to_mathml_none(kind, tex) ⇒ Object



2
3
4
5
6
# File 'lib/maruku/ext/math/mathml_engines/none.rb', line 2

def convert_to_mathml_none(kind, tex)
  code = xelem('code')
  tex_node = xtext(tex)
  code << tex_node
end

#convert_to_mathml_ritex(kind, tex) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/maruku/ext/math/mathml_engines/ritex.rb', line 2

def convert_to_mathml_ritex(kind, tex)
	begin
		if not $ritex_parser
			require 'ritex'
		 	$ritex_parser = Ritex::Parser.new
		end
		
		mathml =  $ritex_parser.parse(tex.strip)
		doc = Document.new(mathml, {:respect_whitespace =>:all}).root
		return doc
	rescue LoadError => e
		maruku_error "Could not load package 'ritex'.\n"+
		"Please install it using:\n"+
		"   $ gem install ritex\n\n"+e.inspect
	rescue Racc::ParseError => e
		maruku_error "Could not parse TeX: \n#{tex}"+
			"\n\n #{e.inspect}"
	end
	nil
end

#convert_to_png_blahtex(kind, tex) ⇒ Object



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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/maruku/ext/math/mathml_engines/blahtex.rb', line 8

def convert_to_png_blahtex(kind, tex)
  FileUtils.mkdir_p get_setting(:html_png_dir)

  # first, we check whether this image has already been processed
  md5sum = Digest::MD5.hexdigest(tex + " params: ")
  result_file = File.join(get_setting(:html_png_dir), md5sum + ".txt")

  if File.exists?(result_file)
    result = File.read(result_file)
  else
    args = [
            '--png',
            '--use-preview-package',
            '--shell-dvipng',
            "dvipng -D #{Shellwords.shellescape(get_setting(:html_png_resolution).to_s)}",
            "--temp-directory #{Shellwords.shellescape(get_setting(:html_png_dir))}",
            "--png-directory #{Shellwords.shellescape(get_setting(:html_png_dir))}"
           ]
    args << '--displaymath' if kind == :equation

    result = run_blahtex(tex, args)
  end

  if result.nil? || result.empty?
    maruku_error "Blahtex error: empty output"
    return
  end

  doc = REXML::Document.new(result)
  png = doc.root.elements.to_a.first
  if png.name != 'png'
    maruku_error "Blahtex error: \n#{doc}"
    return
  end

  raise "No depth element in:\n #{doc}" unless depth = png.xpath('//depth')[0]
  raise "No height element in:\n #{doc}" unless height = png.xpath('//height')[0]
  raise "No md5 element in:\n #{doc}" unless md5 = png.xpath('//md5')[0]

  depth = depth.text.to_f
  height = height.text.to_f
  raise "Height or depth was 0! in \n #{doc}" if height == 0 || depth == 0

  md5 = md5.text

  PNG.new("#{get_setting(:html_png_url)}#{md5}.png", depth, height)
rescue => e
  maruku_error "Error: #{e}"
  nil
end

#convert_to_png_none(kind, tex) ⇒ Object



8
9
10
# File 'lib/maruku/ext/math/mathml_engines/none.rb', line 8

def convert_to_png_none(kind, tex)
  nil
end

#day_suffix(day) ⇒ Object

returns “st”,“nd”,“rd” or “th” as appropriate



237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/maruku/output/to_html.rb', line 237

def day_suffix(day)
  s = {
    1 => 'st',
    2 => 'nd',
    3 => 'rd',
    21 => 'st',
    22 => 'nd',
    23 => 'rd',
    31 => 'st'
  }
  s[day] || 'th';
end

#html_element(name, content = "", attributes = {}) ⇒ Object

Pretty much the same as the HTMLElement constructor except it copies standard attributes out of the Maruku Element’s attributes hash.



388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/maruku/output/to_html.rb', line 388

def html_element(name, content="", attributes={})
  if attributes.empty? && content.is_a?(Hash)
    attributes = content
  end

  Array(HTML4Attributes[name]).each do |att|
    if v = @attributes[att]
      attributes[att.to_s] = v.to_s
    end
  end
  content = yield if block_given?

  HTMLElement.new(name, attributes, content)
end

#maruku_html_signatureObject



257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/maruku/output/to_html.rb', line 257

def maruku_html_signature
  div = xelem('div')
  div['class'] = 'maruku_signature'
  div << xelem('hr')
  span = xelem('span')
  span['style'] = 'font-size: small; font-style: italic'
  div << span << xtext('Created by ')
  a = xelem('a')
  a['href'] = MaRuKu::MARUKU_URL
  a['title'] = 'Maruku: a Markdown-superset interpreter for Ruby'
  a << xtext('Maruku')
  span << xtext(nice_date + ".")
  div
end

#nice_dateObject

formats a nice date



251
252
253
254
255
# File 'lib/maruku/output/to_html.rb', line 251

def nice_date
  Time.now.strftime(" at %H:%M on %A, %B %d") +
    day_suffix(t.day) +
    t.strftime(", %Y")
end

#obfuscate(s) ⇒ Object

Email address



681
682
683
684
685
# File 'lib/maruku/output/to_html.rb', line 681

def obfuscate(s)
  s.bytes.inject('') do |res, char|
    res << "&#%03d;" % char
  end
end

#pixels_per_exObject



75
76
77
# File 'lib/maruku/ext/math/to_html.rb', line 75

def pixels_per_ex
  $pixels_per_ex ||= render_png(:inline, "x").height
end

#render_footnotesObject



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/maruku/output/to_html.rb', line 272

def render_footnotes
  div = xelem('div')
  div['class'] = 'footnotes'
  div << xelem('hr')
  ol = xelem('ol')

  @doc.footnotes_order.each_with_index do |fid, i|
    num = i + 1
    if f = self.footnotes[fid]
      li = f.wrap_as_element('li')
      li['id'] = "#{get_setting(:doc_prefix)}fn:#{num}"

      a = xelem('a')
      a['href'] = "\##{get_setting(:doc_prefix)}fnref:#{num}"
      a['rev'] = 'footnote'
      a << xtext([8617].pack('U*'))

      last = nil
      li.children.reverse_each do |child|
        if child.is_a?(HTMLElement)
          last = child
          break
        end
      end

      if last && last.name == "p"
        last << xtext(' ') << a
      else
        li.children << a
      end
      ol << li
    else
      maruku_error "Could not find footnote id '#{fid}' among [#{self.footnotes.keys.inspect}]."
    end
  end

  div << ol
end

#render_mathml(kind, tex) ⇒ MaRuKu::Out::HTML::HTMLElement

Creates an xml Mathml document of this node’s TeX code.



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/maruku/ext/math/to_html.rb', line 47

def render_mathml(kind, tex)
  engine = get_setting(:html_math_engine)
  method = "convert_to_mathml_#{engine}"
  if self.respond_to? method
    mathml = self.send(method, kind, tex)
    return mathml || convert_to_mathml_none(kind, tex)
  end

  # TODO: Warn here
  puts "A method called #{method} should be defined."
  convert_to_mathml_none(kind, tex)
end

#render_png(kind, tex) ⇒ MaRuKu::Out::HTML::PNG?

Renders a PNG image of this node’s TeX code. Returns

Returns:

  • (MaRuKu::Out::HTML::PNG, nil)

    A struct describing the location and size of the image, or nil if no library is loaded that can render PNGs.



66
67
68
69
70
71
72
73
# File 'lib/maruku/ext/math/to_html.rb', line 66

def render_png(kind, tex)
  engine = get_setting(:html_png_engine)
  method = "convert_to_png_#{engine}".to_sym
  return self.send(method, kind, tex) if self.respond_to? method

  puts "A method called #{method} should be defined."
  nil
end

#render_section_numberObject

nil if not applicable, else SPAN element



458
459
460
461
462
463
464
465
# File 'lib/maruku/output/to_html.rb', line 458

def render_section_number
  return nil unless section_number && !section_number.empty?

  # if we are bound to a section, add section number
  span = xelem('span')
  span['class'] = 'maruku_section_number'
  span << xtext(section_number)
end

#section_numberObject

nil if not applicable, else string



448
449
450
451
452
453
454
455
# File 'lib/maruku/output/to_html.rb', line 448

def section_number
  return nil unless get_setting(:use_numbered_headers)

  n = Array(@attributes[:section_number])
  return nil if n.empty?

  n.join('.') + ". "
end

#to_html(context = {}) ⇒ Object

Render as an HTML fragment (no head, just the content of BODY). (returns a string)



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/maruku/output/to_html.rb', line 60

def to_html(context={})
  output = ""
  children_to_html.each do |e|
    output << e.to_s
  end

  # render footnotes
  unless @doc.footnotes_order.empty?
    output << render_footnotes
  end

  output
end

#to_html_abbrObject



749
750
751
752
753
754
# File 'lib/maruku/output/to_html.rb', line 749

def to_html_abbr
  abbr = xelem('abbr')
  abbr << xtext(children[0])
  abbr['title'] = self.title if self.title
  abbr
end

#to_html_cellObject



828
829
830
831
832
833
834
# File 'lib/maruku/output/to_html.rb', line 828

def to_html_cell
  if @attributes[:scope]
    wrap_as_element('th')
  else
    wrap_as_element('td')
  end
end

#to_html_codeObject



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/maruku/output/to_html.rb', line 512

def to_html_code
  source = self.raw_code

  code_lang = self.lang || self.attributes[:lang] || @doc.attributes[:code_lang]

  code_lang = 'xml' if code_lang == 'html'
  code_lang = 'css21' if code_lang == 'css'

  use_syntax = get_setting :html_use_syntax

  element =
    if use_syntax && code_lang
      begin
        unless $syntax_loaded
          require 'rubygems'
          require 'syntax'
          require 'syntax/convertors/html'
          $syntax_loaded = true
        end
        convertor = Syntax::Convertors::HTML.for_syntax code_lang

        # eliminate trailing newlines otherwise Syntax crashes
        source = source.sub(/\n*\z/, '')

        html = convertor.convert(source)

        html.gsub!(/\&apos;|'/,'&#39;') # IE bug

        d = MaRuKu::HTMLFragment.new(html)
        highlighted = d.to_html.sub(/\A<pre>(.*)<\/pre>\z/m, '\1')
        code = HTMLElement.new('code', { :class => code_lang }, highlighted)

        pre = xelem('pre')
        # add a class here, too, for compatibility with existing implementations
        pre['class'] = code_lang
        pre << code
        pre
      rescue LoadError => e
        maruku_error "Could not load package 'syntax'.\n" +
          "Please install it, for example using 'gem install syntax'."
        to_html_code_using_pre(source, code_lang)
      rescue => e
        maruku_error "Error while using the syntax library for code:\n#{source.inspect}" +
          "Lang is #{code_lang} object is: \n" +
          self.inspect +
          "\nException: #{e.class}: #{e.message}"

        tell_user("Using normal PRE because the syntax library did not work.")
        to_html_code_using_pre(source, code_lang)
      end
    else
      to_html_code_using_pre(source, code_lang)
    end

  color = get_setting(:code_background_color)
  if color != MaRuKu::Globals[:code_background_color]
    element['style'] = "background-color: #{color};"
  end

  add_ws element
end

#to_html_code_using_pre(source, code_lang = nil) ⇒ Object



593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
# File 'lib/maruku/output/to_html.rb', line 593

def to_html_code_using_pre(source, code_lang=nil)
  code = xelem('code')
  pre = xelem('pre')
  pre << code

  if get_setting(:code_show_spaces)
    # 187 = raquo
    # 160 = nbsp
    # 172 = not
    source = source.gsub(/\t/,'&#187;' + '&#160;' * 3).gsub(/ /,'&#172;')
  end

  code << xtext(source)

  code_lang ||= self.attributes[:lang]
  if code_lang
    pre['class'] = code['class'] = code_lang
  end

  pre
end

#to_html_definitionObject



786
787
788
# File 'lib/maruku/output/to_html.rb', line 786

def to_html_definition
  children_to_html
end

#to_html_definition_dataObject



794
795
796
# File 'lib/maruku/output/to_html.rb', line 794

def to_html_definition_data
  add_ws wrap_as_element('dd')
end

#to_html_definition_listObject

Definition lists ###



782
783
784
# File 'lib/maruku/output/to_html.rb', line 782

def to_html_definition_list
  add_ws wrap_as_element('dl')
end

#to_html_definition_termObject



790
791
792
# File 'lib/maruku/output/to_html.rb', line 790

def to_html_definition_term
  add_ws wrap_as_element('dt')
end

#to_html_divObject



120
121
122
# File 'lib/maruku/ext/div.rb', line 120

def to_html_div
  add_ws wrap_as_element('div')
end

#to_html_divrefObject



169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/maruku/ext/math/to_html.rb', line 169

def to_html_divref
  unless hash = self.doc.refid2ref.values.find {|h| h.has_key?(self.refid)}
    maruku_error "Cannot find div #{self.refid.inspect}"
    return xtext("\\ref{#{self.refid}}")
  end
  ref= hash[self.refid]

  a = xelem('a')
  a['class'] = 'maruku-ref'
  a['href'] = "#" + self.refid
  a << xtext(ref.num.to_s)
  a
end

#to_html_document(context = {}) ⇒ Object

Render to a complete HTML document (returns a string)



82
83
84
85
86
87
# File 'lib/maruku/output/to_html.rb', line 82

def to_html_document(context={})
  doc = to_html_document_tree

  xml = doc.to_s
  Xhtml11_mathml2_svg11 + xml
end

#to_html_document_treeObject

Render to a complete HTML document (returns an HTMLElement document tree)



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/maruku/output/to_html.rb', line 156

def to_html_document_tree
  root = xelem('html')
  root['xmlns'] = 'http://www.w3.org/1999/xhtml'
  root['xmlns:svg'] = "http://www.w3.org/2000/svg"
  root['xml:lang'] = self.attributes[:lang] || 'en'

  root << xml_newline
  head = xelem('head')
  root << head

  #<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
  me = xelem('meta')
  me['http-equiv'] = 'Content-type'
  me['content'] = 'application/xhtml+xml;charset=utf-8'
  head << me

  %w(description keywords author revised).each do |m|
    if value = self.attributes[m.to_sym]
      meta = xelem('meta')
      meta['name'] = m
      meta['content'] = value.to_s
      head << meta
    end
  end

  self.attributes.each do |k,v|
    if k.to_s =~ /\Ameta-(.*)\z/
      meta = xelem('meta')
      meta['name'] = $1
      meta['content'] = v.to_s
      head << meta
    end
  end

  # Create title element
  doc_title = self.attributes[:title] || self.attributes[:subject] || ""
  begin
    title_content = MaRuKu::HTMLFragment.new(doc_title).to_html
  rescue
    title_content = xtext(doc_title)
  end
  title = xelem('title') << title_content
  head << title
  add_css_to(head)

  root << xml_newline

  body = xelem('body')

  children_to_html.each do |e|
    body << e.to_s
  end

  # render footnotes
  unless @doc.footnotes_order.empty?
    body << render_footnotes(@doc)
  end

  # When we are rendering a whole document, we add a signature
  # at the bottom.
  if get_setting(:maruku_signature)
    body << maruku_html_signature
  end

  root << body
end

#to_html_email_addressObject



687
688
689
690
# File 'lib/maruku/output/to_html.rb', line 687

def to_html_email_address
  obfuscated = obfuscate(self.email)
  html_element('a', obfuscated, :href => "mailto:#{obfuscated}")
end

#to_html_emphasisObject



432
433
434
# File 'lib/maruku/output/to_html.rb', line 432

def to_html_emphasis
  wrap_as_element('em')
end

#to_html_entityObject



836
837
838
839
840
841
842
843
844
845
846
847
848
849
# File 'lib/maruku/output/to_html.rb', line 836

def to_html_entity
  entity_name = self.entity_name

  if entity = MaRuKu::Out::EntityTable.instance.entity(entity_name)
    entity_name = entity.html_num
  end

  if entity_name.kind_of? Fixnum
    # Convert numeric entities to unicode characters
    xtext([entity_name].pack('U*'))
  else
    "&#{entity_name};"
  end
end

#to_html_eqrefObject



156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/maruku/ext/math/to_html.rb', line 156

def to_html_eqref
  unless eq = self.doc.eqid2eq[self.eqid]
    maruku_error "Cannot find equation #{self.eqid.inspect}"
    return xtext("(eq:#{self.eqid})")
  end

  a = xelem('a')
  a['class'] = 'maruku-eqref'
  a['href'] = "#eq:#{self.eqid}"
  a << xtext("(#{eq.num})")
  a
end

#to_html_equationObject



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/maruku/ext/math/to_html.rb', line 116

def to_html_equation
  mathml = get_setting(:html_math_output_mathml) && render_mathml(:equation, self.math)
  png    = get_setting(:html_math_output_png)    && render_png(:equation, self.math)

  div = xelem('div')
  div['class'] = 'maruku-equation'
  if mathml
    if self.label  # then numerate
      span = xelem('span')
      span['class'] = 'maruku-eq-number'
      span << xtext("(#{self.num})")
      div << span
      div['id'] = "eq:#{self.label}"
    end
    mathml.add_class('maruku-mathml')
    div << mathml.to_html
  end

  if png
    img = adjust_png(png, false)
    div << img
    if self.label  # then numerate
      span = xelem('span')
      span['class'] = 'maruku-eq-number'
      span << xtext("(#{self.num})")
      div << span
      div['id'] = "eq:#{self.label}"
    end
  end

  source_span = xelem('span')
  add_class_to(source_span, 'maruku-eq-tex')
  code = convert_to_mathml_none(:equation, self.math.strip)
  code['style'] = 'display: none'
  source_span << code
  div << source_span

  div
end

#to_html_footnote_referenceObject



756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
# File 'lib/maruku/output/to_html.rb', line 756

def to_html_footnote_reference
  id = self.footnote_id

  # save the order of used footnotes
  order = @doc.footnotes_order

  # footnote has already been used
  return [] if order.include?(id)

  return [] unless @doc.footnotes[id]

  # take next number
  order << id

  num = order.index(id) + 1

  sup = xelem('sup')
  sup['id'] = "#{get_setting(:doc_prefix)}fnref:#{num}"
  a = xelem('a')
  a << xtext(num.to_s)
  a['href'] = "\##{get_setting(:doc_prefix)}fn:#{num}"
  a['rel'] = 'footnote'
  sup << a
end

#to_html_head_cellObject



824
825
826
# File 'lib/maruku/output/to_html.rb', line 824

def to_html_head_cell
  wrap_as_element('th')
end

#to_html_headerObject



467
468
469
470
471
472
473
474
475
476
# File 'lib/maruku/output/to_html.rb', line 467

def to_html_header
  element_name = "h#{self.level}"
  h = wrap_as_element element_name

  if span = render_section_number
    h.children.unshift(span)
  end

  add_ws h
end

#to_html_hruleObject



311
312
313
# File 'lib/maruku/output/to_html.rb', line 311

def to_html_hrule
  xelem('hr')
end

#to_html_im_imageObject



710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/maruku/output/to_html.rb', line 710

def to_html_im_image
  if self.url
    attrs = {}
    attrs['src'] = self.url.to_s
    attrs['alt'] = children_to_s
    attrs['title'] = self.title.to_s if self.title
    html_element('img', nil, attrs)
  else
    maruku_error "Image with no url: #{self.inspect}"
    tell_user "Could not create image without a source URL;" +
      " Using SPAN element as replacement."
    wrap_as_element('span')
  end
end


662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/maruku/output/to_html.rb', line 662

def to_html_im_link
  if self.url
    a = {}
    a['href'] = self.url
    a['title'] = self.title if self.title
    wrap_as_element('a', a)
  else
    maruku_error "Could not find url in #{self.inspect}"
    tell_user "Not creating a link for ref_id = #{id.inspect}."
    wrap_as_element('span')
  end
end

#to_html_imageObject

Images



694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/maruku/output/to_html.rb', line 694

def to_html_image
  a = {}
  id = self.ref_id
  if ref = @doc.refs[sanitize_ref_id(id)] || @doc.refs[sanitize_ref_id(children_to_s)]
    a['src'] = ref[:url].to_s
    a['alt'] = children_to_s
    a['title'] = ref[:title].to_s if ref[:title]
    html_element('img', nil, a)
  else
    maruku_error "Could not find id = #{id.inspect} for\n #{self.inspect}"
    tell_user "Could not create image with ref_id = #{id.inspect};" +
      " Using SPAN element as replacement."
    wrap_as_element('span')
  end
end


636
637
638
639
# File 'lib/maruku/output/to_html.rb', line 636

def to_html_immediate_link
  text = self.url.gsub(/^mailto:/, '') # don't show mailto
  html_element('a', text, 'href' => self.url)
end

#to_html_inline_codeObject



615
616
617
618
619
620
621
622
623
624
625
# File 'lib/maruku/output/to_html.rb', line 615

def to_html_inline_code
  code_attrs = {}
  source = xtext(self.raw_code)

  color = get_setting(:code_background_color)
  if color != MaRuKu::Globals[:code_background_color]
    code_attrs['style'] = "background-color: #{color};" + (code_attrs['style'] || "")
  end

  html_element('code', source, code_attrs)
end

#to_html_inline_mathObject



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/maruku/ext/math/to_html.rb', line 99

def to_html_inline_math
  mathml = get_setting(:html_math_output_mathml) && render_mathml(:inline, self.math)
  if mathml
    mathml.add_class('maruku-mathml')
    return mathml.to_html
  end

  png = get_setting(:html_math_output_png) && render_png(:inline, self.math)

  HTMLElement.new 'span', 'class' => 'maruku-inline' do
    # TODO: It seems weird that we output an empty span if there's no PNG
    if png
      adjust_png(png, true)
    end
  end
end

#to_html_liObject



420
421
422
# File 'lib/maruku/output/to_html.rb', line 420

def to_html_li
  add_ws wrap_as_element('li')
end

#to_html_linebreakObject



315
316
317
# File 'lib/maruku/output/to_html.rb', line 315

def to_html_linebreak
  xelem('br')
end


641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/maruku/output/to_html.rb', line 641

def to_html_link
  a = {}
  id = self.ref_id || children_to_s

  if ref = @doc.refs[sanitize_ref_id(id)] || @doc.refs[sanitize_ref_id(children_to_s)]
    a['href'] = ref[:url] if ref[:url]
    a['title'] = ref[:title] if ref[:title]
  else
    maruku_error "Could not find ref_id = #{id.inspect} for #{self.inspect}\n" +
      "Available refs are #{@doc.refs.keys.inspect}"
    tell_user "Not creating a link for ref_id = #{id.inspect}.\n"
    if (self.ref_id)
      return "[#{children_to_s}][#{id}]"
    else
      return "[#{children_to_s}]"
    end
  end

  wrap_as_element('a', a)
end

#to_html_olObject



416
417
418
# File 'lib/maruku/output/to_html.rb', line 416

def to_html_ol
  add_ws wrap_as_element('ol')
end

#to_html_paragraphObject



412
413
414
# File 'lib/maruku/output/to_html.rb', line 412

def to_html_paragraph
  add_ws wrap_as_element('p')
end

#to_html_quoteObject



424
425
426
# File 'lib/maruku/output/to_html.rb', line 424

def to_html_quote
  add_ws wrap_as_element('blockquote')
end

#to_html_raw_htmlObject

begin maruku_doc

Attribute: filter_html Scope: document

If true, raw HTML is discarded from the output.

end



733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/maruku/output/to_html.rb', line 733

def to_html_raw_html
  return [] if get_setting(:filter_html)
  return parsed_html.to_html if parsed_html

  # If there's no parsed HTML
  raw_html = self.raw_html

  # Creates red box with offending HTML
  tell_user "Wrapping bad html in a PRE with class 'markdown-html-error'\n" +
    raw_html.gsub(/^/, '|')
  pre = xelem('pre')
  pre['style'] = 'border: solid 3px red; background-color: pink'
  pre['class'] = 'markdown-html-error'
  pre << xtext("Maruku could not parse this XML/HTML: \n#{raw_html}")
end

#to_html_ref_definitionObject



899
900
901
# File 'lib/maruku/output/to_html.rb', line 899

def to_html_ref_definition
  []
end

#to_html_strongObject



428
429
430
# File 'lib/maruku/output/to_html.rb', line 428

def to_html_strong
  wrap_as_element('strong')
end

#to_html_tableObject



798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# File 'lib/maruku/output/to_html.rb', line 798

def to_html_table
  num_columns = self.align.size

  head, *rows = @children.each_slice(num_columns).to_a

  table = html_element('table')
  thead = xelem('thead')
  tr = xelem('tr')
  array_to_html(head).inject(tr, &:<<)
  thead << tr
  table << thead

  tbody = xelem('tbody')
  rows.each do |row|
    tr = xelem('tr')
    array_to_html(row).each_with_index do |x, i|
      x['style'] ="text-align: #{self.align[i].to_s};"
      tr << x
    end

    tbody << tr << xml_newline
  end

  table << tbody
end

#to_html_ulObject



403
404
405
406
407
408
409
410
# File 'lib/maruku/output/to_html.rb', line 403

def to_html_ul
  if @attributes[:toc]
    # render toc
    @doc.toc.to_html
  else
    add_ws wrap_as_element('ul')
  end
end

#to_html_xml_instrObject



851
852
853
854
855
856
857
858
859
860
861
# File 'lib/maruku/output/to_html.rb', line 851

def to_html_xml_instr
  target = self.target || ''
  code = self.code || ''

  # A blank target is invalid XML. Just create a text node?
  if target.empty?
    xtext("<?#{code}?>")
  else
    "<?#{target} #{code}?>"
  end
end

#to_latex_ref_definitionObject



903
904
905
# File 'lib/maruku/output/to_html.rb', line 903

def to_latex_ref_definition
  []
end

#wrap_as_element(name, attributes = {}) ⇒ Object

renders children as html and wraps into an element of given name

Sets ‘id’ if meta is set



322
323
324
# File 'lib/maruku/output/to_html.rb', line 322

def wrap_as_element(name, attributes={})
  html_element name, children_to_html, attributes
end

#xelem(type) ⇒ Object

Helper to create an element



95
96
97
# File 'lib/maruku/output/to_html.rb', line 95

def xelem(type)
  HTMLElement.new(type)
end

#xml_newlineObject



99
100
101
# File 'lib/maruku/output/to_html.rb', line 99

def xml_newline
  "\n"
end

#xtext(text) ⇒ Object

Helper to create a text node



90
91
92
# File 'lib/maruku/output/to_html.rb', line 90

def xtext(text)
  CGI.escapeHTML(text)
end