goorgeous.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. output.Write(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. for i := 0; i < len(data); i++ {
  543. if timesFound == 1 {
  544. break
  545. }
  546. if data[i] == char {
  547. if len(data) == i+1 || (len(data) > i+1 && isAcceptablePostClosingChar(data[i+1])) {
  548. last = i
  549. timesFound += 1
  550. }
  551. }
  552. }
  553. return last
  554. }
  555. func generator(p *parser, out *bytes.Buffer, dataIn []byte, offset int, char byte, doInline bool, renderer func(*bytes.Buffer, []byte)) int {
  556. data := dataIn[offset:]
  557. c := byte(char)
  558. start := 1
  559. i := start
  560. if len(data) <= 1 {
  561. return 0
  562. }
  563. lastCharInside := findLastCharInInline(data, c)
  564. // Org mode spec says a non-whitespace character must immediately follow.
  565. // if the current char is the marker, then there's no text between, not a candidate
  566. if isSpace(data[i]) || lastCharInside == i || !isAcceptablePreOpeningChar(dataIn, data, offset) {
  567. return 0
  568. }
  569. if lastCharInside > 0 {
  570. var work bytes.Buffer
  571. if doInline {
  572. p.inline(&work, data[start:lastCharInside])
  573. renderer(out, work.Bytes())
  574. } else {
  575. renderer(out, data[start:lastCharInside])
  576. }
  577. next := lastCharInside + 1
  578. return next
  579. }
  580. return 0
  581. }
  582. // ~~ Text Markup
  583. func generateVerbatim(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  584. return generator(p, out, data, offset, '=', false, p.r.CodeSpan)
  585. }
  586. func generateCode(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  587. return generator(p, out, data, offset, '~', false, p.r.CodeSpan)
  588. }
  589. func generateEmphasis(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  590. return generator(p, out, data, offset, '/', true, p.r.Emphasis)
  591. }
  592. func generateUnderline(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  593. underline := func(out *bytes.Buffer, text []byte) {
  594. out.WriteString("<span style=\"text-decoration: underline;\">")
  595. out.Write(text)
  596. out.WriteString("</span>")
  597. }
  598. return generator(p, out, data, offset, '_', true, underline)
  599. }
  600. func generateBold(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  601. return generator(p, out, data, offset, '*', true, p.r.DoubleEmphasis)
  602. }
  603. func generateStrikethrough(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  604. return generator(p, out, data, offset, '+', true, p.r.StrikeThrough)
  605. }
  606. // ~~ Images and Links (inc. Footnote)
  607. var reLinkOrImg = regexp.MustCompile(`\[\[(.+?)\]\[?(.*?)\]?\]`)
  608. func generateLinkOrImg(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  609. data = data[offset+1:]
  610. start := 1
  611. i := start
  612. var hyperlink []byte
  613. isImage := false
  614. isFootnote := false
  615. closedLink := false
  616. hasContent := false
  617. if bytes.Equal(data[0:3], []byte("fn:")) {
  618. isFootnote = true
  619. } else if data[0] != '[' {
  620. return 0
  621. }
  622. if bytes.Equal(data[1:6], []byte("file:")) {
  623. isImage = true
  624. }
  625. for i < len(data) {
  626. currChar := data[i]
  627. switch {
  628. case charMatches(currChar, ']') && closedLink == false:
  629. if isImage {
  630. hyperlink = data[start+5 : i]
  631. } else if isFootnote {
  632. refid := data[start+2 : i]
  633. if bytes.Equal(refid, bytes.Trim(refid, " ")) {
  634. p.notes = append(p.notes, footnotes{string(refid), "DEFINITION NOT FOUND"})
  635. p.r.FootnoteRef(out, refid, len(p.notes))
  636. return i + 2
  637. } else {
  638. return 0
  639. }
  640. } else if bytes.Equal(data[i-4:i], []byte(".org")) {
  641. orgStart := start
  642. if bytes.Equal(data[orgStart:orgStart+2], []byte("./")) {
  643. orgStart = orgStart + 1
  644. }
  645. hyperlink = data[orgStart : i-4]
  646. } else {
  647. hyperlink = data[start:i]
  648. }
  649. closedLink = true
  650. case charMatches(currChar, '['):
  651. start = i + 1
  652. hasContent = true
  653. case charMatches(currChar, ']') && closedLink == true && hasContent == true && isImage == true:
  654. p.r.Image(out, hyperlink, data[start:i], data[start:i])
  655. return i + 3
  656. case charMatches(currChar, ']') && closedLink == true && hasContent == true:
  657. var tmpBuf bytes.Buffer
  658. p.inline(&tmpBuf, data[start:i])
  659. p.r.Link(out, hyperlink, tmpBuf.Bytes(), tmpBuf.Bytes())
  660. return i + 3
  661. case charMatches(currChar, ']') && closedLink == true && hasContent == false && isImage == true:
  662. p.r.Image(out, hyperlink, hyperlink, hyperlink)
  663. return i + 2
  664. case charMatches(currChar, ']') && closedLink == true && hasContent == false:
  665. p.r.Link(out, hyperlink, hyperlink, hyperlink)
  666. return i + 2
  667. }
  668. i++
  669. }
  670. return 0
  671. }
  672. // Helpers
  673. func skipChar(data []byte, start int, char byte) int {
  674. i := start
  675. for i < len(data) && charMatches(data[i], char) {
  676. i++
  677. }
  678. return i
  679. }
  680. func isSpace(char byte) bool {
  681. return charMatches(char, ' ')
  682. }
  683. func isEmpty(data []byte) bool {
  684. if len(data) == 0 {
  685. return true
  686. }
  687. for i := 0; i < len(data) && !charMatches(data[i], '\n'); i++ {
  688. if !charMatches(data[i], ' ') && !charMatches(data[i], '\t') {
  689. return false
  690. }
  691. }
  692. return true
  693. }
  694. func charMatches(a byte, b byte) bool {
  695. return a == b
  696. }