all repos — grayfriday @ d9ffdb74649c9a714d43540d0f9dc596f742ebba

blackfriday fork with a few changes

html.go (view raw)

  1//
  2// Blackfriday Markdown Processor
  3// Available at http://github.com/russross/blackfriday
  4//
  5// Copyright © 2011 Russ Ross <russ@russross.com>.
  6// Distributed under the Simplified BSD License.
  7// See README.md for details.
  8//
  9
 10//
 11//
 12// HTML rendering backend
 13//
 14//
 15
 16package blackfriday
 17
 18import (
 19	"bytes"
 20	"fmt"
 21	"io"
 22	"regexp"
 23	"strings"
 24)
 25
 26// HTMLFlags control optional behavior of HTML renderer.
 27type HTMLFlags int
 28
 29// HTML renderer configuration options.
 30const (
 31	HTMLFlagsNone           HTMLFlags = 0
 32	SkipHTML                HTMLFlags = 1 << iota // Skip preformatted HTML blocks
 33	SkipStyle                                     // Skip embedded <style> elements
 34	SkipImages                                    // Skip embedded images
 35	SkipLinks                                     // Skip all links
 36	Safelink                                      // Only link to trusted protocols
 37	NofollowLinks                                 // Only link with rel="nofollow"
 38	NoreferrerLinks                               // Only link with rel="noreferrer"
 39	HrefTargetBlank                               // Add a blank target
 40	CompletePage                                  // Generate a complete HTML page
 41	UseXHTML                                      // Generate XHTML output instead of HTML
 42	FootnoteReturnLinks                           // Generate a link at the end of a footnote to return to the source
 43	Smartypants                                   // Enable smart punctuation substitutions
 44	SmartypantsFractions                          // Enable smart fractions (with Smartypants)
 45	SmartypantsDashes                             // Enable smart dashes (with Smartypants)
 46	SmartypantsLatexDashes                        // Enable LaTeX-style dashes (with Smartypants)
 47	SmartypantsAngledQuotes                       // Enable angled double quotes (with Smartypants) for double quotes rendering
 48
 49	TagName               = "[A-Za-z][A-Za-z0-9-]*"
 50	AttributeName         = "[a-zA-Z_:][a-zA-Z0-9:._-]*"
 51	UnquotedValue         = "[^\"'=<>`\\x00-\\x20]+"
 52	SingleQuotedValue     = "'[^']*'"
 53	DoubleQuotedValue     = "\"[^\"]*\""
 54	AttributeValue        = "(?:" + UnquotedValue + "|" + SingleQuotedValue + "|" + DoubleQuotedValue + ")"
 55	AttributeValueSpec    = "(?:" + "\\s*=" + "\\s*" + AttributeValue + ")"
 56	Attribute             = "(?:" + "\\s+" + AttributeName + AttributeValueSpec + "?)"
 57	OpenTag               = "<" + TagName + Attribute + "*" + "\\s*/?>"
 58	CloseTag              = "</" + TagName + "\\s*[>]"
 59	HTMLComment           = "<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->"
 60	ProcessingInstruction = "[<][?].*?[?][>]"
 61	Declaration           = "<![A-Z]+" + "\\s+[^>]*>"
 62	CDATA                 = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>"
 63	HTMLTag               = "(?:" + OpenTag + "|" + CloseTag + "|" + HTMLComment + "|" +
 64		ProcessingInstruction + "|" + Declaration + "|" + CDATA + ")"
 65)
 66
 67var (
 68	htmlTagRe = regexp.MustCompile("(?i)^" + HTMLTag)
 69)
 70
 71// HTMLRendererParameters is a collection of supplementary parameters tweaking
 72// the behavior of various parts of HTML renderer.
 73type HTMLRendererParameters struct {
 74	// Prepend this text to each relative URL.
 75	AbsolutePrefix string
 76	// Add this text to each footnote anchor, to ensure uniqueness.
 77	FootnoteAnchorPrefix string
 78	// Show this text inside the <a> tag for a footnote return link, if the
 79	// HTML_FOOTNOTE_RETURN_LINKS flag is enabled. If blank, the string
 80	// <sup>[return]</sup> is used.
 81	FootnoteReturnLinkContents string
 82	// If set, add this text to the front of each Header ID, to ensure
 83	// uniqueness.
 84	HeaderIDPrefix string
 85	// If set, add this text to the back of each Header ID, to ensure uniqueness.
 86	HeaderIDSuffix string
 87
 88	Title string // Document title (used if CompletePage is set)
 89	CSS   string // Optional CSS file URL (used if CompletePage is set)
 90	Icon  string // Optional icon file URL (used if CompletePage is set)
 91
 92	Flags      HTMLFlags  // Flags allow customizing this renderer's behavior
 93	Extensions Extensions // Extensions give Smartypants and HTML renderer access to Blackfriday's global extensions
 94}
 95
 96// HTMLRenderer is a type that implements the Renderer interface for HTML output.
 97//
 98// Do not create this directly, instead use the NewHTMLRenderer function.
 99type HTMLRenderer struct {
100	HTMLRendererParameters
101
102	closeTag string // how to end singleton tags: either " />" or ">"
103
104	// Track header IDs to prevent ID collision in a single generation.
105	headerIDs map[string]int
106
107	lastOutputLen int
108	disableTags   int
109
110	sr *SPRenderer
111}
112
113const (
114	xhtmlClose = " />"
115	htmlClose  = ">"
116)
117
118// NewHTMLRenderer creates and configures an HTMLRenderer object, which
119// satisfies the Renderer interface.
120func NewHTMLRenderer(params HTMLRendererParameters) *HTMLRenderer {
121	// configure the rendering engine
122	closeTag := htmlClose
123	if params.Flags&UseXHTML != 0 {
124		closeTag = xhtmlClose
125	}
126
127	if params.FootnoteReturnLinkContents == "" {
128		params.FootnoteReturnLinkContents = `<sup>[return]</sup>`
129	}
130
131	return &HTMLRenderer{
132		HTMLRendererParameters: params,
133
134		closeTag:  closeTag,
135		headerIDs: make(map[string]int),
136
137		sr: NewSmartypantsRenderer(params.Flags),
138	}
139}
140
141func isHTMLTag(tag []byte, tagname string) bool {
142	found, _ := findHTMLTagPos(tag, tagname)
143	return found
144}
145
146// Look for a character, but ignore it when it's in any kind of quotes, it
147// might be JavaScript
148func skipUntilCharIgnoreQuotes(html []byte, start int, char byte) int {
149	inSingleQuote := false
150	inDoubleQuote := false
151	inGraveQuote := false
152	i := start
153	for i < len(html) {
154		switch {
155		case html[i] == char && !inSingleQuote && !inDoubleQuote && !inGraveQuote:
156			return i
157		case html[i] == '\'':
158			inSingleQuote = !inSingleQuote
159		case html[i] == '"':
160			inDoubleQuote = !inDoubleQuote
161		case html[i] == '`':
162			inGraveQuote = !inGraveQuote
163		}
164		i++
165	}
166	return start
167}
168
169func findHTMLTagPos(tag []byte, tagname string) (bool, int) {
170	i := 0
171	if i < len(tag) && tag[0] != '<' {
172		return false, -1
173	}
174	i++
175	i = skipSpace(tag, i)
176
177	if i < len(tag) && tag[i] == '/' {
178		i++
179	}
180
181	i = skipSpace(tag, i)
182	j := 0
183	for ; i < len(tag); i, j = i+1, j+1 {
184		if j >= len(tagname) {
185			break
186		}
187
188		if strings.ToLower(string(tag[i]))[0] != tagname[j] {
189			return false, -1
190		}
191	}
192
193	if i == len(tag) {
194		return false, -1
195	}
196
197	rightAngle := skipUntilCharIgnoreQuotes(tag, i, '>')
198	if rightAngle >= i {
199		return true, rightAngle
200	}
201
202	return false, -1
203}
204
205func skipSpace(tag []byte, i int) int {
206	for i < len(tag) && isspace(tag[i]) {
207		i++
208	}
209	return i
210}
211
212func isRelativeLink(link []byte) (yes bool) {
213	// a tag begin with '#'
214	if link[0] == '#' {
215		return true
216	}
217
218	// link begin with '/' but not '//', the second maybe a protocol relative link
219	if len(link) >= 2 && link[0] == '/' && link[1] != '/' {
220		return true
221	}
222
223	// only the root '/'
224	if len(link) == 1 && link[0] == '/' {
225		return true
226	}
227
228	// current directory : begin with "./"
229	if bytes.HasPrefix(link, []byte("./")) {
230		return true
231	}
232
233	// parent directory : begin with "../"
234	if bytes.HasPrefix(link, []byte("../")) {
235		return true
236	}
237
238	return false
239}
240
241func (r *HTMLRenderer) ensureUniqueHeaderID(id string) string {
242	for count, found := r.headerIDs[id]; found; count, found = r.headerIDs[id] {
243		tmp := fmt.Sprintf("%s-%d", id, count+1)
244
245		if _, tmpFound := r.headerIDs[tmp]; !tmpFound {
246			r.headerIDs[id] = count + 1
247			id = tmp
248		} else {
249			id = id + "-1"
250		}
251	}
252
253	if _, found := r.headerIDs[id]; !found {
254		r.headerIDs[id] = 0
255	}
256
257	return id
258}
259
260func (r *HTMLRenderer) addAbsPrefix(link []byte) []byte {
261	if r.AbsolutePrefix != "" && isRelativeLink(link) && link[0] != '.' {
262		newDest := r.AbsolutePrefix
263		if link[0] != '/' {
264			newDest += "/"
265		}
266		newDest += string(link)
267		return []byte(newDest)
268	}
269	return link
270}
271
272func appendLinkAttrs(attrs []string, flags HTMLFlags, link []byte) []string {
273	if isRelativeLink(link) {
274		return attrs
275	}
276	val := []string{}
277	if flags&NofollowLinks != 0 {
278		val = append(val, "nofollow")
279	}
280	if flags&NoreferrerLinks != 0 {
281		val = append(val, "noreferrer")
282	}
283	if flags&HrefTargetBlank != 0 {
284		attrs = append(attrs, "target=\"_blank\"")
285	}
286	if len(val) == 0 {
287		return attrs
288	}
289	attr := fmt.Sprintf("rel=%q", strings.Join(val, " "))
290	return append(attrs, attr)
291}
292
293func isMailto(link []byte) bool {
294	return bytes.HasPrefix(link, []byte("mailto:"))
295}
296
297func needSkipLink(flags HTMLFlags, dest []byte) bool {
298	if flags&SkipLinks != 0 {
299		return true
300	}
301	return flags&Safelink != 0 && !isSafeLink(dest) && !isMailto(dest)
302}
303
304func isSmartypantable(node *Node) bool {
305	pt := node.Parent.Type
306	return pt != Link && pt != CodeBlock && pt != Code
307}
308
309func appendLanguageAttr(attrs []string, info []byte) []string {
310	infoWords := bytes.Split(info, []byte("\t "))
311	if len(infoWords) > 0 && len(infoWords[0]) > 0 {
312		attrs = append(attrs, fmt.Sprintf("class=\"language-%s\"", infoWords[0]))
313	}
314	return attrs
315}
316
317var (
318	gtBytes    = []byte{'>'}
319	spaceBytes = []byte{' '}
320)
321
322func (r *HTMLRenderer) tag(w io.Writer, name []byte, attrs []string) {
323	w.Write(name)
324	if len(attrs) > 0 {
325		w.Write(spaceBytes)
326		w.Write([]byte(strings.Join(attrs, " ")))
327	}
328	w.Write(gtBytes)
329	r.lastOutputLen = 1
330}
331
332func footnoteRef(prefix string, node *Node) []byte {
333	urlFrag := prefix + string(slugify(node.Destination))
334	anchor := fmt.Sprintf(`<a rel="footnote" href="#fn:%s">%d</a>`, urlFrag, node.NoteID)
335	return []byte(fmt.Sprintf(`<sup class="footnote-ref" id="fnref:%s">%s</sup>`, urlFrag, anchor))
336}
337
338func footnoteItem(prefix string, slug []byte) []byte {
339	return []byte(fmt.Sprintf(`<li id="fn:%s%s">`, prefix, slug))
340}
341
342func footnoteReturnLink(prefix, returnLink string, slug []byte) []byte {
343	const format = ` <a class="footnote-return" href="#fnref:%s%s">%s</a>`
344	return []byte(fmt.Sprintf(format, prefix, slug, returnLink))
345}
346
347func itemOpenCR(node *Node) bool {
348	if node.Prev == nil {
349		return false
350	}
351	ld := node.Parent.ListData
352	return !ld.Tight && ld.ListFlags&ListTypeDefinition == 0
353}
354
355func skipParagraphTags(node *Node) bool {
356	grandparent := node.Parent.Parent
357	if grandparent == nil || grandparent.Type != List {
358		return false
359	}
360	tightOrTerm := grandparent.Tight || node.Parent.ListFlags&ListTypeTerm != 0
361	return grandparent.Type == List && tightOrTerm
362}
363
364func cellAlignment(align CellAlignFlags) string {
365	switch align {
366	case TableAlignmentLeft:
367		return "left"
368	case TableAlignmentRight:
369		return "right"
370	case TableAlignmentCenter:
371		return "center"
372	default:
373		return ""
374	}
375}
376
377func (r *HTMLRenderer) out(w io.Writer, text []byte) {
378	if r.disableTags > 0 {
379		w.Write(htmlTagRe.ReplaceAll(text, []byte{}))
380	} else {
381		w.Write(text)
382	}
383	r.lastOutputLen = len(text)
384}
385
386func (r *HTMLRenderer) cr(w io.Writer) {
387	if r.lastOutputLen > 0 {
388		r.out(w, []byte{'\n'})
389	}
390}
391
392var (
393	brTag              = []byte("<br>")
394	brXHTMLTag         = []byte("<br />")
395	emTag              = []byte("<em>")
396	emCloseTag         = []byte("</em>")
397	strongTag          = []byte("<strong>")
398	strongCloseTag     = []byte("</strong>")
399	delTag             = []byte("<del>")
400	delCloseTag        = []byte("</del>")
401	ttTag              = []byte("<tt>")
402	ttCloseTag         = []byte("</tt>")
403	aTag               = []byte("<a")
404	aCloseTag          = []byte("</a>")
405	preTag             = []byte("<pre>")
406	preCloseTag        = []byte("</pre>")
407	codeTag            = []byte("<code>")
408	codeCloseTag       = []byte("</code>")
409	pTag               = []byte("<p>")
410	pCloseTag          = []byte("</p>")
411	blockquoteTag      = []byte("<blockquote>")
412	blockquoteCloseTag = []byte("</blockquote>")
413	hrTag              = []byte("<hr>")
414	hrXHTMLTag         = []byte("<hr />")
415	ulTag              = []byte("<ul>")
416	ulCloseTag         = []byte("</ul>")
417	olTag              = []byte("<ol>")
418	olCloseTag         = []byte("</ol>")
419	dlTag              = []byte("<dl>")
420	dlCloseTag         = []byte("</dl>")
421	liTag              = []byte("<li>")
422	liCloseTag         = []byte("</li>")
423	ddTag              = []byte("<dd>")
424	ddCloseTag         = []byte("</dd>")
425	dtTag              = []byte("<dt>")
426	dtCloseTag         = []byte("</dt>")
427	tableTag           = []byte("<table>")
428	tableCloseTag      = []byte("</table>")
429	tdTag              = []byte("<td")
430	tdCloseTag         = []byte("</td>")
431	thTag              = []byte("<th")
432	thCloseTag         = []byte("</th>")
433	theadTag           = []byte("<thead>")
434	theadCloseTag      = []byte("</thead>")
435	tbodyTag           = []byte("<tbody>")
436	tbodyCloseTag      = []byte("</tbody>")
437	trTag              = []byte("<tr>")
438	trCloseTag         = []byte("</tr>")
439	h1Tag              = []byte("<h1")
440	h1CloseTag         = []byte("</h1>")
441	h2Tag              = []byte("<h2")
442	h2CloseTag         = []byte("</h2>")
443	h3Tag              = []byte("<h3")
444	h3CloseTag         = []byte("</h3>")
445	h4Tag              = []byte("<h4")
446	h4CloseTag         = []byte("</h4>")
447	h5Tag              = []byte("<h5")
448	h5CloseTag         = []byte("</h5>")
449	h6Tag              = []byte("<h6")
450	h6CloseTag         = []byte("</h6>")
451
452	footnotesDivBytes      = []byte("\n<div class=\"footnotes\">\n\n")
453	footnotesCloseDivBytes = []byte("\n</div>\n")
454)
455
456func headerTagsFromLevel(level int) ([]byte, []byte) {
457	switch level {
458	case 1:
459		return h1Tag, h1CloseTag
460	case 2:
461		return h2Tag, h2CloseTag
462	case 3:
463		return h3Tag, h3CloseTag
464	case 4:
465		return h4Tag, h4CloseTag
466	case 5:
467		return h5Tag, h5CloseTag
468	default:
469		return h6Tag, h6CloseTag
470	}
471}
472
473func (r *HTMLRenderer) outHRTag(w io.Writer) {
474	if r.Flags&UseXHTML == 0 {
475		r.out(w, hrTag)
476	} else {
477		r.out(w, hrXHTMLTag)
478	}
479}
480
481// RenderNode is a default renderer of a single node of a syntax tree. For
482// block nodes it will be called twice: first time with entering=true, second
483// time with entering=false, so that it could know when it's working on an open
484// tag and when on close. It writes the result to w.
485//
486// The return value is a way to tell the calling walker to adjust its walk
487// pattern: e.g. it can terminate the traversal by returning Terminate. Or it
488// can ask the walker to skip a subtree of this node by returning SkipChildren.
489// The typical behavior is to return GoToNext, which asks for the usual
490// traversal to the next node.
491func (r *HTMLRenderer) RenderNode(w io.Writer, node *Node, entering bool) WalkStatus {
492	attrs := []string{}
493	switch node.Type {
494	case Text:
495		if r.Flags&Smartypants != 0 {
496			var tmp bytes.Buffer
497			escapeHTML(&tmp, node.Literal)
498			r.sr.Process(w, tmp.Bytes())
499		} else {
500			if node.Parent.Type == Link {
501				escLink(w, node.Literal)
502			} else {
503				escapeHTML(w, node.Literal)
504			}
505		}
506	case Softbreak:
507		r.out(w, []byte{'\n'})
508		// TODO: make it configurable via out(renderer.softbreak)
509	case Hardbreak:
510		if r.Flags&UseXHTML == 0 {
511			r.out(w, brTag)
512		} else {
513			r.out(w, brXHTMLTag)
514		}
515		r.cr(w)
516	case Emph:
517		if entering {
518			r.out(w, emTag)
519		} else {
520			r.out(w, emCloseTag)
521		}
522	case Strong:
523		if entering {
524			r.out(w, strongTag)
525		} else {
526			r.out(w, strongCloseTag)
527		}
528	case Del:
529		if entering {
530			r.out(w, delTag)
531		} else {
532			r.out(w, delCloseTag)
533		}
534	case HTMLSpan:
535		if r.Flags&SkipHTML != 0 {
536			break
537		}
538		if r.Flags&SkipStyle != 0 && isHTMLTag(node.Literal, "style") {
539			break
540		}
541		//if options.safe {
542		//	out(w, "<!-- raw HTML omitted -->")
543		//} else {
544		r.out(w, node.Literal)
545		//}
546	case Link:
547		// mark it but don't link it if it is not a safe link: no smartypants
548		dest := node.LinkData.Destination
549		if needSkipLink(r.Flags, dest) {
550			if entering {
551				r.out(w, ttTag)
552			} else {
553				r.out(w, ttCloseTag)
554			}
555		} else {
556			if entering {
557				dest = r.addAbsPrefix(dest)
558				var hrefBuff bytes.Buffer
559				hrefBuff.WriteString("href=\"")
560				escLink(&hrefBuff, dest)
561				hrefBuff.WriteByte('"')
562				attrs = append(attrs, hrefBuff.String())
563				if node.NoteID != 0 {
564					r.out(w, footnoteRef(r.FootnoteAnchorPrefix, node))
565					break
566				}
567				attrs = appendLinkAttrs(attrs, r.Flags, dest)
568				if len(node.LinkData.Title) > 0 {
569					var titleBuff bytes.Buffer
570					titleBuff.WriteString("title=\"")
571					escapeHTML(&titleBuff, node.LinkData.Title)
572					titleBuff.WriteByte('"')
573					attrs = append(attrs, titleBuff.String())
574				}
575				r.tag(w, aTag, attrs)
576			} else {
577				if node.NoteID != 0 {
578					break
579				}
580				r.out(w, aCloseTag)
581			}
582		}
583	case Image:
584		if r.Flags&SkipImages != 0 {
585			return SkipChildren
586		}
587		if entering {
588			dest := node.LinkData.Destination
589			dest = r.addAbsPrefix(dest)
590			if r.disableTags == 0 {
591				//if options.safe && potentiallyUnsafe(dest) {
592				//out(w, `<img src="" alt="`)
593				//} else {
594				r.out(w, []byte(`<img src="`))
595				escLink(w, dest)
596				r.out(w, []byte(`" alt="`))
597				//}
598			}
599			r.disableTags++
600		} else {
601			r.disableTags--
602			if r.disableTags == 0 {
603				if node.LinkData.Title != nil {
604					r.out(w, []byte(`" title="`))
605					escapeHTML(w, node.LinkData.Title)
606				}
607				r.out(w, []byte(`" />`))
608			}
609		}
610	case Code:
611		r.out(w, codeTag)
612		escapeHTML(w, node.Literal)
613		r.out(w, codeCloseTag)
614	case Document:
615		break
616	case Paragraph:
617		if skipParagraphTags(node) {
618			break
619		}
620		if entering {
621			// TODO: untangle this clusterfuck about when the newlines need
622			// to be added and when not.
623			if node.Prev != nil {
624				switch node.Prev.Type {
625				case HTMLBlock, List, Paragraph, Header, CodeBlock, BlockQuote, HorizontalRule:
626					r.cr(w)
627				}
628			}
629			if node.Parent.Type == BlockQuote && node.Prev == nil {
630				r.cr(w)
631			}
632			r.out(w, pTag)
633		} else {
634			r.out(w, pCloseTag)
635			if !(node.Parent.Type == Item && node.Next == nil) {
636				r.cr(w)
637			}
638		}
639	case BlockQuote:
640		if entering {
641			r.cr(w)
642			r.out(w, blockquoteTag)
643		} else {
644			r.out(w, blockquoteCloseTag)
645			r.cr(w)
646		}
647	case HTMLBlock:
648		if r.Flags&SkipHTML != 0 {
649			break
650		}
651		r.cr(w)
652		r.out(w, node.Literal)
653		r.cr(w)
654	case Header:
655		openTag, closeTag := headerTagsFromLevel(node.Level)
656		if entering {
657			if node.IsTitleblock {
658				attrs = append(attrs, `class="title"`)
659			}
660			if node.HeaderID != "" {
661				id := r.ensureUniqueHeaderID(node.HeaderID)
662				if r.HeaderIDPrefix != "" {
663					id = r.HeaderIDPrefix + id
664				}
665				if r.HeaderIDSuffix != "" {
666					id = id + r.HeaderIDSuffix
667				}
668				attrs = append(attrs, fmt.Sprintf(`id="%s"`, id))
669			}
670			r.cr(w)
671			r.tag(w, openTag, attrs)
672		} else {
673			r.out(w, closeTag)
674			if !(node.Parent.Type == Item && node.Next == nil) {
675				r.cr(w)
676			}
677		}
678	case HorizontalRule:
679		r.cr(w)
680		r.outHRTag(w)
681		r.cr(w)
682	case List:
683		openTag := ulTag
684		closeTag := ulCloseTag
685		if node.ListFlags&ListTypeOrdered != 0 {
686			openTag = olTag
687			closeTag = olCloseTag
688		}
689		if node.ListFlags&ListTypeDefinition != 0 {
690			openTag = dlTag
691			closeTag = dlCloseTag
692		}
693		if entering {
694			if node.IsFootnotesList {
695				r.out(w, footnotesDivBytes)
696				r.outHRTag(w)
697				r.cr(w)
698			}
699			r.cr(w)
700			if node.Parent.Type == Item && node.Parent.Parent.Tight {
701				r.cr(w)
702			}
703			r.tag(w, openTag[:len(openTag)-1], attrs)
704			r.cr(w)
705		} else {
706			r.out(w, closeTag)
707			//cr(w)
708			//if node.parent.Type != Item {
709			//	cr(w)
710			//}
711			if node.Parent.Type == Item && node.Next != nil {
712				r.cr(w)
713			}
714			if node.Parent.Type == Document || node.Parent.Type == BlockQuote {
715				r.cr(w)
716			}
717			if node.IsFootnotesList {
718				r.out(w, footnotesCloseDivBytes)
719			}
720		}
721	case Item:
722		openTag := liTag
723		closeTag := liCloseTag
724		if node.ListFlags&ListTypeDefinition != 0 {
725			openTag = ddTag
726			closeTag = ddCloseTag
727		}
728		if node.ListFlags&ListTypeTerm != 0 {
729			openTag = dtTag
730			closeTag = dtCloseTag
731		}
732		if entering {
733			if itemOpenCR(node) {
734				r.cr(w)
735			}
736			if node.ListData.RefLink != nil {
737				slug := slugify(node.ListData.RefLink)
738				r.out(w, footnoteItem(r.FootnoteAnchorPrefix, slug))
739				break
740			}
741			r.out(w, openTag)
742		} else {
743			if node.ListData.RefLink != nil {
744				slug := slugify(node.ListData.RefLink)
745				if r.Flags&FootnoteReturnLinks != 0 {
746					r.out(w, footnoteReturnLink(r.FootnoteAnchorPrefix, r.FootnoteReturnLinkContents, slug))
747				}
748			}
749			r.out(w, closeTag)
750			r.cr(w)
751		}
752	case CodeBlock:
753		attrs = appendLanguageAttr(attrs, node.Info)
754		r.cr(w)
755		r.out(w, preTag)
756		r.tag(w, codeTag[:len(codeTag)-1], attrs)
757		escapeHTML(w, node.Literal)
758		r.out(w, codeCloseTag)
759		r.out(w, preCloseTag)
760		if node.Parent.Type != Item {
761			r.cr(w)
762		}
763	case Table:
764		if entering {
765			r.cr(w)
766			r.out(w, tableTag)
767		} else {
768			r.out(w, tableCloseTag)
769			r.cr(w)
770		}
771	case TableCell:
772		openTag := tdTag
773		closeTag := tdCloseTag
774		if node.IsHeader {
775			openTag = thTag
776			closeTag = thCloseTag
777		}
778		if entering {
779			align := cellAlignment(node.Align)
780			if align != "" {
781				attrs = append(attrs, fmt.Sprintf(`align="%s"`, align))
782			}
783			if node.Prev == nil {
784				r.cr(w)
785			}
786			r.tag(w, openTag, attrs)
787		} else {
788			r.out(w, closeTag)
789			r.cr(w)
790		}
791	case TableHead:
792		if entering {
793			r.cr(w)
794			r.out(w, theadTag)
795		} else {
796			r.out(w, theadCloseTag)
797			r.cr(w)
798		}
799	case TableBody:
800		if entering {
801			r.cr(w)
802			r.out(w, tbodyTag)
803			// XXX: this is to adhere to a rather silly test. Should fix test.
804			if node.FirstChild == nil {
805				r.cr(w)
806			}
807		} else {
808			r.out(w, tbodyCloseTag)
809			r.cr(w)
810		}
811	case TableRow:
812		if entering {
813			r.cr(w)
814			r.out(w, trTag)
815		} else {
816			r.out(w, trCloseTag)
817			r.cr(w)
818		}
819	default:
820		panic("Unknown node type " + node.Type.String())
821	}
822	return GoToNext
823}
824
825func (r *HTMLRenderer) writeDocumentHeader(w *bytes.Buffer) {
826	if r.Flags&CompletePage == 0 {
827		return
828	}
829	ending := ""
830	if r.Flags&UseXHTML != 0 {
831		w.WriteString("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" ")
832		w.WriteString("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n")
833		w.WriteString("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n")
834		ending = " /"
835	} else {
836		w.WriteString("<!DOCTYPE html>\n")
837		w.WriteString("<html>\n")
838	}
839	w.WriteString("<head>\n")
840	w.WriteString("  <title>")
841	if r.Flags&Smartypants != 0 {
842		r.sr.Process(w, []byte(r.Title))
843	} else {
844		escapeHTML(w, []byte(r.Title))
845	}
846	w.WriteString("</title>\n")
847	w.WriteString("  <meta name=\"GENERATOR\" content=\"Blackfriday Markdown Processor v")
848	w.WriteString(Version)
849	w.WriteString("\"")
850	w.WriteString(ending)
851	w.WriteString(">\n")
852	w.WriteString("  <meta charset=\"utf-8\"")
853	w.WriteString(ending)
854	w.WriteString(">\n")
855	if r.CSS != "" {
856		w.WriteString("  <link rel=\"stylesheet\" type=\"text/css\" href=\"")
857		escapeHTML(w, []byte(r.CSS))
858		w.WriteString("\"")
859		w.WriteString(ending)
860		w.WriteString(">\n")
861	}
862	if r.Icon != "" {
863		w.WriteString("  <link rel=\"icon\" type=\"image/x-icon\" href=\"")
864		escapeHTML(w, []byte(r.Icon))
865		w.WriteString("\"")
866		w.WriteString(ending)
867		w.WriteString(">\n")
868	}
869	w.WriteString("</head>\n")
870	w.WriteString("<body>\n\n")
871}
872
873func (r *HTMLRenderer) writeTOC(w *bytes.Buffer, ast *Node) {
874	buf := bytes.Buffer{}
875
876	inHeader := false
877	tocLevel := 0
878	headerCount := 0
879
880	ast.Walk(func(node *Node, entering bool) WalkStatus {
881		if node.Type == Header && !node.HeaderData.IsTitleblock {
882			inHeader = entering
883			if entering {
884				node.HeaderID = fmt.Sprintf("toc_%d", headerCount)
885				if node.Level == tocLevel {
886					buf.WriteString("</li>\n\n<li>")
887				} else if node.Level < tocLevel {
888					for node.Level < tocLevel {
889						tocLevel--
890						buf.WriteString("</li>\n</ul>")
891					}
892					buf.WriteString("</li>\n\n<li>")
893				} else {
894					for node.Level > tocLevel {
895						tocLevel++
896						buf.WriteString("\n<ul>\n<li>")
897					}
898				}
899
900				fmt.Fprintf(&buf, `<a href="#toc_%d">`, headerCount)
901				headerCount++
902			} else {
903				buf.WriteString("</a>")
904			}
905			return GoToNext
906		}
907
908		if inHeader {
909			return r.RenderNode(&buf, node, entering)
910		}
911
912		return GoToNext
913	})
914
915	for ; tocLevel > 0; tocLevel-- {
916		buf.WriteString("</li>\n</ul>")
917	}
918
919	if buf.Len() > 0 {
920		w.WriteString("<nav>\n")
921		w.Write(buf.Bytes())
922		w.WriteString("\n\n</nav>\n")
923	}
924	r.lastOutputLen = buf.Len()
925}
926
927func (r *HTMLRenderer) writeDocumentFooter(w *bytes.Buffer) {
928	if r.Flags&CompletePage == 0 {
929		return
930	}
931	w.WriteString("\n</body>\n</html>\n")
932}
933
934// Render walks the specified syntax (sub)tree and returns a HTML document.
935func (r *HTMLRenderer) Render(ast *Node) []byte {
936	//println("render_Blackfriday")
937	//dump(ast)
938	var buff bytes.Buffer
939	r.writeDocumentHeader(&buff)
940	if r.Extensions&TOC != 0 || r.Extensions&OmitContents != 0 {
941		r.writeTOC(&buff, ast)
942		if r.Extensions&OmitContents != 0 {
943			return buff.Bytes()
944		}
945	}
946	ast.Walk(func(node *Node, entering bool) WalkStatus {
947		return r.RenderNode(&buff, node, entering)
948	})
949	r.writeDocumentFooter(&buff)
950	return buff.Bytes()
951}