block.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  1. package parser
  2. import (
  3. "bytes"
  4. "html"
  5. "regexp"
  6. "strconv"
  7. "unicode"
  8. "github.com/gomarkdown/markdown/ast"
  9. )
  10. // Parsing block-level elements.
  11. const (
  12. charEntity = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});"
  13. escapable = "[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]"
  14. )
  15. const (
  16. captionTable = "Table: "
  17. captionFigure = "Figure: "
  18. captionQuote = "Quote: "
  19. )
  20. var (
  21. reBackslashOrAmp = regexp.MustCompile(`[\&]`)
  22. reEntityOrEscapedChar = regexp.MustCompile(`(?i)\\` + escapable + "|" + charEntity)
  23. // blockTags is a set of tags that are recognized as HTML block tags.
  24. // Any of these can be included in markdown text without special escaping.
  25. blockTags = map[string]struct{}{
  26. "blockquote": {},
  27. "del": {},
  28. "dd": {},
  29. "div": {},
  30. "dl": {},
  31. "dt": {},
  32. "fieldset": {},
  33. "form": {},
  34. "h1": {},
  35. "h2": {},
  36. "h3": {},
  37. "h4": {},
  38. "h5": {},
  39. "h6": {},
  40. // TODO: technically block but breaks Inline HTML (Simple).text
  41. //"hr": {},
  42. "iframe": {},
  43. "ins": {},
  44. "li": {},
  45. "math": {},
  46. "noscript": {},
  47. "ol": {},
  48. "pre": {},
  49. "p": {},
  50. "script": {},
  51. "style": {},
  52. "table": {},
  53. "ul": {},
  54. // HTML5
  55. "address": {},
  56. "article": {},
  57. "aside": {},
  58. "canvas": {},
  59. "details": {},
  60. "dialog": {},
  61. "figcaption": {},
  62. "figure": {},
  63. "footer": {},
  64. "header": {},
  65. "hgroup": {},
  66. "main": {},
  67. "nav": {},
  68. "output": {},
  69. "progress": {},
  70. "section": {},
  71. "video": {},
  72. }
  73. )
  74. // sanitizeHeadingID returns a sanitized anchor name for the given text.
  75. // Taken from https://github.com/shurcooL/sanitized_anchor_name/blob/master/main.go#L14:1
  76. func sanitizeHeadingID(text string) string {
  77. var anchorName []rune
  78. var futureDash = false
  79. for _, r := range text {
  80. switch {
  81. case unicode.IsLetter(r) || unicode.IsNumber(r):
  82. if futureDash && len(anchorName) > 0 {
  83. anchorName = append(anchorName, '-')
  84. }
  85. futureDash = false
  86. anchorName = append(anchorName, unicode.ToLower(r))
  87. default:
  88. futureDash = true
  89. }
  90. }
  91. if len(anchorName) == 0 {
  92. return "empty"
  93. }
  94. return string(anchorName)
  95. }
  96. // Parse Block-level data.
  97. // Note: this function and many that it calls assume that
  98. // the input buffer ends with a newline.
  99. func (p *Parser) Block(data []byte) {
  100. // this is called recursively: enforce a maximum depth
  101. if p.nesting >= p.maxNesting {
  102. return
  103. }
  104. p.nesting++
  105. // parse out one block-level construct at a time
  106. for len(data) > 0 {
  107. // attributes that can be specific before a block element:
  108. //
  109. // {#id .class1 .class2 key="value"}
  110. if p.extensions&Attributes != 0 {
  111. data = p.attribute(data)
  112. }
  113. if p.extensions&Includes != 0 {
  114. f := p.readInclude
  115. path, address, consumed := p.isInclude(data)
  116. if consumed == 0 {
  117. path, address, consumed = p.isCodeInclude(data)
  118. f = p.readCodeInclude
  119. }
  120. if consumed > 0 {
  121. included := f(p.includeStack.Last(), path, address)
  122. // if we find a caption below this, we need to include it in 'included', so
  123. // that the caption will be part of the include text. (+1 to skip newline)
  124. for _, caption := range []string{captionFigure, captionTable, captionQuote} {
  125. if _, _, capcon := p.caption(data[consumed+1:], []byte(caption)); capcon > 0 {
  126. included = append(included, data[consumed+1:consumed+1+capcon]...)
  127. consumed += 1 + capcon
  128. break // there can only be 1 caption.
  129. }
  130. }
  131. p.includeStack.Push(path)
  132. p.Block(included)
  133. p.includeStack.Pop()
  134. data = data[consumed:]
  135. continue
  136. }
  137. }
  138. // user supplied parser function
  139. if p.Opts.ParserHook != nil {
  140. node, blockdata, consumed := p.Opts.ParserHook(data)
  141. if consumed > 0 {
  142. data = data[consumed:]
  143. if node != nil {
  144. p.AddBlock(node)
  145. if blockdata != nil {
  146. p.Block(blockdata)
  147. p.Finalize(node)
  148. }
  149. }
  150. continue
  151. }
  152. }
  153. // prefixed heading:
  154. //
  155. // # Heading 1
  156. // ## Heading 2
  157. // ...
  158. // ###### Heading 6
  159. if p.isPrefixHeading(data) {
  160. data = data[p.prefixHeading(data):]
  161. continue
  162. }
  163. // prefixed special heading:
  164. // (there are no levels.)
  165. //
  166. // .# Abstract
  167. if p.isPrefixSpecialHeading(data) {
  168. data = data[p.prefixSpecialHeading(data):]
  169. continue
  170. }
  171. // block of preformatted HTML:
  172. //
  173. // <div>
  174. // ...
  175. // </div>
  176. if len(data) == 0 {
  177. continue
  178. }
  179. if data[0] == '<' {
  180. if i := p.html(data, true); i > 0 {
  181. data = data[i:]
  182. continue
  183. }
  184. }
  185. // title block
  186. //
  187. // % stuff
  188. // % more stuff
  189. // % even more stuff
  190. if p.extensions&Titleblock != 0 {
  191. if data[0] == '%' {
  192. if i := p.titleBlock(data, true); i > 0 {
  193. data = data[i:]
  194. continue
  195. }
  196. }
  197. }
  198. // blank lines. note: returns the # of bytes to skip
  199. if i := IsEmpty(data); i > 0 {
  200. data = data[i:]
  201. continue
  202. }
  203. // indented code block:
  204. //
  205. // func max(a, b int) int {
  206. // if a > b {
  207. // return a
  208. // }
  209. // return b
  210. // }
  211. if p.codePrefix(data) > 0 {
  212. data = data[p.code(data):]
  213. continue
  214. }
  215. // fenced code block:
  216. //
  217. // ``` go
  218. // func fact(n int) int {
  219. // if n <= 1 {
  220. // return n
  221. // }
  222. // return n * fact(n-1)
  223. // }
  224. // ```
  225. if p.extensions&FencedCode != 0 {
  226. if i := p.fencedCodeBlock(data, true); i > 0 {
  227. data = data[i:]
  228. continue
  229. }
  230. }
  231. // horizontal rule:
  232. //
  233. // ------
  234. // or
  235. // ******
  236. // or
  237. // ______
  238. if isHRule(data) {
  239. i := skipUntilChar(data, 0, '\n')
  240. hr := ast.HorizontalRule{}
  241. hr.Literal = bytes.Trim(data[:i], " \n")
  242. p.AddBlock(&hr)
  243. data = data[i:]
  244. continue
  245. }
  246. // block quote:
  247. //
  248. // > A big quote I found somewhere
  249. // > on the web
  250. if p.quotePrefix(data) > 0 {
  251. data = data[p.quote(data):]
  252. continue
  253. }
  254. // aside:
  255. //
  256. // A> The proof is too large to fit
  257. // A> in the margin.
  258. if p.extensions&Mmark != 0 {
  259. if p.asidePrefix(data) > 0 {
  260. data = data[p.aside(data):]
  261. continue
  262. }
  263. }
  264. // figure block:
  265. //
  266. // !---
  267. // ![Alt Text](img.jpg "This is an image")
  268. // ![Alt Text](img2.jpg "This is a second image")
  269. // !---
  270. if p.extensions&Mmark != 0 {
  271. if i := p.figureBlock(data, true); i > 0 {
  272. data = data[i:]
  273. continue
  274. }
  275. }
  276. if p.extensions&Tables != 0 {
  277. if i := p.table(data); i > 0 {
  278. data = data[i:]
  279. continue
  280. }
  281. }
  282. // an itemized/unordered list:
  283. //
  284. // * Item 1
  285. // * Item 2
  286. //
  287. // also works with + or -
  288. if p.uliPrefix(data) > 0 {
  289. data = data[p.list(data, 0, 0, '.'):]
  290. continue
  291. }
  292. // a numbered/ordered list:
  293. //
  294. // 1. Item 1
  295. // 2. Item 2
  296. if i := p.oliPrefix(data); i > 0 {
  297. start := 0
  298. delim := byte('.')
  299. if i > 2 {
  300. if p.extensions&OrderedListStart != 0 {
  301. s := string(data[:i-2])
  302. start, _ = strconv.Atoi(s)
  303. if start == 1 {
  304. start = 0
  305. }
  306. }
  307. delim = data[i-2]
  308. }
  309. data = data[p.list(data, ast.ListTypeOrdered, start, delim):]
  310. continue
  311. }
  312. // definition lists:
  313. //
  314. // Term 1
  315. // : Definition a
  316. // : Definition b
  317. //
  318. // Term 2
  319. // : Definition c
  320. if p.extensions&DefinitionLists != 0 {
  321. if p.dliPrefix(data) > 0 {
  322. data = data[p.list(data, ast.ListTypeDefinition, 0, '.'):]
  323. continue
  324. }
  325. }
  326. if p.extensions&MathJax != 0 {
  327. if i := p.blockMath(data); i > 0 {
  328. data = data[i:]
  329. continue
  330. }
  331. }
  332. // document matters:
  333. //
  334. // {frontmatter}/{mainmatter}/{backmatter}
  335. if p.extensions&Mmark != 0 {
  336. if i := p.documentMatter(data); i > 0 {
  337. data = data[i:]
  338. continue
  339. }
  340. }
  341. // anything else must look like a normal paragraph
  342. // note: this finds underlined headings, too
  343. idx := p.paragraph(data)
  344. data = data[idx:]
  345. }
  346. p.nesting--
  347. }
  348. func (p *Parser) AddBlock(n ast.Node) ast.Node {
  349. p.closeUnmatchedBlocks()
  350. if p.attr != nil {
  351. if c := n.AsContainer(); c != nil {
  352. c.Attribute = p.attr
  353. }
  354. if l := n.AsLeaf(); l != nil {
  355. l.Attribute = p.attr
  356. }
  357. p.attr = nil
  358. }
  359. return p.addChild(n)
  360. }
  361. func (p *Parser) isPrefixHeading(data []byte) bool {
  362. if len(data) > 0 && data[0] != '#' {
  363. return false
  364. }
  365. if p.extensions&SpaceHeadings != 0 {
  366. level := skipCharN(data, 0, '#', 6)
  367. if level == len(data) || data[level] != ' ' {
  368. return false
  369. }
  370. }
  371. return true
  372. }
  373. func (p *Parser) prefixHeading(data []byte) int {
  374. level := skipCharN(data, 0, '#', 6)
  375. i := skipChar(data, level, ' ')
  376. end := skipUntilChar(data, i, '\n')
  377. skip := end
  378. id := ""
  379. if p.extensions&HeadingIDs != 0 {
  380. j, k := 0, 0
  381. // find start/end of heading id
  382. for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ {
  383. }
  384. for k = j + 1; k < end && data[k] != '}'; k++ {
  385. }
  386. // extract heading id iff found
  387. if j < end && k < end {
  388. id = string(data[j+2 : k])
  389. end = j
  390. skip = k + 1
  391. for end > 0 && data[end-1] == ' ' {
  392. end--
  393. }
  394. }
  395. }
  396. for end > 0 && data[end-1] == '#' {
  397. if isBackslashEscaped(data, end-1) {
  398. break
  399. }
  400. end--
  401. }
  402. for end > 0 && data[end-1] == ' ' {
  403. end--
  404. }
  405. if end > i {
  406. block := &ast.Heading{
  407. HeadingID: id,
  408. Level: level,
  409. }
  410. if id == "" && p.extensions&AutoHeadingIDs != 0 {
  411. block.HeadingID = sanitizeHeadingID(string(data[i:end]))
  412. p.allHeadingsWithAutoID = append(p.allHeadingsWithAutoID, block)
  413. }
  414. block.Content = data[i:end]
  415. p.AddBlock(block)
  416. }
  417. return skip
  418. }
  419. func (p *Parser) isPrefixSpecialHeading(data []byte) bool {
  420. if p.extensions|Mmark == 0 {
  421. return false
  422. }
  423. if len(data) < 4 {
  424. return false
  425. }
  426. if data[0] != '.' {
  427. return false
  428. }
  429. if data[1] != '#' {
  430. return false
  431. }
  432. if data[2] == '#' { // we don't support level, so nack this.
  433. return false
  434. }
  435. if p.extensions&SpaceHeadings != 0 {
  436. if data[2] != ' ' {
  437. return false
  438. }
  439. }
  440. return true
  441. }
  442. func (p *Parser) prefixSpecialHeading(data []byte) int {
  443. i := skipChar(data, 2, ' ') // ".#" skipped
  444. end := skipUntilChar(data, i, '\n')
  445. skip := end
  446. id := ""
  447. if p.extensions&HeadingIDs != 0 {
  448. j, k := 0, 0
  449. // find start/end of heading id
  450. for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ {
  451. }
  452. for k = j + 1; k < end && data[k] != '}'; k++ {
  453. }
  454. // extract heading id iff found
  455. if j < end && k < end {
  456. id = string(data[j+2 : k])
  457. end = j
  458. skip = k + 1
  459. for end > 0 && data[end-1] == ' ' {
  460. end--
  461. }
  462. }
  463. }
  464. for end > 0 && data[end-1] == '#' {
  465. if isBackslashEscaped(data, end-1) {
  466. break
  467. }
  468. end--
  469. }
  470. for end > 0 && data[end-1] == ' ' {
  471. end--
  472. }
  473. if end > i {
  474. block := &ast.Heading{
  475. HeadingID: id,
  476. IsSpecial: true,
  477. Level: 1, // always level 1.
  478. }
  479. if id == "" && p.extensions&AutoHeadingIDs != 0 {
  480. block.HeadingID = sanitizeHeadingID(string(data[i:end]))
  481. p.allHeadingsWithAutoID = append(p.allHeadingsWithAutoID, block)
  482. }
  483. block.Literal = data[i:end]
  484. block.Content = data[i:end]
  485. p.AddBlock(block)
  486. }
  487. return skip
  488. }
  489. func (p *Parser) isUnderlinedHeading(data []byte) int {
  490. // test of level 1 heading
  491. if data[0] == '=' {
  492. i := skipChar(data, 1, '=')
  493. i = skipChar(data, i, ' ')
  494. if i < len(data) && data[i] == '\n' {
  495. return 1
  496. }
  497. return 0
  498. }
  499. // test of level 2 heading
  500. if data[0] == '-' {
  501. i := skipChar(data, 1, '-')
  502. i = skipChar(data, i, ' ')
  503. if i < len(data) && data[i] == '\n' {
  504. return 2
  505. }
  506. return 0
  507. }
  508. return 0
  509. }
  510. func (p *Parser) titleBlock(data []byte, doRender bool) int {
  511. if data[0] != '%' {
  512. return 0
  513. }
  514. splitData := bytes.Split(data, []byte("\n"))
  515. var i int
  516. for idx, b := range splitData {
  517. if !bytes.HasPrefix(b, []byte("%")) {
  518. i = idx // - 1
  519. break
  520. }
  521. }
  522. data = bytes.Join(splitData[0:i], []byte("\n"))
  523. consumed := len(data)
  524. data = bytes.TrimPrefix(data, []byte("% "))
  525. data = bytes.Replace(data, []byte("\n% "), []byte("\n"), -1)
  526. block := &ast.Heading{
  527. Level: 1,
  528. IsTitleblock: true,
  529. }
  530. block.Content = data
  531. p.AddBlock(block)
  532. return consumed
  533. }
  534. func (p *Parser) html(data []byte, doRender bool) int {
  535. var i, j int
  536. // identify the opening tag
  537. if data[0] != '<' {
  538. return 0
  539. }
  540. curtag, tagfound := p.htmlFindTag(data[1:])
  541. // handle special cases
  542. if !tagfound {
  543. // check for an HTML comment
  544. if size := p.htmlComment(data, doRender); size > 0 {
  545. return size
  546. }
  547. // check for an <hr> tag
  548. if size := p.htmlHr(data, doRender); size > 0 {
  549. return size
  550. }
  551. // no special case recognized
  552. return 0
  553. }
  554. // look for an unindented matching closing tag
  555. // followed by a blank line
  556. found := false
  557. /*
  558. closetag := []byte("\n</" + curtag + ">")
  559. j = len(curtag) + 1
  560. for !found {
  561. // scan for a closing tag at the beginning of a line
  562. if skip := bytes.Index(data[j:], closetag); skip >= 0 {
  563. j += skip + len(closetag)
  564. } else {
  565. break
  566. }
  567. // see if it is the only thing on the line
  568. if skip := IsEmpty(data[j:]); skip > 0 {
  569. // see if it is followed by a blank line/eof
  570. j += skip
  571. if j >= len(data) {
  572. found = true
  573. i = j
  574. } else {
  575. if skip := IsEmpty(data[j:]); skip > 0 {
  576. j += skip
  577. found = true
  578. i = j
  579. }
  580. }
  581. }
  582. }
  583. */
  584. // if not found, try a second pass looking for indented match
  585. // but not if tag is "ins" or "del" (following original Markdown.pl)
  586. if !found && curtag != "ins" && curtag != "del" {
  587. i = 1
  588. for i < len(data) {
  589. i++
  590. for i < len(data) && !(data[i-1] == '<' && data[i] == '/') {
  591. i++
  592. }
  593. if i+2+len(curtag) >= len(data) {
  594. break
  595. }
  596. j = p.htmlFindEnd(curtag, data[i-1:])
  597. if j > 0 {
  598. i += j - 1
  599. found = true
  600. break
  601. }
  602. }
  603. }
  604. if !found {
  605. return 0
  606. }
  607. // the end of the block has been found
  608. if doRender {
  609. // trim newlines
  610. end := backChar(data, i, '\n')
  611. htmlBLock := &ast.HTMLBlock{Leaf: ast.Leaf{Content: data[:end]}}
  612. p.AddBlock(htmlBLock)
  613. finalizeHTMLBlock(htmlBLock)
  614. }
  615. return i
  616. }
  617. func finalizeHTMLBlock(block *ast.HTMLBlock) {
  618. block.Literal = block.Content
  619. block.Content = nil
  620. }
  621. // HTML comment, lax form
  622. func (p *Parser) htmlComment(data []byte, doRender bool) int {
  623. i := p.inlineHTMLComment(data)
  624. // needs to end with a blank line
  625. if j := IsEmpty(data[i:]); j > 0 {
  626. size := i + j
  627. if doRender {
  628. // trim trailing newlines
  629. end := backChar(data, size, '\n')
  630. htmlBLock := &ast.HTMLBlock{Leaf: ast.Leaf{Content: data[:end]}}
  631. p.AddBlock(htmlBLock)
  632. finalizeHTMLBlock(htmlBLock)
  633. }
  634. return size
  635. }
  636. return 0
  637. }
  638. // HR, which is the only self-closing block tag considered
  639. func (p *Parser) htmlHr(data []byte, doRender bool) int {
  640. if len(data) < 4 {
  641. return 0
  642. }
  643. if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') {
  644. return 0
  645. }
  646. if data[3] != ' ' && data[3] != '/' && data[3] != '>' {
  647. // not an <hr> tag after all; at least not a valid one
  648. return 0
  649. }
  650. i := 3
  651. for i < len(data) && data[i] != '>' && data[i] != '\n' {
  652. i++
  653. }
  654. if i < len(data) && data[i] == '>' {
  655. i++
  656. if j := IsEmpty(data[i:]); j > 0 {
  657. size := i + j
  658. if doRender {
  659. // trim newlines
  660. end := backChar(data, size, '\n')
  661. htmlBlock := &ast.HTMLBlock{Leaf: ast.Leaf{Content: data[:end]}}
  662. p.AddBlock(htmlBlock)
  663. finalizeHTMLBlock(htmlBlock)
  664. }
  665. return size
  666. }
  667. }
  668. return 0
  669. }
  670. func (p *Parser) htmlFindTag(data []byte) (string, bool) {
  671. i := skipAlnum(data, 0)
  672. key := string(data[:i])
  673. if _, ok := blockTags[key]; ok {
  674. return key, true
  675. }
  676. return "", false
  677. }
  678. func (p *Parser) htmlFindEnd(tag string, data []byte) int {
  679. // assume data[0] == '<' && data[1] == '/' already tested
  680. if tag == "hr" {
  681. return 2
  682. }
  683. // check if tag is a match
  684. closetag := []byte("</" + tag + ">")
  685. if !bytes.HasPrefix(data, closetag) {
  686. return 0
  687. }
  688. i := len(closetag)
  689. // check that the rest of the line is blank
  690. skip := 0
  691. if skip = IsEmpty(data[i:]); skip == 0 {
  692. return 0
  693. }
  694. i += skip
  695. skip = 0
  696. if i >= len(data) {
  697. return i
  698. }
  699. if p.extensions&LaxHTMLBlocks != 0 {
  700. return i
  701. }
  702. if skip = IsEmpty(data[i:]); skip == 0 {
  703. // following line must be blank
  704. return 0
  705. }
  706. return i + skip
  707. }
  708. func IsEmpty(data []byte) int {
  709. // it is okay to call isEmpty on an empty buffer
  710. if len(data) == 0 {
  711. return 0
  712. }
  713. var i int
  714. for i = 0; i < len(data) && data[i] != '\n'; i++ {
  715. if data[i] != ' ' && data[i] != '\t' {
  716. return 0
  717. }
  718. }
  719. i = skipCharN(data, i, '\n', 1)
  720. return i
  721. }
  722. func isHRule(data []byte) bool {
  723. i := 0
  724. // skip up to three spaces
  725. for i < 3 && data[i] == ' ' {
  726. i++
  727. }
  728. // look at the hrule char
  729. if data[i] != '*' && data[i] != '-' && data[i] != '_' {
  730. return false
  731. }
  732. c := data[i]
  733. // the whole line must be the char or whitespace
  734. n := 0
  735. for i < len(data) && data[i] != '\n' {
  736. switch {
  737. case data[i] == c:
  738. n++
  739. case data[i] != ' ':
  740. return false
  741. }
  742. i++
  743. }
  744. return n >= 3
  745. }
  746. // isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data,
  747. // and returns the end index if so, or 0 otherwise. It also returns the marker found.
  748. // If syntax is not nil, it gets set to the syntax specified in the fence line.
  749. func isFenceLine(data []byte, syntax *string, oldmarker string) (end int, marker string) {
  750. i, size := 0, 0
  751. n := len(data)
  752. // skip up to three spaces
  753. for i < n && i < 3 && data[i] == ' ' {
  754. i++
  755. }
  756. // check for the marker characters: ~ or `
  757. if i >= n {
  758. return 0, ""
  759. }
  760. if data[i] != '~' && data[i] != '`' {
  761. return 0, ""
  762. }
  763. c := data[i]
  764. // the whole line must be the same char or whitespace
  765. for i < n && data[i] == c {
  766. size++
  767. i++
  768. }
  769. // the marker char must occur at least 3 times
  770. if size < 3 {
  771. return 0, ""
  772. }
  773. marker = string(data[i-size : i])
  774. // if this is the end marker, it must match the beginning marker
  775. if oldmarker != "" && marker != oldmarker {
  776. return 0, ""
  777. }
  778. // if just read the beginning marker, read the syntax
  779. if oldmarker == "" {
  780. i = skipChar(data, i, ' ')
  781. if i >= n {
  782. if i == n {
  783. return i, marker
  784. }
  785. return 0, ""
  786. }
  787. syntaxStart, syntaxLen := syntaxRange(data, &i)
  788. if syntaxStart == 0 && syntaxLen == 0 {
  789. return 0, ""
  790. }
  791. // caller wants the syntax
  792. if syntax != nil {
  793. *syntax = string(data[syntaxStart : syntaxStart+syntaxLen])
  794. }
  795. }
  796. i = skipChar(data, i, ' ')
  797. if i >= n || data[i] != '\n' {
  798. if i == n {
  799. return i, marker
  800. }
  801. return 0, ""
  802. }
  803. return i + 1, marker // Take newline into account.
  804. }
  805. func syntaxRange(data []byte, iout *int) (int, int) {
  806. n := len(data)
  807. syn := 0
  808. i := *iout
  809. syntaxStart := i
  810. if data[i] == '{' {
  811. i++
  812. syntaxStart++
  813. for i < n && data[i] != '}' && data[i] != '\n' {
  814. syn++
  815. i++
  816. }
  817. if i >= n || data[i] != '}' {
  818. return 0, 0
  819. }
  820. // strip all whitespace at the beginning and the end
  821. // of the {} block
  822. for syn > 0 && IsSpace(data[syntaxStart]) {
  823. syntaxStart++
  824. syn--
  825. }
  826. for syn > 0 && IsSpace(data[syntaxStart+syn-1]) {
  827. syn--
  828. }
  829. i++
  830. } else {
  831. for i < n && !IsSpace(data[i]) {
  832. syn++
  833. i++
  834. }
  835. }
  836. *iout = i
  837. return syntaxStart, syn
  838. }
  839. // fencedCodeBlock returns the end index if data contains a fenced code block at the beginning,
  840. // or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects.
  841. // If doRender is true, a final newline is mandatory to recognize the fenced code block.
  842. func (p *Parser) fencedCodeBlock(data []byte, doRender bool) int {
  843. var syntax string
  844. beg, marker := isFenceLine(data, &syntax, "")
  845. if beg == 0 || beg >= len(data) {
  846. return 0
  847. }
  848. var work bytes.Buffer
  849. work.WriteString(syntax)
  850. work.WriteByte('\n')
  851. for {
  852. // safe to assume beg < len(data)
  853. // check for the end of the code block
  854. fenceEnd, _ := isFenceLine(data[beg:], nil, marker)
  855. if fenceEnd != 0 {
  856. beg += fenceEnd
  857. break
  858. }
  859. // copy the current line
  860. end := skipUntilChar(data, beg, '\n') + 1
  861. // did we reach the end of the buffer without a closing marker?
  862. if end >= len(data) {
  863. return 0
  864. }
  865. // verbatim copy to the working buffer
  866. if doRender {
  867. work.Write(data[beg:end])
  868. }
  869. beg = end
  870. }
  871. if doRender {
  872. codeBlock := &ast.CodeBlock{
  873. IsFenced: true,
  874. }
  875. codeBlock.Content = work.Bytes() // TODO: get rid of temp buffer
  876. if p.extensions&Mmark == 0 {
  877. p.AddBlock(codeBlock)
  878. finalizeCodeBlock(codeBlock)
  879. return beg
  880. }
  881. // Check for caption and if found make it a figure.
  882. if captionContent, id, consumed := p.caption(data[beg:], []byte(captionFigure)); consumed > 0 {
  883. figure := &ast.CaptionFigure{}
  884. caption := &ast.Caption{}
  885. figure.HeadingID = id
  886. p.Inline(caption, captionContent)
  887. p.AddBlock(figure)
  888. codeBlock.AsLeaf().Attribute = figure.AsContainer().Attribute
  889. p.addChild(codeBlock)
  890. finalizeCodeBlock(codeBlock)
  891. p.addChild(caption)
  892. p.Finalize(figure)
  893. beg += consumed
  894. return beg
  895. }
  896. // Still here, normal block
  897. p.AddBlock(codeBlock)
  898. finalizeCodeBlock(codeBlock)
  899. }
  900. return beg
  901. }
  902. func unescapeChar(str []byte) []byte {
  903. if str[0] == '\\' {
  904. return []byte{str[1]}
  905. }
  906. return []byte(html.UnescapeString(string(str)))
  907. }
  908. func unescapeString(str []byte) []byte {
  909. if reBackslashOrAmp.Match(str) {
  910. return reEntityOrEscapedChar.ReplaceAllFunc(str, unescapeChar)
  911. }
  912. return str
  913. }
  914. func finalizeCodeBlock(code *ast.CodeBlock) {
  915. c := code.Content
  916. if code.IsFenced {
  917. newlinePos := bytes.IndexByte(c, '\n')
  918. firstLine := c[:newlinePos]
  919. rest := c[newlinePos+1:]
  920. code.Info = unescapeString(bytes.Trim(firstLine, "\n"))
  921. code.Literal = rest
  922. } else {
  923. code.Literal = c
  924. }
  925. code.Content = nil
  926. }
  927. // returns blockquote prefix length
  928. func (p *Parser) quotePrefix(data []byte) int {
  929. i := 0
  930. n := len(data)
  931. for i < 3 && i < n && data[i] == ' ' {
  932. i++
  933. }
  934. if i < n && data[i] == '>' {
  935. if i+1 < n && data[i+1] == ' ' {
  936. return i + 2
  937. }
  938. return i + 1
  939. }
  940. return 0
  941. }
  942. // blockquote ends with at least one blank line
  943. // followed by something without a blockquote prefix
  944. func (p *Parser) terminateBlockquote(data []byte, beg, end int) bool {
  945. if IsEmpty(data[beg:]) <= 0 {
  946. return false
  947. }
  948. if end >= len(data) {
  949. return true
  950. }
  951. return p.quotePrefix(data[end:]) == 0 && IsEmpty(data[end:]) == 0
  952. }
  953. // parse a blockquote fragment
  954. func (p *Parser) quote(data []byte) int {
  955. var raw bytes.Buffer
  956. beg, end := 0, 0
  957. for beg < len(data) {
  958. end = beg
  959. // Step over whole lines, collecting them. While doing that, check for
  960. // fenced code and if one's found, incorporate it altogether,
  961. // irregardless of any contents inside it
  962. for end < len(data) && data[end] != '\n' {
  963. if p.extensions&FencedCode != 0 {
  964. if i := p.fencedCodeBlock(data[end:], false); i > 0 {
  965. // -1 to compensate for the extra end++ after the loop:
  966. end += i - 1
  967. break
  968. }
  969. }
  970. end++
  971. }
  972. end = skipCharN(data, end, '\n', 1)
  973. if pre := p.quotePrefix(data[beg:]); pre > 0 {
  974. // skip the prefix
  975. beg += pre
  976. } else if p.terminateBlockquote(data, beg, end) {
  977. break
  978. }
  979. // this line is part of the blockquote
  980. raw.Write(data[beg:end])
  981. beg = end
  982. }
  983. if p.extensions&Mmark == 0 {
  984. block := p.AddBlock(&ast.BlockQuote{})
  985. p.Block(raw.Bytes())
  986. p.Finalize(block)
  987. return end
  988. }
  989. if captionContent, id, consumed := p.caption(data[end:], []byte(captionQuote)); consumed > 0 {
  990. figure := &ast.CaptionFigure{}
  991. caption := &ast.Caption{}
  992. figure.HeadingID = id
  993. p.Inline(caption, captionContent)
  994. p.AddBlock(figure) // this discard any attributes
  995. block := &ast.BlockQuote{}
  996. block.AsContainer().Attribute = figure.AsContainer().Attribute
  997. p.addChild(block)
  998. p.Block(raw.Bytes())
  999. p.Finalize(block)
  1000. p.addChild(caption)
  1001. p.Finalize(figure)
  1002. end += consumed
  1003. return end
  1004. }
  1005. block := p.AddBlock(&ast.BlockQuote{})
  1006. p.Block(raw.Bytes())
  1007. p.Finalize(block)
  1008. return end
  1009. }
  1010. // returns prefix length for block code
  1011. func (p *Parser) codePrefix(data []byte) int {
  1012. n := len(data)
  1013. if n >= 1 && data[0] == '\t' {
  1014. return 1
  1015. }
  1016. if n >= 4 && data[3] == ' ' && data[2] == ' ' && data[1] == ' ' && data[0] == ' ' {
  1017. return 4
  1018. }
  1019. return 0
  1020. }
  1021. func (p *Parser) code(data []byte) int {
  1022. var work bytes.Buffer
  1023. i := 0
  1024. for i < len(data) {
  1025. beg := i
  1026. i = skipUntilChar(data, i, '\n')
  1027. i = skipCharN(data, i, '\n', 1)
  1028. blankline := IsEmpty(data[beg:i]) > 0
  1029. if pre := p.codePrefix(data[beg:i]); pre > 0 {
  1030. beg += pre
  1031. } else if !blankline {
  1032. // non-empty, non-prefixed line breaks the pre
  1033. i = beg
  1034. break
  1035. }
  1036. // verbatim copy to the working buffer
  1037. if blankline {
  1038. work.WriteByte('\n')
  1039. } else {
  1040. work.Write(data[beg:i])
  1041. }
  1042. }
  1043. // trim all the \n off the end of work
  1044. workbytes := work.Bytes()
  1045. eol := backChar(workbytes, len(workbytes), '\n')
  1046. if eol != len(workbytes) {
  1047. work.Truncate(eol)
  1048. }
  1049. work.WriteByte('\n')
  1050. codeBlock := &ast.CodeBlock{
  1051. IsFenced: false,
  1052. }
  1053. // TODO: get rid of temp buffer
  1054. codeBlock.Content = work.Bytes()
  1055. p.AddBlock(codeBlock)
  1056. finalizeCodeBlock(codeBlock)
  1057. return i
  1058. }
  1059. // returns unordered list item prefix
  1060. func (p *Parser) uliPrefix(data []byte) int {
  1061. // start with up to 3 spaces
  1062. i := skipCharN(data, 0, ' ', 3)
  1063. if i >= len(data)-1 {
  1064. return 0
  1065. }
  1066. // need one of {'*', '+', '-'} followed by a space or a tab
  1067. if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
  1068. (data[i+1] != ' ' && data[i+1] != '\t') {
  1069. return 0
  1070. }
  1071. return i + 2
  1072. }
  1073. // returns ordered list item prefix
  1074. func (p *Parser) oliPrefix(data []byte) int {
  1075. // start with up to 3 spaces
  1076. i := skipCharN(data, 0, ' ', 3)
  1077. // count the digits
  1078. start := i
  1079. for i < len(data) && data[i] >= '0' && data[i] <= '9' {
  1080. i++
  1081. }
  1082. if start == i || i >= len(data)-1 {
  1083. return 0
  1084. }
  1085. // we need >= 1 digits followed by a dot and a space or a tab
  1086. if data[i] != '.' && data[i] != ')' || !(data[i+1] == ' ' || data[i+1] == '\t') {
  1087. return 0
  1088. }
  1089. return i + 2
  1090. }
  1091. // returns definition list item prefix
  1092. func (p *Parser) dliPrefix(data []byte) int {
  1093. if len(data) < 2 {
  1094. return 0
  1095. }
  1096. // need a ':' followed by a space or a tab
  1097. if data[0] != ':' || !(data[1] == ' ' || data[1] == '\t') {
  1098. return 0
  1099. }
  1100. // TODO: this is a no-op (data[0] is ':' so not ' ').
  1101. // Maybe the intent was to eat spaces before ':' ?
  1102. // either way, no change in tests
  1103. i := skipChar(data, 0, ' ')
  1104. return i + 2
  1105. }
  1106. // TODO: maybe it was meant to be like below
  1107. // either way, no change in tests
  1108. /*
  1109. func (p *Parser) dliPrefix(data []byte) int {
  1110. i := skipChar(data, 0, ' ')
  1111. if i+len(data) < 2 {
  1112. return 0
  1113. }
  1114. // need a ':' followed by a space or a tab
  1115. if data[i] != ':' || !(data[i+1] == ' ' || data[i+1] == '\t') {
  1116. return 0
  1117. }
  1118. return i + 2
  1119. }
  1120. */
  1121. // parse ordered or unordered list block
  1122. func (p *Parser) list(data []byte, flags ast.ListType, start int, delim byte) int {
  1123. i := 0
  1124. flags |= ast.ListItemBeginningOfList
  1125. list := &ast.List{
  1126. ListFlags: flags,
  1127. Tight: true,
  1128. Start: start,
  1129. Delimiter: delim,
  1130. }
  1131. block := p.AddBlock(list)
  1132. for i < len(data) {
  1133. skip := p.listItem(data[i:], &flags)
  1134. if flags&ast.ListItemContainsBlock != 0 {
  1135. list.Tight = false
  1136. }
  1137. i += skip
  1138. if skip == 0 || flags&ast.ListItemEndOfList != 0 {
  1139. break
  1140. }
  1141. flags &= ^ast.ListItemBeginningOfList
  1142. }
  1143. above := block.GetParent()
  1144. finalizeList(list)
  1145. p.tip = above
  1146. return i
  1147. }
  1148. // Returns true if the list item is not the same type as its parent list
  1149. func (p *Parser) listTypeChanged(data []byte, flags *ast.ListType) bool {
  1150. if p.dliPrefix(data) > 0 && *flags&ast.ListTypeDefinition == 0 {
  1151. return true
  1152. } else if p.oliPrefix(data) > 0 && *flags&ast.ListTypeOrdered == 0 {
  1153. return true
  1154. } else if p.uliPrefix(data) > 0 && (*flags&ast.ListTypeOrdered != 0 || *flags&ast.ListTypeDefinition != 0) {
  1155. return true
  1156. }
  1157. return false
  1158. }
  1159. // Returns true if block ends with a blank line, descending if needed
  1160. // into lists and sublists.
  1161. func endsWithBlankLine(block ast.Node) bool {
  1162. // TODO: figure this out. Always false now.
  1163. for block != nil {
  1164. //if block.lastLineBlank {
  1165. //return true
  1166. //}
  1167. switch block.(type) {
  1168. case *ast.List, *ast.ListItem:
  1169. block = ast.GetLastChild(block)
  1170. default:
  1171. return false
  1172. }
  1173. }
  1174. return false
  1175. }
  1176. func finalizeList(list *ast.List) {
  1177. items := list.Parent.GetChildren()
  1178. lastItemIdx := len(items) - 1
  1179. for i, item := range items {
  1180. isLastItem := i == lastItemIdx
  1181. // check for non-final list item ending with blank line:
  1182. if !isLastItem && endsWithBlankLine(item) {
  1183. list.Tight = false
  1184. break
  1185. }
  1186. // recurse into children of list item, to see if there are spaces
  1187. // between any of them:
  1188. subItems := item.GetParent().GetChildren()
  1189. lastSubItemIdx := len(subItems) - 1
  1190. for j, subItem := range subItems {
  1191. isLastSubItem := j == lastSubItemIdx
  1192. if (!isLastItem || !isLastSubItem) && endsWithBlankLine(subItem) {
  1193. list.Tight = false
  1194. break
  1195. }
  1196. }
  1197. }
  1198. }
  1199. // Parse a single list item.
  1200. // Assumes initial prefix is already removed if this is a sublist.
  1201. func (p *Parser) listItem(data []byte, flags *ast.ListType) int {
  1202. // keep track of the indentation of the first line
  1203. itemIndent := 0
  1204. if data[0] == '\t' {
  1205. itemIndent += 4
  1206. } else {
  1207. for itemIndent < 3 && data[itemIndent] == ' ' {
  1208. itemIndent++
  1209. }
  1210. }
  1211. var (
  1212. bulletChar byte = '*'
  1213. delimiter byte = '.'
  1214. )
  1215. i := p.uliPrefix(data)
  1216. if i == 0 {
  1217. i = p.oliPrefix(data)
  1218. if i > 0 {
  1219. delimiter = data[i-2]
  1220. }
  1221. } else {
  1222. bulletChar = data[i-2]
  1223. }
  1224. if i == 0 {
  1225. i = p.dliPrefix(data)
  1226. // reset definition term flag
  1227. if i > 0 {
  1228. *flags &= ^ast.ListTypeTerm
  1229. }
  1230. }
  1231. if i == 0 {
  1232. // if in definition list, set term flag and continue
  1233. if *flags&ast.ListTypeDefinition != 0 {
  1234. *flags |= ast.ListTypeTerm
  1235. } else {
  1236. return 0
  1237. }
  1238. }
  1239. // skip leading whitespace on first line
  1240. i = skipChar(data, i, ' ')
  1241. // find the end of the line
  1242. line := i
  1243. for i > 0 && i < len(data) && data[i-1] != '\n' {
  1244. i++
  1245. }
  1246. // get working buffer
  1247. var raw bytes.Buffer
  1248. // put the first line into the working buffer
  1249. raw.Write(data[line:i])
  1250. line = i
  1251. // process the following lines
  1252. containsBlankLine := false
  1253. sublist := 0
  1254. gatherlines:
  1255. for line < len(data) {
  1256. i++
  1257. // find the end of this line
  1258. for i < len(data) && data[i-1] != '\n' {
  1259. i++
  1260. }
  1261. // if it is an empty line, guess that it is part of this item
  1262. // and move on to the next line
  1263. if IsEmpty(data[line:i]) > 0 {
  1264. containsBlankLine = true
  1265. line = i
  1266. continue
  1267. }
  1268. // calculate the indentation
  1269. indent := 0
  1270. indentIndex := 0
  1271. if data[line] == '\t' {
  1272. indentIndex++
  1273. indent += 4
  1274. } else {
  1275. for indent < 4 && line+indent < i && data[line+indent] == ' ' {
  1276. indent++
  1277. indentIndex++
  1278. }
  1279. }
  1280. chunk := data[line+indentIndex : i]
  1281. // If there is a fence line (marking starting of a code block)
  1282. // without indent do not process it as part of the list.
  1283. if p.extensions&FencedCode != 0 {
  1284. fenceLineEnd, _ := isFenceLine(chunk, nil, "")
  1285. if fenceLineEnd > 0 && indent == 0 {
  1286. *flags |= ast.ListItemEndOfList
  1287. break gatherlines
  1288. }
  1289. }
  1290. // evaluate how this line fits in
  1291. switch {
  1292. // is this a nested list item?
  1293. case (p.uliPrefix(chunk) > 0 && !isHRule(chunk)) || p.oliPrefix(chunk) > 0 || p.dliPrefix(chunk) > 0:
  1294. // if indent is 4 or more spaces on unordered or ordered lists
  1295. // we need to add leadingWhiteSpaces + 1 spaces in the beginning of the chunk
  1296. if indentIndex >= 4 && p.dliPrefix(chunk) <= 0 {
  1297. leadingWhiteSpaces := skipChar(chunk, 0, ' ')
  1298. chunk = data[line+indentIndex-(leadingWhiteSpaces+1) : i]
  1299. }
  1300. // to be a nested list, it must be indented more
  1301. // if not, it is either a different kind of list
  1302. // or the next item in the same list
  1303. if indent <= itemIndent {
  1304. if p.listTypeChanged(chunk, flags) {
  1305. *flags |= ast.ListItemEndOfList
  1306. } else if containsBlankLine {
  1307. *flags |= ast.ListItemContainsBlock
  1308. }
  1309. break gatherlines
  1310. }
  1311. if containsBlankLine {
  1312. *flags |= ast.ListItemContainsBlock
  1313. }
  1314. // is this the first item in the nested list?
  1315. if sublist == 0 {
  1316. sublist = raw.Len()
  1317. // in the case of dliPrefix we are too late and need to search back for the definition item, which
  1318. // should be on the previous line, we then adjust sublist to start there.
  1319. if p.dliPrefix(chunk) > 0 {
  1320. sublist = backUntilChar(raw.Bytes(), raw.Len()-1, '\n')
  1321. }
  1322. }
  1323. // is this a nested prefix heading?
  1324. case p.isPrefixHeading(chunk), p.isPrefixSpecialHeading(chunk):
  1325. // if the heading is not indented, it is not nested in the list
  1326. // and thus ends the list
  1327. if containsBlankLine && indent < 4 {
  1328. *flags |= ast.ListItemEndOfList
  1329. break gatherlines
  1330. }
  1331. *flags |= ast.ListItemContainsBlock
  1332. // anything following an empty line is only part
  1333. // of this item if it is indented 4 spaces
  1334. // (regardless of the indentation of the beginning of the item)
  1335. case containsBlankLine && indent < 4:
  1336. if *flags&ast.ListTypeDefinition != 0 && i < len(data)-1 {
  1337. // is the next item still a part of this list?
  1338. next := skipUntilChar(data, i, '\n')
  1339. for next < len(data)-1 && data[next] == '\n' {
  1340. next++
  1341. }
  1342. if i < len(data)-1 && data[i] != ':' && next < len(data)-1 && data[next] != ':' {
  1343. *flags |= ast.ListItemEndOfList
  1344. }
  1345. } else {
  1346. *flags |= ast.ListItemEndOfList
  1347. }
  1348. break gatherlines
  1349. // a blank line means this should be parsed as a block
  1350. case containsBlankLine:
  1351. raw.WriteByte('\n')
  1352. *flags |= ast.ListItemContainsBlock
  1353. }
  1354. // if this line was preceded by one or more blanks,
  1355. // re-introduce the blank into the buffer
  1356. if containsBlankLine {
  1357. containsBlankLine = false
  1358. raw.WriteByte('\n')
  1359. }
  1360. // add the line into the working buffer without prefix
  1361. raw.Write(chunk)
  1362. line = i
  1363. }
  1364. rawBytes := raw.Bytes()
  1365. listItem := &ast.ListItem{
  1366. ListFlags: *flags,
  1367. Tight: false,
  1368. BulletChar: bulletChar,
  1369. Delimiter: delimiter,
  1370. }
  1371. p.AddBlock(listItem)
  1372. // render the contents of the list item
  1373. if *flags&ast.ListItemContainsBlock != 0 && *flags&ast.ListTypeTerm == 0 {
  1374. // intermediate render of block item, except for definition term
  1375. if sublist > 0 {
  1376. p.Block(rawBytes[:sublist])
  1377. p.Block(rawBytes[sublist:])
  1378. } else {
  1379. p.Block(rawBytes)
  1380. }
  1381. } else {
  1382. // intermediate render of inline item
  1383. para := &ast.Paragraph{}
  1384. if sublist > 0 {
  1385. para.Content = rawBytes[:sublist]
  1386. } else {
  1387. para.Content = rawBytes
  1388. }
  1389. p.addChild(para)
  1390. if sublist > 0 {
  1391. p.Block(rawBytes[sublist:])
  1392. }
  1393. }
  1394. return line
  1395. }
  1396. // render a single paragraph that has already been parsed out
  1397. func (p *Parser) renderParagraph(data []byte) {
  1398. if len(data) == 0 {
  1399. return
  1400. }
  1401. // trim leading spaces
  1402. beg := skipChar(data, 0, ' ')
  1403. end := len(data)
  1404. // trim trailing newline
  1405. if data[len(data)-1] == '\n' {
  1406. end--
  1407. }
  1408. // trim trailing spaces
  1409. for end > beg && data[end-1] == ' ' {
  1410. end--
  1411. }
  1412. para := &ast.Paragraph{}
  1413. para.Content = data[beg:end]
  1414. p.AddBlock(para)
  1415. }
  1416. // blockMath handle block surround with $$
  1417. func (p *Parser) blockMath(data []byte) int {
  1418. if len(data) <= 4 || data[0] != '$' || data[1] != '$' || data[2] == '$' {
  1419. return 0
  1420. }
  1421. // find next $$
  1422. var end int
  1423. for end = 2; end+1 < len(data) && (data[end] != '$' || data[end+1] != '$'); end++ {
  1424. }
  1425. // $$ not match
  1426. if end+1 == len(data) {
  1427. return 0
  1428. }
  1429. // render the display math
  1430. mathBlock := &ast.MathBlock{}
  1431. mathBlock.Literal = data[2:end]
  1432. p.AddBlock(mathBlock)
  1433. return end + 2
  1434. }
  1435. func (p *Parser) paragraph(data []byte) int {
  1436. // prev: index of 1st char of previous line
  1437. // line: index of 1st char of current line
  1438. // i: index of cursor/end of current line
  1439. var prev, line, i int
  1440. tabSize := tabSizeDefault
  1441. if p.extensions&TabSizeEight != 0 {
  1442. tabSize = tabSizeDouble
  1443. }
  1444. // keep going until we find something to mark the end of the paragraph
  1445. for i < len(data) {
  1446. // mark the beginning of the current line
  1447. prev = line
  1448. current := data[i:]
  1449. line = i
  1450. // did we find a reference or a footnote? If so, end a paragraph
  1451. // preceding it and report that we have consumed up to the end of that
  1452. // reference:
  1453. if refEnd := isReference(p, current, tabSize); refEnd > 0 {
  1454. p.renderParagraph(data[:i])
  1455. return i + refEnd
  1456. }
  1457. // did we find a blank line marking the end of the paragraph?
  1458. if n := IsEmpty(current); n > 0 {
  1459. // did this blank line followed by a definition list item?
  1460. if p.extensions&DefinitionLists != 0 {
  1461. if i < len(data)-1 && data[i+1] == ':' {
  1462. listLen := p.list(data[prev:], ast.ListTypeDefinition, 0, '.')
  1463. return prev + listLen
  1464. }
  1465. }
  1466. p.renderParagraph(data[:i])
  1467. return i + n
  1468. }
  1469. // an underline under some text marks a heading, so our paragraph ended on prev line
  1470. if i > 0 {
  1471. if level := p.isUnderlinedHeading(current); level > 0 {
  1472. // render the paragraph
  1473. p.renderParagraph(data[:prev])
  1474. // ignore leading and trailing whitespace
  1475. eol := i - 1
  1476. for prev < eol && data[prev] == ' ' {
  1477. prev++
  1478. }
  1479. for eol > prev && data[eol-1] == ' ' {
  1480. eol--
  1481. }
  1482. block := &ast.Heading{
  1483. Level: level,
  1484. }
  1485. if p.extensions&AutoHeadingIDs != 0 {
  1486. block.HeadingID = sanitizeHeadingID(string(data[prev:eol]))
  1487. p.allHeadingsWithAutoID = append(p.allHeadingsWithAutoID, block)
  1488. }
  1489. block.Content = data[prev:eol]
  1490. p.AddBlock(block)
  1491. // find the end of the underline
  1492. return skipUntilChar(data, i, '\n')
  1493. }
  1494. }
  1495. // if the next line starts a block of HTML, then the paragraph ends here
  1496. if p.extensions&LaxHTMLBlocks != 0 {
  1497. if data[i] == '<' && p.html(current, false) > 0 {
  1498. // rewind to before the HTML block
  1499. p.renderParagraph(data[:i])
  1500. return i
  1501. }
  1502. }
  1503. // if there's a prefixed heading or a horizontal rule after this, paragraph is over
  1504. if p.isPrefixHeading(current) || p.isPrefixSpecialHeading(current) || isHRule(current) {
  1505. p.renderParagraph(data[:i])
  1506. return i
  1507. }
  1508. // if there's a block quote, paragraph is over
  1509. if p.quotePrefix(current) > 0 {
  1510. p.renderParagraph(data[:i])
  1511. return i
  1512. }
  1513. // if there's a fenced code block, paragraph is over
  1514. if p.extensions&FencedCode != 0 {
  1515. if p.fencedCodeBlock(current, false) > 0 {
  1516. p.renderParagraph(data[:i])
  1517. return i
  1518. }
  1519. }
  1520. // if there's a figure block, paragraph is over
  1521. if p.extensions&Mmark != 0 {
  1522. if p.figureBlock(current, false) > 0 {
  1523. p.renderParagraph(data[:i])
  1524. return i
  1525. }
  1526. }
  1527. // if there's a table, paragraph is over
  1528. if p.extensions&Tables != 0 {
  1529. if j, _, _ := p.tableHeader(current, false); j > 0 {
  1530. p.renderParagraph(data[:i])
  1531. return i
  1532. }
  1533. }
  1534. // if there's a definition list item, prev line is a definition term
  1535. if p.extensions&DefinitionLists != 0 {
  1536. if p.dliPrefix(current) != 0 {
  1537. ret := p.list(data[prev:], ast.ListTypeDefinition, 0, '.')
  1538. return ret + prev
  1539. }
  1540. }
  1541. // if there's a list after this, paragraph is over
  1542. if p.extensions&NoEmptyLineBeforeBlock != 0 {
  1543. if p.uliPrefix(current) != 0 ||
  1544. p.oliPrefix(current) != 0 ||
  1545. p.quotePrefix(current) != 0 ||
  1546. p.codePrefix(current) != 0 {
  1547. p.renderParagraph(data[:i])
  1548. return i
  1549. }
  1550. }
  1551. // otherwise, scan to the beginning of the next line
  1552. nl := bytes.IndexByte(data[i:], '\n')
  1553. if nl >= 0 {
  1554. i += nl + 1
  1555. } else {
  1556. i += len(data[i:])
  1557. }
  1558. }
  1559. p.renderParagraph(data[:i])
  1560. return i
  1561. }
  1562. // skipChar advances i as long as data[i] == c
  1563. func skipChar(data []byte, i int, c byte) int {
  1564. n := len(data)
  1565. for i < n && data[i] == c {
  1566. i++
  1567. }
  1568. return i
  1569. }
  1570. // like skipChar but only skips up to max characters
  1571. func skipCharN(data []byte, i int, c byte, max int) int {
  1572. n := len(data)
  1573. for i < n && max > 0 && data[i] == c {
  1574. i++
  1575. max--
  1576. }
  1577. return i
  1578. }
  1579. // skipUntilChar advances i as long as data[i] != c
  1580. func skipUntilChar(data []byte, i int, c byte) int {
  1581. n := len(data)
  1582. for i < n && data[i] != c {
  1583. i++
  1584. }
  1585. return i
  1586. }
  1587. func skipAlnum(data []byte, i int) int {
  1588. n := len(data)
  1589. for i < n && IsAlnum(data[i]) {
  1590. i++
  1591. }
  1592. return i
  1593. }
  1594. func skipSpace(data []byte, i int) int {
  1595. n := len(data)
  1596. for i < n && IsSpace(data[i]) {
  1597. i++
  1598. }
  1599. return i
  1600. }
  1601. func backChar(data []byte, i int, c byte) int {
  1602. for i > 0 && data[i-1] == c {
  1603. i--
  1604. }
  1605. return i
  1606. }
  1607. func backUntilChar(data []byte, i int, c byte) int {
  1608. for i > 0 && data[i-1] != c {
  1609. i--
  1610. }
  1611. return i
  1612. }