Command line client for Write.as https://write.as/apps/cli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

950 lines
24 KiB

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