block.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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. "html"
  16. "regexp"
  17. "strings"
  18. "unicode"
  19. )
  20. const (
  21. charEntity = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});"
  22. escapable = "[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]"
  23. )
  24. var (
  25. reBackslashOrAmp = regexp.MustCompile("[\\&]")
  26. reEntityOrEscapedChar = regexp.MustCompile("(?i)\\\\" + escapable + "|" + charEntity)
  27. )
  28. // Parse block-level data.
  29. // Note: this function and many that it calls assume that
  30. // the input buffer ends with a newline.
  31. func (p *Markdown) block(data []byte) {
  32. // this is called recursively: enforce a maximum depth
  33. if p.nesting >= p.maxNesting {
  34. return
  35. }
  36. p.nesting++
  37. // parse out one block-level construct at a time
  38. for len(data) > 0 {
  39. // prefixed heading:
  40. //
  41. // # Heading 1
  42. // ## Heading 2
  43. // ...
  44. // ###### Heading 6
  45. if p.isPrefixHeading(data) {
  46. data = data[p.prefixHeading(data):]
  47. continue
  48. }
  49. // block of preformatted HTML:
  50. //
  51. // <div>
  52. // ...
  53. // </div>
  54. if data[0] == '<' {
  55. if i := p.html(data, true); i > 0 {
  56. data = data[i:]
  57. continue
  58. }
  59. }
  60. // title block
  61. //
  62. // % stuff
  63. // % more stuff
  64. // % even more stuff
  65. if p.extensions&Titleblock != 0 {
  66. if data[0] == '%' {
  67. if i := p.titleBlock(data, true); i > 0 {
  68. data = data[i:]
  69. continue
  70. }
  71. }
  72. }
  73. // blank lines. note: returns the # of bytes to skip
  74. if i := p.isEmpty(data); i > 0 {
  75. data = data[i:]
  76. continue
  77. }
  78. // indented code block:
  79. //
  80. // func max(a, b int) int {
  81. // if a > b {
  82. // return a
  83. // }
  84. // return b
  85. // }
  86. if p.codePrefix(data) > 0 {
  87. data = data[p.code(data):]
  88. continue
  89. }
  90. // fenced code block:
  91. //
  92. // ``` go
  93. // func fact(n int) int {
  94. // if n <= 1 {
  95. // return n
  96. // }
  97. // return n * fact(n-1)
  98. // }
  99. // ```
  100. if p.extensions&FencedCode != 0 {
  101. if i := p.fencedCodeBlock(data, true); i > 0 {
  102. data = data[i:]
  103. continue
  104. }
  105. }
  106. // horizontal rule:
  107. //
  108. // ------
  109. // or
  110. // ******
  111. // or
  112. // ______
  113. if p.isHRule(data) {
  114. p.addBlock(HorizontalRule, nil)
  115. var i int
  116. for i = 0; i < len(data) && data[i] != '\n'; i++ {
  117. }
  118. data = data[i:]
  119. continue
  120. }
  121. // block quote:
  122. //
  123. // > A big quote I found somewhere
  124. // > on the web
  125. if p.quotePrefix(data) > 0 {
  126. data = data[p.quote(data):]
  127. continue
  128. }
  129. // table:
  130. //
  131. // Name | Age | Phone
  132. // ------|-----|---------
  133. // Bob | 31 | 555-1234
  134. // Alice | 27 | 555-4321
  135. if p.extensions&Tables != 0 {
  136. if i := p.table(data); i > 0 {
  137. data = data[i:]
  138. continue
  139. }
  140. }
  141. // an itemized/unordered list:
  142. //
  143. // * Item 1
  144. // * Item 2
  145. //
  146. // also works with + or -
  147. if p.uliPrefix(data) > 0 {
  148. data = data[p.list(data, 0):]
  149. continue
  150. }
  151. // a numbered/ordered list:
  152. //
  153. // 1. Item 1
  154. // 2. Item 2
  155. if p.oliPrefix(data) > 0 {
  156. data = data[p.list(data, ListTypeOrdered):]
  157. continue
  158. }
  159. // definition lists:
  160. //
  161. // Term 1
  162. // : Definition a
  163. // : Definition b
  164. //
  165. // Term 2
  166. // : Definition c
  167. if p.extensions&DefinitionLists != 0 {
  168. if p.dliPrefix(data) > 0 {
  169. data = data[p.list(data, ListTypeDefinition):]
  170. continue
  171. }
  172. }
  173. // anything else must look like a normal paragraph
  174. // note: this finds underlined headings, too
  175. data = data[p.paragraph(data):]
  176. }
  177. p.nesting--
  178. }
  179. func (p *Markdown) addBlock(typ NodeType, content []byte) *Node {
  180. p.closeUnmatchedBlocks()
  181. container := p.addChild(typ, 0)
  182. container.content = content
  183. return container
  184. }
  185. func (p *Markdown) isPrefixHeading(data []byte) bool {
  186. if data[0] != '#' {
  187. return false
  188. }
  189. if p.extensions&SpaceHeadings != 0 {
  190. level := 0
  191. for level < 6 && level < len(data) && data[level] == '#' {
  192. level++
  193. }
  194. if level == len(data) || data[level] != ' ' {
  195. return false
  196. }
  197. }
  198. return true
  199. }
  200. func (p *Markdown) prefixHeading(data []byte) int {
  201. level := 0
  202. for level < 6 && level < len(data) && data[level] == '#' {
  203. level++
  204. }
  205. i := skipChar(data, level, ' ')
  206. end := skipUntilChar(data, i, '\n')
  207. skip := end
  208. id := ""
  209. if p.extensions&HeadingIDs != 0 {
  210. j, k := 0, 0
  211. // find start/end of heading id
  212. for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ {
  213. }
  214. for k = j + 1; k < end && data[k] != '}'; k++ {
  215. }
  216. // extract heading id iff found
  217. if j < end && k < end {
  218. id = string(data[j+2 : k])
  219. end = j
  220. skip = k + 1
  221. for end > 0 && data[end-1] == ' ' {
  222. end--
  223. }
  224. }
  225. }
  226. for end > 0 && data[end-1] == '#' {
  227. if isBackslashEscaped(data, end-1) {
  228. break
  229. }
  230. end--
  231. }
  232. for end > 0 && data[end-1] == ' ' {
  233. end--
  234. }
  235. if end > i {
  236. if id == "" && p.extensions&AutoHeadingIDs != 0 {
  237. id = SanitizedAnchorName(string(data[i:end]))
  238. }
  239. block := p.addBlock(Heading, data[i:end])
  240. block.HeadingID = id
  241. block.Level = level
  242. }
  243. return skip
  244. }
  245. func (p *Markdown) isUnderlinedHeading(data []byte) int {
  246. // test of level 1 heading
  247. if data[0] == '=' {
  248. i := skipChar(data, 1, '=')
  249. i = skipChar(data, i, ' ')
  250. if i < len(data) && data[i] == '\n' {
  251. return 1
  252. }
  253. return 0
  254. }
  255. // test of level 2 heading
  256. if data[0] == '-' {
  257. i := skipChar(data, 1, '-')
  258. i = skipChar(data, i, ' ')
  259. if i < len(data) && data[i] == '\n' {
  260. return 2
  261. }
  262. return 0
  263. }
  264. return 0
  265. }
  266. func (p *Markdown) titleBlock(data []byte, doRender bool) int {
  267. if data[0] != '%' {
  268. return 0
  269. }
  270. splitData := bytes.Split(data, []byte("\n"))
  271. var i int
  272. for idx, b := range splitData {
  273. if !bytes.HasPrefix(b, []byte("%")) {
  274. i = idx // - 1
  275. break
  276. }
  277. }
  278. data = bytes.Join(splitData[0:i], []byte("\n"))
  279. consumed := len(data)
  280. data = bytes.TrimPrefix(data, []byte("% "))
  281. data = bytes.Replace(data, []byte("\n% "), []byte("\n"), -1)
  282. block := p.addBlock(Heading, data)
  283. block.Level = 1
  284. block.IsTitleblock = true
  285. return consumed
  286. }
  287. func (p *Markdown) html(data []byte, doRender bool) int {
  288. var i, j int
  289. // identify the opening tag
  290. if data[0] != '<' {
  291. return 0
  292. }
  293. curtag, tagfound := p.htmlFindTag(data[1:])
  294. // handle special cases
  295. if !tagfound {
  296. // check for an HTML comment
  297. if size := p.htmlComment(data, doRender); size > 0 {
  298. return size
  299. }
  300. // check for an <hr> tag
  301. if size := p.htmlHr(data, doRender); size > 0 {
  302. return size
  303. }
  304. // no special case recognized
  305. return 0
  306. }
  307. // look for an unindented matching closing tag
  308. // followed by a blank line
  309. found := false
  310. /*
  311. closetag := []byte("\n</" + curtag + ">")
  312. j = len(curtag) + 1
  313. for !found {
  314. // scan for a closing tag at the beginning of a line
  315. if skip := bytes.Index(data[j:], closetag); skip >= 0 {
  316. j += skip + len(closetag)
  317. } else {
  318. break
  319. }
  320. // see if it is the only thing on the line
  321. if skip := p.isEmpty(data[j:]); skip > 0 {
  322. // see if it is followed by a blank line/eof
  323. j += skip
  324. if j >= len(data) {
  325. found = true
  326. i = j
  327. } else {
  328. if skip := p.isEmpty(data[j:]); skip > 0 {
  329. j += skip
  330. found = true
  331. i = j
  332. }
  333. }
  334. }
  335. }
  336. */
  337. // if not found, try a second pass looking for indented match
  338. // but not if tag is "ins" or "del" (following original Markdown.pl)
  339. if !found && curtag != "ins" && curtag != "del" {
  340. i = 1
  341. for i < len(data) {
  342. i++
  343. for i < len(data) && !(data[i-1] == '<' && data[i] == '/') {
  344. i++
  345. }
  346. if i+2+len(curtag) >= len(data) {
  347. break
  348. }
  349. j = p.htmlFindEnd(curtag, data[i-1:])
  350. if j > 0 {
  351. i += j - 1
  352. found = true
  353. break
  354. }
  355. }
  356. }
  357. if !found {
  358. return 0
  359. }
  360. // the end of the block has been found
  361. if doRender {
  362. // trim newlines
  363. end := i
  364. for end > 0 && data[end-1] == '\n' {
  365. end--
  366. }
  367. finalizeHTMLBlock(p.addBlock(HTMLBlock, data[:end]))
  368. }
  369. return i
  370. }
  371. func finalizeHTMLBlock(block *Node) {
  372. block.Literal = block.content
  373. block.content = nil
  374. }
  375. // HTML comment, lax form
  376. func (p *Markdown) htmlComment(data []byte, doRender bool) int {
  377. i := p.inlineHTMLComment(data)
  378. // needs to end with a blank line
  379. if j := p.isEmpty(data[i:]); j > 0 {
  380. size := i + j
  381. if doRender {
  382. // trim trailing newlines
  383. end := size
  384. for end > 0 && data[end-1] == '\n' {
  385. end--
  386. }
  387. block := p.addBlock(HTMLBlock, data[:end])
  388. finalizeHTMLBlock(block)
  389. }
  390. return size
  391. }
  392. return 0
  393. }
  394. // HR, which is the only self-closing block tag considered
  395. func (p *Markdown) htmlHr(data []byte, doRender bool) int {
  396. if len(data) < 4 {
  397. return 0
  398. }
  399. if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') {
  400. return 0
  401. }
  402. if data[3] != ' ' && data[3] != '/' && data[3] != '>' {
  403. // not an <hr> tag after all; at least not a valid one
  404. return 0
  405. }
  406. i := 3
  407. for i < len(data) && data[i] != '>' && data[i] != '\n' {
  408. i++
  409. }
  410. if i < len(data) && data[i] == '>' {
  411. i++
  412. if j := p.isEmpty(data[i:]); j > 0 {
  413. size := i + j
  414. if doRender {
  415. // trim newlines
  416. end := size
  417. for end > 0 && data[end-1] == '\n' {
  418. end--
  419. }
  420. finalizeHTMLBlock(p.addBlock(HTMLBlock, data[:end]))
  421. }
  422. return size
  423. }
  424. }
  425. return 0
  426. }
  427. func (p *Markdown) htmlFindTag(data []byte) (string, bool) {
  428. i := 0
  429. for i < len(data) && isalnum(data[i]) {
  430. i++
  431. }
  432. key := string(data[:i])
  433. if _, ok := blockTags[key]; ok {
  434. return key, true
  435. }
  436. return "", false
  437. }
  438. func (p *Markdown) htmlFindEnd(tag string, data []byte) int {
  439. // assume data[0] == '<' && data[1] == '/' already tested
  440. if tag == "hr" {
  441. return 2
  442. }
  443. // check if tag is a match
  444. closetag := []byte("</" + tag + ">")
  445. if !bytes.HasPrefix(data, closetag) {
  446. return 0
  447. }
  448. i := len(closetag)
  449. // check that the rest of the line is blank
  450. skip := 0
  451. if skip = p.isEmpty(data[i:]); skip == 0 {
  452. return 0
  453. }
  454. i += skip
  455. skip = 0
  456. if i >= len(data) {
  457. return i
  458. }
  459. if p.extensions&LaxHTMLBlocks != 0 {
  460. return i
  461. }
  462. if skip = p.isEmpty(data[i:]); skip == 0 {
  463. // following line must be blank
  464. return 0
  465. }
  466. return i + skip
  467. }
  468. func (*Markdown) isEmpty(data []byte) int {
  469. // it is okay to call isEmpty on an empty buffer
  470. if len(data) == 0 {
  471. return 0
  472. }
  473. var i int
  474. for i = 0; i < len(data) && data[i] != '\n'; i++ {
  475. if data[i] != ' ' && data[i] != '\t' {
  476. return 0
  477. }
  478. }
  479. if i < len(data) && data[i] == '\n' {
  480. i++
  481. }
  482. return i
  483. }
  484. func (*Markdown) isHRule(data []byte) bool {
  485. i := 0
  486. // skip up to three spaces
  487. for i < 3 && data[i] == ' ' {
  488. i++
  489. }
  490. // look at the hrule char
  491. if data[i] != '*' && data[i] != '-' && data[i] != '_' {
  492. return false
  493. }
  494. c := data[i]
  495. // the whole line must be the char or whitespace
  496. n := 0
  497. for i < len(data) && data[i] != '\n' {
  498. switch {
  499. case data[i] == c:
  500. n++
  501. case data[i] != ' ':
  502. return false
  503. }
  504. i++
  505. }
  506. return n >= 3
  507. }
  508. // isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data,
  509. // and returns the end index if so, or 0 otherwise. It also returns the marker found.
  510. // If info is not nil, it gets set to the syntax specified in the fence line.
  511. func isFenceLine(data []byte, info *string, oldmarker string) (end int, marker string) {
  512. i, size := 0, 0
  513. // skip up to three spaces
  514. for i < len(data) && i < 3 && data[i] == ' ' {
  515. i++
  516. }
  517. // check for the marker characters: ~ or `
  518. if i >= len(data) {
  519. return 0, ""
  520. }
  521. if data[i] != '~' && data[i] != '`' {
  522. return 0, ""
  523. }
  524. c := data[i]
  525. // the whole line must be the same char or whitespace
  526. for i < len(data) && data[i] == c {
  527. size++
  528. i++
  529. }
  530. // the marker char must occur at least 3 times
  531. if size < 3 {
  532. return 0, ""
  533. }
  534. marker = string(data[i-size : i])
  535. // if this is the end marker, it must match the beginning marker
  536. if oldmarker != "" && marker != oldmarker {
  537. return 0, ""
  538. }
  539. // TODO(shurcooL): It's probably a good idea to simplify the 2 code paths here
  540. // into one, always get the info string, and discard it if the caller doesn't care.
  541. if info != nil {
  542. infoLength := 0
  543. i = skipChar(data, i, ' ')
  544. if i >= len(data) {
  545. if i == len(data) {
  546. return i, marker
  547. }
  548. return 0, ""
  549. }
  550. infoStart := i
  551. if data[i] == '{' {
  552. i++
  553. infoStart++
  554. for i < len(data) && data[i] != '}' && data[i] != '\n' {
  555. infoLength++
  556. i++
  557. }
  558. if i >= len(data) || data[i] != '}' {
  559. return 0, ""
  560. }
  561. // strip all whitespace at the beginning and the end
  562. // of the {} block
  563. for infoLength > 0 && isspace(data[infoStart]) {
  564. infoStart++
  565. infoLength--
  566. }
  567. for infoLength > 0 && isspace(data[infoStart+infoLength-1]) {
  568. infoLength--
  569. }
  570. i++
  571. i = skipChar(data, i, ' ')
  572. } else {
  573. for i < len(data) && !isverticalspace(data[i]) {
  574. infoLength++
  575. i++
  576. }
  577. }
  578. *info = strings.TrimSpace(string(data[infoStart : infoStart+infoLength]))
  579. }
  580. if i == len(data) {
  581. return i, marker
  582. }
  583. if i > len(data) || data[i] != '\n' {
  584. return 0, ""
  585. }
  586. return i + 1, marker // Take newline into account.
  587. }
  588. // fencedCodeBlock returns the end index if data contains a fenced code block at the beginning,
  589. // or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects.
  590. // If doRender is true, a final newline is mandatory to recognize the fenced code block.
  591. func (p *Markdown) fencedCodeBlock(data []byte, doRender bool) int {
  592. var info string
  593. beg, marker := isFenceLine(data, &info, "")
  594. if beg == 0 || beg >= len(data) {
  595. return 0
  596. }
  597. fenceLength := beg - 1
  598. var work bytes.Buffer
  599. work.Write([]byte(info))
  600. work.WriteByte('\n')
  601. for {
  602. // safe to assume beg < len(data)
  603. // check for the end of the code block
  604. fenceEnd, _ := isFenceLine(data[beg:], nil, marker)
  605. if fenceEnd != 0 {
  606. beg += fenceEnd
  607. break
  608. }
  609. // copy the current line
  610. end := skipUntilChar(data, beg, '\n') + 1
  611. // did we reach the end of the buffer without a closing marker?
  612. if end >= len(data) {
  613. return 0
  614. }
  615. // verbatim copy to the working buffer
  616. if doRender {
  617. work.Write(data[beg:end])
  618. }
  619. beg = end
  620. }
  621. if doRender {
  622. block := p.addBlock(CodeBlock, work.Bytes()) // TODO: get rid of temp buffer
  623. block.IsFenced = true
  624. block.FenceLength = fenceLength
  625. finalizeCodeBlock(block)
  626. }
  627. return beg
  628. }
  629. func unescapeChar(str []byte) []byte {
  630. if str[0] == '\\' {
  631. return []byte{str[1]}
  632. }
  633. return []byte(html.UnescapeString(string(str)))
  634. }
  635. func unescapeString(str []byte) []byte {
  636. if reBackslashOrAmp.Match(str) {
  637. return reEntityOrEscapedChar.ReplaceAllFunc(str, unescapeChar)
  638. }
  639. return str
  640. }
  641. func finalizeCodeBlock(block *Node) {
  642. if block.IsFenced {
  643. newlinePos := bytes.IndexByte(block.content, '\n')
  644. firstLine := block.content[:newlinePos]
  645. rest := block.content[newlinePos+1:]
  646. block.Info = unescapeString(bytes.Trim(firstLine, "\n"))
  647. block.Literal = rest
  648. } else {
  649. block.Literal = block.content
  650. }
  651. block.content = nil
  652. }
  653. func (p *Markdown) table(data []byte) int {
  654. table := p.addBlock(Table, nil)
  655. i, columns := p.tableHeader(data)
  656. if i == 0 {
  657. p.tip = table.Parent
  658. table.Unlink()
  659. return 0
  660. }
  661. p.addBlock(TableBody, nil)
  662. for i < len(data) {
  663. pipes, rowStart := 0, i
  664. for ; i < len(data) && data[i] != '\n'; i++ {
  665. if data[i] == '|' {
  666. pipes++
  667. }
  668. }
  669. if pipes == 0 {
  670. i = rowStart
  671. break
  672. }
  673. // include the newline in data sent to tableRow
  674. if i < len(data) && data[i] == '\n' {
  675. i++
  676. }
  677. p.tableRow(data[rowStart:i], columns, false)
  678. }
  679. return i
  680. }
  681. // check if the specified position is preceded by an odd number of backslashes
  682. func isBackslashEscaped(data []byte, i int) bool {
  683. backslashes := 0
  684. for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' {
  685. backslashes++
  686. }
  687. return backslashes&1 == 1
  688. }
  689. func (p *Markdown) tableHeader(data []byte) (size int, columns []CellAlignFlags) {
  690. i := 0
  691. colCount := 1
  692. for i = 0; i < len(data) && data[i] != '\n'; i++ {
  693. if data[i] == '|' && !isBackslashEscaped(data, i) {
  694. colCount++
  695. }
  696. }
  697. // doesn't look like a table header
  698. if colCount == 1 {
  699. return
  700. }
  701. // include the newline in the data sent to tableRow
  702. j := i
  703. if j < len(data) && data[j] == '\n' {
  704. j++
  705. }
  706. header := data[:j]
  707. // column count ignores pipes at beginning or end of line
  708. if data[0] == '|' {
  709. colCount--
  710. }
  711. if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) {
  712. colCount--
  713. }
  714. columns = make([]CellAlignFlags, colCount)
  715. // move on to the header underline
  716. i++
  717. if i >= len(data) {
  718. return
  719. }
  720. if data[i] == '|' && !isBackslashEscaped(data, i) {
  721. i++
  722. }
  723. i = skipChar(data, i, ' ')
  724. // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3
  725. // and trailing | optional on last column
  726. col := 0
  727. for i < len(data) && data[i] != '\n' {
  728. dashes := 0
  729. if data[i] == ':' {
  730. i++
  731. columns[col] |= TableAlignmentLeft
  732. dashes++
  733. }
  734. for i < len(data) && data[i] == '-' {
  735. i++
  736. dashes++
  737. }
  738. if i < len(data) && data[i] == ':' {
  739. i++
  740. columns[col] |= TableAlignmentRight
  741. dashes++
  742. }
  743. for i < len(data) && data[i] == ' ' {
  744. i++
  745. }
  746. if i == len(data) {
  747. return
  748. }
  749. // end of column test is messy
  750. switch {
  751. case dashes < 3:
  752. // not a valid column
  753. return
  754. case data[i] == '|' && !isBackslashEscaped(data, i):
  755. // marker found, now skip past trailing whitespace
  756. col++
  757. i++
  758. for i < len(data) && data[i] == ' ' {
  759. i++
  760. }
  761. // trailing junk found after last column
  762. if col >= colCount && i < len(data) && data[i] != '\n' {
  763. return
  764. }
  765. case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount:
  766. // something else found where marker was required
  767. return
  768. case data[i] == '\n':
  769. // marker is optional for the last column
  770. col++
  771. default:
  772. // trailing junk found after last column
  773. return
  774. }
  775. }
  776. if col != colCount {
  777. return
  778. }
  779. p.addBlock(TableHead, nil)
  780. p.tableRow(header, columns, true)
  781. size = i
  782. if size < len(data) && data[size] == '\n' {
  783. size++
  784. }
  785. return
  786. }
  787. func (p *Markdown) tableRow(data []byte, columns []CellAlignFlags, header bool) {
  788. p.addBlock(TableRow, nil)
  789. i, col := 0, 0
  790. if data[i] == '|' && !isBackslashEscaped(data, i) {
  791. i++
  792. }
  793. for col = 0; col < len(columns) && i < len(data); col++ {
  794. for i < len(data) && data[i] == ' ' {
  795. i++
  796. }
  797. cellStart := i
  798. for i < len(data) && (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' {
  799. i++
  800. }
  801. cellEnd := i
  802. // skip the end-of-cell marker, possibly taking us past end of buffer
  803. i++
  804. for cellEnd > cellStart && cellEnd-1 < len(data) && data[cellEnd-1] == ' ' {
  805. cellEnd--
  806. }
  807. cell := p.addBlock(TableCell, data[cellStart:cellEnd])
  808. cell.IsHeader = header
  809. cell.Align = columns[col]
  810. }
  811. // pad it out with empty columns to get the right number
  812. for ; col < len(columns); col++ {
  813. cell := p.addBlock(TableCell, nil)
  814. cell.IsHeader = header
  815. cell.Align = columns[col]
  816. }
  817. // silently ignore rows with too many cells
  818. }
  819. // returns blockquote prefix length
  820. func (p *Markdown) quotePrefix(data []byte) int {
  821. i := 0
  822. for i < 3 && i < len(data) && data[i] == ' ' {
  823. i++
  824. }
  825. if i < len(data) && data[i] == '>' {
  826. if i+1 < len(data) && data[i+1] == ' ' {
  827. return i + 2
  828. }
  829. return i + 1
  830. }
  831. return 0
  832. }
  833. // blockquote ends with at least one blank line
  834. // followed by something without a blockquote prefix
  835. func (p *Markdown) terminateBlockquote(data []byte, beg, end int) bool {
  836. if p.isEmpty(data[beg:]) <= 0 {
  837. return false
  838. }
  839. if end >= len(data) {
  840. return true
  841. }
  842. return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0
  843. }
  844. // parse a blockquote fragment
  845. func (p *Markdown) quote(data []byte) int {
  846. block := p.addBlock(BlockQuote, nil)
  847. var raw bytes.Buffer
  848. beg, end := 0, 0
  849. for beg < len(data) {
  850. end = beg
  851. // Step over whole lines, collecting them. While doing that, check for
  852. // fenced code and if one's found, incorporate it altogether,
  853. // irregardless of any contents inside it
  854. for end < len(data) && data[end] != '\n' {
  855. if p.extensions&FencedCode != 0 {
  856. if i := p.fencedCodeBlock(data[end:], false); i > 0 {
  857. // -1 to compensate for the extra end++ after the loop:
  858. end += i - 1
  859. break
  860. }
  861. }
  862. end++
  863. }
  864. if end < len(data) && data[end] == '\n' {
  865. end++
  866. }
  867. if pre := p.quotePrefix(data[beg:]); pre > 0 {
  868. // skip the prefix
  869. beg += pre
  870. } else if p.terminateBlockquote(data, beg, end) {
  871. break
  872. }
  873. // this line is part of the blockquote
  874. raw.Write(data[beg:end])
  875. beg = end
  876. }
  877. p.block(raw.Bytes())
  878. p.finalize(block)
  879. return end
  880. }
  881. // returns prefix length for block code
  882. func (p *Markdown) codePrefix(data []byte) int {
  883. if len(data) >= 1 && data[0] == '\t' {
  884. return 1
  885. }
  886. if len(data) >= 4 && data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' {
  887. return 4
  888. }
  889. return 0
  890. }
  891. func (p *Markdown) code(data []byte) int {
  892. var work bytes.Buffer
  893. i := 0
  894. for i < len(data) {
  895. beg := i
  896. for i < len(data) && data[i] != '\n' {
  897. i++
  898. }
  899. if i < len(data) && data[i] == '\n' {
  900. i++
  901. }
  902. blankline := p.isEmpty(data[beg:i]) > 0
  903. if pre := p.codePrefix(data[beg:i]); pre > 0 {
  904. beg += pre
  905. } else if !blankline {
  906. // non-empty, non-prefixed line breaks the pre
  907. i = beg
  908. break
  909. }
  910. // verbatim copy to the working buffer
  911. if blankline {
  912. work.WriteByte('\n')
  913. } else {
  914. work.Write(data[beg:i])
  915. }
  916. }
  917. // trim all the \n off the end of work
  918. workbytes := work.Bytes()
  919. eol := len(workbytes)
  920. for eol > 0 && workbytes[eol-1] == '\n' {
  921. eol--
  922. }
  923. if eol != len(workbytes) {
  924. work.Truncate(eol)
  925. }
  926. work.WriteByte('\n')
  927. block := p.addBlock(CodeBlock, work.Bytes()) // TODO: get rid of temp buffer
  928. block.IsFenced = false
  929. finalizeCodeBlock(block)
  930. return i
  931. }
  932. // returns unordered list item prefix
  933. func (p *Markdown) uliPrefix(data []byte) int {
  934. i := 0
  935. // start with up to 3 spaces
  936. for i < len(data) && i < 3 && data[i] == ' ' {
  937. i++
  938. }
  939. if i >= len(data)-1 {
  940. return 0
  941. }
  942. // need one of {'*', '+', '-'} followed by a space or a tab
  943. if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
  944. (data[i+1] != ' ' && data[i+1] != '\t') {
  945. return 0
  946. }
  947. return i + 2
  948. }
  949. // returns ordered list item prefix
  950. func (p *Markdown) oliPrefix(data []byte) int {
  951. i := 0
  952. // start with up to 3 spaces
  953. for i < 3 && i < len(data) && data[i] == ' ' {
  954. i++
  955. }
  956. // count the digits
  957. start := i
  958. for i < len(data) && data[i] >= '0' && data[i] <= '9' {
  959. i++
  960. }
  961. if start == i || i >= len(data)-1 {
  962. return 0
  963. }
  964. // we need >= 1 digits followed by a dot and a space or a tab
  965. if data[i] != '.' || !(data[i+1] == ' ' || data[i+1] == '\t') {
  966. return 0
  967. }
  968. return i + 2
  969. }
  970. // returns definition list item prefix
  971. func (p *Markdown) dliPrefix(data []byte) int {
  972. if len(data) < 2 {
  973. return 0
  974. }
  975. i := 0
  976. // need a ':' followed by a space or a tab
  977. if data[i] != ':' || !(data[i+1] == ' ' || data[i+1] == '\t') {
  978. return 0
  979. }
  980. for i < len(data) && data[i] == ' ' {
  981. i++
  982. }
  983. return i + 2
  984. }
  985. // parse ordered or unordered list block
  986. func (p *Markdown) list(data []byte, flags ListType) int {
  987. i := 0
  988. flags |= ListItemBeginningOfList
  989. block := p.addBlock(List, nil)
  990. block.ListFlags = flags
  991. block.Tight = true
  992. for i < len(data) {
  993. skip := p.listItem(data[i:], &flags)
  994. if flags&ListItemContainsBlock != 0 {
  995. block.ListData.Tight = false
  996. }
  997. i += skip
  998. if skip == 0 || flags&ListItemEndOfList != 0 {
  999. break
  1000. }
  1001. flags &= ^ListItemBeginningOfList
  1002. }
  1003. above := block.Parent
  1004. finalizeList(block)
  1005. p.tip = above
  1006. return i
  1007. }
  1008. // Returns true if the list item is not the same type as its parent list
  1009. func (p *Markdown) listTypeChanged(data []byte, flags *ListType) bool {
  1010. if p.dliPrefix(data) > 0 && *flags&ListTypeDefinition == 0 {
  1011. return true
  1012. } else if p.oliPrefix(data) > 0 && *flags&ListTypeOrdered == 0 {
  1013. return true
  1014. } else if p.uliPrefix(data) > 0 && (*flags&ListTypeOrdered != 0 || *flags&ListTypeDefinition != 0) {
  1015. return true
  1016. }
  1017. return false
  1018. }
  1019. // Returns true if block ends with a blank line, descending if needed
  1020. // into lists and sublists.
  1021. func endsWithBlankLine(block *Node) bool {
  1022. // TODO: figure this out. Always false now.
  1023. for block != nil {
  1024. //if block.lastLineBlank {
  1025. //return true
  1026. //}
  1027. t := block.Type
  1028. if t == List || t == Item {
  1029. block = block.LastChild
  1030. } else {
  1031. break
  1032. }
  1033. }
  1034. return false
  1035. }
  1036. func finalizeList(block *Node) {
  1037. block.open = false
  1038. item := block.FirstChild
  1039. for item != nil {
  1040. // check for non-final list item ending with blank line:
  1041. if endsWithBlankLine(item) && item.Next != nil {
  1042. block.ListData.Tight = false
  1043. break
  1044. }
  1045. // recurse into children of list item, to see if there are spaces
  1046. // between any of them:
  1047. subItem := item.FirstChild
  1048. for subItem != nil {
  1049. if endsWithBlankLine(subItem) && (item.Next != nil || subItem.Next != nil) {
  1050. block.ListData.Tight = false
  1051. break
  1052. }
  1053. subItem = subItem.Next
  1054. }
  1055. item = item.Next
  1056. }
  1057. }
  1058. // Parse a single list item.
  1059. // Assumes initial prefix is already removed if this is a sublist.
  1060. func (p *Markdown) listItem(data []byte, flags *ListType) int {
  1061. // keep track of the indentation of the first line
  1062. itemIndent := 0
  1063. if data[0] == '\t' {
  1064. itemIndent += 4
  1065. } else {
  1066. for itemIndent < 3 && data[itemIndent] == ' ' {
  1067. itemIndent++
  1068. }
  1069. }
  1070. var bulletChar byte = '*'
  1071. i := p.uliPrefix(data)
  1072. if i == 0 {
  1073. i = p.oliPrefix(data)
  1074. } else {
  1075. bulletChar = data[i-2]
  1076. }
  1077. if i == 0 {
  1078. i = p.dliPrefix(data)
  1079. // reset definition term flag
  1080. if i > 0 {
  1081. *flags &= ^ListTypeTerm
  1082. }
  1083. }
  1084. if i == 0 {
  1085. // if in definition list, set term flag and continue
  1086. if *flags&ListTypeDefinition != 0 {
  1087. *flags |= ListTypeTerm
  1088. } else {
  1089. return 0
  1090. }
  1091. }
  1092. // skip leading whitespace on first line
  1093. for i < len(data) && data[i] == ' ' {
  1094. i++
  1095. }
  1096. // find the end of the line
  1097. line := i
  1098. for i > 0 && i < len(data) && data[i-1] != '\n' {
  1099. i++
  1100. }
  1101. // get working buffer
  1102. var raw bytes.Buffer
  1103. // put the first line into the working buffer
  1104. raw.Write(data[line:i])
  1105. line = i
  1106. // process the following lines
  1107. containsBlankLine := false
  1108. sublist := 0
  1109. codeBlockMarker := ""
  1110. gatherlines:
  1111. for line < len(data) {
  1112. i++
  1113. // find the end of this line
  1114. for i < len(data) && data[i-1] != '\n' {
  1115. i++
  1116. }
  1117. // if it is an empty line, guess that it is part of this item
  1118. // and move on to the next line
  1119. if p.isEmpty(data[line:i]) > 0 {
  1120. containsBlankLine = true
  1121. line = i
  1122. continue
  1123. }
  1124. // calculate the indentation
  1125. indent := 0
  1126. indentIndex := 0
  1127. if data[line] == '\t' {
  1128. indentIndex++
  1129. indent += 4
  1130. } else {
  1131. for indent < 4 && line+indent < i && data[line+indent] == ' ' {
  1132. indent++
  1133. indentIndex++
  1134. }
  1135. }
  1136. chunk := data[line+indentIndex : i]
  1137. if p.extensions&FencedCode != 0 {
  1138. // determine if in or out of codeblock
  1139. // if in codeblock, ignore normal list processing
  1140. _, marker := isFenceLine(chunk, nil, codeBlockMarker)
  1141. if marker != "" {
  1142. if codeBlockMarker == "" {
  1143. // start of codeblock
  1144. codeBlockMarker = marker
  1145. } else {
  1146. // end of codeblock.
  1147. codeBlockMarker = ""
  1148. }
  1149. }
  1150. // we are in a codeblock, write line, and continue
  1151. if codeBlockMarker != "" || marker != "" {
  1152. raw.Write(data[line+indentIndex : i])
  1153. line = i
  1154. continue gatherlines
  1155. }
  1156. }
  1157. // evaluate how this line fits in
  1158. switch {
  1159. // is this a nested list item?
  1160. case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) ||
  1161. p.oliPrefix(chunk) > 0 ||
  1162. p.dliPrefix(chunk) > 0:
  1163. // to be a nested list, it must be indented more
  1164. // if not, it is either a different kind of list
  1165. // or the next item in the same list
  1166. if indent <= itemIndent {
  1167. if p.listTypeChanged(chunk, flags) {
  1168. *flags |= ListItemEndOfList
  1169. } else if containsBlankLine {
  1170. *flags |= ListItemContainsBlock
  1171. }
  1172. break gatherlines
  1173. }
  1174. if containsBlankLine {
  1175. *flags |= ListItemContainsBlock
  1176. }
  1177. // is this the first item in the nested list?
  1178. if sublist == 0 {
  1179. sublist = raw.Len()
  1180. }
  1181. // is this a nested prefix heading?
  1182. case p.isPrefixHeading(chunk):
  1183. // if the heading is not indented, it is not nested in the list
  1184. // and thus ends the list
  1185. if containsBlankLine && indent < 4 {
  1186. *flags |= ListItemEndOfList
  1187. break gatherlines
  1188. }
  1189. *flags |= ListItemContainsBlock
  1190. // anything following an empty line is only part
  1191. // of this item if it is indented 4 spaces
  1192. // (regardless of the indentation of the beginning of the item)
  1193. case containsBlankLine && indent < 4:
  1194. if *flags&ListTypeDefinition != 0 && i < len(data)-1 {
  1195. // is the next item still a part of this list?
  1196. next := i
  1197. for next < len(data) && data[next] != '\n' {
  1198. next++
  1199. }
  1200. for next < len(data)-1 && data[next] == '\n' {
  1201. next++
  1202. }
  1203. if i < len(data)-1 && data[i] != ':' && data[next] != ':' {
  1204. *flags |= ListItemEndOfList
  1205. }
  1206. } else {
  1207. *flags |= ListItemEndOfList
  1208. }
  1209. break gatherlines
  1210. // a blank line means this should be parsed as a block
  1211. case containsBlankLine:
  1212. raw.WriteByte('\n')
  1213. *flags |= ListItemContainsBlock
  1214. }
  1215. // if this line was preceded by one or more blanks,
  1216. // re-introduce the blank into the buffer
  1217. if containsBlankLine {
  1218. containsBlankLine = false
  1219. raw.WriteByte('\n')
  1220. }
  1221. // add the line into the working buffer without prefix
  1222. raw.Write(data[line+indentIndex : i])
  1223. line = i
  1224. }
  1225. rawBytes := raw.Bytes()
  1226. block := p.addBlock(Item, nil)
  1227. block.ListFlags = *flags
  1228. block.Tight = false
  1229. block.BulletChar = bulletChar
  1230. block.Delimiter = '.' // Only '.' is possible in Markdown, but ')' will also be possible in CommonMark
  1231. // render the contents of the list item
  1232. if *flags&ListItemContainsBlock != 0 && *flags&ListTypeTerm == 0 {
  1233. // intermediate render of block item, except for definition term
  1234. if sublist > 0 {
  1235. p.block(rawBytes[:sublist])
  1236. p.block(rawBytes[sublist:])
  1237. } else {
  1238. p.block(rawBytes)
  1239. }
  1240. } else {
  1241. // intermediate render of inline item
  1242. if sublist > 0 {
  1243. child := p.addChild(Paragraph, 0)
  1244. child.content = rawBytes[:sublist]
  1245. p.block(rawBytes[sublist:])
  1246. } else {
  1247. child := p.addChild(Paragraph, 0)
  1248. child.content = rawBytes
  1249. }
  1250. }
  1251. return line
  1252. }
  1253. // render a single paragraph that has already been parsed out
  1254. func (p *Markdown) renderParagraph(data []byte) {
  1255. if len(data) == 0 {
  1256. return
  1257. }
  1258. // trim leading spaces
  1259. beg := 0
  1260. for data[beg] == ' ' {
  1261. beg++
  1262. }
  1263. end := len(data)
  1264. // trim trailing newline
  1265. if data[len(data)-1] == '\n' {
  1266. end--
  1267. }
  1268. // trim trailing spaces
  1269. for end > beg && data[end-1] == ' ' {
  1270. end--
  1271. }
  1272. p.addBlock(Paragraph, data[beg:end])
  1273. }
  1274. func (p *Markdown) paragraph(data []byte) int {
  1275. // prev: index of 1st char of previous line
  1276. // line: index of 1st char of current line
  1277. // i: index of cursor/end of current line
  1278. var prev, line, i int
  1279. tabSize := TabSizeDefault
  1280. if p.extensions&TabSizeEight != 0 {
  1281. tabSize = TabSizeDouble
  1282. }
  1283. // keep going until we find something to mark the end of the paragraph
  1284. for i < len(data) {
  1285. // mark the beginning of the current line
  1286. prev = line
  1287. current := data[i:]
  1288. line = i
  1289. // did we find a reference or a footnote? If so, end a paragraph
  1290. // preceding it and report that we have consumed up to the end of that
  1291. // reference:
  1292. if refEnd := isReference(p, current, tabSize); refEnd > 0 {
  1293. p.renderParagraph(data[:i])
  1294. return i + refEnd
  1295. }
  1296. // did we find a blank line marking the end of the paragraph?
  1297. if n := p.isEmpty(current); n > 0 {
  1298. // did this blank line followed by a definition list item?
  1299. if p.extensions&DefinitionLists != 0 {
  1300. if i < len(data)-1 && data[i+1] == ':' {
  1301. return p.list(data[prev:], ListTypeDefinition)
  1302. }
  1303. }
  1304. p.renderParagraph(data[:i])
  1305. return i + n
  1306. }
  1307. // an underline under some text marks a heading, so our paragraph ended on prev line
  1308. if i > 0 {
  1309. if level := p.isUnderlinedHeading(current); level > 0 {
  1310. // render the paragraph
  1311. p.renderParagraph(data[:prev])
  1312. // ignore leading and trailing whitespace
  1313. eol := i - 1
  1314. for prev < eol && data[prev] == ' ' {
  1315. prev++
  1316. }
  1317. for eol > prev && data[eol-1] == ' ' {
  1318. eol--
  1319. }
  1320. id := ""
  1321. if p.extensions&AutoHeadingIDs != 0 {
  1322. id = SanitizedAnchorName(string(data[prev:eol]))
  1323. }
  1324. block := p.addBlock(Heading, data[prev:eol])
  1325. block.Level = level
  1326. block.HeadingID = id
  1327. // find the end of the underline
  1328. for i < len(data) && data[i] != '\n' {
  1329. i++
  1330. }
  1331. return i
  1332. }
  1333. }
  1334. // if the next line starts a block of HTML, then the paragraph ends here
  1335. if p.extensions&LaxHTMLBlocks != 0 {
  1336. if data[i] == '<' && p.html(current, false) > 0 {
  1337. // rewind to before the HTML block
  1338. p.renderParagraph(data[:i])
  1339. return i
  1340. }
  1341. }
  1342. // if there's a prefixed heading or a horizontal rule after this, paragraph is over
  1343. if p.isPrefixHeading(current) || p.isHRule(current) {
  1344. p.renderParagraph(data[:i])
  1345. return i
  1346. }
  1347. // if there's a fenced code block, paragraph is over
  1348. if p.extensions&FencedCode != 0 {
  1349. if p.fencedCodeBlock(current, false) > 0 {
  1350. p.renderParagraph(data[:i])
  1351. return i
  1352. }
  1353. }
  1354. // if there's a definition list item, prev line is a definition term
  1355. if p.extensions&DefinitionLists != 0 {
  1356. if p.dliPrefix(current) != 0 {
  1357. ret := p.list(data[prev:], ListTypeDefinition)
  1358. return ret
  1359. }
  1360. }
  1361. // if there's a list after this, paragraph is over
  1362. if p.extensions&NoEmptyLineBeforeBlock != 0 {
  1363. if p.uliPrefix(current) != 0 ||
  1364. p.oliPrefix(current) != 0 ||
  1365. p.quotePrefix(current) != 0 ||
  1366. p.codePrefix(current) != 0 {
  1367. p.renderParagraph(data[:i])
  1368. return i
  1369. }
  1370. }
  1371. // otherwise, scan to the beginning of the next line
  1372. nl := bytes.IndexByte(data[i:], '\n')
  1373. if nl >= 0 {
  1374. i += nl + 1
  1375. } else {
  1376. i += len(data[i:])
  1377. }
  1378. }
  1379. p.renderParagraph(data[:i])
  1380. return i
  1381. }
  1382. func skipChar(data []byte, start int, char byte) int {
  1383. i := start
  1384. for i < len(data) && data[i] == char {
  1385. i++
  1386. }
  1387. return i
  1388. }
  1389. func skipUntilChar(text []byte, start int, char byte) int {
  1390. i := start
  1391. for i < len(text) && text[i] != char {
  1392. i++
  1393. }
  1394. return i
  1395. }
  1396. // SanitizedAnchorName returns a sanitized anchor name for the given text.
  1397. //
  1398. // It implements the algorithm specified in the package comment.
  1399. func SanitizedAnchorName(text string) string {
  1400. var anchorName []rune
  1401. futureDash := false
  1402. for _, r := range text {
  1403. switch {
  1404. case unicode.IsLetter(r) || unicode.IsNumber(r):
  1405. if futureDash && len(anchorName) > 0 {
  1406. anchorName = append(anchorName, '-')
  1407. }
  1408. futureDash = false
  1409. anchorName = append(anchorName, unicode.ToLower(r))
  1410. default:
  1411. futureDash = true
  1412. }
  1413. }
  1414. return string(anchorName)
  1415. }