all repos — grayfriday @ f805c775f5d24cd1ef697388d34e09b1b34c87a4

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