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.
 
 
 

1421 lines
28 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. // Functions to parse block-level elements.
  11. //
  12. package blackfriday
  13. import (
  14. "bytes"
  15. "github.com/shurcooL/sanitized_anchor_name"
  16. )
  17. // Parse block-level data.
  18. // Note: this function and many that it calls assume that
  19. // the input buffer ends with a newline.
  20. func (p *parser) block(out *bytes.Buffer, data []byte) {
  21. if len(data) == 0 || data[len(data)-1] != '\n' {
  22. panic("block input is missing terminating newline")
  23. }
  24. // this is called recursively: enforce a maximum depth
  25. if p.nesting >= p.maxNesting {
  26. return
  27. }
  28. p.nesting++
  29. // parse out one block-level construct at a time
  30. for len(data) > 0 {
  31. // prefixed header:
  32. //
  33. // # Header 1
  34. // ## Header 2
  35. // ...
  36. // ###### Header 6
  37. if p.isPrefixHeader(data) {
  38. data = data[p.prefixHeader(out, data):]
  39. continue
  40. }
  41. // block of preformatted HTML:
  42. //
  43. // <div>
  44. // ...
  45. // </div>
  46. if data[0] == '<' {
  47. if i := p.html(out, data, true); i > 0 {
  48. data = data[i:]
  49. continue
  50. }
  51. }
  52. // title block
  53. //
  54. // % stuff
  55. // % more stuff
  56. // % even more stuff
  57. if p.flags&EXTENSION_TITLEBLOCK != 0 {
  58. if data[0] == '%' {
  59. if i := p.titleBlock(out, data, true); i > 0 {
  60. data = data[i:]
  61. continue
  62. }
  63. }
  64. }
  65. // blank lines. note: returns the # of bytes to skip
  66. if i := p.isEmpty(data); i > 0 {
  67. data = data[i:]
  68. continue
  69. }
  70. // indented code block:
  71. //
  72. // func max(a, b int) int {
  73. // if a > b {
  74. // return a
  75. // }
  76. // return b
  77. // }
  78. if p.codePrefix(data) > 0 {
  79. data = data[p.code(out, data):]
  80. continue
  81. }
  82. // fenced code block:
  83. //
  84. // ``` go
  85. // func fact(n int) int {
  86. // if n <= 1 {
  87. // return n
  88. // }
  89. // return n * fact(n-1)
  90. // }
  91. // ```
  92. if p.flags&EXTENSION_FENCED_CODE != 0 {
  93. if i := p.fencedCode(out, data, true); i > 0 {
  94. data = data[i:]
  95. continue
  96. }
  97. }
  98. // horizontal rule:
  99. //
  100. // ------
  101. // or
  102. // ******
  103. // or
  104. // ______
  105. if p.isHRule(data) {
  106. p.r.HRule(out)
  107. var i int
  108. for i = 0; data[i] != '\n'; i++ {
  109. }
  110. data = data[i:]
  111. continue
  112. }
  113. // block quote:
  114. //
  115. // > A big quote I found somewhere
  116. // > on the web
  117. if p.quotePrefix(data) > 0 {
  118. data = data[p.quote(out, data):]
  119. continue
  120. }
  121. // table:
  122. //
  123. // Name | Age | Phone
  124. // ------|-----|---------
  125. // Bob | 31 | 555-1234
  126. // Alice | 27 | 555-4321
  127. if p.flags&EXTENSION_TABLES != 0 {
  128. if i := p.table(out, data); i > 0 {
  129. data = data[i:]
  130. continue
  131. }
  132. }
  133. // an itemized/unordered list:
  134. //
  135. // * Item 1
  136. // * Item 2
  137. //
  138. // also works with + or -
  139. if p.uliPrefix(data) > 0 {
  140. data = data[p.list(out, data, 0):]
  141. continue
  142. }
  143. // a numbered/ordered list:
  144. //
  145. // 1. Item 1
  146. // 2. Item 2
  147. if p.oliPrefix(data) > 0 {
  148. data = data[p.list(out, data, LIST_TYPE_ORDERED):]
  149. continue
  150. }
  151. // definition lists:
  152. //
  153. // Term 1
  154. // : Definition a
  155. // : Definition b
  156. //
  157. // Term 2
  158. // : Definition c
  159. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  160. if p.dliPrefix(data) > 0 {
  161. data = data[p.list(out, data, LIST_TYPE_DEFINITION):]
  162. continue
  163. }
  164. }
  165. // anything else must look like a normal paragraph
  166. // note: this finds underlined headers, too
  167. data = data[p.paragraph(out, data):]
  168. }
  169. p.nesting--
  170. }
  171. func (p *parser) isPrefixHeader(data []byte) bool {
  172. if data[0] != '#' {
  173. return false
  174. }
  175. if p.flags&EXTENSION_SPACE_HEADERS != 0 {
  176. level := 0
  177. for level < 6 && data[level] == '#' {
  178. level++
  179. }
  180. if data[level] != ' ' {
  181. return false
  182. }
  183. }
  184. return true
  185. }
  186. func (p *parser) prefixHeader(out *bytes.Buffer, data []byte) int {
  187. level := 0
  188. for level < 6 && data[level] == '#' {
  189. level++
  190. }
  191. i := skipChar(data, level, ' ')
  192. end := skipUntilChar(data, i, '\n')
  193. skip := end
  194. id := ""
  195. if p.flags&EXTENSION_HEADER_IDS != 0 {
  196. j, k := 0, 0
  197. // find start/end of header id
  198. for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ {
  199. }
  200. for k = j + 1; k < end && data[k] != '}'; k++ {
  201. }
  202. // extract header id iff found
  203. if j < end && k < end {
  204. id = string(data[j+2 : k])
  205. end = j
  206. skip = k + 1
  207. for end > 0 && data[end-1] == ' ' {
  208. end--
  209. }
  210. }
  211. }
  212. for end > 0 && data[end-1] == '#' {
  213. if isBackslashEscaped(data, end-1) {
  214. break
  215. }
  216. end--
  217. }
  218. for end > 0 && data[end-1] == ' ' {
  219. end--
  220. }
  221. if end > i {
  222. if id == "" && p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
  223. id = sanitized_anchor_name.Create(string(data[i:end]))
  224. }
  225. work := func() bool {
  226. p.inline(out, data[i:end])
  227. return true
  228. }
  229. p.r.Header(out, work, level, id)
  230. }
  231. return skip
  232. }
  233. func (p *parser) isUnderlinedHeader(data []byte) int {
  234. // test of level 1 header
  235. if data[0] == '=' {
  236. i := skipChar(data, 1, '=')
  237. i = skipChar(data, i, ' ')
  238. if data[i] == '\n' {
  239. return 1
  240. } else {
  241. return 0
  242. }
  243. }
  244. // test of level 2 header
  245. if data[0] == '-' {
  246. i := skipChar(data, 1, '-')
  247. i = skipChar(data, i, ' ')
  248. if data[i] == '\n' {
  249. return 2
  250. } else {
  251. return 0
  252. }
  253. }
  254. return 0
  255. }
  256. func (p *parser) titleBlock(out *bytes.Buffer, data []byte, doRender bool) int {
  257. if data[0] != '%' {
  258. return 0
  259. }
  260. splitData := bytes.Split(data, []byte("\n"))
  261. var i int
  262. for idx, b := range splitData {
  263. if !bytes.HasPrefix(b, []byte("%")) {
  264. i = idx // - 1
  265. break
  266. }
  267. }
  268. data = bytes.Join(splitData[0:i], []byte("\n"))
  269. p.r.TitleBlock(out, data)
  270. return len(data)
  271. }
  272. func (p *parser) html(out *bytes.Buffer, data []byte, doRender bool) int {
  273. var i, j int
  274. // identify the opening tag
  275. if data[0] != '<' {
  276. return 0
  277. }
  278. curtag, tagfound := p.htmlFindTag(data[1:])
  279. // handle special cases
  280. if !tagfound {
  281. // check for an HTML comment
  282. if size := p.htmlComment(out, data, doRender); size > 0 {
  283. return size
  284. }
  285. // check for an <hr> tag
  286. if size := p.htmlHr(out, data, doRender); size > 0 {
  287. return size
  288. }
  289. // check for HTML CDATA
  290. if size := p.htmlCDATA(out, data, doRender); size > 0 {
  291. return size
  292. }
  293. // no special case recognized
  294. return 0
  295. }
  296. // look for an unindented matching closing tag
  297. // followed by a blank line
  298. found := false
  299. /*
  300. closetag := []byte("\n</" + curtag + ">")
  301. j = len(curtag) + 1
  302. for !found {
  303. // scan for a closing tag at the beginning of a line
  304. if skip := bytes.Index(data[j:], closetag); skip >= 0 {
  305. j += skip + len(closetag)
  306. } else {
  307. break
  308. }
  309. // see if it is the only thing on the line
  310. if skip := p.isEmpty(data[j:]); skip > 0 {
  311. // see if it is followed by a blank line/eof
  312. j += skip
  313. if j >= len(data) {
  314. found = true
  315. i = j
  316. } else {
  317. if skip := p.isEmpty(data[j:]); skip > 0 {
  318. j += skip
  319. found = true
  320. i = j
  321. }
  322. }
  323. }
  324. }
  325. */
  326. // if not found, try a second pass looking for indented match
  327. // but not if tag is "ins" or "del" (following original Markdown.pl)
  328. if !found && curtag != "ins" && curtag != "del" {
  329. i = 1
  330. for i < len(data) {
  331. i++
  332. for i < len(data) && !(data[i-1] == '<' && data[i] == '/') {
  333. i++
  334. }
  335. if i+2+len(curtag) >= len(data) {
  336. break
  337. }
  338. j = p.htmlFindEnd(curtag, data[i-1:])
  339. if j > 0 {
  340. i += j - 1
  341. found = true
  342. break
  343. }
  344. }
  345. }
  346. if !found {
  347. return 0
  348. }
  349. // the end of the block has been found
  350. if doRender {
  351. // trim newlines
  352. end := i
  353. for end > 0 && data[end-1] == '\n' {
  354. end--
  355. }
  356. p.r.BlockHtml(out, data[:end])
  357. }
  358. return i
  359. }
  360. func (p *parser) renderHTMLBlock(out *bytes.Buffer, data []byte, start int, doRender bool) int {
  361. // html block needs to end with a blank line
  362. if i := p.isEmpty(data[start:]); i > 0 {
  363. size := start + i
  364. if doRender {
  365. // trim trailing newlines
  366. end := size
  367. for end > 0 && data[end-1] == '\n' {
  368. end--
  369. }
  370. p.r.BlockHtml(out, data[:end])
  371. }
  372. return size
  373. }
  374. return 0
  375. }
  376. // HTML comment, lax form
  377. func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int {
  378. i := p.inlineHTMLComment(out, data)
  379. return p.renderHTMLBlock(out, data, i, doRender)
  380. }
  381. // HTML CDATA section
  382. func (p *parser) htmlCDATA(out *bytes.Buffer, data []byte, doRender bool) int {
  383. const cdataTag = "<![cdata["
  384. const cdataTagLen = len(cdataTag)
  385. if len(data) < cdataTagLen+1 {
  386. return 0
  387. }
  388. if !bytes.Equal(bytes.ToLower(data[:cdataTagLen]), []byte(cdataTag)) {
  389. return 0
  390. }
  391. i := cdataTagLen
  392. // scan for an end-of-comment marker, across lines if necessary
  393. for i < len(data) && !(data[i-2] == ']' && data[i-1] == ']' && data[i] == '>') {
  394. i++
  395. }
  396. i++
  397. // no end-of-comment marker
  398. if i >= len(data) {
  399. return 0
  400. }
  401. return p.renderHTMLBlock(out, data, i, doRender)
  402. }
  403. // HR, which is the only self-closing block tag considered
  404. func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int {
  405. if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') {
  406. return 0
  407. }
  408. if data[3] != ' ' && data[3] != '/' && data[3] != '>' {
  409. // not an <hr> tag after all; at least not a valid one
  410. return 0
  411. }
  412. i := 3
  413. for data[i] != '>' && data[i] != '\n' {
  414. i++
  415. }
  416. if data[i] == '>' {
  417. return p.renderHTMLBlock(out, data, i+1, doRender)
  418. }
  419. return 0
  420. }
  421. func (p *parser) htmlFindTag(data []byte) (string, bool) {
  422. i := 0
  423. for isalnum(data[i]) {
  424. i++
  425. }
  426. key := string(data[:i])
  427. if _, ok := blockTags[key]; ok {
  428. return key, true
  429. }
  430. return "", false
  431. }
  432. func (p *parser) htmlFindEnd(tag string, data []byte) int {
  433. // assume data[0] == '<' && data[1] == '/' already tested
  434. // check if tag is a match
  435. closetag := []byte("</" + tag + ">")
  436. if !bytes.HasPrefix(data, closetag) {
  437. return 0
  438. }
  439. i := len(closetag)
  440. // check that the rest of the line is blank
  441. skip := 0
  442. if skip = p.isEmpty(data[i:]); skip == 0 {
  443. return 0
  444. }
  445. i += skip
  446. skip = 0
  447. if i >= len(data) {
  448. return i
  449. }
  450. if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
  451. return i
  452. }
  453. if skip = p.isEmpty(data[i:]); skip == 0 {
  454. // following line must be blank
  455. return 0
  456. }
  457. return i + skip
  458. }
  459. func (p *parser) isEmpty(data []byte) int {
  460. // it is okay to call isEmpty on an empty buffer
  461. if len(data) == 0 {
  462. return 0
  463. }
  464. var i int
  465. for i = 0; i < len(data) && data[i] != '\n'; i++ {
  466. if data[i] != ' ' && data[i] != '\t' {
  467. return 0
  468. }
  469. }
  470. return i + 1
  471. }
  472. func (p *parser) isHRule(data []byte) bool {
  473. i := 0
  474. // skip up to three spaces
  475. for i < 3 && data[i] == ' ' {
  476. i++
  477. }
  478. // look at the hrule char
  479. if data[i] != '*' && data[i] != '-' && data[i] != '_' {
  480. return false
  481. }
  482. c := data[i]
  483. // the whole line must be the char or whitespace
  484. n := 0
  485. for data[i] != '\n' {
  486. switch {
  487. case data[i] == c:
  488. n++
  489. case data[i] != ' ':
  490. return false
  491. }
  492. i++
  493. }
  494. return n >= 3
  495. }
  496. func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (skip int, marker string) {
  497. i, size := 0, 0
  498. skip = 0
  499. // skip up to three spaces
  500. for i < len(data) && i < 3 && data[i] == ' ' {
  501. i++
  502. }
  503. if i >= len(data) {
  504. return
  505. }
  506. // check for the marker characters: ~ or `
  507. if data[i] != '~' && data[i] != '`' {
  508. return
  509. }
  510. c := data[i]
  511. // the whole line must be the same char or whitespace
  512. for i < len(data) && data[i] == c {
  513. size++
  514. i++
  515. }
  516. if i >= len(data) {
  517. return
  518. }
  519. // the marker char must occur at least 3 times
  520. if size < 3 {
  521. return
  522. }
  523. marker = string(data[i-size : i])
  524. // if this is the end marker, it must match the beginning marker
  525. if oldmarker != "" && marker != oldmarker {
  526. return
  527. }
  528. if syntax != nil {
  529. syn := 0
  530. i = skipChar(data, i, ' ')
  531. if i >= len(data) {
  532. return
  533. }
  534. syntaxStart := i
  535. if data[i] == '{' {
  536. i++
  537. syntaxStart++
  538. for i < len(data) && data[i] != '}' && data[i] != '\n' {
  539. syn++
  540. i++
  541. }
  542. if i >= len(data) || data[i] != '}' {
  543. return
  544. }
  545. // strip all whitespace at the beginning and the end
  546. // of the {} block
  547. for syn > 0 && isspace(data[syntaxStart]) {
  548. syntaxStart++
  549. syn--
  550. }
  551. for syn > 0 && isspace(data[syntaxStart+syn-1]) {
  552. syn--
  553. }
  554. i++
  555. } else {
  556. for i < len(data) && !isspace(data[i]) {
  557. syn++
  558. i++
  559. }
  560. }
  561. language := string(data[syntaxStart : syntaxStart+syn])
  562. *syntax = &language
  563. }
  564. i = skipChar(data, i, ' ')
  565. if i >= len(data) || data[i] != '\n' {
  566. return
  567. }
  568. skip = i + 1
  569. return
  570. }
  571. func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int {
  572. var lang *string
  573. beg, marker := p.isFencedCode(data, &lang, "")
  574. if beg == 0 || beg >= len(data) {
  575. return 0
  576. }
  577. var work bytes.Buffer
  578. for {
  579. // safe to assume beg < len(data)
  580. // check for the end of the code block
  581. fenceEnd, _ := p.isFencedCode(data[beg:], nil, marker)
  582. if fenceEnd != 0 {
  583. beg += fenceEnd
  584. break
  585. }
  586. // copy the current line
  587. end := skipUntilChar(data, beg, '\n') + 1
  588. // did we reach the end of the buffer without a closing marker?
  589. if end >= len(data) {
  590. return 0
  591. }
  592. // verbatim copy to the working buffer
  593. if doRender {
  594. work.Write(data[beg:end])
  595. }
  596. beg = end
  597. }
  598. syntax := ""
  599. if lang != nil {
  600. syntax = *lang
  601. }
  602. if doRender {
  603. p.r.BlockCode(out, work.Bytes(), syntax)
  604. }
  605. return beg
  606. }
  607. func (p *parser) table(out *bytes.Buffer, data []byte) int {
  608. var header bytes.Buffer
  609. i, columns := p.tableHeader(&header, data)
  610. if i == 0 {
  611. return 0
  612. }
  613. var body bytes.Buffer
  614. for i < len(data) {
  615. pipes, rowStart := 0, i
  616. for ; data[i] != '\n'; i++ {
  617. if data[i] == '|' {
  618. pipes++
  619. }
  620. }
  621. if pipes == 0 {
  622. i = rowStart
  623. break
  624. }
  625. // include the newline in data sent to tableRow
  626. i++
  627. p.tableRow(&body, data[rowStart:i], columns, false)
  628. }
  629. p.r.Table(out, header.Bytes(), body.Bytes(), columns)
  630. return i
  631. }
  632. // check if the specified position is preceded by an odd number of backslashes
  633. func isBackslashEscaped(data []byte, i int) bool {
  634. backslashes := 0
  635. for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' {
  636. backslashes++
  637. }
  638. return backslashes&1 == 1
  639. }
  640. func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) {
  641. i := 0
  642. colCount := 1
  643. for i = 0; data[i] != '\n'; i++ {
  644. if data[i] == '|' && !isBackslashEscaped(data, i) {
  645. colCount++
  646. }
  647. }
  648. // doesn't look like a table header
  649. if colCount == 1 {
  650. return
  651. }
  652. // include the newline in the data sent to tableRow
  653. header := data[:i+1]
  654. // column count ignores pipes at beginning or end of line
  655. if data[0] == '|' {
  656. colCount--
  657. }
  658. if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) {
  659. colCount--
  660. }
  661. columns = make([]int, colCount)
  662. // move on to the header underline
  663. i++
  664. if i >= len(data) {
  665. return
  666. }
  667. if data[i] == '|' && !isBackslashEscaped(data, i) {
  668. i++
  669. }
  670. i = skipChar(data, i, ' ')
  671. // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3
  672. // and trailing | optional on last column
  673. col := 0
  674. for data[i] != '\n' {
  675. dashes := 0
  676. if data[i] == ':' {
  677. i++
  678. columns[col] |= TABLE_ALIGNMENT_LEFT
  679. dashes++
  680. }
  681. for data[i] == '-' {
  682. i++
  683. dashes++
  684. }
  685. if data[i] == ':' {
  686. i++
  687. columns[col] |= TABLE_ALIGNMENT_RIGHT
  688. dashes++
  689. }
  690. for data[i] == ' ' {
  691. i++
  692. }
  693. // end of column test is messy
  694. switch {
  695. case dashes < 3:
  696. // not a valid column
  697. return
  698. case data[i] == '|' && !isBackslashEscaped(data, i):
  699. // marker found, now skip past trailing whitespace
  700. col++
  701. i++
  702. for data[i] == ' ' {
  703. i++
  704. }
  705. // trailing junk found after last column
  706. if col >= colCount && data[i] != '\n' {
  707. return
  708. }
  709. case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount:
  710. // something else found where marker was required
  711. return
  712. case data[i] == '\n':
  713. // marker is optional for the last column
  714. col++
  715. default:
  716. // trailing junk found after last column
  717. return
  718. }
  719. }
  720. if col != colCount {
  721. return
  722. }
  723. p.tableRow(out, header, columns, true)
  724. size = i + 1
  725. return
  726. }
  727. func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) {
  728. i, col := 0, 0
  729. var rowWork bytes.Buffer
  730. if data[i] == '|' && !isBackslashEscaped(data, i) {
  731. i++
  732. }
  733. for col = 0; col < len(columns) && i < len(data); col++ {
  734. for data[i] == ' ' {
  735. i++
  736. }
  737. cellStart := i
  738. for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' {
  739. i++
  740. }
  741. cellEnd := i
  742. // skip the end-of-cell marker, possibly taking us past end of buffer
  743. i++
  744. for cellEnd > cellStart && data[cellEnd-1] == ' ' {
  745. cellEnd--
  746. }
  747. var cellWork bytes.Buffer
  748. p.inline(&cellWork, data[cellStart:cellEnd])
  749. if header {
  750. p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col])
  751. } else {
  752. p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col])
  753. }
  754. }
  755. // pad it out with empty columns to get the right number
  756. for ; col < len(columns); col++ {
  757. if header {
  758. p.r.TableHeaderCell(&rowWork, nil, columns[col])
  759. } else {
  760. p.r.TableCell(&rowWork, nil, columns[col])
  761. }
  762. }
  763. // silently ignore rows with too many cells
  764. p.r.TableRow(out, rowWork.Bytes())
  765. }
  766. // returns blockquote prefix length
  767. func (p *parser) quotePrefix(data []byte) int {
  768. i := 0
  769. for i < 3 && data[i] == ' ' {
  770. i++
  771. }
  772. if data[i] == '>' {
  773. if data[i+1] == ' ' {
  774. return i + 2
  775. }
  776. return i + 1
  777. }
  778. return 0
  779. }
  780. // blockquote ends with at least one blank line
  781. // followed by something without a blockquote prefix
  782. func (p *parser) terminateBlockquote(data []byte, beg, end int) bool {
  783. if p.isEmpty(data[beg:]) <= 0 {
  784. return false
  785. }
  786. if end >= len(data) {
  787. return true
  788. }
  789. return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0
  790. }
  791. // parse a blockquote fragment
  792. func (p *parser) quote(out *bytes.Buffer, data []byte) int {
  793. var raw bytes.Buffer
  794. beg, end := 0, 0
  795. for beg < len(data) {
  796. end = beg
  797. // Step over whole lines, collecting them. While doing that, check for
  798. // fenced code and if one's found, incorporate it altogether,
  799. // irregardless of any contents inside it
  800. for data[end] != '\n' {
  801. if p.flags&EXTENSION_FENCED_CODE != 0 {
  802. if i := p.fencedCode(out, data[end:], false); i > 0 {
  803. // -1 to compensate for the extra end++ after the loop:
  804. end += i - 1
  805. break
  806. }
  807. }
  808. end++
  809. }
  810. end++
  811. if pre := p.quotePrefix(data[beg:]); pre > 0 {
  812. // skip the prefix
  813. beg += pre
  814. } else if p.terminateBlockquote(data, beg, end) {
  815. break
  816. }
  817. // this line is part of the blockquote
  818. raw.Write(data[beg:end])
  819. beg = end
  820. }
  821. var cooked bytes.Buffer
  822. p.block(&cooked, raw.Bytes())
  823. p.r.BlockQuote(out, cooked.Bytes())
  824. return end
  825. }
  826. // returns prefix length for block code
  827. func (p *parser) codePrefix(data []byte) int {
  828. if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' {
  829. return 4
  830. }
  831. return 0
  832. }
  833. func (p *parser) code(out *bytes.Buffer, data []byte) int {
  834. var work bytes.Buffer
  835. i := 0
  836. for i < len(data) {
  837. beg := i
  838. for data[i] != '\n' {
  839. i++
  840. }
  841. i++
  842. blankline := p.isEmpty(data[beg:i]) > 0
  843. if pre := p.codePrefix(data[beg:i]); pre > 0 {
  844. beg += pre
  845. } else if !blankline {
  846. // non-empty, non-prefixed line breaks the pre
  847. i = beg
  848. break
  849. }
  850. // verbatim copy to the working buffeu
  851. if blankline {
  852. work.WriteByte('\n')
  853. } else {
  854. work.Write(data[beg:i])
  855. }
  856. }
  857. // trim all the \n off the end of work
  858. workbytes := work.Bytes()
  859. eol := len(workbytes)
  860. for eol > 0 && workbytes[eol-1] == '\n' {
  861. eol--
  862. }
  863. if eol != len(workbytes) {
  864. work.Truncate(eol)
  865. }
  866. work.WriteByte('\n')
  867. p.r.BlockCode(out, work.Bytes(), "")
  868. return i
  869. }
  870. // returns unordered list item prefix
  871. func (p *parser) uliPrefix(data []byte) int {
  872. i := 0
  873. // start with up to 3 spaces
  874. for i < 3 && data[i] == ' ' {
  875. i++
  876. }
  877. // need a *, +, or - followed by a space
  878. if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
  879. data[i+1] != ' ' {
  880. return 0
  881. }
  882. return i + 2
  883. }
  884. // returns ordered list item prefix
  885. func (p *parser) oliPrefix(data []byte) int {
  886. i := 0
  887. // start with up to 3 spaces
  888. for i < 3 && data[i] == ' ' {
  889. i++
  890. }
  891. // count the digits
  892. start := i
  893. for data[i] >= '0' && data[i] <= '9' {
  894. i++
  895. }
  896. // we need >= 1 digits followed by a dot and a space
  897. if start == i || data[i] != '.' || data[i+1] != ' ' {
  898. return 0
  899. }
  900. return i + 2
  901. }
  902. // returns definition list item prefix
  903. func (p *parser) dliPrefix(data []byte) int {
  904. i := 0
  905. // need a : followed by a spaces
  906. if data[i] != ':' || data[i+1] != ' ' {
  907. return 0
  908. }
  909. for data[i] == ' ' {
  910. i++
  911. }
  912. return i + 2
  913. }
  914. // parse ordered or unordered list block
  915. func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int {
  916. i := 0
  917. flags |= LIST_ITEM_BEGINNING_OF_LIST
  918. work := func() bool {
  919. for i < len(data) {
  920. skip := p.listItem(out, data[i:], &flags)
  921. i += skip
  922. if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 {
  923. break
  924. }
  925. flags &= ^LIST_ITEM_BEGINNING_OF_LIST
  926. }
  927. return true
  928. }
  929. p.r.List(out, work, flags)
  930. return i
  931. }
  932. // Parse a single list item.
  933. // Assumes initial prefix is already removed if this is a sublist.
  934. func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int {
  935. // keep track of the indentation of the first line
  936. itemIndent := 0
  937. for itemIndent < 3 && data[itemIndent] == ' ' {
  938. itemIndent++
  939. }
  940. i := p.uliPrefix(data)
  941. if i == 0 {
  942. i = p.oliPrefix(data)
  943. }
  944. if i == 0 {
  945. i = p.dliPrefix(data)
  946. // reset definition term flag
  947. if i > 0 {
  948. *flags &= ^LIST_TYPE_TERM
  949. }
  950. }
  951. if i == 0 {
  952. // if in defnition list, set term flag and continue
  953. if *flags&LIST_TYPE_DEFINITION != 0 {
  954. *flags |= LIST_TYPE_TERM
  955. } else {
  956. return 0
  957. }
  958. }
  959. // skip leading whitespace on first line
  960. for data[i] == ' ' {
  961. i++
  962. }
  963. // find the end of the line
  964. line := i
  965. for i > 0 && data[i-1] != '\n' {
  966. i++
  967. }
  968. // get working buffer
  969. var raw bytes.Buffer
  970. // put the first line into the working buffer
  971. raw.Write(data[line:i])
  972. line = i
  973. // process the following lines
  974. containsBlankLine := false
  975. sublist := 0
  976. gatherlines:
  977. for line < len(data) {
  978. i++
  979. // find the end of this line
  980. for data[i-1] != '\n' {
  981. i++
  982. }
  983. // if it is an empty line, guess that it is part of this item
  984. // and move on to the next line
  985. if p.isEmpty(data[line:i]) > 0 {
  986. containsBlankLine = true
  987. raw.Write(data[line:i])
  988. line = i
  989. continue
  990. }
  991. // calculate the indentation
  992. indent := 0
  993. for indent < 4 && line+indent < i && data[line+indent] == ' ' {
  994. indent++
  995. }
  996. chunk := data[line+indent : i]
  997. // evaluate how this line fits in
  998. switch {
  999. // is this a nested list item?
  1000. case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) ||
  1001. p.oliPrefix(chunk) > 0 ||
  1002. p.dliPrefix(chunk) > 0:
  1003. if containsBlankLine {
  1004. // end the list if the type changed after a blank line
  1005. if indent <= itemIndent &&
  1006. ((*flags&LIST_TYPE_ORDERED != 0 && p.uliPrefix(chunk) > 0) ||
  1007. (*flags&LIST_TYPE_ORDERED == 0 && p.oliPrefix(chunk) > 0)) {
  1008. *flags |= LIST_ITEM_END_OF_LIST
  1009. break gatherlines
  1010. }
  1011. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1012. }
  1013. // to be a nested list, it must be indented more
  1014. // if not, it is the next item in the same list
  1015. if indent <= itemIndent {
  1016. break gatherlines
  1017. }
  1018. // is this the first item in the nested list?
  1019. if sublist == 0 {
  1020. sublist = raw.Len()
  1021. }
  1022. // is this a nested prefix header?
  1023. case p.isPrefixHeader(chunk):
  1024. // if the header is not indented, it is not nested in the list
  1025. // and thus ends the list
  1026. if containsBlankLine && indent < 4 {
  1027. *flags |= LIST_ITEM_END_OF_LIST
  1028. break gatherlines
  1029. }
  1030. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1031. // anything following an empty line is only part
  1032. // of this item if it is indented 4 spaces
  1033. // (regardless of the indentation of the beginning of the item)
  1034. case containsBlankLine && indent < 4:
  1035. if *flags&LIST_TYPE_DEFINITION != 0 && i < len(data)-1 {
  1036. // is the next item still a part of this list?
  1037. next := i
  1038. for data[next] != '\n' {
  1039. next++
  1040. }
  1041. for next < len(data)-1 && data[next] == '\n' {
  1042. next++
  1043. }
  1044. if i < len(data)-1 && data[i] != ':' && data[next] != ':' {
  1045. *flags |= LIST_ITEM_END_OF_LIST
  1046. }
  1047. } else {
  1048. *flags |= LIST_ITEM_END_OF_LIST
  1049. }
  1050. break gatherlines
  1051. // a blank line means this should be parsed as a block
  1052. case containsBlankLine:
  1053. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1054. }
  1055. containsBlankLine = false
  1056. // add the line into the working buffer without prefix
  1057. raw.Write(data[line+indent : i])
  1058. line = i
  1059. }
  1060. rawBytes := raw.Bytes()
  1061. // render the contents of the list item
  1062. var cooked bytes.Buffer
  1063. if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 && *flags&LIST_TYPE_TERM == 0 {
  1064. // intermediate render of block item, except for definition term
  1065. if sublist > 0 {
  1066. p.block(&cooked, rawBytes[:sublist])
  1067. p.block(&cooked, rawBytes[sublist:])
  1068. } else {
  1069. p.block(&cooked, rawBytes)
  1070. }
  1071. } else {
  1072. // intermediate render of inline item
  1073. if sublist > 0 {
  1074. p.inline(&cooked, rawBytes[:sublist])
  1075. p.block(&cooked, rawBytes[sublist:])
  1076. } else {
  1077. p.inline(&cooked, rawBytes)
  1078. }
  1079. }
  1080. // render the actual list item
  1081. cookedBytes := cooked.Bytes()
  1082. parsedEnd := len(cookedBytes)
  1083. // strip trailing newlines
  1084. for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' {
  1085. parsedEnd--
  1086. }
  1087. p.r.ListItem(out, cookedBytes[:parsedEnd], *flags)
  1088. return line
  1089. }
  1090. // render a single paragraph that has already been parsed out
  1091. func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) {
  1092. if len(data) == 0 {
  1093. return
  1094. }
  1095. // trim leading spaces
  1096. beg := 0
  1097. for data[beg] == ' ' {
  1098. beg++
  1099. }
  1100. // trim trailing newline
  1101. end := len(data) - 1
  1102. // trim trailing spaces
  1103. for end > beg && data[end-1] == ' ' {
  1104. end--
  1105. }
  1106. work := func() bool {
  1107. p.inline(out, data[beg:end])
  1108. return true
  1109. }
  1110. p.r.Paragraph(out, work)
  1111. }
  1112. func (p *parser) paragraph(out *bytes.Buffer, data []byte) int {
  1113. // prev: index of 1st char of previous line
  1114. // line: index of 1st char of current line
  1115. // i: index of cursor/end of current line
  1116. var prev, line, i int
  1117. // keep going until we find something to mark the end of the paragraph
  1118. for i < len(data) {
  1119. // mark the beginning of the current line
  1120. prev = line
  1121. current := data[i:]
  1122. line = i
  1123. // did we find a blank line marking the end of the paragraph?
  1124. if n := p.isEmpty(current); n > 0 {
  1125. // did this blank line followed by a definition list item?
  1126. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  1127. if i < len(data)-1 && data[i+1] == ':' {
  1128. return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
  1129. }
  1130. }
  1131. p.renderParagraph(out, data[:i])
  1132. return i + n
  1133. }
  1134. // an underline under some text marks a header, so our paragraph ended on prev line
  1135. if i > 0 {
  1136. if level := p.isUnderlinedHeader(current); level > 0 {
  1137. // render the paragraph
  1138. p.renderParagraph(out, data[:prev])
  1139. // ignore leading and trailing whitespace
  1140. eol := i - 1
  1141. for prev < eol && data[prev] == ' ' {
  1142. prev++
  1143. }
  1144. for eol > prev && data[eol-1] == ' ' {
  1145. eol--
  1146. }
  1147. // render the header
  1148. // this ugly double closure avoids forcing variables onto the heap
  1149. work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool {
  1150. return func() bool {
  1151. pp.inline(o, d)
  1152. return true
  1153. }
  1154. }(out, p, data[prev:eol])
  1155. id := ""
  1156. if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
  1157. id = sanitized_anchor_name.Create(string(data[prev:eol]))
  1158. }
  1159. p.r.Header(out, work, level, id)
  1160. // find the end of the underline
  1161. for data[i] != '\n' {
  1162. i++
  1163. }
  1164. return i
  1165. }
  1166. }
  1167. // if the next line starts a block of HTML, then the paragraph ends here
  1168. if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
  1169. if data[i] == '<' && p.html(out, current, false) > 0 {
  1170. // rewind to before the HTML block
  1171. p.renderParagraph(out, data[:i])
  1172. return i
  1173. }
  1174. }
  1175. // if there's a prefixed header or a horizontal rule after this, paragraph is over
  1176. if p.isPrefixHeader(current) || p.isHRule(current) {
  1177. p.renderParagraph(out, data[:i])
  1178. return i
  1179. }
  1180. // if there's a fenced code block, paragraph is over
  1181. if p.flags&EXTENSION_FENCED_CODE != 0 {
  1182. if p.fencedCode(out, current, false) > 0 {
  1183. p.renderParagraph(out, data[:i])
  1184. return i
  1185. }
  1186. }
  1187. // if there's a definition list item, prev line is a definition term
  1188. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  1189. if p.dliPrefix(current) != 0 {
  1190. return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
  1191. }
  1192. }
  1193. // if there's a list after this, paragraph is over
  1194. if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 {
  1195. if p.uliPrefix(current) != 0 ||
  1196. p.oliPrefix(current) != 0 ||
  1197. p.quotePrefix(current) != 0 ||
  1198. p.codePrefix(current) != 0 {
  1199. p.renderParagraph(out, data[:i])
  1200. return i
  1201. }
  1202. }
  1203. // otherwise, scan to the beginning of the next line
  1204. for data[i] != '\n' {
  1205. i++
  1206. }
  1207. i++
  1208. }
  1209. p.renderParagraph(out, data[:i])
  1210. return i
  1211. }