You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

803 lines
20 KiB

  1. package goorgeous
  2. import (
  3. "bufio"
  4. "bytes"
  5. "regexp"
  6. "github.com/russross/blackfriday"
  7. "github.com/shurcooL/sanitized_anchor_name"
  8. )
  9. type inlineParser func(p *parser, out *bytes.Buffer, data []byte, offset int) int
  10. type footnotes struct {
  11. id string
  12. def string
  13. }
  14. type parser struct {
  15. r blackfriday.Renderer
  16. inlineCallback [256]inlineParser
  17. notes []footnotes
  18. }
  19. // NewParser returns a new parser with the inlineCallbacks required for org content
  20. func NewParser(renderer blackfriday.Renderer) *parser {
  21. p := new(parser)
  22. p.r = renderer
  23. p.inlineCallback['='] = generateVerbatim
  24. p.inlineCallback['~'] = generateCode
  25. p.inlineCallback['/'] = generateEmphasis
  26. p.inlineCallback['_'] = generateUnderline
  27. p.inlineCallback['*'] = generateBold
  28. p.inlineCallback['+'] = generateStrikethrough
  29. p.inlineCallback['['] = generateLinkOrImg
  30. return p
  31. }
  32. // OrgCommon is the easiest way to parse a byte slice of org content and makes assumptions
  33. // that the caller wants to use blackfriday's HTMLRenderer with XHTML
  34. func OrgCommon(input []byte) []byte {
  35. renderer := blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML, "", "")
  36. return OrgOptions(input, renderer)
  37. }
  38. // Org is a convenience name for OrgOptions
  39. func Org(input []byte, renderer blackfriday.Renderer) []byte {
  40. return OrgOptions(input, renderer)
  41. }
  42. // OrgOptions takes an org content byte slice and a renderer to use
  43. func OrgOptions(input []byte, renderer blackfriday.Renderer) []byte {
  44. // in the case that we need to render something in isEmpty but there isn't a new line char
  45. input = append(input, '\n')
  46. var output bytes.Buffer
  47. p := NewParser(renderer)
  48. scanner := bufio.NewScanner(bytes.NewReader(input))
  49. // used to capture code blocks
  50. marker := ""
  51. syntax := ""
  52. listType := ""
  53. inParagraph := false
  54. inList := false
  55. inTable := false
  56. inFixedWidthArea := false
  57. var tmpBlock bytes.Buffer
  58. for scanner.Scan() {
  59. data := scanner.Bytes()
  60. if !isEmpty(data) && isComment(data) || IsKeyword(data) {
  61. switch {
  62. case inList:
  63. if tmpBlock.Len() > 0 {
  64. p.generateList(&output, tmpBlock.Bytes(), listType)
  65. }
  66. inList = false
  67. listType = ""
  68. tmpBlock.Reset()
  69. case inTable:
  70. if tmpBlock.Len() > 0 {
  71. p.generateTable(&output, tmpBlock.Bytes())
  72. }
  73. inTable = false
  74. tmpBlock.Reset()
  75. case inParagraph:
  76. if tmpBlock.Len() > 0 {
  77. p.generateParagraph(&output, tmpBlock.Bytes()[:len(tmpBlock.Bytes())-1])
  78. }
  79. inParagraph = false
  80. tmpBlock.Reset()
  81. case inFixedWidthArea:
  82. if tmpBlock.Len() > 0 {
  83. tmpBlock.WriteString("</pre>\n")
  84. output.Write(tmpBlock.Bytes())
  85. }
  86. inFixedWidthArea = false
  87. tmpBlock.Reset()
  88. }
  89. }
  90. switch {
  91. case isEmpty(data):
  92. switch {
  93. case inList:
  94. if tmpBlock.Len() > 0 {
  95. p.generateList(&output, tmpBlock.Bytes(), listType)
  96. }
  97. inList = false
  98. listType = ""
  99. tmpBlock.Reset()
  100. case inTable:
  101. if tmpBlock.Len() > 0 {
  102. p.generateTable(&output, tmpBlock.Bytes())
  103. }
  104. inTable = false
  105. tmpBlock.Reset()
  106. case inParagraph:
  107. if tmpBlock.Len() > 0 {
  108. p.generateParagraph(&output, tmpBlock.Bytes()[:len(tmpBlock.Bytes())-1])
  109. }
  110. inParagraph = false
  111. tmpBlock.Reset()
  112. case inFixedWidthArea:
  113. if tmpBlock.Len() > 0 {
  114. tmpBlock.WriteString("</pre>\n")
  115. output.Write(tmpBlock.Bytes())
  116. }
  117. inFixedWidthArea = false
  118. tmpBlock.Reset()
  119. case marker != "":
  120. tmpBlock.WriteByte('\n')
  121. default:
  122. continue
  123. }
  124. case isPropertyDrawer(data) || marker == "PROPERTIES":
  125. if marker == "" {
  126. marker = "PROPERTIES"
  127. }
  128. if bytes.Equal(data, []byte(":END:")) {
  129. marker = ""
  130. }
  131. continue
  132. case isBlock(data) || marker != "":
  133. matches := reBlock.FindSubmatch(data)
  134. if len(matches) > 0 {
  135. if string(matches[1]) == "END" {
  136. switch marker {
  137. case "QUOTE":
  138. var tmpBuf bytes.Buffer
  139. p.inline(&tmpBuf, tmpBlock.Bytes())
  140. p.r.BlockQuote(&output, tmpBuf.Bytes())
  141. case "CENTER":
  142. var tmpBuf bytes.Buffer
  143. output.WriteString("<center>\n")
  144. p.inline(&tmpBuf, tmpBlock.Bytes())
  145. output.Write(tmpBuf.Bytes())
  146. output.WriteString("</center>\n")
  147. default:
  148. tmpBlock.WriteByte('\n')
  149. p.r.BlockCode(&output, tmpBlock.Bytes(), syntax)
  150. }
  151. marker = ""
  152. tmpBlock.Reset()
  153. continue
  154. }
  155. }
  156. if marker != "" {
  157. if marker != "SRC" && marker != "EXAMPLE" {
  158. var tmpBuf bytes.Buffer
  159. tmpBuf.Write([]byte("<p>\n"))
  160. p.inline(&tmpBuf, data)
  161. tmpBuf.WriteByte('\n')
  162. tmpBuf.Write([]byte("</p>\n"))
  163. tmpBlock.Write(tmpBuf.Bytes())
  164. } else {
  165. tmpBlock.WriteByte('\n')
  166. tmpBlock.Write(data)
  167. }
  168. } else {
  169. marker = string(matches[2])
  170. syntax = string(matches[3])
  171. }
  172. case isFootnoteDef(data):
  173. matches := reFootnoteDef.FindSubmatch(data)
  174. for i := range p.notes {
  175. if p.notes[i].id == string(matches[1]) {
  176. p.notes[i].def = string(matches[2])
  177. }
  178. }
  179. case isTable(data):
  180. if inTable != true {
  181. inTable = true
  182. }
  183. tmpBlock.Write(data)
  184. tmpBlock.WriteByte('\n')
  185. case IsKeyword(data):
  186. continue
  187. case isComment(data):
  188. p.generateComment(&output, data)
  189. case isHeadline(data):
  190. p.generateHeadline(&output, data)
  191. case isDefinitionList(data):
  192. if inList != true {
  193. listType = "dl"
  194. inList = true
  195. }
  196. var work bytes.Buffer
  197. flags := blackfriday.LIST_TYPE_DEFINITION
  198. matches := reDefinitionList.FindSubmatch(data)
  199. flags |= blackfriday.LIST_TYPE_TERM
  200. p.inline(&work, matches[1])
  201. p.r.ListItem(&tmpBlock, work.Bytes(), flags)
  202. work.Reset()
  203. flags &= ^blackfriday.LIST_TYPE_TERM
  204. p.inline(&work, matches[2])
  205. p.r.ListItem(&tmpBlock, work.Bytes(), flags)
  206. case isUnorderedList(data):
  207. if inList != true {
  208. listType = "ul"
  209. inList = true
  210. }
  211. matches := reUnorderedList.FindSubmatch(data)
  212. var work bytes.Buffer
  213. p.inline(&work, matches[2])
  214. p.r.ListItem(&tmpBlock, work.Bytes(), 0)
  215. case isOrderedList(data):
  216. if inList != true {
  217. listType = "ol"
  218. inList = true
  219. }
  220. matches := reOrderedList.FindSubmatch(data)
  221. var work bytes.Buffer
  222. tmpBlock.WriteString("<li")
  223. if len(matches[2]) > 0 {
  224. tmpBlock.WriteString(" value=\"")
  225. tmpBlock.Write(matches[2])
  226. tmpBlock.WriteString("\"")
  227. matches[3] = matches[3][1:]
  228. }
  229. p.inline(&work, matches[3])
  230. tmpBlock.WriteString(">")
  231. tmpBlock.Write(work.Bytes())
  232. tmpBlock.WriteString("</li>\n")
  233. case isHorizontalRule(data):
  234. p.r.HRule(&output)
  235. case isExampleLine(data):
  236. if inParagraph == true {
  237. if len(tmpBlock.Bytes()) > 0 {
  238. p.generateParagraph(&output, tmpBlock.Bytes()[:len(tmpBlock.Bytes())-1])
  239. inParagraph = false
  240. }
  241. tmpBlock.Reset()
  242. }
  243. if inFixedWidthArea != true {
  244. tmpBlock.WriteString("<pre class=\"example\">\n")
  245. inFixedWidthArea = true
  246. }
  247. matches := reExampleLine.FindSubmatch(data)
  248. tmpBlock.Write(matches[1])
  249. tmpBlock.WriteString("\n")
  250. break
  251. default:
  252. if inParagraph == false {
  253. inParagraph = true
  254. if inFixedWidthArea == true {
  255. if tmpBlock.Len() > 0 {
  256. tmpBlock.WriteString("</pre>")
  257. output.Write(tmpBlock.Bytes())
  258. }
  259. inFixedWidthArea = false
  260. tmpBlock.Reset()
  261. }
  262. }
  263. tmpBlock.Write(data)
  264. tmpBlock.WriteByte('\n')
  265. }
  266. }
  267. if len(tmpBlock.Bytes()) > 0 {
  268. if inParagraph == true {
  269. p.generateParagraph(&output, tmpBlock.Bytes()[:len(tmpBlock.Bytes())-1])
  270. } else if inFixedWidthArea == true {
  271. tmpBlock.WriteString("</pre>\n")
  272. output.Write(tmpBlock.Bytes())
  273. }
  274. }
  275. // Writing footnote def. list
  276. if len(p.notes) > 0 {
  277. flags := blackfriday.LIST_ITEM_BEGINNING_OF_LIST
  278. p.r.Footnotes(&output, func() bool {
  279. for i := range p.notes {
  280. p.r.FootnoteItem(&output, []byte(p.notes[i].id), []byte(p.notes[i].def), flags)
  281. }
  282. return true
  283. })
  284. }
  285. return output.Bytes()
  286. }
  287. // Org Syntax has been broken up into 4 distinct sections based on
  288. // the org-syntax draft (http://orgmode.org/worg/dev/org-syntax.html):
  289. // - Headlines
  290. // - Greater Elements
  291. // - Elements
  292. // - Objects
  293. // Headlines
  294. func isHeadline(data []byte) bool {
  295. if !charMatches(data[0], '*') {
  296. return false
  297. }
  298. level := 0
  299. for level < 6 && charMatches(data[level], '*') {
  300. level++
  301. }
  302. return charMatches(data[level], ' ')
  303. }
  304. func (p *parser) generateHeadline(out *bytes.Buffer, data []byte) {
  305. level := 1
  306. status := ""
  307. priority := ""
  308. for level < 6 && data[level] == '*' {
  309. level++
  310. }
  311. start := skipChar(data, level, ' ')
  312. data = data[start:]
  313. i := 0
  314. // Check if has a status so it can be rendered as a separate span that can be hidden or
  315. // modified with CSS classes
  316. if hasStatus(data[i:4]) {
  317. status = string(data[i:4])
  318. i += 5 // one extra character for the next whitespace
  319. }
  320. // Check if the next byte is a priority marker
  321. if data[i] == '[' && hasPriority(data[i+1]) {
  322. priority = string(data[i+1])
  323. i += 4 // for "[c]" + ' '
  324. }
  325. tags, tagsFound := findTags(data, i)
  326. headlineID := sanitized_anchor_name.Create(string(data[i:]))
  327. generate := func() bool {
  328. dataEnd := len(data)
  329. if tagsFound > 0 {
  330. dataEnd = tagsFound
  331. }
  332. headline := bytes.TrimRight(data[i:dataEnd], " \t")
  333. if status != "" {
  334. out.WriteString("<span class=\"todo " + status + "\">" + status + "</span>")
  335. out.WriteByte(' ')
  336. }
  337. if priority != "" {
  338. out.WriteString("<span class=\"priority " + priority + "\">[" + priority + "]</span>")
  339. out.WriteByte(' ')
  340. }
  341. p.inline(out, headline)
  342. if tagsFound > 0 {
  343. for _, tag := range tags {
  344. out.WriteByte(' ')
  345. out.WriteString("<span class=\"tags " + tag + "\">" + tag + "</span>")
  346. out.WriteByte(' ')
  347. }
  348. }
  349. return true
  350. }
  351. p.r.Header(out, generate, level, headlineID)
  352. }
  353. func hasStatus(data []byte) bool {
  354. return bytes.Contains(data, []byte("TODO")) || bytes.Contains(data, []byte("DONE"))
  355. }
  356. func hasPriority(char byte) bool {
  357. return (charMatches(char, 'A') || charMatches(char, 'B') || charMatches(char, 'C'))
  358. }
  359. func findTags(data []byte, start int) ([]string, int) {
  360. tags := []string{}
  361. tagOpener := 0
  362. tagMarker := tagOpener
  363. for tIdx := start; tIdx < len(data); tIdx++ {
  364. if tagMarker > 0 && data[tIdx] == ':' {
  365. tags = append(tags, string(data[tagMarker+1:tIdx]))
  366. tagMarker = tIdx
  367. }
  368. if data[tIdx] == ':' && tagOpener == 0 && data[tIdx-1] == ' ' {
  369. tagMarker = tIdx
  370. tagOpener = tIdx
  371. }
  372. }
  373. return tags, tagOpener
  374. }
  375. // Greater Elements
  376. // ~~ Definition Lists
  377. var reDefinitionList = regexp.MustCompile(`^\s*-\s+(.+?)\s+::\s+(.*)`)
  378. func isDefinitionList(data []byte) bool {
  379. return reDefinitionList.Match(data)
  380. }
  381. // ~~ Example lines
  382. var reExampleLine = regexp.MustCompile(`^\s*:\s(\s*.*)|^\s*:$`)
  383. func isExampleLine(data []byte) bool {
  384. return reExampleLine.Match(data)
  385. }
  386. // ~~ Ordered Lists
  387. var reOrderedList = regexp.MustCompile(`^(\s*)\d+\.\s+\[?@?(\d*)\]?(.+)`)
  388. func isOrderedList(data []byte) bool {
  389. return reOrderedList.Match(data)
  390. }
  391. // ~~ Unordered Lists
  392. var reUnorderedList = regexp.MustCompile(`^(\s*)[-\+]\s+(.+)`)
  393. func isUnorderedList(data []byte) bool {
  394. return reUnorderedList.Match(data)
  395. }
  396. // ~~ Tables
  397. var reTableHeaders = regexp.MustCompile(`^[|+-]*$`)
  398. func isTable(data []byte) bool {
  399. return charMatches(data[0], '|')
  400. }
  401. func (p *parser) generateTable(output *bytes.Buffer, data []byte) {
  402. var table bytes.Buffer
  403. rows := bytes.Split(bytes.Trim(data, "\n"), []byte("\n"))
  404. hasTableHeaders := len(rows) > 1
  405. if len(rows) > 1 {
  406. hasTableHeaders = reTableHeaders.Match(rows[1])
  407. }
  408. tbodySet := false
  409. for idx, row := range rows {
  410. var rowBuff bytes.Buffer
  411. if hasTableHeaders && idx == 0 {
  412. table.WriteString("<thead>")
  413. for _, cell := range bytes.Split(row[1:len(row)-1], []byte("|")) {
  414. p.r.TableHeaderCell(&rowBuff, bytes.Trim(cell, " \t"), 0)
  415. }
  416. p.r.TableRow(&table, rowBuff.Bytes())
  417. table.WriteString("</thead>\n")
  418. } else if hasTableHeaders && idx == 1 {
  419. continue
  420. } else {
  421. if !tbodySet {
  422. table.WriteString("<tbody>")
  423. tbodySet = true
  424. }
  425. if !reTableHeaders.Match(row) {
  426. for _, cell := range bytes.Split(row[1:len(row)-1], []byte("|")) {
  427. var cellBuff bytes.Buffer
  428. p.inline(&cellBuff, bytes.Trim(cell, " \t"))
  429. p.r.TableCell(&rowBuff, cellBuff.Bytes(), 0)
  430. }
  431. p.r.TableRow(&table, rowBuff.Bytes())
  432. }
  433. if tbodySet && idx == len(rows)-1 {
  434. table.WriteString("</tbody>\n")
  435. tbodySet = false
  436. }
  437. }
  438. }
  439. output.WriteString("\n<table>\n")
  440. output.Write(table.Bytes())
  441. output.WriteString("</table>\n")
  442. }
  443. // ~~ Property Drawers
  444. func isPropertyDrawer(data []byte) bool {
  445. return bytes.Equal(data, []byte(":PROPERTIES:"))
  446. }
  447. // ~~ Dynamic Blocks
  448. var reBlock = regexp.MustCompile(`^#\+(BEGIN|END)_(\w+)\s*([0-9A-Za-z_\-]*)?`)
  449. func isBlock(data []byte) bool {
  450. return reBlock.Match(data)
  451. }
  452. // ~~ Footnotes
  453. var reFootnoteDef = regexp.MustCompile(`^\[fn:([\w]+)\] +(.+)`)
  454. func isFootnoteDef(data []byte) bool {
  455. return reFootnoteDef.Match(data)
  456. }
  457. // Elements
  458. // ~~ Keywords
  459. func IsKeyword(data []byte) bool {
  460. return len(data) > 2 && charMatches(data[0], '#') && charMatches(data[1], '+') && !charMatches(data[2], ' ')
  461. }
  462. // ~~ Comments
  463. func isComment(data []byte) bool {
  464. return charMatches(data[0], '#') && charMatches(data[1], ' ')
  465. }
  466. func (p *parser) generateComment(out *bytes.Buffer, data []byte) {
  467. var work bytes.Buffer
  468. work.WriteString("<!-- ")
  469. work.Write(data[2:])
  470. work.WriteString(" -->")
  471. work.WriteByte('\n')
  472. out.Write(work.Bytes())
  473. }
  474. // ~~ Horizontal Rules
  475. var reHorizontalRule = regexp.MustCompile(`^\s*?-----\s?$`)
  476. func isHorizontalRule(data []byte) bool {
  477. return reHorizontalRule.Match(data)
  478. }
  479. // ~~ Paragraphs
  480. func (p *parser) generateParagraph(out *bytes.Buffer, data []byte) {
  481. generate := func() bool {
  482. p.inline(out, bytes.Trim(data, " "))
  483. return true
  484. }
  485. p.r.Paragraph(out, generate)
  486. }
  487. func (p *parser) generateList(output *bytes.Buffer, data []byte, listType string) {
  488. generateList := func() bool {
  489. output.WriteByte('\n')
  490. p.inline(output, bytes.Trim(data, " "))
  491. return true
  492. }
  493. switch listType {
  494. case "ul":
  495. p.r.List(output, generateList, 0)
  496. case "ol":
  497. p.r.List(output, generateList, blackfriday.LIST_TYPE_ORDERED)
  498. case "dl":
  499. p.r.List(output, generateList, blackfriday.LIST_TYPE_DEFINITION)
  500. }
  501. }
  502. // Objects
  503. func (p *parser) inline(out *bytes.Buffer, data []byte) {
  504. i, end := 0, 0
  505. for i < len(data) {
  506. for end < len(data) && p.inlineCallback[data[end]] == nil {
  507. end++
  508. }
  509. p.r.Entity(out, data[i:end])
  510. if end >= len(data) {
  511. break
  512. }
  513. i = end
  514. handler := p.inlineCallback[data[i]]
  515. if consumed := handler(p, out, data, i); consumed > 0 {
  516. i += consumed
  517. end = i
  518. continue
  519. }
  520. end = i + 1
  521. }
  522. }
  523. func isAcceptablePreOpeningChar(dataIn, data []byte, offset int) bool {
  524. if len(dataIn) == len(data) {
  525. return true
  526. }
  527. char := dataIn[offset-1]
  528. return charMatches(char, ' ') || isPreChar(char)
  529. }
  530. func isPreChar(char byte) bool {
  531. return charMatches(char, '>') || charMatches(char, '(') || charMatches(char, '{') || charMatches(char, '[')
  532. }
  533. func isAcceptablePostClosingChar(char byte) bool {
  534. return charMatches(char, ' ') || isTerminatingChar(char)
  535. }
  536. func isTerminatingChar(char byte) bool {
  537. return charMatches(char, '.') || charMatches(char, ',') || charMatches(char, '?') || charMatches(char, '!') || charMatches(char, ')') || charMatches(char, '}') || charMatches(char, ']')
  538. }
  539. func findLastCharInInline(data []byte, char byte) int {
  540. timesFound := 0
  541. last := 0
  542. // Start from character after the inline indicator
  543. for i := 1; i < len(data); i++ {
  544. if timesFound == 1 {
  545. break
  546. }
  547. if data[i] == char {
  548. if len(data) == i+1 || (len(data) > i+1 && isAcceptablePostClosingChar(data[i+1])) {
  549. last = i
  550. timesFound += 1
  551. }
  552. }
  553. }
  554. return last
  555. }
  556. func generator(p *parser, out *bytes.Buffer, dataIn []byte, offset int, char byte, doInline bool, renderer func(*bytes.Buffer, []byte)) int {
  557. data := dataIn[offset:]
  558. c := byte(char)
  559. start := 1
  560. i := start
  561. if len(data) <= 1 {
  562. return 0
  563. }
  564. lastCharInside := findLastCharInInline(data, c)
  565. // Org mode spec says a non-whitespace character must immediately follow.
  566. // if the current char is the marker, then there's no text between, not a candidate
  567. if isSpace(data[i]) || lastCharInside == i || !isAcceptablePreOpeningChar(dataIn, data, offset) {
  568. return 0
  569. }
  570. if lastCharInside > 0 {
  571. var work bytes.Buffer
  572. if doInline {
  573. p.inline(&work, data[start:lastCharInside])
  574. renderer(out, work.Bytes())
  575. } else {
  576. renderer(out, data[start:lastCharInside])
  577. }
  578. next := lastCharInside + 1
  579. return next
  580. }
  581. return 0
  582. }
  583. // ~~ Text Markup
  584. func generateVerbatim(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  585. return generator(p, out, data, offset, '=', false, p.r.CodeSpan)
  586. }
  587. func generateCode(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  588. return generator(p, out, data, offset, '~', false, p.r.CodeSpan)
  589. }
  590. func generateEmphasis(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  591. return generator(p, out, data, offset, '/', true, p.r.Emphasis)
  592. }
  593. func generateUnderline(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  594. underline := func(out *bytes.Buffer, text []byte) {
  595. out.WriteString("<span style=\"text-decoration: underline;\">")
  596. out.Write(text)
  597. out.WriteString("</span>")
  598. }
  599. return generator(p, out, data, offset, '_', true, underline)
  600. }
  601. func generateBold(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  602. return generator(p, out, data, offset, '*', true, p.r.DoubleEmphasis)
  603. }
  604. func generateStrikethrough(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  605. return generator(p, out, data, offset, '+', true, p.r.StrikeThrough)
  606. }
  607. // ~~ Images and Links (inc. Footnote)
  608. var reLinkOrImg = regexp.MustCompile(`\[\[(.+?)\]\[?(.*?)\]?\]`)
  609. func generateLinkOrImg(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  610. data = data[offset+1:]
  611. start := 1
  612. i := start
  613. var hyperlink []byte
  614. isImage := false
  615. isFootnote := false
  616. closedLink := false
  617. hasContent := false
  618. if bytes.Equal(data[0:3], []byte("fn:")) {
  619. isFootnote = true
  620. } else if data[0] != '[' {
  621. return 0
  622. }
  623. if bytes.Equal(data[1:6], []byte("file:")) {
  624. isImage = true
  625. }
  626. for i < len(data) {
  627. currChar := data[i]
  628. switch {
  629. case charMatches(currChar, ']') && closedLink == false:
  630. if isImage {
  631. hyperlink = data[start+5 : i]
  632. } else if isFootnote {
  633. refid := data[start+2 : i]
  634. if bytes.Equal(refid, bytes.Trim(refid, " ")) {
  635. p.notes = append(p.notes, footnotes{string(refid), "DEFINITION NOT FOUND"})
  636. p.r.FootnoteRef(out, refid, len(p.notes))
  637. return i + 2
  638. } else {
  639. return 0
  640. }
  641. } else if bytes.Equal(data[i-4:i], []byte(".org")) {
  642. orgStart := start
  643. if bytes.Equal(data[orgStart:orgStart+2], []byte("./")) {
  644. orgStart = orgStart + 1
  645. }
  646. hyperlink = data[orgStart : i-4]
  647. } else {
  648. hyperlink = data[start:i]
  649. }
  650. closedLink = true
  651. case charMatches(currChar, '['):
  652. start = i + 1
  653. hasContent = true
  654. case charMatches(currChar, ']') && closedLink == true && hasContent == true && isImage == true:
  655. p.r.Image(out, hyperlink, data[start:i], data[start:i])
  656. return i + 3
  657. case charMatches(currChar, ']') && closedLink == true && hasContent == true:
  658. var tmpBuf bytes.Buffer
  659. p.inline(&tmpBuf, data[start:i])
  660. p.r.Link(out, hyperlink, tmpBuf.Bytes(), tmpBuf.Bytes())
  661. return i + 3
  662. case charMatches(currChar, ']') && closedLink == true && hasContent == false && isImage == true:
  663. p.r.Image(out, hyperlink, hyperlink, hyperlink)
  664. return i + 2
  665. case charMatches(currChar, ']') && closedLink == true && hasContent == false:
  666. p.r.Link(out, hyperlink, hyperlink, hyperlink)
  667. return i + 2
  668. }
  669. i++
  670. }
  671. return 0
  672. }
  673. // Helpers
  674. func skipChar(data []byte, start int, char byte) int {
  675. i := start
  676. for i < len(data) && charMatches(data[i], char) {
  677. i++
  678. }
  679. return i
  680. }
  681. func isSpace(char byte) bool {
  682. return charMatches(char, ' ')
  683. }
  684. func isEmpty(data []byte) bool {
  685. if len(data) == 0 {
  686. return true
  687. }
  688. for i := 0; i < len(data) && !charMatches(data[i], '\n'); i++ {
  689. if !charMatches(data[i], ' ') && !charMatches(data[i], '\t') {
  690. return false
  691. }
  692. }
  693. return true
  694. }
  695. func charMatches(a byte, b byte) bool {
  696. return a == b
  697. }