Module: MaRuKu::Out::HTML

Includes:
Defaults, REXML
Included in:
MDElement
Defined in:
lib/maruku.rb,
lib/maruku/output/to_html.rb

Overview

Functions for exporting to HTML.

Constant Summary

Constants included from Defaults

Defaults::DEFAULT_CODE_COLOR, Defaults::DefaultAttributes

Instance Method Summary collapse

Instance Method Details

#add_whitespace(element) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/maruku/output/to_html.rb', line 147

def add_whitespace(element)
	blocks = ['p','pre','h1','h2','h3','h4','h5','h6',
		'style','table','div','ul','ol','li','dl','dt',
		'head','blockquote','tr','thead','td','dd','title',
		'link','hr']
		
	element.get_elements( "//*" ).each do |e|
		if blocks.include? e.name
			e.parent.insert_before(e, Text.new("\n"))
			e.parent.insert_after(e, Text.new("\n"))
		end
	end

	element.get_elements( "//br" ).each do |e|
		e.parent.insert_after(e, Text.new("\n"))
	end
end

#add_ws(e) ⇒ Object



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

def add_ws(e)
	[Text.new("\n"), e, Text.new("\n")]
end

#array_to_html(array) ⇒ Object



617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/maruku/output/to_html.rb', line 617

def array_to_html(array)
	e = []
	array.each do |c|
		method = c.kind_of?(MDElement) ? 
		   "to_html_#{c.node_type}" : "to_html"

		if not c.respond_to?(method)
			#raise "Object does not answer to #{method}: #{c.class} #{c.inspect}"
			next
		end

		h =  c.send(method)

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

		if h.kind_of?Array
			e = e + h #h.each do |hh| e << hh end
		else
			e << h
		end
	end
	e
end

#children_to_htmlObject

Convert each child to html



613
614
615
# File 'lib/maruku/output/to_html.rb', line 613

def children_to_html
	array_to_html(@children)
end

#create_html_element(name) ⇒ Object



241
242
243
244
245
246
247
# File 'lib/maruku/output/to_html.rb', line 241

def create_html_element(name)
	m = Element.new name
		if (v=@attributes[:id]   ) then m.attributes['id'   ] = v.to_s end
		if (v=@attributes[:style]) then m.attributes['style'] = v.to_s end
		if (v=@attributes[:class]) then m.attributes['class'] = v.to_s end
	m
end

#day_suffix(day) ⇒ Object

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



166
167
168
169
170
171
172
173
174
# File 'lib/maruku/output/to_html.rb', line 166

def day_suffix(day)
	return 'th' if day == 11
	case day%10
		when 1; 'st'
		when 2; 'nd'
		when 3; 'rd'
		else 'th'
	end
end

#maruku_html_signatureObject



185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/maruku/output/to_html.rb', line 185

def maruku_html_signature		
	div = Element.new 'div'
		div.attributes['class'] = 'maruku_signature'
		Element.new 'hr', div
		span = Element.new 'span', div
			span.attributes['style'] = 'font-size: small; font-style: italic'
			span << Text.new('Created by ')
			a = Element.new('a', span)
				a.attributes['href'] = 'http://maruku.rubyforge.org'
				a.attributes['title'] = 'Maruku: a Markdown interpreter for Ruby'
				a << Text.new('Maruku')
			span << Text.new(nice_date+".")
	div
end

#nice_dateObject

formats a nice date



177
178
179
180
181
182
183
# File 'lib/maruku/output/to_html.rb', line 177

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

#obfuscate(s) ⇒ Object

Email address



435
436
437
438
439
440
441
# File 'lib/maruku/output/to_html.rb', line 435

def obfuscate(s)
	res = ''
	s.each_byte do |char|
		res +=  "&#%03d;" % char
	end
	res
end

#render_footnotesObject



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/maruku/output/to_html.rb', line 200

def render_footnotes
	div = Element.new 'div'
	div.attributes['class'] = 'footnotes'
	div <<  Element.new('hr')
		ol = Element.new 'ol'
		@doc.footnotes_order.each_with_index do |fid, i| num = i+1
			f = self.footnotes[fid]
			if f
				li = f.wrap_as_element('li')
				li.attributes['id'] = "fn:#{num}"
				
				a = Element.new 'a'
					a.attributes['href'] = "#fnref:#{num}"
					a.attributes['rev'] = 'footnote'
					a<< Text.new('&#8617;', true, nil, true)
				li.insert_after(li.children.last, a)
				ol << li
			else
				maruku_error"Could not find footnote '#{fid}'"
			end
		end
	div << ol
	div
end

#render_section_numberObject

nil if not applicable, else SPAN element



282
283
284
285
286
287
288
289
290
291
292
# File 'lib/maruku/output/to_html.rb', line 282

def render_section_number
	# if we are bound to a section, add section number
	if num = section_number
		span = Element.new 'span'
		span.attributes['class'] = 'maruku_section_number'
		span << Text.new(section_number)
		span
	else
		nil
	end
end

#section_numberObject

nil if not applicable, else string



270
271
272
273
274
275
276
277
278
279
# File 'lib/maruku/output/to_html.rb', line 270

def section_number
	return nil if not @doc.attributes[:use_numbered_headers]
	
	n = @attributes[:section_number]
	if n && (not n.empty?)
		 n.join('.')+". "
	else
		nil
	end
end

#source2html(source) ⇒ Object



304
305
306
307
308
# File 'lib/maruku/output/to_html.rb', line 304

def source2html(source)
	source = source.gsub(/&/,'&amp;')
	source = Text.normalize(source)
	Text.new(source, true, nil, false )
end

#to_html(context = {}) ⇒ Object

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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/maruku/output/to_html.rb', line 49

def to_html(context={})
	indent = context[:indent] || -1
	ie_hack = context[:ie_hack] ||true
	
	div = Element.new 'dummy'
		children_to_html.each do |e|
			div << e
		end

		# render footnotes
		if @doc.footnotes_order.size > 0
			div << render_footnotes
		end
	
	doc = Document.new(nil,{:respect_whitespace =>:all})
	doc << div
	
	# REXML Bug? if indent!=-1 whitespace is not respected for 'pre' elements
	# containing code.
	xml =""
	div.write_children(xml,indent,transitive=true,ie_hack)
	xml
end

#to_html_abbrObject



519
520
521
522
523
524
# File 'lib/maruku/output/to_html.rb', line 519

def to_html_abbr
	abbr = Element.new 'abbr'
	abbr << Text.new(children[0])
	abbr.attributes['title'] = self.title if self.title
	abbr
end

#to_html_cellObject



588
# File 'lib/maruku/output/to_html.rb', line 588

def to_html_cell; wrap_as_element('td') end

#to_html_codeObject



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/maruku/output/to_html.rb', line 310

def to_html_code; 
	source = self.raw_code

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

	lang = 'xml' if lang=='html'
	use_syntax = get_setting(:html_use_syntax)
	
	element = 
	if use_syntax && lang
		begin
			convertor = Syntax::Convertors::HTML.for_syntax lang
			
			# eliminate trailing newlines otherwise Syntax crashes
			source = source.gsub(/\n*\Z/,'')
			
			html = convertor.convert( source )
		
			pre = Document.new(html, {:respect_whitespace =>:all}).root
			pre.attributes['class'] = lang
			pre
		rescue Object => e
			maruku_error"Error while using the syntax library for code:\n#{source.inspect}"+
			 "Lang is #{lang} object is: \n"+
			  self.inspect + 
			"\nException: #{e.class}: #{e.message}\n\t#{e.backtrace.join("\n\t")}"
			
			tell_user("Using normal PRE because the syntax library did not work.")
			to_html_code_using_pre(source)
		end
	else
		to_html_code_using_pre(source)
	end
	
	color = get_setting(:code_background_color,DEFAULT_CODE_COLOR)
	if color != DEFAULT_CODE_COLOR
		element.attributes['style'] = "background-color: #{color};"
	end
	element
end

#to_html_code_using_pre(source) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/maruku/output/to_html.rb', line 351

def to_html_code_using_pre(source)
	pre = create_html_element  'pre'
	code = Element.new 'code', pre
	s = source
	
	s  = s.gsub(/&/,'&amp;')
	s = Text.normalize(s)
	s  = s.gsub(/\&apos;/,'&#39;') # IE bug
	s  = s.gsub(/'/,'&#39;') # IE bug

	show_spaces = get_setting(:code_show_spaces) 
	if show_spaces
		s.gsub!(/\t/,'&raquo;'+'&nbsp;'*3)
		s.gsub!(/ /,'&not;')
	end

	text = Text.new(s, respect_ws=true, parent=nil, raw=true )
	
	code << text
	pre
end

#to_html_definitionObject



549
# File 'lib/maruku/output/to_html.rb', line 549

def to_html_definition() children_to_html end

#to_html_definition_dataObject



551
# File 'lib/maruku/output/to_html.rb', line 551

def to_html_definition_data() add_ws wrap_as_element('dd') end

#to_html_definition_listObject

Definition lists ###



548
# File 'lib/maruku/output/to_html.rb', line 548

def to_html_definition_list() add_ws wrap_as_element('dl') end

#to_html_definition_termObject



550
# File 'lib/maruku/output/to_html.rb', line 550

def to_html_definition_term() add_ws wrap_as_element('dt') end

#to_html_document(context = {}) ⇒ Object

Render to a complete HTML document (returns a string)



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/maruku/output/to_html.rb', line 74

def to_html_document(context={})
	indent = context[:indent] || -1
	ie_hack = context[:ie_hack] ||true
	doc = to_html_document_tree
	xml  = "" 
	
	# REXML Bug? if indent!=-1 whitespace is not respected for 'pre' elements
	# containing code.
	doc.write(xml,indent,transitive=true,ie_hack);
			
	xhtml10strict  = "<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>\n"
	xhtml10strict + xml
end

#to_html_document_treeObject

Render to a complete HTML document (returns a REXML document tree)



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
# File 'lib/maruku/output/to_html.rb', line 91

def to_html_document_tree
	doc = Document.new(nil,{:respect_whitespace =>:all})
#	doc << XMLDecl.new
	
	root = Element.new('html', doc)
	root.add_namespace('http://www.w3.org/1999/xhtml')
	
	lang = self.attributes[:lang] || 'en'
	root.attributes['lang'] = lang
	root.attributes['xml:lang'] = lang
	
	head = Element.new 'head', root
	
		#<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
		me = Element.new 'meta', head
		me.attributes['http-equiv'] = 'Content-type'
		me.attributes['content'] = 'text/html; charset=utf-8'	
	
		# Create title element
		doc_title = self.attributes[:title] || self.attributes[:subject] || ""
		title = Element.new 'title', head
			title << Text.new(doc_title)
			
		
		css = self.attributes[:css]
		if css
			# <link type="text/css" rel="stylesheet" href="..." />
			link = Element.new 'link'
			link.attributes['type'] = 'text/css'
			link.attributes['rel'] = 'stylesheet'
			link.attributes['href'] = css
			head << link
		end
		
	body = Element.new 'body'
	
		children_to_html.each do |e|
			body << e
		end

		# render footnotes
		if @doc.footnotes_order.size > 0
			body << render_footnotes
		end
		
		# When we are rendering a whole document, we add a signature 
		# at the bottom. 
		if get_boolean_setting(:maruku_signature)
			body << maruku_html_signature 
		end
		
	root << body
	
	doc
end

#to_html_email_addressObject



443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/maruku/output/to_html.rb', line 443

def to_html_email_address
	email = self.email
	a = create_html_element 'a'
		#a.attributes['href'] = Text.new("mailto:"+obfuscate(email),false,nil,true)
		#a.attributes.add Attribute.new('href',Text.new(
		#"mailto:"+obfuscate(email),false,nil,true))
		# Sorry, for the moment it doesn't work
		a.attributes['href'] = "mailto:#{email}"
		
		a << Text.new(obfuscate(email),false,nil,true)
	a
end

#to_html_emphasisObject



267
# File 'lib/maruku/output/to_html.rb', line 267

def to_html_emphasis;  wrap_as_element('em')               end

#to_html_entityObject



590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'lib/maruku/output/to_html.rb', line 590

def to_html_entity 
	entity_name = self.entity_name
	
	# Fix for Internet Explorer
	if entity_name == 'apos'
		entity_name = 39
	end
	
	if entity_name.kind_of? Fixnum
#			Entity.new(entity_name)
		Text.new('&#%d;' % [entity_name],  false, nil, true)
	else
		Text.new('&%s;' % [entity_name])
	end
end

#to_html_footnote_referenceObject



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/maruku/output/to_html.rb', line 526

def to_html_footnote_reference
	id = self.footnote_id
	
	# save the order of used footnotes
	order = @doc.footnotes_order
	
	# take next number
	order << id
	num = order.size; 
	
	sup = Element.new 'sup'
	sup.attributes['id'] = "fnref:#{num}"
		a = Element.new 'a'
		a << Text.new(num.to_s)
		a.attributes['href'] = "\#fn:#{num}"
		a.attributes['rel'] = 'footnote'
	sup << a
		
	sup
end

#to_html_head_cellObject



587
# File 'lib/maruku/output/to_html.rb', line 587

def to_html_head_cell; wrap_as_element('th') end

#to_html_headerObject



294
295
296
297
298
299
300
301
302
# File 'lib/maruku/output/to_html.rb', line 294

def to_html_header
	element_name = "h#{self.level}" 
	h = wrap_as_element element_name
	
	if span = render_section_number
		h.insert_before(h.children.first, span)
	end
	add_ws h
end

#to_html_hruleObject



226
# File 'lib/maruku/output/to_html.rb', line 226

def to_html_hrule; create_html_element 'hr' end

#to_html_im_imageObject



476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/maruku/output/to_html.rb', line 476

def to_html_im_image
	if not url = self.url
		maruku_error"Image with no url: #{self.inspect}"
		tell_user "Could not create image with ref_id = #{id.inspect};"+
		 +" Using SPAN element as replacement."
		return wrap_as_element('span')
	end
	title = self.title
	a =  create_html_element 'img'
		a.attributes['src'] = url
		a.attributes['title'] = title if title
	return a
end


416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/maruku/output/to_html.rb', line 416

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

#to_html_imageObject

Images



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/maruku/output/to_html.rb', line 458

def to_html_image
	a =  create_html_element 'img'
	id = self.ref_id
	if ref = @doc.refs[id]
		url = ref[:url]
		a.attributes['src'] = url
		[:title, :class, :style].each do |s| 
			a.attributes[s.to_s] = ref[s] if ref[s]
		end
	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."
			return wrap_as_element('span')
	end
	return a
end


386
387
388
389
390
391
392
393
# File 'lib/maruku/output/to_html.rb', line 386

def to_html_immediate_link
	a =  create_html_element 'a'
	url = self.url
	text = url.gsub(/^mailto:/,'') # don't show mailto
	a << Text.new(text)
	a.attributes['href'] = url
	a
end

#to_html_inline_codeObject



373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/maruku/output/to_html.rb', line 373

def to_html_inline_code; 
	pre =  create_html_element 'code'
		source = self.raw_code
		pre << source2html(source) 
		
		color = get_setting(:code_background_color, DEFAULT_CODE_COLOR)
		if color != DEFAULT_CODE_COLOR
			pre.attributes['style'] = "background-color: #{color};"
		end
		
	pre
end

#to_html_liObject



263
# File 'lib/maruku/output/to_html.rb', line 263

def to_html_li;        add_ws wrap_as_element('li')        end

#to_html_li_spanObject



264
# File 'lib/maruku/output/to_html.rb', line 264

def to_html_li_span;   add_ws wrap_as_element('li')        end

#to_html_linebreakObject



227
# File 'lib/maruku/output/to_html.rb', line 227

def to_html_linebreak; Element.new 'br' end


395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/maruku/output/to_html.rb', line 395

def to_html_link
	a =  wrap_as_element 'a'
	id = self.ref_id
	# if empty, use text
	if id.size == 0
		id = children.to_s.downcase
	end
	
	if ref = @doc.refs[id]
		url = ref[:url]
		title = ref[:title]
		a.attributes['href'] = url if url
		a.attributes['title'] = title if title
	else
		maruku_error"Could not find ref_id = #{id.inspect} for #{self.inspect}"
		tell_user "Not creating a link for ref_id = #{id.inspect}."
		return wrap_as_element('span')
	end
	return a
end

#to_html_olObject



262
# File 'lib/maruku/output/to_html.rb', line 262

def to_html_ol;        add_ws wrap_as_element('ol')        end

#to_html_paragraphObject



261
# File 'lib/maruku/output/to_html.rb', line 261

def to_html_paragraph; add_ws wrap_as_element('p')                end

#to_html_quoteObject



265
# File 'lib/maruku/output/to_html.rb', line 265

def to_html_quote;     add_ws wrap_as_element('blockquote')  end

#to_html_raw_htmlObject



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/maruku/output/to_html.rb', line 490

def to_html_raw_html
	raw_html = self.raw_html
	if rexml_doc = @parsed_html
		root = rexml_doc.root
		if root.nil?
			s = "Bug in REXML: root() of Document is nil: \n#{rexml_doc.inspect}\n"+
			"Raw HTML:\n#{raw_html.inspect}"
			maruku_error s
			tell_user 'The REXML version you have has a bug, omitting HTML'
			div = Element.new 'div'
			#div << Text.new(s)
			return div
		end
		
		# copies the @children array (FIXME is it deep?)
		elements =  root.to_a 
		return elements
	else # invalid
		# Creates red box with offending HTML
		tell_user "Wrapping bad html in a PRE with class 'markdown-html-error'\n"+
			add_tabs(raw_html,1,'|')
		pre = Element.new('pre')
		pre.attributes['style'] = 'border: solid 3px red; background-color: pink'
		pre.attributes['class'] = 'markdown-html-error'
		pre << Text.new("HTML parse error: \n#{raw_html}", true)
		return pre
	end
end

#to_html_ref_definitionObject



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

def to_html_ref_definition; [] end

#to_html_strongObject



266
# File 'lib/maruku/output/to_html.rb', line 266

def to_html_strong;    wrap_as_element('strong')           end

#to_html_tableObject

FIXME: Ugly code



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
580
581
582
583
584
585
# File 'lib/maruku/output/to_html.rb', line 554

def to_html_table
	align = self.align
	num_columns = align.size

	head = @children.slice(0, num_columns)
	rows = []
	i = num_columns
	while i<@children.size
		rows << @children.slice(i, num_columns)
		i += num_columns
	end
	
	table = create_html_element 'table'
		thead = Element.new 'thead'
		tr = Element.new 'tr'
			array_to_html(head).each do |x| tr<<x end
		thead << tr
		table << thead
		
		tbody = Element.new 'tbody'
		rows.each do |row|
			tr = Element.new 'tr'
				array_to_html(row).each_with_index do |x,i| 
					x.attributes['style'] ="text-align: #{align[i].to_s};" 
					tr<<x 
				end
					
			tbody << tr
		end
		table << tbody
	table
end

#to_html_ulObject



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

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

#to_html_xml_instrObject



606
607
608
609
610
# File 'lib/maruku/output/to_html.rb', line 606

def to_html_xml_instr
	target = self.target || ''
	code = self.code || ''
	REXML::Instruction.new(target, code)
end

#to_latex_ref_definitionObject



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

def to_latex_ref_definition; [] end

#wrap_as_element(name) ⇒ Object

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

Sets ‘id’ if meta is set



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

def wrap_as_element(name)
	m = create_html_element name
		children_to_html.each do |e| m << e; end
		
#			m << Comment.new( "{"+self.al.to_md+"}") if not self.al.empty?
#			m << Comment.new( @attributes.inspect) if not @attributes.empty?
	m
end