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