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.

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