html.go 24 KB

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