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



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/maruku/output/to_html.rb', line 152

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



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

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

#array_to_html(array) ⇒ Object



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

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



611
612
613
# File 'lib/maruku/output/to_html.rb', line 611

def children_to_html
	array_to_html(@children)
end

#create_html_element(name) ⇒ Object



245
246
247
248
249
250
251
# File 'lib/maruku/output/to_html.rb', line 245

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



171
172
173
174
175
176
177
178
# File 'lib/maruku/output/to_html.rb', line 171

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

#maruku_html_signatureObject



189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/maruku/output/to_html.rb', line 189

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'
				a << Text.new('Maruku')
			span << Text.new(nice_date+".")
	div
end

#nice_dateObject

formats a nice date



181
182
183
184
185
186
187
# File 'lib/maruku/output/to_html.rb', line 181

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



444
445
446
447
448
449
450
# File 'lib/maruku/output/to_html.rb', line 444

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

#render_footnotesObject



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

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



286
287
288
289
290
291
292
293
294
295
296
# File 'lib/maruku/output/to_html.rb', line 286

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



274
275
276
277
278
279
280
281
282
283
# File 'lib/maruku/output/to_html.rb', line 274

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



308
309
310
311
312
# File 'lib/maruku/output/to_html.rb', line 308

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)



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

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
	#add_whitespace(doc)
	
	# 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



531
532
533
534
535
536
# File 'lib/maruku/output/to_html.rb', line 531

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



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

def to_html_cell; wrap_as_element('td') end

#to_html_codeObject



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
350
351
352
353
354
355
356
357
358
359
# File 'lib/maruku/output/to_html.rb', line 314

def to_html_code; 
	source = self.raw_code

	lang = @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 )
		
			show_spaces = get_setting(:code_show_spaces) 
			if show_spaces
				s.gsub!(/\t/,'&raquo;'+'&nbsp;'*3)
				s.gsub!(/ /,'&not;')
			end
		
			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



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/maruku/output/to_html.rb', line 361

def to_html_code_using_pre(source)
	pre = Element.new 'pre'
	code = Element.new 'code', pre
	s = source
	
	s  = s.gsub(/&/,'&amp;')
	s = Text.normalize(s)

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

	text = Text.new(s, true, nil, false )
	
	code << text
	pre
end

#to_html_definitionObject



562
563
564
# File 'lib/maruku/output/to_html.rb', line 562

def to_html_definition		
	children_to_html
end

#to_html_definition_dataObject



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

def to_html_definition_data; wrap_as_element('dd') end

#to_html_definition_listObject

Definition lists ###



559
560
561
# File 'lib/maruku/output/to_html.rb', line 559

def to_html_definition_list
	wrap_as_element('dl')
end

#to_html_definition_termObject



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

def to_html_definition_term; wrap_as_element('dt') end

#to_html_document(context = {}) ⇒ Object

Render to a complete HTML document (returns a string)



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

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)



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
146
147
148
149
150
# File 'lib/maruku/output/to_html.rb', line 94

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 = @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 = @attributes[:title] || @attributes[:subject] || ""
		title = Element.new 'title', head
			title << Text.new(doc_title)
			
		# Encoding
		
		
		
		css = @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. 
		body << maruku_html_signature
		
	root << body
	
#	add_whitespace(doc)
	doc
end

#to_html_email_addressObject



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

def to_html_email_address
	email = self.email
	a = Element.new '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



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

def to_html_emphasis;  wrap_as_element('em')               end

#to_html_entityObject



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

def to_html_entity 
	entity_name = self.entity_name
	Text.new('&%s;' % [entity_name])
end

#to_html_footnote_referenceObject



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'lib/maruku/output/to_html.rb', line 538

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



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

def to_html_head_cell; wrap_as_element('th') end

#to_html_headerObject



298
299
300
301
302
303
304
305
306
# File 'lib/maruku/output/to_html.rb', line 298

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



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

def to_html_hrule; Element.new 'hr' end

#to_html_im_imageObject



487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/maruku/output/to_html.rb', line 487

def to_html_im_image
	a =  Element.new 'img'
	url = self.url
	title = self.title
	if not 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
	a.attributes['src'] = url
	a.attributes['title'] = title if title
	return a
end


424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/maruku/output/to_html.rb', line 424

def to_html_im_link
	a =  wrap_as_element 'a'
	url = self.url
	title = self.title
	if url
		a.attributes['href'] = url
		a.attributes['title'] = title if title
	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
	return a
end

#to_html_imageObject

Images



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/maruku/output/to_html.rb', line 467

def to_html_image
	a =  Element.new 'img'
	id = self.ref_id
	if ref = @doc.refs[id]
		url = ref[:url]
		a.attributes['src'] = url
		[:title, :class, :style].each do |s| 
			if ref[s] then
				a.attributes[s.to_s] = ref[s]
			end
		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


394
395
396
397
398
399
400
401
# File 'lib/maruku/output/to_html.rb', line 394

def to_html_immediate_link
	a = Element.new '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



381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/maruku/output/to_html.rb', line 381

def to_html_inline_code; 
	pre = Element.new '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



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

def to_html_li;        add_ws wrap_as_element('li')        end

#to_html_li_spanObject



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

def to_html_li_span;   add_ws wrap_as_element('li')        end

#to_html_linebreakObject



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

def to_html_linebreak; Element.new 'br' end


403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/maruku/output/to_html.rb', line 403

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



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

def to_html_ol;        add_ws wrap_as_element('ol')        end

#to_html_paragraphObject



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

def to_html_paragraph; add_ws wrap_as_element('p')                end

#to_html_quoteObject



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

def to_html_quote;     add_ws wrap_as_element('blockquote')  end

#to_html_raw_htmlObject



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/maruku/output/to_html.rb', line 502

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



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

def to_html_ref_definition; [] end

#to_html_strongObject



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

def to_html_strong;    wrap_as_element('strong')           end

#to_html_tableObject

Table ###



569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/maruku/output/to_html.rb', line 569

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



254
255
256
257
258
259
260
261
262
# File 'lib/maruku/output/to_html.rb', line 254

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_latex_ref_definitionObject



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

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



236
237
238
239
240
241
242
243
# File 'lib/maruku/output/to_html.rb', line 236

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