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 "regexp"
22 "strconv"
23 "strings"
24)
25
26// Html renderer configuration options.
27const (
28 HTML_SKIP_HTML = 1 << iota // skip preformatted HTML blocks
29 HTML_SKIP_STYLE // skip embedded <style> elements
30 HTML_SKIP_IMAGES // skip embedded images
31 HTML_SKIP_LINKS // skip all links
32 HTML_SAFELINK // only link to trusted protocols
33 HTML_NOFOLLOW_LINKS // only link with rel="nofollow"
34 HTML_NOREFERRER_LINKS // only link with rel="noreferrer"
35 HTML_HREF_TARGET_BLANK // add a blank target
36 HTML_TOC // generate a table of contents
37 HTML_OMIT_CONTENTS // skip the main contents (for a standalone table of contents)
38 HTML_COMPLETE_PAGE // generate a complete HTML page
39 HTML_USE_XHTML // generate XHTML output instead of HTML
40 HTML_USE_SMARTYPANTS // enable smart punctuation substitutions
41 HTML_SMARTYPANTS_FRACTIONS // enable smart fractions (with HTML_USE_SMARTYPANTS)
42 HTML_SMARTYPANTS_LATEX_DASHES // enable LaTeX-style dashes (with HTML_USE_SMARTYPANTS)
43 HTML_SMARTYPANTS_ANGLED_QUOTES // enable angled double quotes (with HTML_USE_SMARTYPANTS) for double quotes rendering
44 HTML_FOOTNOTE_RETURN_LINKS // generate a link at the end of a footnote to return to the source
45)
46
47var (
48 alignments = []string{
49 "left",
50 "right",
51 "center",
52 }
53
54 // TODO: improve this regexp to catch all possible entities:
55 htmlEntity = regexp.MustCompile(`&[a-z]{2,5};`)
56)
57
58type HtmlRendererParameters struct {
59 // Prepend this text to each relative URL.
60 AbsolutePrefix string
61 // Add this text to each footnote anchor, to ensure uniqueness.
62 FootnoteAnchorPrefix string
63 // Show this text inside the <a> tag for a footnote return link, if the
64 // HTML_FOOTNOTE_RETURN_LINKS flag is enabled. If blank, the string
65 // <sup>[return]</sup> is used.
66 FootnoteReturnLinkContents string
67 // If set, add this text to the front of each Header ID, to ensure
68 // uniqueness.
69 HeaderIDPrefix string
70 // If set, add this text to the back of each Header ID, to ensure uniqueness.
71 HeaderIDSuffix string
72}
73
74// Html is a type that implements the Renderer interface for HTML output.
75//
76// Do not create this directly, instead use the HtmlRenderer function.
77type Html struct {
78 flags int // HTML_* options
79 closeTag string // how to end singleton tags: either " />" or ">"
80 title string // document title
81 css string // optional css file url (used with HTML_COMPLETE_PAGE)
82
83 parameters HtmlRendererParameters
84
85 // table of contents data
86 tocMarker int
87 headerCount int
88 currentLevel int
89 toc *bytes.Buffer
90
91 // Track header IDs to prevent ID collision in a single generation.
92 headerIDs map[string]int
93
94 smartypants *smartypantsRenderer
95}
96
97const (
98 xhtmlClose = " />"
99 htmlClose = ">"
100)
101
102// HtmlRenderer creates and configures an Html object, which
103// satisfies the Renderer interface.
104//
105// flags is a set of HTML_* options ORed together.
106// title is the title of the document, and css is a URL for the document's
107// stylesheet.
108// title and css are only used when HTML_COMPLETE_PAGE is selected.
109func HtmlRenderer(flags int, title string, css string) Renderer {
110 return HtmlRendererWithParameters(flags, title, css, HtmlRendererParameters{})
111}
112
113func HtmlRendererWithParameters(flags int, title string,
114 css string, renderParameters HtmlRendererParameters) Renderer {
115 // configure the rendering engine
116 closeTag := htmlClose
117 if flags&HTML_USE_XHTML != 0 {
118 closeTag = xhtmlClose
119 }
120
121 if renderParameters.FootnoteReturnLinkContents == "" {
122 renderParameters.FootnoteReturnLinkContents = `<sup>[return]</sup>`
123 }
124
125 return &Html{
126 flags: flags,
127 closeTag: closeTag,
128 title: title,
129 css: css,
130 parameters: renderParameters,
131
132 headerCount: 0,
133 currentLevel: 0,
134 toc: new(bytes.Buffer),
135
136 headerIDs: make(map[string]int),
137
138 smartypants: smartypants(flags),
139 }
140}
141
142// Using if statements is a bit faster than a switch statement. As the compiler
143// improves, this should be unnecessary this is only worthwhile because
144// attrEscape is the single largest CPU user in normal use.
145// Also tried using map, but that gave a ~3x slowdown.
146func escapeSingleChar(char byte) (string, bool) {
147 if char == '"' {
148 return """, true
149 }
150 if char == '&' {
151 return "&", true
152 }
153 if char == '<' {
154 return "<", true
155 }
156 if char == '>' {
157 return ">", true
158 }
159 return "", false
160}
161
162func attrEscape(out *bytes.Buffer, src []byte) {
163 org := 0
164 for i, ch := range src {
165 if entity, ok := escapeSingleChar(ch); ok {
166 if i > org {
167 // copy all the normal characters since the last escape
168 out.Write(src[org:i])
169 }
170 org = i + 1
171 out.WriteString(entity)
172 }
173 }
174 if org < len(src) {
175 out.Write(src[org:])
176 }
177}
178
179func entityEscapeWithSkip(out *bytes.Buffer, src []byte, skipRanges [][]int) {
180 end := 0
181 for _, rang := range skipRanges {
182 attrEscape(out, src[end:rang[0]])
183 out.Write(src[rang[0]:rang[1]])
184 end = rang[1]
185 }
186 attrEscape(out, src[end:])
187}
188
189func (options *Html) GetFlags() int {
190 return options.flags
191}
192
193func (options *Html) TitleBlock(out *bytes.Buffer, text []byte) {
194 text = bytes.TrimPrefix(text, []byte("% "))
195 text = bytes.Replace(text, []byte("\n% "), []byte("\n"), -1)
196 out.WriteString("<h1 class=\"title\">")
197 out.Write(text)
198 out.WriteString("\n</h1>")
199}
200
201func (options *Html) Header(out *bytes.Buffer, text func() bool, level int, id string) {
202 marker := out.Len()
203 doubleSpace(out)
204
205 if id == "" && options.flags&HTML_TOC != 0 {
206 id = fmt.Sprintf("toc_%d", options.headerCount)
207 }
208
209 if id != "" {
210 id = options.ensureUniqueHeaderID(id)
211
212 if options.parameters.HeaderIDPrefix != "" {
213 id = options.parameters.HeaderIDPrefix + id
214 }
215
216 if options.parameters.HeaderIDSuffix != "" {
217 id = id + options.parameters.HeaderIDSuffix
218 }
219
220 out.WriteString(fmt.Sprintf("<h%d id=\"%s\">", level, id))
221 } else {
222 out.WriteString(fmt.Sprintf("<h%d>", level))
223 }
224
225 tocMarker := out.Len()
226 if !text() {
227 out.Truncate(marker)
228 return
229 }
230
231 // are we building a table of contents?
232 if options.flags&HTML_TOC != 0 {
233 options.TocHeaderWithAnchor(out.Bytes()[tocMarker:], level, id)
234 }
235
236 out.WriteString(fmt.Sprintf("</h%d>\n", level))
237}
238
239func (options *Html) BlockHtml(out *bytes.Buffer, text []byte) {
240 if options.flags&HTML_SKIP_HTML != 0 {
241 return
242 }
243
244 doubleSpace(out)
245 out.Write(text)
246 out.WriteByte('\n')
247}
248
249func (options *Html) HRule(out *bytes.Buffer) {
250 doubleSpace(out)
251 out.WriteString("<hr")
252 out.WriteString(options.closeTag)
253 out.WriteByte('\n')
254}
255
256func (options *Html) BlockCode(out *bytes.Buffer, text []byte, lang string) {
257 doubleSpace(out)
258
259 // parse out the language names/classes
260 count := 0
261 for _, elt := range strings.Fields(lang) {
262 if elt[0] == '.' {
263 elt = elt[1:]
264 }
265 if len(elt) == 0 {
266 continue
267 }
268 if count == 0 {
269 out.WriteString("<pre><code class=\"language-")
270 } else {
271 out.WriteByte(' ')
272 }
273 attrEscape(out, []byte(elt))
274 count++
275 }
276
277 if count == 0 {
278 out.WriteString("<pre><code>")
279 } else {
280 out.WriteString("\">")
281 }
282
283 attrEscape(out, text)
284 out.WriteString("</code></pre>\n")
285}
286
287func (options *Html) BlockQuote(out *bytes.Buffer, text []byte) {
288 doubleSpace(out)
289 out.WriteString("<blockquote>\n")
290 out.Write(text)
291 out.WriteString("</blockquote>\n")
292}
293
294func (options *Html) Table(out *bytes.Buffer, header []byte, body []byte, columnData []int) {
295 doubleSpace(out)
296 out.WriteString("<table>\n<thead>\n")
297 out.Write(header)
298 out.WriteString("</thead>\n\n<tbody>\n")
299 out.Write(body)
300 out.WriteString("</tbody>\n</table>\n")
301}
302
303func (options *Html) TableRow(out *bytes.Buffer, text []byte) {
304 doubleSpace(out)
305 out.WriteString("<tr>\n")
306 out.Write(text)
307 out.WriteString("\n</tr>\n")
308}
309
310func (options *Html) TableHeaderCell(out *bytes.Buffer, text []byte, align int) {
311 doubleSpace(out)
312 switch align {
313 case TABLE_ALIGNMENT_LEFT:
314 out.WriteString("<th align=\"left\">")
315 case TABLE_ALIGNMENT_RIGHT:
316 out.WriteString("<th align=\"right\">")
317 case TABLE_ALIGNMENT_CENTER:
318 out.WriteString("<th align=\"center\">")
319 default:
320 out.WriteString("<th>")
321 }
322
323 out.Write(text)
324 out.WriteString("</th>")
325}
326
327func (options *Html) TableCell(out *bytes.Buffer, text []byte, align int) {
328 doubleSpace(out)
329 switch align {
330 case TABLE_ALIGNMENT_LEFT:
331 out.WriteString("<td align=\"left\">")
332 case TABLE_ALIGNMENT_RIGHT:
333 out.WriteString("<td align=\"right\">")
334 case TABLE_ALIGNMENT_CENTER:
335 out.WriteString("<td align=\"center\">")
336 default:
337 out.WriteString("<td>")
338 }
339
340 out.Write(text)
341 out.WriteString("</td>")
342}
343
344func (options *Html) Footnotes(out *bytes.Buffer, text func() bool) {
345 out.WriteString("<div class=\"footnotes\">\n")
346 options.HRule(out)
347 options.List(out, text, LIST_TYPE_ORDERED)
348 out.WriteString("</div>\n")
349}
350
351func (options *Html) FootnoteItem(out *bytes.Buffer, name, text []byte, flags int) {
352 if flags&LIST_ITEM_CONTAINS_BLOCK != 0 || flags&LIST_ITEM_BEGINNING_OF_LIST != 0 {
353 doubleSpace(out)
354 }
355 slug := slugify(name)
356 out.WriteString(`<li id="`)
357 out.WriteString(`fn:`)
358 out.WriteString(options.parameters.FootnoteAnchorPrefix)
359 out.Write(slug)
360 out.WriteString(`">`)
361 out.Write(text)
362 if options.flags&HTML_FOOTNOTE_RETURN_LINKS != 0 {
363 out.WriteString(` <a class="footnote-return" href="#`)
364 out.WriteString(`fnref:`)
365 out.WriteString(options.parameters.FootnoteAnchorPrefix)
366 out.Write(slug)
367 out.WriteString(`">`)
368 out.WriteString(options.parameters.FootnoteReturnLinkContents)
369 out.WriteString(`</a>`)
370 }
371 out.WriteString("</li>\n")
372}
373
374func (options *Html) List(out *bytes.Buffer, text func() bool, flags int) {
375 marker := out.Len()
376 doubleSpace(out)
377
378 if flags&LIST_TYPE_DEFINITION != 0 {
379 out.WriteString("<dl>")
380 } else if flags&LIST_TYPE_ORDERED != 0 {
381 out.WriteString("<ol>")
382 } else {
383 out.WriteString("<ul>")
384 }
385 if !text() {
386 out.Truncate(marker)
387 return
388 }
389 if flags&LIST_TYPE_DEFINITION != 0 {
390 out.WriteString("</dl>\n")
391 } else if flags&LIST_TYPE_ORDERED != 0 {
392 out.WriteString("</ol>\n")
393 } else {
394 out.WriteString("</ul>\n")
395 }
396}
397
398func (options *Html) ListItem(out *bytes.Buffer, text []byte, flags int) {
399 if (flags&LIST_ITEM_CONTAINS_BLOCK != 0 && flags&LIST_TYPE_DEFINITION == 0) ||
400 flags&LIST_ITEM_BEGINNING_OF_LIST != 0 {
401 doubleSpace(out)
402 }
403 if flags&LIST_TYPE_TERM != 0 {
404 out.WriteString("<dt>")
405 } else if flags&LIST_TYPE_DEFINITION != 0 {
406 out.WriteString("<dd>")
407 } else {
408 out.WriteString("<li>")
409 }
410 out.Write(text)
411 if flags&LIST_TYPE_TERM != 0 {
412 out.WriteString("</dt>\n")
413 } else if flags&LIST_TYPE_DEFINITION != 0 {
414 out.WriteString("</dd>\n")
415 } else {
416 out.WriteString("</li>\n")
417 }
418}
419
420func (options *Html) Paragraph(out *bytes.Buffer, text func() bool) {
421 marker := out.Len()
422 doubleSpace(out)
423
424 out.WriteString("<p>")
425 if !text() {
426 out.Truncate(marker)
427 return
428 }
429 out.WriteString("</p>\n")
430}
431
432func (options *Html) AutoLink(out *bytes.Buffer, link []byte, kind int) {
433 skipRanges := htmlEntity.FindAllIndex(link, -1)
434 if options.flags&HTML_SAFELINK != 0 && !isSafeLink(link) && kind != LINK_TYPE_EMAIL {
435 // mark it but don't link it if it is not a safe link: no smartypants
436 out.WriteString("<tt>")
437 entityEscapeWithSkip(out, link, skipRanges)
438 out.WriteString("</tt>")
439 return
440 }
441
442 out.WriteString("<a href=\"")
443 if kind == LINK_TYPE_EMAIL {
444 out.WriteString("mailto:")
445 } else {
446 options.maybeWriteAbsolutePrefix(out, link)
447 }
448
449 entityEscapeWithSkip(out, link, skipRanges)
450
451 var relAttrs []string
452 if options.flags&HTML_NOFOLLOW_LINKS != 0 && !isRelativeLink(link) {
453 relAttrs = append(relAttrs, "nofollow")
454 }
455 if options.flags&HTML_NOREFERRER_LINKS != 0 && !isRelativeLink(link) {
456 relAttrs = append(relAttrs, "noreferrer")
457 }
458 if len(relAttrs) > 0 {
459 out.WriteString(fmt.Sprintf("\" rel=\"%s", strings.Join(relAttrs, " ")))
460 }
461
462 // blank target only add to external link
463 if options.flags&HTML_HREF_TARGET_BLANK != 0 && !isRelativeLink(link) {
464 out.WriteString("\" target=\"_blank")
465 }
466
467 out.WriteString("\">")
468
469 // Pretty print: if we get an email address as
470 // an actual URI, e.g. `mailto:foo@bar.com`, we don't
471 // want to print the `mailto:` prefix
472 switch {
473 case bytes.HasPrefix(link, []byte("mailto://")):
474 attrEscape(out, link[len("mailto://"):])
475 case bytes.HasPrefix(link, []byte("mailto:")):
476 attrEscape(out, link[len("mailto:"):])
477 default:
478 entityEscapeWithSkip(out, link, skipRanges)
479 }
480
481 out.WriteString("</a>")
482}
483
484func (options *Html) CodeSpan(out *bytes.Buffer, text []byte) {
485 out.WriteString("<code>")
486 attrEscape(out, text)
487 out.WriteString("</code>")
488}
489
490func (options *Html) DoubleEmphasis(out *bytes.Buffer, text []byte) {
491 out.WriteString("<strong>")
492 out.Write(text)
493 out.WriteString("</strong>")
494}
495
496func (options *Html) Emphasis(out *bytes.Buffer, text []byte) {
497 if len(text) == 0 {
498 return
499 }
500 out.WriteString("<em>")
501 out.Write(text)
502 out.WriteString("</em>")
503}
504
505func (options *Html) maybeWriteAbsolutePrefix(out *bytes.Buffer, link []byte) {
506 if options.parameters.AbsolutePrefix != "" && isRelativeLink(link) && link[0] != '.' {
507 out.WriteString(options.parameters.AbsolutePrefix)
508 if link[0] != '/' {
509 out.WriteByte('/')
510 }
511 }
512}
513
514func (options *Html) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
515 if options.flags&HTML_SKIP_IMAGES != 0 {
516 return
517 }
518
519 out.WriteString("<img src=\"")
520 options.maybeWriteAbsolutePrefix(out, link)
521 attrEscape(out, link)
522 out.WriteString("\" alt=\"")
523 if len(alt) > 0 {
524 attrEscape(out, alt)
525 }
526 if len(title) > 0 {
527 out.WriteString("\" title=\"")
528 attrEscape(out, title)
529 }
530
531 out.WriteByte('"')
532 out.WriteString(options.closeTag)
533}
534
535func (options *Html) LineBreak(out *bytes.Buffer) {
536 out.WriteString("<br")
537 out.WriteString(options.closeTag)
538 out.WriteByte('\n')
539}
540
541func (options *Html) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
542 if options.flags&HTML_SKIP_LINKS != 0 {
543 // write the link text out but don't link it, just mark it with typewriter font
544 out.WriteString("<tt>")
545 attrEscape(out, content)
546 out.WriteString("</tt>")
547 return
548 }
549
550 if options.flags&HTML_SAFELINK != 0 && !isSafeLink(link) {
551 // write the link text out but don't link it, just mark it with typewriter font
552 out.WriteString("<tt>")
553 attrEscape(out, content)
554 out.WriteString("</tt>")
555 return
556 }
557
558 out.WriteString("<a href=\"")
559 options.maybeWriteAbsolutePrefix(out, link)
560 attrEscape(out, link)
561 if len(title) > 0 {
562 out.WriteString("\" title=\"")
563 attrEscape(out, title)
564 }
565 var relAttrs []string
566 if options.flags&HTML_NOFOLLOW_LINKS != 0 && !isRelativeLink(link) {
567 relAttrs = append(relAttrs, "nofollow")
568 }
569 if options.flags&HTML_NOREFERRER_LINKS != 0 && !isRelativeLink(link) {
570 relAttrs = append(relAttrs, "noreferrer")
571 }
572 if len(relAttrs) > 0 {
573 out.WriteString(fmt.Sprintf("\" rel=\"%s", strings.Join(relAttrs, " ")))
574 }
575
576 // blank target only add to external link
577 if options.flags&HTML_HREF_TARGET_BLANK != 0 && !isRelativeLink(link) {
578 out.WriteString("\" target=\"_blank")
579 }
580
581 out.WriteString("\">")
582 out.Write(content)
583 out.WriteString("</a>")
584 return
585}
586
587func (options *Html) RawHtmlTag(out *bytes.Buffer, text []byte) {
588 if options.flags&HTML_SKIP_HTML != 0 {
589 return
590 }
591 if options.flags&HTML_SKIP_STYLE != 0 && isHtmlTag(text, "style") {
592 return
593 }
594 if options.flags&HTML_SKIP_LINKS != 0 && isHtmlTag(text, "a") {
595 return
596 }
597 if options.flags&HTML_SKIP_IMAGES != 0 && isHtmlTag(text, "img") {
598 return
599 }
600 out.Write(text)
601}
602
603func (options *Html) TripleEmphasis(out *bytes.Buffer, text []byte) {
604 out.WriteString("<strong><em>")
605 out.Write(text)
606 out.WriteString("</em></strong>")
607}
608
609func (options *Html) StrikeThrough(out *bytes.Buffer, text []byte) {
610 out.WriteString("<del>")
611 out.Write(text)
612 out.WriteString("</del>")
613}
614
615func (options *Html) FootnoteRef(out *bytes.Buffer, ref []byte, id int) {
616 slug := slugify(ref)
617 out.WriteString(`<sup class="footnote-ref" id="`)
618 out.WriteString(`fnref:`)
619 out.WriteString(options.parameters.FootnoteAnchorPrefix)
620 out.Write(slug)
621 out.WriteString(`"><a rel="footnote" href="#`)
622 out.WriteString(`fn:`)
623 out.WriteString(options.parameters.FootnoteAnchorPrefix)
624 out.Write(slug)
625 out.WriteString(`">`)
626 out.WriteString(strconv.Itoa(id))
627 out.WriteString(`</a></sup>`)
628}
629
630func (options *Html) Entity(out *bytes.Buffer, entity []byte) {
631 out.Write(entity)
632}
633
634func (options *Html) NormalText(out *bytes.Buffer, text []byte) {
635 if options.flags&HTML_USE_SMARTYPANTS != 0 {
636 options.Smartypants(out, text)
637 } else {
638 attrEscape(out, text)
639 }
640}
641
642func (options *Html) Smartypants(out *bytes.Buffer, text []byte) {
643 smrt := smartypantsData{false, false}
644
645 // first do normal entity escaping
646 var escaped bytes.Buffer
647 attrEscape(&escaped, text)
648 text = escaped.Bytes()
649
650 mark := 0
651 for i := 0; i < len(text); i++ {
652 if action := options.smartypants[text[i]]; action != nil {
653 if i > mark {
654 out.Write(text[mark:i])
655 }
656
657 previousChar := byte(0)
658 if i > 0 {
659 previousChar = text[i-1]
660 }
661 i += action(out, &smrt, previousChar, text[i:])
662 mark = i + 1
663 }
664 }
665
666 if mark < len(text) {
667 out.Write(text[mark:])
668 }
669}
670
671func (options *Html) DocumentHeader(out *bytes.Buffer) {
672 if options.flags&HTML_COMPLETE_PAGE == 0 {
673 return
674 }
675
676 ending := ""
677 if options.flags&HTML_USE_XHTML != 0 {
678 out.WriteString("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" ")
679 out.WriteString("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n")
680 out.WriteString("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n")
681 ending = " /"
682 } else {
683 out.WriteString("<!DOCTYPE html>\n")
684 out.WriteString("<html>\n")
685 }
686 out.WriteString("<head>\n")
687 out.WriteString(" <title>")
688 options.NormalText(out, []byte(options.title))
689 out.WriteString("</title>\n")
690 out.WriteString(" <meta name=\"GENERATOR\" content=\"Blackfriday Markdown Processor v")
691 out.WriteString(VERSION)
692 out.WriteString("\"")
693 out.WriteString(ending)
694 out.WriteString(">\n")
695 out.WriteString(" <meta charset=\"utf-8\"")
696 out.WriteString(ending)
697 out.WriteString(">\n")
698 if options.css != "" {
699 out.WriteString(" <link rel=\"stylesheet\" type=\"text/css\" href=\"")
700 attrEscape(out, []byte(options.css))
701 out.WriteString("\"")
702 out.WriteString(ending)
703 out.WriteString(">\n")
704 }
705 out.WriteString("</head>\n")
706 out.WriteString("<body>\n")
707
708 options.tocMarker = out.Len()
709}
710
711func (options *Html) DocumentFooter(out *bytes.Buffer) {
712 // finalize and insert the table of contents
713 if options.flags&HTML_TOC != 0 {
714 options.TocFinalize()
715
716 // now we have to insert the table of contents into the document
717 var temp bytes.Buffer
718
719 // start by making a copy of everything after the document header
720 temp.Write(out.Bytes()[options.tocMarker:])
721
722 // now clear the copied material from the main output buffer
723 out.Truncate(options.tocMarker)
724
725 // corner case spacing issue
726 if options.flags&HTML_COMPLETE_PAGE != 0 {
727 out.WriteByte('\n')
728 }
729
730 // insert the table of contents
731 out.WriteString("<nav>\n")
732 out.Write(options.toc.Bytes())
733 out.WriteString("</nav>\n")
734
735 // corner case spacing issue
736 if options.flags&HTML_COMPLETE_PAGE == 0 && options.flags&HTML_OMIT_CONTENTS == 0 {
737 out.WriteByte('\n')
738 }
739
740 // write out everything that came after it
741 if options.flags&HTML_OMIT_CONTENTS == 0 {
742 out.Write(temp.Bytes())
743 }
744 }
745
746 if options.flags&HTML_COMPLETE_PAGE != 0 {
747 out.WriteString("\n</body>\n")
748 out.WriteString("</html>\n")
749 }
750
751}
752
753func (options *Html) TocHeaderWithAnchor(text []byte, level int, anchor string) {
754 for level > options.currentLevel {
755 switch {
756 case bytes.HasSuffix(options.toc.Bytes(), []byte("</li>\n")):
757 // this sublist can nest underneath a header
758 size := options.toc.Len()
759 options.toc.Truncate(size - len("</li>\n"))
760
761 case options.currentLevel > 0:
762 options.toc.WriteString("<li>")
763 }
764 if options.toc.Len() > 0 {
765 options.toc.WriteByte('\n')
766 }
767 options.toc.WriteString("<ul>\n")
768 options.currentLevel++
769 }
770
771 for level < options.currentLevel {
772 options.toc.WriteString("</ul>")
773 if options.currentLevel > 1 {
774 options.toc.WriteString("</li>\n")
775 }
776 options.currentLevel--
777 }
778
779 options.toc.WriteString("<li><a href=\"#")
780 if anchor != "" {
781 options.toc.WriteString(anchor)
782 } else {
783 options.toc.WriteString("toc_")
784 options.toc.WriteString(strconv.Itoa(options.headerCount))
785 }
786 options.toc.WriteString("\">")
787 options.headerCount++
788
789 options.toc.Write(text)
790
791 options.toc.WriteString("</a></li>\n")
792}
793
794func (options *Html) TocHeader(text []byte, level int) {
795 options.TocHeaderWithAnchor(text, level, "")
796}
797
798func (options *Html) TocFinalize() {
799 for options.currentLevel > 1 {
800 options.toc.WriteString("</ul></li>\n")
801 options.currentLevel--
802 }
803
804 if options.currentLevel > 0 {
805 options.toc.WriteString("</ul>\n")
806 }
807}
808
809func isHtmlTag(tag []byte, tagname string) bool {
810 found, _ := findHtmlTagPos(tag, tagname)
811 return found
812}
813
814// Look for a character, but ignore it when it's in any kind of quotes, it
815// might be JavaScript
816func skipUntilCharIgnoreQuotes(html []byte, start int, char byte) int {
817 inSingleQuote := false
818 inDoubleQuote := false
819 inGraveQuote := false
820 i := start
821 for i < len(html) {
822 switch {
823 case html[i] == char && !inSingleQuote && !inDoubleQuote && !inGraveQuote:
824 return i
825 case html[i] == '\'':
826 inSingleQuote = !inSingleQuote
827 case html[i] == '"':
828 inDoubleQuote = !inDoubleQuote
829 case html[i] == '`':
830 inGraveQuote = !inGraveQuote
831 }
832 i++
833 }
834 return start
835}
836
837func findHtmlTagPos(tag []byte, tagname string) (bool, int) {
838 i := 0
839 if i < len(tag) && tag[0] != '<' {
840 return false, -1
841 }
842 i++
843 i = skipSpace(tag, i)
844
845 if i < len(tag) && tag[i] == '/' {
846 i++
847 }
848
849 i = skipSpace(tag, i)
850 j := 0
851 for ; i < len(tag); i, j = i+1, j+1 {
852 if j >= len(tagname) {
853 break
854 }
855
856 if strings.ToLower(string(tag[i]))[0] != tagname[j] {
857 return false, -1
858 }
859 }
860
861 if i == len(tag) {
862 return false, -1
863 }
864
865 rightAngle := skipUntilCharIgnoreQuotes(tag, i, '>')
866 if rightAngle > i {
867 return true, rightAngle
868 }
869
870 return false, -1
871}
872
873func skipUntilChar(text []byte, start int, char byte) int {
874 i := start
875 for i < len(text) && text[i] != char {
876 i++
877 }
878 return i
879}
880
881func skipSpace(tag []byte, i int) int {
882 for i < len(tag) && isspace(tag[i]) {
883 i++
884 }
885 return i
886}
887
888func skipChar(data []byte, start int, char byte) int {
889 i := start
890 for i < len(data) && data[i] == char {
891 i++
892 }
893 return i
894}
895
896func doubleSpace(out *bytes.Buffer) {
897 if out.Len() > 0 {
898 out.WriteByte('\n')
899 }
900}
901
902func isRelativeLink(link []byte) (yes bool) {
903 // a tag begin with '#'
904 if link[0] == '#' {
905 return true
906 }
907
908 // link begin with '/' but not '//', the second maybe a protocol relative link
909 if len(link) >= 2 && link[0] == '/' && link[1] != '/' {
910 return true
911 }
912
913 // only the root '/'
914 if len(link) == 1 && link[0] == '/' {
915 return true
916 }
917
918 // current directory : begin with "./"
919 if bytes.HasPrefix(link, []byte("./")) {
920 return true
921 }
922
923 // parent directory : begin with "../"
924 if bytes.HasPrefix(link, []byte("../")) {
925 return true
926 }
927
928 return false
929}
930
931func (options *Html) ensureUniqueHeaderID(id string) string {
932 for count, found := options.headerIDs[id]; found; count, found = options.headerIDs[id] {
933 tmp := fmt.Sprintf("%s-%d", id, count+1)
934
935 if _, tmpFound := options.headerIDs[tmp]; !tmpFound {
936 options.headerIDs[id] = count + 1
937 id = tmp
938 } else {
939 id = id + "-1"
940 }
941 }
942
943 if _, found := options.headerIDs[id]; !found {
944 options.headerIDs[id] = 0
945 }
946
947 return id
948}