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

{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.escapeHTML(text) ⇒ Object

Escape text for use in HTML (content or attributes) by running it through standard XML escaping (quotes and angle brackets and ampersands)



9
10
11
12
13
# File 'lib/maruku/output/to_html.rb', line 9

def self.escapeHTML(text)
  CGI.escapeHTML(text)
  # TODO: When we drop Rubies < 1.9.3, re-add .gsub(/[^[:print:]\n\r\t]/, '') to
  # get rid of non-printable control characters.
end

Instance Method Details

#add_class_to(el, cl) ⇒ Object



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

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

#add_css_to(head) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/maruku/output/to_html.rb', line 231

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



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

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



877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/maruku/output/to_html.rb', line 877

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



873
874
875
# File 'lib/maruku/output/to_html.rb', line 873

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



245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/maruku/output/to_html.rb', line 245

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.



396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/maruku/output/to_html.rb', line 396

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

  Array(HTML4Attributes[name]).each do |att|
    if v = @attributes[att]
      attributes[att.to_s] = MaRuKu::Out::HTML.escapeHTML(v.to_s)
    end
  end

  content = yield if block_given?

  HTMLElement.new(name, attributes, content)
end

#maruku_html_signatureObject



265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/maruku/output/to_html.rb', line 265

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



259
260
261
262
263
# File 'lib/maruku/output/to_html.rb', line 259

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



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

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



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
310
311
312
313
314
315
316
317
# File 'lib/maruku/output/to_html.rb', line 280

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
  raise "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

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

#render_section_numberObject

nil if not applicable, else SPAN element



465
466
467
468
469
470
471
472
# File 'lib/maruku/output/to_html.rb', line 465

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



455
456
457
458
459
460
461
462
# File 'lib/maruku/output/to_html.rb', line 455

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)



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/maruku/output/to_html.rb', line 68

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



756
757
758
759
760
761
# File 'lib/maruku/output/to_html.rb', line 756

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

#to_html_cellObject



837
838
839
840
841
842
843
# File 'lib/maruku/output/to_html.rb', line 837

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

#to_html_citationObject



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/maruku/ext/math/to_html.rb', line 176

def to_html_citation
  span = xelem('span')
  span['class'] = 'maruku-citation'
  span << xtext('[')
  self.cites.each do |c|
    if c =~ /(\w+):(\d\d\d\d\w{2,3})/ # INSPIRE
      a = xelem('a')
      a << xtext(c)
      a['href'] = "http://inspirehep.net/search?p=#{$1}%3A#{$2}"
      span << a << xtext(',')
    elsif c =~ /MR(\d+)/ # MathReviews
      a = xelem('a')
      a << xtext(c)
      a['href'] = "http://www.ams.org/mathscinet-getitem?mr=#{$1}"
      span << a << xtext(',')
    else
      span << xtext(c + ',')
    end
  end
  span.children.last.chop! unless span.children.last == '['
  span << xtext(']')
  span
end

#to_html_codeObject



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
573
574
575
576
577
578
579
# File 'lib/maruku/output/to_html.rb', line 519

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



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/maruku/output/to_html.rb', line 600

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



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

def to_html_definition
  children_to_html
end

#to_html_definition_dataObject



801
802
803
# File 'lib/maruku/output/to_html.rb', line 801

def to_html_definition_data
  add_ws wrap_as_element('dd')
end

#to_html_definition_listObject

Definition lists ###



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

def to_html_definition_list
  add_ws wrap_as_element('dl')
end

#to_html_definition_termObject



797
798
799
# File 'lib/maruku/output/to_html.rb', line 797

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



162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/maruku/ext/math/to_html.rb', line 162

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)



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

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)



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
222
223
224
225
226
227
228
229
# File 'lib/maruku/output/to_html.rb', line 164

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
  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



694
695
696
697
# File 'lib/maruku/output/to_html.rb', line 694

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

#to_html_emphasisObject



439
440
441
# File 'lib/maruku/output/to_html.rb', line 439

def to_html_emphasis
  wrap_as_element('em')
end

#to_html_entityObject



845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/maruku/output/to_html.rb', line 845

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? Integer
    # Convert numeric entities to unicode characters
    xtext([entity_name].pack('U*'))
  else
    "&#{entity_name};"
  end
end

#to_html_eqrefObject



149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/maruku/ext/math/to_html.rb', line 149

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
# 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

  div
end

#to_html_footnote_referenceObject



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/maruku/output/to_html.rb', line 763

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



833
834
835
# File 'lib/maruku/output/to_html.rb', line 833

def to_html_head_cell
  wrap_as_element('th')
end

#to_html_headerObject



474
475
476
477
478
479
480
481
482
483
# File 'lib/maruku/output/to_html.rb', line 474

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



319
320
321
# File 'lib/maruku/output/to_html.rb', line 319

def to_html_hrule
  xelem('hr')
end

#to_html_im_imageObject



717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/maruku/output/to_html.rb', line 717

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


669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/maruku/output/to_html.rb', line 669

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



701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# File 'lib/maruku/output/to_html.rb', line 701

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


643
644
645
646
# File 'lib/maruku/output/to_html.rb', line 643

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



622
623
624
625
626
627
628
629
630
631
632
# File 'lib/maruku/output/to_html.rb', line 622

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



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

def to_html_li
  add_ws wrap_as_element('li')
end

#to_html_linebreakObject



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

def to_html_linebreak
  xelem('br')
end


648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/maruku/output/to_html.rb', line 648

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



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

def to_html_ol
  add_ws wrap_as_element('ol')
end

#to_html_paragraphObject



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

def to_html_paragraph
  add_ws wrap_as_element('p')
end

#to_html_quoteObject



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

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



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/maruku/output/to_html.rb', line 740

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



908
909
910
# File 'lib/maruku/output/to_html.rb', line 908

def to_html_ref_definition
  []
end

#to_html_strongObject



435
436
437
# File 'lib/maruku/output/to_html.rb', line 435

def to_html_strong
  wrap_as_element('strong')
end

#to_html_tableObject



805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
# File 'lib/maruku/output/to_html.rb', line 805

def to_html_table
  num_columns = self.align.size

  # The table data is passed as a multi-dimensional array
  # we just need to split the head from the body
  head, *rows = @children

  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



410
411
412
413
414
415
416
417
# File 'lib/maruku/output/to_html.rb', line 410

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



860
861
862
863
864
865
866
867
868
869
870
# File 'lib/maruku/output/to_html.rb', line 860

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



912
913
914
# File 'lib/maruku/output/to_html.rb', line 912

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



330
331
332
# File 'lib/maruku/output/to_html.rb', line 330

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

#xelem(type) ⇒ Object

Helper to create an element



103
104
105
# File 'lib/maruku/output/to_html.rb', line 103

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

#xml_newlineObject



107
108
109
# File 'lib/maruku/output/to_html.rb', line 107

def xml_newline
  "\n"
end

#xtext(text) ⇒ Object

Helper to create a text node



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

def xtext(text)
  MaRuKu::Out::HTML.escapeHTML(text)
end