block.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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.fencedCodeBlock(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 (*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 (*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. // isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data,
  497. // and returns the end index if so, or 0 otherwise. It also returns the marker found.
  498. // If syntax is not nil, it gets set to the syntax specified in the fence line.
  499. // A final newline is mandatory to recognize the fence line, unless newlineOptional is true.
  500. func isFenceLine(data []byte, syntax *string, oldmarker string, newlineOptional bool) (end int, marker string) {
  501. i, size := 0, 0
  502. // skip up to three spaces
  503. for i < len(data) && i < 3 && data[i] == ' ' {
  504. i++
  505. }
  506. // check for the marker characters: ~ or `
  507. if i >= len(data) {
  508. return 0, ""
  509. }
  510. if data[i] != '~' && data[i] != '`' {
  511. return 0, ""
  512. }
  513. c := data[i]
  514. // the whole line must be the same char or whitespace
  515. for i < len(data) && data[i] == c {
  516. size++
  517. i++
  518. }
  519. // the marker char must occur at least 3 times
  520. if size < 3 {
  521. return 0, ""
  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 0, ""
  527. }
  528. // TODO(shurcooL): It's probably a good idea to simplify the 2 code paths here
  529. // into one, always get the syntax, and discard it if the caller doesn't care.
  530. if syntax != nil {
  531. syn := 0
  532. i = skipChar(data, i, ' ')
  533. if i >= len(data) {
  534. if newlineOptional && i == len(data) {
  535. return i, marker
  536. }
  537. return 0, ""
  538. }
  539. syntaxStart := i
  540. if data[i] == '{' {
  541. i++
  542. syntaxStart++
  543. for i < len(data) && data[i] != '}' && data[i] != '\n' {
  544. syn++
  545. i++
  546. }
  547. if i >= len(data) || data[i] != '}' {
  548. return 0, ""
  549. }
  550. // strip all whitespace at the beginning and the end
  551. // of the {} block
  552. for syn > 0 && isspace(data[syntaxStart]) {
  553. syntaxStart++
  554. syn--
  555. }
  556. for syn > 0 && isspace(data[syntaxStart+syn-1]) {
  557. syn--
  558. }
  559. i++
  560. } else {
  561. for i < len(data) && !isspace(data[i]) {
  562. syn++
  563. i++
  564. }
  565. }
  566. *syntax = string(data[syntaxStart : syntaxStart+syn])
  567. }
  568. i = skipChar(data, i, ' ')
  569. if i >= len(data) || data[i] != '\n' {
  570. if newlineOptional && i == len(data) {
  571. return i, marker
  572. }
  573. return 0, ""
  574. }
  575. return i + 1, marker // Take newline into account.
  576. }
  577. // fencedCodeBlock returns the end index if data contains a fenced code block at the beginning,
  578. // or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects.
  579. // If doRender is true, a final newline is mandatory to recognize the fenced code block.
  580. func (p *parser) fencedCodeBlock(out *bytes.Buffer, data []byte, doRender bool) int {
  581. var syntax string
  582. beg, marker := isFenceLine(data, &syntax, "", false)
  583. if beg == 0 || beg >= len(data) {
  584. return 0
  585. }
  586. var work bytes.Buffer
  587. for {
  588. // safe to assume beg < len(data)
  589. // check for the end of the code block
  590. newlineOptional := !doRender
  591. fenceEnd, _ := isFenceLine(data[beg:], nil, marker, newlineOptional)
  592. if fenceEnd != 0 {
  593. beg += fenceEnd
  594. break
  595. }
  596. // copy the current line
  597. end := skipUntilChar(data, beg, '\n') + 1
  598. // did we reach the end of the buffer without a closing marker?
  599. if end >= len(data) {
  600. return 0
  601. }
  602. // verbatim copy to the working buffer
  603. if doRender {
  604. work.Write(data[beg:end])
  605. }
  606. beg = end
  607. }
  608. if doRender {
  609. p.r.BlockCode(out, work.Bytes(), syntax)
  610. }
  611. return beg
  612. }
  613. func (p *parser) table(out *bytes.Buffer, data []byte) int {
  614. var header bytes.Buffer
  615. i, columns := p.tableHeader(&header, data)
  616. if i == 0 {
  617. return 0
  618. }
  619. var body bytes.Buffer
  620. for i < len(data) {
  621. pipes, rowStart := 0, i
  622. for ; data[i] != '\n'; i++ {
  623. if data[i] == '|' {
  624. pipes++
  625. }
  626. }
  627. if pipes == 0 {
  628. i = rowStart
  629. break
  630. }
  631. // include the newline in data sent to tableRow
  632. i++
  633. p.tableRow(&body, data[rowStart:i], columns, false)
  634. }
  635. p.r.Table(out, header.Bytes(), body.Bytes(), columns)
  636. return i
  637. }
  638. // check if the specified position is preceded by an odd number of backslashes
  639. func isBackslashEscaped(data []byte, i int) bool {
  640. backslashes := 0
  641. for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' {
  642. backslashes++
  643. }
  644. return backslashes&1 == 1
  645. }
  646. func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) {
  647. i := 0
  648. colCount := 1
  649. for i = 0; data[i] != '\n'; i++ {
  650. if data[i] == '|' && !isBackslashEscaped(data, i) {
  651. colCount++
  652. }
  653. }
  654. // doesn't look like a table header
  655. if colCount == 1 {
  656. return
  657. }
  658. // include the newline in the data sent to tableRow
  659. header := data[:i+1]
  660. // column count ignores pipes at beginning or end of line
  661. if data[0] == '|' {
  662. colCount--
  663. }
  664. if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) {
  665. colCount--
  666. }
  667. columns = make([]int, colCount)
  668. // move on to the header underline
  669. i++
  670. if i >= len(data) {
  671. return
  672. }
  673. if data[i] == '|' && !isBackslashEscaped(data, i) {
  674. i++
  675. }
  676. i = skipChar(data, i, ' ')
  677. // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3
  678. // and trailing | optional on last column
  679. col := 0
  680. for data[i] != '\n' {
  681. dashes := 0
  682. if data[i] == ':' {
  683. i++
  684. columns[col] |= TABLE_ALIGNMENT_LEFT
  685. dashes++
  686. }
  687. for data[i] == '-' {
  688. i++
  689. dashes++
  690. }
  691. if data[i] == ':' {
  692. i++
  693. columns[col] |= TABLE_ALIGNMENT_RIGHT
  694. dashes++
  695. }
  696. for data[i] == ' ' {
  697. i++
  698. }
  699. // end of column test is messy
  700. switch {
  701. case dashes < 3:
  702. // not a valid column
  703. return
  704. case data[i] == '|' && !isBackslashEscaped(data, i):
  705. // marker found, now skip past trailing whitespace
  706. col++
  707. i++
  708. for data[i] == ' ' {
  709. i++
  710. }
  711. // trailing junk found after last column
  712. if col >= colCount && data[i] != '\n' {
  713. return
  714. }
  715. case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount:
  716. // something else found where marker was required
  717. return
  718. case data[i] == '\n':
  719. // marker is optional for the last column
  720. col++
  721. default:
  722. // trailing junk found after last column
  723. return
  724. }
  725. }
  726. if col != colCount {
  727. return
  728. }
  729. p.tableRow(out, header, columns, true)
  730. size = i + 1
  731. return
  732. }
  733. func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) {
  734. i, col := 0, 0
  735. var rowWork bytes.Buffer
  736. if data[i] == '|' && !isBackslashEscaped(data, i) {
  737. i++
  738. }
  739. for col = 0; col < len(columns) && i < len(data); col++ {
  740. for data[i] == ' ' {
  741. i++
  742. }
  743. cellStart := i
  744. for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' {
  745. i++
  746. }
  747. cellEnd := i
  748. // skip the end-of-cell marker, possibly taking us past end of buffer
  749. i++
  750. for cellEnd > cellStart && data[cellEnd-1] == ' ' {
  751. cellEnd--
  752. }
  753. var cellWork bytes.Buffer
  754. p.inline(&cellWork, data[cellStart:cellEnd])
  755. if header {
  756. p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col])
  757. } else {
  758. p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col])
  759. }
  760. }
  761. // pad it out with empty columns to get the right number
  762. for ; col < len(columns); col++ {
  763. if header {
  764. p.r.TableHeaderCell(&rowWork, nil, columns[col])
  765. } else {
  766. p.r.TableCell(&rowWork, nil, columns[col])
  767. }
  768. }
  769. // silently ignore rows with too many cells
  770. p.r.TableRow(out, rowWork.Bytes())
  771. }
  772. // returns blockquote prefix length
  773. func (p *parser) quotePrefix(data []byte) int {
  774. i := 0
  775. for i < 3 && data[i] == ' ' {
  776. i++
  777. }
  778. if data[i] == '>' {
  779. if data[i+1] == ' ' {
  780. return i + 2
  781. }
  782. return i + 1
  783. }
  784. return 0
  785. }
  786. // blockquote ends with at least one blank line
  787. // followed by something without a blockquote prefix
  788. func (p *parser) terminateBlockquote(data []byte, beg, end int) bool {
  789. if p.isEmpty(data[beg:]) <= 0 {
  790. return false
  791. }
  792. if end >= len(data) {
  793. return true
  794. }
  795. return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0
  796. }
  797. // parse a blockquote fragment
  798. func (p *parser) quote(out *bytes.Buffer, data []byte) int {
  799. var raw bytes.Buffer
  800. beg, end := 0, 0
  801. for beg < len(data) {
  802. end = beg
  803. // Step over whole lines, collecting them. While doing that, check for
  804. // fenced code and if one's found, incorporate it altogether,
  805. // irregardless of any contents inside it
  806. for data[end] != '\n' {
  807. if p.flags&EXTENSION_FENCED_CODE != 0 {
  808. if i := p.fencedCodeBlock(out, data[end:], false); i > 0 {
  809. // -1 to compensate for the extra end++ after the loop:
  810. end += i - 1
  811. break
  812. }
  813. }
  814. end++
  815. }
  816. end++
  817. if pre := p.quotePrefix(data[beg:]); pre > 0 {
  818. // skip the prefix
  819. beg += pre
  820. } else if p.terminateBlockquote(data, beg, end) {
  821. break
  822. }
  823. // this line is part of the blockquote
  824. raw.Write(data[beg:end])
  825. beg = end
  826. }
  827. var cooked bytes.Buffer
  828. p.block(&cooked, raw.Bytes())
  829. p.r.BlockQuote(out, cooked.Bytes())
  830. return end
  831. }
  832. // returns prefix length for block code
  833. func (p *parser) codePrefix(data []byte) int {
  834. if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' {
  835. return 4
  836. }
  837. return 0
  838. }
  839. func (p *parser) code(out *bytes.Buffer, data []byte) int {
  840. var work bytes.Buffer
  841. i := 0
  842. for i < len(data) {
  843. beg := i
  844. for data[i] != '\n' {
  845. i++
  846. }
  847. i++
  848. blankline := p.isEmpty(data[beg:i]) > 0
  849. if pre := p.codePrefix(data[beg:i]); pre > 0 {
  850. beg += pre
  851. } else if !blankline {
  852. // non-empty, non-prefixed line breaks the pre
  853. i = beg
  854. break
  855. }
  856. // verbatim copy to the working buffeu
  857. if blankline {
  858. work.WriteByte('\n')
  859. } else {
  860. work.Write(data[beg:i])
  861. }
  862. }
  863. // trim all the \n off the end of work
  864. workbytes := work.Bytes()
  865. eol := len(workbytes)
  866. for eol > 0 && workbytes[eol-1] == '\n' {
  867. eol--
  868. }
  869. if eol != len(workbytes) {
  870. work.Truncate(eol)
  871. }
  872. work.WriteByte('\n')
  873. p.r.BlockCode(out, work.Bytes(), "")
  874. return i
  875. }
  876. // returns unordered list item prefix
  877. func (p *parser) uliPrefix(data []byte) int {
  878. i := 0
  879. // start with up to 3 spaces
  880. for i < 3 && data[i] == ' ' {
  881. i++
  882. }
  883. // need a *, +, or - followed by a space
  884. if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
  885. data[i+1] != ' ' {
  886. return 0
  887. }
  888. return i + 2
  889. }
  890. // returns ordered list item prefix
  891. func (p *parser) oliPrefix(data []byte) int {
  892. i := 0
  893. // start with up to 3 spaces
  894. for i < 3 && data[i] == ' ' {
  895. i++
  896. }
  897. // count the digits
  898. start := i
  899. for data[i] >= '0' && data[i] <= '9' {
  900. i++
  901. }
  902. // we need >= 1 digits followed by a dot and a space
  903. if start == i || data[i] != '.' || data[i+1] != ' ' {
  904. return 0
  905. }
  906. return i + 2
  907. }
  908. // returns definition list item prefix
  909. func (p *parser) dliPrefix(data []byte) int {
  910. i := 0
  911. // need a : followed by a spaces
  912. if data[i] != ':' || data[i+1] != ' ' {
  913. return 0
  914. }
  915. for data[i] == ' ' {
  916. i++
  917. }
  918. return i + 2
  919. }
  920. // parse ordered or unordered list block
  921. func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int {
  922. i := 0
  923. flags |= LIST_ITEM_BEGINNING_OF_LIST
  924. work := func() bool {
  925. for i < len(data) {
  926. skip := p.listItem(out, data[i:], &flags)
  927. i += skip
  928. if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 {
  929. break
  930. }
  931. flags &= ^LIST_ITEM_BEGINNING_OF_LIST
  932. }
  933. return true
  934. }
  935. p.r.List(out, work, flags)
  936. return i
  937. }
  938. // Parse a single list item.
  939. // Assumes initial prefix is already removed if this is a sublist.
  940. func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int {
  941. // keep track of the indentation of the first line
  942. itemIndent := 0
  943. for itemIndent < 3 && data[itemIndent] == ' ' {
  944. itemIndent++
  945. }
  946. i := p.uliPrefix(data)
  947. if i == 0 {
  948. i = p.oliPrefix(data)
  949. }
  950. if i == 0 {
  951. i = p.dliPrefix(data)
  952. // reset definition term flag
  953. if i > 0 {
  954. *flags &= ^LIST_TYPE_TERM
  955. }
  956. }
  957. if i == 0 {
  958. // if in defnition list, set term flag and continue
  959. if *flags&LIST_TYPE_DEFINITION != 0 {
  960. *flags |= LIST_TYPE_TERM
  961. } else {
  962. return 0
  963. }
  964. }
  965. // skip leading whitespace on first line
  966. for data[i] == ' ' {
  967. i++
  968. }
  969. // find the end of the line
  970. line := i
  971. for i > 0 && data[i-1] != '\n' {
  972. i++
  973. }
  974. // get working buffer
  975. var raw bytes.Buffer
  976. // put the first line into the working buffer
  977. raw.Write(data[line:i])
  978. line = i
  979. // process the following lines
  980. containsBlankLine := false
  981. sublist := 0
  982. gatherlines:
  983. for line < len(data) {
  984. i++
  985. // find the end of this line
  986. for data[i-1] != '\n' {
  987. i++
  988. }
  989. // if it is an empty line, guess that it is part of this item
  990. // and move on to the next line
  991. if p.isEmpty(data[line:i]) > 0 {
  992. containsBlankLine = true
  993. raw.Write(data[line:i])
  994. line = i
  995. continue
  996. }
  997. // calculate the indentation
  998. indent := 0
  999. for indent < 4 && line+indent < i && data[line+indent] == ' ' {
  1000. indent++
  1001. }
  1002. chunk := data[line+indent : i]
  1003. // evaluate how this line fits in
  1004. switch {
  1005. // is this a nested list item?
  1006. case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) ||
  1007. p.oliPrefix(chunk) > 0 ||
  1008. p.dliPrefix(chunk) > 0:
  1009. if containsBlankLine {
  1010. // end the list if the type changed after a blank line
  1011. if indent <= itemIndent &&
  1012. ((*flags&LIST_TYPE_ORDERED != 0 && p.uliPrefix(chunk) > 0) ||
  1013. (*flags&LIST_TYPE_ORDERED == 0 && p.oliPrefix(chunk) > 0)) {
  1014. *flags |= LIST_ITEM_END_OF_LIST
  1015. break gatherlines
  1016. }
  1017. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1018. }
  1019. // to be a nested list, it must be indented more
  1020. // if not, it is the next item in the same list
  1021. if indent <= itemIndent {
  1022. break gatherlines
  1023. }
  1024. // is this the first item in the nested list?
  1025. if sublist == 0 {
  1026. sublist = raw.Len()
  1027. }
  1028. // is this a nested prefix header?
  1029. case p.isPrefixHeader(chunk):
  1030. // if the header is not indented, it is not nested in the list
  1031. // and thus ends the list
  1032. if containsBlankLine && indent < 4 {
  1033. *flags |= LIST_ITEM_END_OF_LIST
  1034. break gatherlines
  1035. }
  1036. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1037. // anything following an empty line is only part
  1038. // of this item if it is indented 4 spaces
  1039. // (regardless of the indentation of the beginning of the item)
  1040. case containsBlankLine && indent < 4:
  1041. if *flags&LIST_TYPE_DEFINITION != 0 && i < len(data)-1 {
  1042. // is the next item still a part of this list?
  1043. next := i
  1044. for data[next] != '\n' {
  1045. next++
  1046. }
  1047. for next < len(data)-1 && data[next] == '\n' {
  1048. next++
  1049. }
  1050. if i < len(data)-1 && data[i] != ':' && data[next] != ':' {
  1051. *flags |= LIST_ITEM_END_OF_LIST
  1052. }
  1053. } else {
  1054. *flags |= LIST_ITEM_END_OF_LIST
  1055. }
  1056. break gatherlines
  1057. // a blank line means this should be parsed as a block
  1058. case containsBlankLine:
  1059. *flags |= LIST_ITEM_CONTAINS_BLOCK
  1060. }
  1061. containsBlankLine = false
  1062. // add the line into the working buffer without prefix
  1063. raw.Write(data[line+indent : i])
  1064. line = i
  1065. }
  1066. // If reached end of data, the Renderer.ListItem call we're going to make below
  1067. // is definitely the last in the list.
  1068. if line >= len(data) {
  1069. *flags |= LIST_ITEM_END_OF_LIST
  1070. }
  1071. rawBytes := raw.Bytes()
  1072. // render the contents of the list item
  1073. var cooked bytes.Buffer
  1074. if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 && *flags&LIST_TYPE_TERM == 0 {
  1075. // intermediate render of block item, except for definition term
  1076. if sublist > 0 {
  1077. p.block(&cooked, rawBytes[:sublist])
  1078. p.block(&cooked, rawBytes[sublist:])
  1079. } else {
  1080. p.block(&cooked, rawBytes)
  1081. }
  1082. } else {
  1083. // intermediate render of inline item
  1084. if sublist > 0 {
  1085. p.inline(&cooked, rawBytes[:sublist])
  1086. p.block(&cooked, rawBytes[sublist:])
  1087. } else {
  1088. p.inline(&cooked, rawBytes)
  1089. }
  1090. }
  1091. // render the actual list item
  1092. cookedBytes := cooked.Bytes()
  1093. parsedEnd := len(cookedBytes)
  1094. // strip trailing newlines
  1095. for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' {
  1096. parsedEnd--
  1097. }
  1098. p.r.ListItem(out, cookedBytes[:parsedEnd], *flags)
  1099. return line
  1100. }
  1101. // render a single paragraph that has already been parsed out
  1102. func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) {
  1103. if len(data) == 0 {
  1104. return
  1105. }
  1106. // trim leading spaces
  1107. beg := 0
  1108. for data[beg] == ' ' {
  1109. beg++
  1110. }
  1111. // trim trailing newline
  1112. end := len(data) - 1
  1113. // trim trailing spaces
  1114. for end > beg && data[end-1] == ' ' {
  1115. end--
  1116. }
  1117. work := func() bool {
  1118. p.inline(out, data[beg:end])
  1119. return true
  1120. }
  1121. p.r.Paragraph(out, work)
  1122. }
  1123. func (p *parser) paragraph(out *bytes.Buffer, data []byte) int {
  1124. // prev: index of 1st char of previous line
  1125. // line: index of 1st char of current line
  1126. // i: index of cursor/end of current line
  1127. var prev, line, i int
  1128. // keep going until we find something to mark the end of the paragraph
  1129. for i < len(data) {
  1130. // mark the beginning of the current line
  1131. prev = line
  1132. current := data[i:]
  1133. line = i
  1134. // did we find a blank line marking the end of the paragraph?
  1135. if n := p.isEmpty(current); n > 0 {
  1136. // did this blank line followed by a definition list item?
  1137. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  1138. if i < len(data)-1 && data[i+1] == ':' {
  1139. return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
  1140. }
  1141. }
  1142. p.renderParagraph(out, data[:i])
  1143. return i + n
  1144. }
  1145. // an underline under some text marks a header, so our paragraph ended on prev line
  1146. if i > 0 {
  1147. if level := p.isUnderlinedHeader(current); level > 0 {
  1148. // render the paragraph
  1149. p.renderParagraph(out, data[:prev])
  1150. // ignore leading and trailing whitespace
  1151. eol := i - 1
  1152. for prev < eol && data[prev] == ' ' {
  1153. prev++
  1154. }
  1155. for eol > prev && data[eol-1] == ' ' {
  1156. eol--
  1157. }
  1158. // render the header
  1159. // this ugly double closure avoids forcing variables onto the heap
  1160. work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool {
  1161. return func() bool {
  1162. pp.inline(o, d)
  1163. return true
  1164. }
  1165. }(out, p, data[prev:eol])
  1166. id := ""
  1167. if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
  1168. id = sanitized_anchor_name.Create(string(data[prev:eol]))
  1169. }
  1170. p.r.Header(out, work, level, id)
  1171. // find the end of the underline
  1172. for data[i] != '\n' {
  1173. i++
  1174. }
  1175. return i
  1176. }
  1177. }
  1178. // if the next line starts a block of HTML, then the paragraph ends here
  1179. if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
  1180. if data[i] == '<' && p.html(out, current, false) > 0 {
  1181. // rewind to before the HTML block
  1182. p.renderParagraph(out, data[:i])
  1183. return i
  1184. }
  1185. }
  1186. // if there's a prefixed header or a horizontal rule after this, paragraph is over
  1187. if p.isPrefixHeader(current) || p.isHRule(current) {
  1188. p.renderParagraph(out, data[:i])
  1189. return i
  1190. }
  1191. // if there's a fenced code block, paragraph is over
  1192. if p.flags&EXTENSION_FENCED_CODE != 0 {
  1193. if p.fencedCodeBlock(out, current, false) > 0 {
  1194. p.renderParagraph(out, data[:i])
  1195. return i
  1196. }
  1197. }
  1198. // if there's a definition list item, prev line is a definition term
  1199. if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
  1200. if p.dliPrefix(current) != 0 {
  1201. return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
  1202. }
  1203. }
  1204. // if there's a list after this, paragraph is over
  1205. if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 {
  1206. if p.uliPrefix(current) != 0 ||
  1207. p.oliPrefix(current) != 0 ||
  1208. p.quotePrefix(current) != 0 ||
  1209. p.codePrefix(current) != 0 {
  1210. p.renderParagraph(out, data[:i])
  1211. return i
  1212. }
  1213. }
  1214. // otherwise, scan to the beginning of the next line
  1215. for data[i] != '\n' {
  1216. i++
  1217. }
  1218. i++
  1219. }
  1220. p.renderParagraph(out, data[:i])
  1221. return i
  1222. }