block.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  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. // no special case recognized
  290. return 0
  291. }
  292. // look for an unindented matching closing tag
  293. // followed by a blank line
  294. found := false
  295. /*
  296. closetag := []byte("\n</" + curtag + ">")
  297. j = len(curtag) + 1
  298. for !found {
  299. // scan for a closing tag at the beginning of a line
  300. if skip := bytes.Index(data[j:], closetag); skip >= 0 {
  301. j += skip + len(closetag)
  302. } else {
  303. break
  304. }
  305. // see if it is the only thing on the line
  306. if skip := p.isEmpty(data[j:]); skip > 0 {
  307. // see if it is followed by a blank line/eof
  308. j += skip
  309. if j >= len(data) {
  310. found = true
  311. i = j
  312. } else {
  313. if skip := p.isEmpty(data[j:]); skip > 0 {
  314. j += skip
  315. found = true
  316. i = j
  317. }
  318. }
  319. }
  320. }
  321. */
  322. // if not found, try a second pass looking for indented match
  323. // but not if tag is "ins" or "del" (following original Markdown.pl)
  324. if !found && curtag != "ins" && curtag != "del" {
  325. i = 1
  326. for i < len(data) {
  327. i++
  328. for i < len(data) && !(data[i-1] == '<' && data[i] == '/') {
  329. i++
  330. }
  331. if i+2+len(curtag) >= len(data) {
  332. break
  333. }
  334. j = p.htmlFindEnd(curtag, data[i-1:])
  335. if j > 0 {
  336. i += j - 1
  337. found = true
  338. break
  339. }
  340. }
  341. }
  342. if !found {
  343. return 0
  344. }
  345. // the end of the block has been found
  346. if doRender {
  347. // trim newlines
  348. end := i
  349. for end > 0 && data[end-1] == '\n' {
  350. end--
  351. }
  352. p.r.BlockHtml(out, data[:end])
  353. }
  354. return i
  355. }
  356. // HTML comment, lax form
  357. func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int {
  358. i := p.inlineHtmlComment(out, data)
  359. // needs to end with a blank line
  360. if j := p.isEmpty(data[i:]); j > 0 {
  361. size := i + j
  362. if doRender {
  363. // trim trailing newlines
  364. end := size
  365. for end > 0 && data[end-1] == '\n' {
  366. end--
  367. }
  368. p.r.BlockHtml(out, data[:end])
  369. }
  370. return size
  371. }
  372. return 0
  373. }
  374. // HR, which is the only self-closing block tag considered
  375. func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int {
  376. if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') {
  377. return 0
  378. }
  379. if data[3] != ' ' && data[3] != '/' && data[3] != '>' {
  380. // not an <hr> tag after all; at least not a valid one
  381. return 0
  382. }
  383. i := 3
  384. for data[i] != '>' && data[i] != '\n' {
  385. i++
  386. }
  387. if data[i] == '>' {
  388. i++
  389. if j := p.isEmpty(data[i:]); j > 0 {
  390. size := i + j
  391. if doRender {
  392. // trim newlines
  393. end := size
  394. for end > 0 && data[end-1] == '\n' {
  395. end--
  396. }
  397. p.r.BlockHtml(out, data[:end])
  398. }
  399. return size
  400. }
  401. }
  402. return 0
  403. }
  404. func (p *parser) htmlFindTag(data []byte) (string, bool) {
  405. i := 0
  406. for isalnum(data[i]) {
  407. i++
  408. }
  409. key := string(data[:i])
  410. if _, ok := blockTags[key]; ok {
  411. return key, true
  412. }
  413. return "", false
  414. }
  415. func (p *parser) htmlFindEnd(tag string, data []byte) int {
  416. // assume data[0] == '<' && data[1] == '/' already tested
  417. // check if tag is a match
  418. closetag := []byte("</" + tag + ">")
  419. if !bytes.HasPrefix(data, closetag) {
  420. return 0
  421. }
  422. i := len(closetag)
  423. // check that the rest of the line is blank
  424. skip := 0
  425. if skip = p.isEmpty(data[i:]); skip == 0 {
  426. return 0
  427. }
  428. i += skip
  429. skip = 0
  430. if i >= len(data) {
  431. return i
  432. }
  433. if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
  434. return i
  435. }
  436. if skip = p.isEmpty(data[i:]); skip == 0 {
  437. // following line must be blank
  438. return 0
  439. }
  440. return i + skip
  441. }
  442. func (p *parser) isEmpty(data []byte) int {
  443. // it is okay to call isEmpty on an empty buffer
  444. if len(data) == 0 {
  445. return 0
  446. }
  447. var i int
  448. for i = 0; i < len(data) && data[i] != '\n'; i++ {
  449. if data[i] != ' ' && data[i] != '\t' {
  450. return 0
  451. }
  452. }
  453. return i + 1
  454. }
  455. func (p *parser) isHRule(data []byte) bool {
  456. i := 0
  457. // skip up to three spaces
  458. for i < 3 && data[i] == ' ' {
  459. i++
  460. }
  461. // look at the hrule char
  462. if data[i] != '*' && data[i] != '-' && data[i] != '_' {
  463. return false
  464. }
  465. c := data[i]
  466. // the whole line must be the char or whitespace
  467. n := 0
  468. for data[i] != '\n' {
  469. switch {
  470. case data[i] == c:
  471. n++
  472. case data[i] != ' ':
  473. return false
  474. }
  475. i++
  476. }
  477. return n >= 3
  478. }
  479. func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (skip int, marker string) {
  480. i, size := 0, 0
  481. skip = 0
  482. // skip up to three spaces
  483. for i < len(data) && i < 3 && data[i] == ' ' {
  484. i++
  485. }
  486. if i >= len(data) {
  487. return
  488. }
  489. // check for the marker characters: ~ or `
  490. if data[i] != '~' && data[i] != '`' {
  491. return
  492. }
  493. c := data[i]
  494. // the whole line must be the same char or whitespace
  495. for i < len(data) && data[i] == c {
  496. size++
  497. i++
  498. }
  499. if i >= len(data) {
  500. return
  501. }
  502. // the marker char must occur at least 3 times
  503. if size < 3 {
  504. return
  505. }
  506. marker = string(data[i-size : i])
  507. // if this is the end marker, it must match the beginning marker
  508. if oldmarker != "" && marker != oldmarker {
  509. return
  510. }
  511. if syntax != nil {
  512. syn := 0
  513. i = skipChar(data, i, ' ')
  514. if i >= len(data) {
  515. return
  516. }
  517. syntaxStart := i
  518. if data[i] == '{' {
  519. i++
  520. syntaxStart++
  521. for i < len(data) && data[i] != '}' && data[i] != '\n' {
  522. syn++
  523. i++
  524. }
  525. if i >= len(data) || data[i] != '}' {
  526. return
  527. }
  528. // strip all whitespace at the beginning and the end
  529. // of the {} block
  530. for syn > 0 && isspace(data[syntaxStart]) {
  531. syntaxStart++
  532. syn--
  533. }
  534. for syn > 0 && isspace(data[syntaxStart+syn-1]) {
  535. syn--
  536. }
  537. i++
  538. } else {
  539. for i < len(data) && !isspace(data[i]) {
  540. syn++
  541. i++
  542. }
  543. }
  544. language := string(data[syntaxStart : syntaxStart+syn])
  545. *syntax = &language
  546. }
  547. i = skipChar(data, i, ' ')
  548. if i >= len(data) || data[i] != '\n' {
  549. return
  550. }
  551. skip = i + 1
  552. return
  553. }
  554. func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int {
  555. var lang *string
  556. beg, marker := p.isFencedCode(data, &lang, "")
  557. if beg == 0 || beg >= len(data) {
  558. return 0
  559. }
  560. var work bytes.Buffer
  561. for {
  562. // safe to assume beg < len(data)
  563. // check for the end of the code block
  564. fenceEnd, _ := p.isFencedCode(data[beg:], nil, marker)
  565. if fenceEnd != 0 {
  566. beg += fenceEnd
  567. break
  568. }
  569. // copy the current line
  570. end := skipUntilChar(data, beg, '\n') + 1
  571. // did we reach the end of the buffer without a closing marker?
  572. if end >= len(data) {
  573. return 0
  574. }
  575. // verbatim copy to the working buffer
  576. if doRender {
  577. work.Write(data[beg:end])
  578. }
  579. beg = end
  580. }
  581. syntax := ""
  582. if lang != nil {
  583. syntax = *lang
  584. }
  585. if doRender {
  586. p.r.BlockCode(out, work.Bytes(), syntax)
  587. }
  588. return beg
  589. }
  590. func (p *parser) table(out *bytes.Buffer, data []byte) int {
  591. var header bytes.Buffer
  592. i, columns := p.tableHeader(&header, data)
  593. if i == 0 {
  594. return 0
  595. }
  596. var body bytes.Buffer
  597. for i < len(data) {
  598. pipes, rowStart := 0, i
  599. for ; data[i] != '\n'; i++ {
  600. if data[i] == '|' {
  601. pipes++
  602. }
  603. }
  604. if pipes == 0 {
  605. i = rowStart
  606. break
  607. }
  608. // include the newline in data sent to tableRow
  609. i++
  610. p.tableRow(&body, data[rowStart:i], columns, false)
  611. }
  612. p.r.Table(out, header.Bytes(), body.Bytes(), columns)
  613. return i
  614. }
  615. // check if the specified position is preceded by an odd number of backslashes
  616. func isBackslashEscaped(data []byte, i int) bool {
  617. backslashes := 0
  618. for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' {
  619. backslashes++
  620. }
  621. return backslashes&1 == 1
  622. }
  623. func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) {
  624. i := 0
  625. colCount := 1
  626. for i = 0; data[i] != '\n'; i++ {
  627. if data[i] == '|' && !isBackslashEscaped(data, i) {
  628. colCount++
  629. }
  630. }
  631. // doesn't look like a table header
  632. if colCount == 1 {
  633. return
  634. }
  635. // include the newline in the data sent to tableRow
  636. header := data[:i+1]
  637. // column count ignores pipes at beginning or end of line
  638. if data[0] == '|' {
  639. colCount--
  640. }
  641. if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) {
  642. colCount--
  643. }
  644. columns = make([]int, colCount)
  645. // move on to the header underline
  646. i++
  647. if i >= len(data) {
  648. return
  649. }
  650. if data[i] == '|' && !isBackslashEscaped(data, i) {
  651. i++
  652. }
  653. i = skipChar(data, i, ' ')
  654. // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3
  655. // and trailing | optional on last column
  656. col := 0
  657. for data[i] != '\n' {
  658. dashes := 0
  659. if data[i] == ':' {
  660. i++
  661. columns[col] |= TABLE_ALIGNMENT_LEFT
  662. dashes++
  663. }
  664. for data[i] == '-' {
  665. i++
  666. dashes++
  667. }
  668. if data[i] == ':' {
  669. i++
  670. columns[col] |= TABLE_ALIGNMENT_RIGHT
  671. dashes++
  672. }
  673. for data[i] == ' ' {
  674. i++
  675. }
  676. // end of column test is messy
  677. switch {
  678. case dashes < 3:
  679. // not a valid column
  680. return
  681. case data[i] == '|' && !isBackslashEscaped(data, i):
  682. // marker found, now skip past trailing whitespace
  683. col++
  684. i++
  685. for data[i] == ' ' {
  686. i++
  687. }
  688. // trailing junk found after last column
  689. if col >= colCount && data[i] != '\n' {
  690. return
  691. }
  692. case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount:
  693. // something else found where marker was required
  694. return
  695. case data[i] == '\n':
  696. // marker is optional for the last column
  697. col++
  698. default:
  699. // trailing junk found after last column
  700. return
  701. }
  702. }
  703. if col != colCount {
  704. return
  705. }
  706. p.tableRow(out, header, columns, true)
  707. size = i + 1
  708. return
  709. }
  710. func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) {
  711. i, col := 0, 0
  712. var rowWork bytes.Buffer
  713. if data[i] == '|' && !isBackslashEscaped(data, i) {
  714. i++
  715. }
  716. for col = 0; col < len(columns) && i < len(data); col++ {
  717. for data[i] == ' ' {
  718. i++
  719. }
  720. cellStart := i
  721. for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' {
  722. i++
  723. }
  724. cellEnd := i
  725. // skip the end-of-cell marker, possibly taking us past end of buffer
  726. i++
  727. for cellEnd > cellStart && data[cellEnd-1] == ' ' {
  728. cellEnd--
  729. }
  730. var cellWork bytes.Buffer
  731. p.inline(&cellWork, data[cellStart:cellEnd])
  732. if header {
  733. p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col])
  734. } else {
  735. p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col])
  736. }
  737. }
  738. // pad it out with empty columns to get the right number
  739. for ; col < len(columns); col++ {
  740. if header {
  741. p.r.TableHeaderCell(&rowWork, nil, columns[col])
  742. } else {
  743. p.r.TableCell(&rowWork, nil, columns[col])
  744. }
  745. }
  746. // silently ignore rows with too many cells
  747. p.r.TableRow(out, rowWork.Bytes())
  748. }
  749. // returns blockquote prefix length
  750. func (p *parser) quotePrefix(data []byte) int {
  751. i := 0
  752. for i < 3 && data[i] == ' ' {
  753. i++
  754. }
  755. if data[i] == '>' {
  756. if data[i+1] == ' ' {
  757. return i + 2
  758. }
  759. return i + 1
  760. }
  761. return 0
  762. }
  763. // blockquote ends with at least one blank line
  764. // followed by something without a blockquote prefix
  765. func (p *parser) terminateBlockquote(data []byte, beg, end int) bool {
  766. if p.isEmpty(data[beg:]) <= 0 {
  767. return false
  768. }
  769. if end >= len(data) {
  770. return true
  771. }
  772. return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0
  773. }
  774. // parse a blockquote fragment
  775. func (p *parser) quote(out *bytes.Buffer, data []byte) int {
  776. var raw bytes.Buffer
  777. beg, end := 0, 0
  778. for beg < len(data) {
  779. end = beg
  780. // Step over whole lines, collecting them. While doing that, check for
  781. // fenced code and if one's found, incorporate it altogether,
  782. // irregardless of any contents inside it
  783. for data[end] != '\n' {
  784. if p.flags&EXTENSION_FENCED_CODE != 0 {
  785. if i := p.fencedCode(out, data[end:], false); i > 0 {
  786. // -1 to compensate for the extra end++ after the loop:
  787. end += i - 1
  788. break
  789. }
  790. }
  791. end++
  792. }
  793. end++
  794. if pre := p.quotePrefix(data[beg:]); pre > 0 {
  795. // skip the prefix
  796. beg += pre
  797. } else if p.terminateBlockquote(data, beg, end) {
  798. break
  799. }
  800. // this line is part of the blockquote
  801. raw.Write(data[beg:end])
  802. beg = end
  803. }
  804. var cooked bytes.Buffer
  805. p.block(&cooked, raw.Bytes())
  806. p.r.BlockQuote(out, cooked.Bytes())
  807. return end
  808. }
  809. // returns prefix length for block code
  810. func (p *parser) codePrefix(data []byte) int {
  811. if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' {
  812. return 4
  813. }
  814. return 0
  815. }
  816. func (p *parser) code(out *bytes.Buffer, data []byte) int {
  817. var work bytes.Buffer
  818. i := 0
  819. for i < len(data) {
  820. beg := i
  821. for data[i] != '\n' {
  822. i++
  823. }
  824. i++
  825. blankline := p.isEmpty(data[beg:i]) > 0
  826. if pre := p.codePrefix(data[beg:i]); pre > 0 {
  827. beg += pre
  828. } else if !blankline {
  829. // non-empty, non-prefixed line breaks the pre
  830. i = beg
  831. break
  832. }
  833. // verbatim copy to the working buffeu
  834. if blankline {
  835. work.WriteByte('\n')
  836. } else {
  837. work.Write(data[beg:i])
  838. }
  839. }
  840. // trim all the \n off the end of work
  841. workbytes := work.Bytes()
  842. eol := len(workbytes)
  843. for eol > 0 && workbytes[eol-1] == '\n' {
  844. eol--
  845. }
  846. if eol != len(workbytes) {
  847. work.Truncate(eol)
  848. }
  849. work.WriteByte('\n')
  850. p.r.BlockCode(out, work.Bytes(), "")
  851. return i
  852. }
  853. // returns unordered list item prefix
  854. func (p *parser) uliPrefix(data []byte) int {
  855. i := 0
  856. // start with up to 3 spaces
  857. for i < 3 && data[i] == ' ' {
  858. i++
  859. }
  860. // need a *, +, or - followed by a space
  861. if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
  862. data[i+1] != ' ' {
  863. return 0
  864. }
  865. return i + 2
  866. }
  867. // returns ordered list item prefix
  868. func (p *parser) oliPrefix(data []byte) int {
  869. i := 0
  870. // start with up to 3 spaces
  871. for i < 3 && data[i] == ' ' {
  872. i++
  873. }
  874. // count the digits
  875. start := i
  876. for data[i] >= '0' && data[i] <= '9' {
  877. i++
  878. }
  879. // we need >= 1 digits followed by a dot and a space
  880. if start == i || data[i] != '.' || data[i+1] != ' ' {
  881. return 0
  882. }
  883. return i + 2
  884. }
  885. // returns definition list item prefix
  886. func (p *parser) dliPrefix(data []byte) int {
  887. i := 0
  888. // need a : followed by a spaces
  889. if data[i] != ':' || data[i+1] != ' ' {
  890. return 0
  891. }
  892. for data[i] == ' ' {
  893. i++
  894. }
  895. return i + 2
  896. }
  897. // parse ordered or unordered list block
  898. func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int {
  899. i := 0
  900. flags |= LIST_ITEM_BEGINNING_OF_LIST
  901. work := func() bool {
  902. for i < len(data) {
  903. skip := p.listItem(out, data[i:], &flags)
  904. i += skip
  905. if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 {
  906. break
  907. }
  908. flags &= ^LIST_ITEM_BEGINNING_OF_LIST
  909. }
  910. return true
  911. }
  912. p.r.List(out, work, flags)
  913. return i
  914. }
  915. // Parse a single list item.
  916. // Assumes initial prefix is already removed if this is a sublist.
  917. func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int {
  918. // keep track of the indentation of the first line
  919. itemIndent := 0
  920. for itemIndent < 3 && data[itemIndent] == ' ' {
  921. itemIndent++
  922. }
  923. i := p.uliPrefix(data)
  924. if i == 0 {
  925. i = p.oliPrefix(data)
  926. }
  927. if i == 0 {
  928. i = p.dliPrefix(data)
  929. // reset definition term flag
  930. if i > 0 {
  931. *flags &= ^LIST_TYPE_TERM
  932. }
  933. }
  934. if i == 0 {
  935. // if in defnition list, set term flag and continue
  936. if *flags&LIST_TYPE_DEFINITION != 0 {
  937. *flags |= LIST_TYPE_TERM
  938. } else {
  939. return 0
  940. }
  941. }
  942. // skip leading whitespace on first line
  943. for data[i] == ' ' {
  944. i++
  945. }
  946. // find the end of the line
  947. line := i
  948. for i > 0 && data[i-1] != '\n' {
  949. i++
  950. }
  951. // get working buffer
  952. var raw bytes.Buffer
  953. // put the first line into the working buffer
  954. raw.Write(data[line:i])
  955. line = i
  956. // process the following lines
  957. containsBlankLine := false
  958. sublist := 0
  959. gatherlines:
  960. for line < len(data) {
  961. i++
  962. // find the end of this line
  963. for data[i-1] != '\n' {
  964. i++
  965. }
  966. // if it is an empty line, guess that it is part of this item
  967. // and move on to the next line
  968. if p.isEmpty(data[line:i]) > 0 {
  969. containsBlankLine = true
  970. line = i
  971. continue
  972. }
  973. // calculate the indentation
  974. indent := 0
  975. for indent < 4 && line+indent < i && data[line+indent] == ' ' {
  976. indent++
  977. }
  978. chunk := data[line+indent : i]
  979. // evaluate how this line fits in
  980. switch {
  981. // is this a nested list item?
  982. case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) ||
  983. p.oliPrefix(chunk) > 0 ||
  984. p.dliPrefix(chunk) > 0:
  985. if containsBlankLine {
  986. *flags |= LIST_ITEM_CONTAINS_BLOCK
  987. }
  988. // to be a nested list, it must be indented more
  989. // if not, it is the next item in the same list
  990. if indent <= itemIndent {
  991. break gatherlines
  992. }
  993. // is this the first item in the nested list?
  994. if sublist == 0 {
  995. sublist = raw.Len()
  996. }
  997. // is this a nested prefix header?
  998. case p.isPrefixHeader(chunk):
  999. // if the header is not indented, it is not nested in the list
  1000. // and thus ends the list
  1001. if containsBlankLine && indent < 4 {
  1002. *flags |= LIST_ITEM_END_OF_LIST
  1003. break gatherlines
  1004. }
  1005. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1006. // anything following an empty line is only part
  1007. // of this item if it is indented 4 spaces
  1008. // (regardless of the indentation of the beginning of the item)
  1009. case containsBlankLine && indent < 4:
  1010. if *flags&LIST_TYPE_DEFINITION != 0 && i < len(data)-1 {
  1011. // is the next item still a part of this list?
  1012. next := i
  1013. for data[next] != '\n' {
  1014. next++
  1015. }
  1016. for next < len(data)-1 && data[next] == '\n' {
  1017. next++
  1018. }
  1019. if i < len(data)-1 && data[i] != ':' && data[next] != ':' {
  1020. *flags |= LIST_ITEM_END_OF_LIST
  1021. }
  1022. } else {
  1023. *flags |= LIST_ITEM_END_OF_LIST
  1024. }
  1025. break gatherlines
  1026. // a blank line means this should be parsed as a block
  1027. case containsBlankLine:
  1028. raw.WriteByte('\n')
  1029. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1030. }
  1031. // if this line was preceeded by one or more blanks,
  1032. // re-introduce the blank into the buffer
  1033. if containsBlankLine {
  1034. containsBlankLine = false
  1035. raw.WriteByte('\n')
  1036. }
  1037. // add the line into the working buffer without prefix
  1038. raw.Write(data[line+indent : i])
  1039. line = i
  1040. }
  1041. rawBytes := raw.Bytes()
  1042. // render the contents of the list item
  1043. var cooked bytes.Buffer
  1044. if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 && *flags&LIST_TYPE_TERM == 0 {
  1045. // intermediate render of block item, except for definition term
  1046. if sublist > 0 {
  1047. p.block(&cooked, rawBytes[:sublist])
  1048. p.block(&cooked, rawBytes[sublist:])
  1049. } else {
  1050. p.block(&cooked, rawBytes)
  1051. }
  1052. } else {
  1053. // intermediate render of inline item
  1054. if sublist > 0 {
  1055. p.inline(&cooked, rawBytes[:sublist])
  1056. p.block(&cooked, rawBytes[sublist:])
  1057. } else {
  1058. p.inline(&cooked, rawBytes)
  1059. }
  1060. }
  1061. // render the actual list item
  1062. cookedBytes := cooked.Bytes()
  1063. parsedEnd := len(cookedBytes)
  1064. // strip trailing newlines
  1065. for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' {
  1066. parsedEnd--
  1067. }
  1068. p.r.ListItem(out, cookedBytes[:parsedEnd], *flags)
  1069. return line
  1070. }
  1071. // render a single paragraph that has already been parsed out
  1072. func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) {
  1073. if len(data) == 0 {
  1074. return
  1075. }
  1076. // trim leading spaces
  1077. beg := 0
  1078. for data[beg] == ' ' {
  1079. beg++
  1080. }
  1081. // trim trailing newline
  1082. end := len(data) - 1
  1083. // trim trailing spaces
  1084. for end > beg && data[end-1] == ' ' {
  1085. end--
  1086. }
  1087. work := func() bool {
  1088. p.inline(out, data[beg:end])
  1089. return true
  1090. }
  1091. p.r.Paragraph(out, work)
  1092. }
  1093. func (p *parser) paragraph(out *bytes.Buffer, data []byte) int {
  1094. // prev: index of 1st char of previous line
  1095. // line: index of 1st char of current line
  1096. // i: index of cursor/end of current line
  1097. var prev, line, i int
  1098. // keep going until we find something to mark the end of the paragraph
  1099. for i < len(data) {
  1100. // mark the beginning of the current line
  1101. prev = line
  1102. current := data[i:]
  1103. line = i
  1104. // did we find a blank line marking the end of the paragraph?
  1105. if n := p.isEmpty(current); n > 0 {
  1106. // did this blank line followed by a definition list item?
  1107. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  1108. if i < len(data)-1 && data[i+1] == ':' {
  1109. return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
  1110. }
  1111. }
  1112. p.renderParagraph(out, data[:i])
  1113. return i + n
  1114. }
  1115. // an underline under some text marks a header, so our paragraph ended on prev line
  1116. if i > 0 {
  1117. if level := p.isUnderlinedHeader(current); level > 0 {
  1118. // render the paragraph
  1119. p.renderParagraph(out, data[:prev])
  1120. // ignore leading and trailing whitespace
  1121. eol := i - 1
  1122. for prev < eol && data[prev] == ' ' {
  1123. prev++
  1124. }
  1125. for eol > prev && data[eol-1] == ' ' {
  1126. eol--
  1127. }
  1128. // render the header
  1129. // this ugly double closure avoids forcing variables onto the heap
  1130. work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool {
  1131. return func() bool {
  1132. pp.inline(o, d)
  1133. return true
  1134. }
  1135. }(out, p, data[prev:eol])
  1136. id := ""
  1137. if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
  1138. id = sanitized_anchor_name.Create(string(data[prev:eol]))
  1139. }
  1140. p.r.Header(out, work, level, id)
  1141. // find the end of the underline
  1142. for data[i] != '\n' {
  1143. i++
  1144. }
  1145. return i
  1146. }
  1147. }
  1148. // if the next line starts a block of HTML, then the paragraph ends here
  1149. if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
  1150. if data[i] == '<' && p.html(out, current, false) > 0 {
  1151. // rewind to before the HTML block
  1152. p.renderParagraph(out, data[:i])
  1153. return i
  1154. }
  1155. }
  1156. // if there's a prefixed header or a horizontal rule after this, paragraph is over
  1157. if p.isPrefixHeader(current) || p.isHRule(current) {
  1158. p.renderParagraph(out, data[:i])
  1159. return i
  1160. }
  1161. // if there's a fenced code block, paragraph is over
  1162. if p.flags&EXTENSION_FENCED_CODE != 0 {
  1163. if p.fencedCode(out, current, false) > 0 {
  1164. p.renderParagraph(out, data[:i])
  1165. return i
  1166. }
  1167. }
  1168. // if there's a definition list item, prev line is a definition term
  1169. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  1170. if p.dliPrefix(current) != 0 {
  1171. return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
  1172. }
  1173. }
  1174. // if there's a list after this, paragraph is over
  1175. if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 {
  1176. if p.uliPrefix(current) != 0 ||
  1177. p.oliPrefix(current) != 0 ||
  1178. p.quotePrefix(current) != 0 ||
  1179. p.codePrefix(current) != 0 {
  1180. p.renderParagraph(out, data[:i])
  1181. return i
  1182. }
  1183. }
  1184. // otherwise, scan to the beginning of the next line
  1185. for data[i] != '\n' {
  1186. i++
  1187. }
  1188. i++
  1189. }
  1190. p.renderParagraph(out, data[:i])
  1191. return i
  1192. }