markdown.go (view raw)
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//
11//
12// Markdown parsing and processing
13//
14//
15
16// Blackfriday markdown processor.
17//
18// Translates plain text with simple formatting rules into HTML or LaTeX.
19package blackfriday
20
21import (
22 "bytes"
23 "unicode/utf8"
24)
25
26const VERSION = "1.1"
27
28// These are the supported markdown parsing extensions.
29// OR these values together to select multiple extensions.
30const (
31 EXTENSION_NO_INTRA_EMPHASIS = 1 << iota // ignore emphasis markers inside words
32 EXTENSION_TABLES // render tables
33 EXTENSION_FENCED_CODE // render fenced code blocks
34 EXTENSION_AUTOLINK // detect embedded URLs that are not explicitly marked
35 EXTENSION_STRIKETHROUGH // strikethrough text using ~~test~~
36 EXTENSION_LAX_HTML_BLOCKS // loosen up HTML block parsing rules
37 EXTENSION_SPACE_HEADERS // be strict about prefix header rules
38 EXTENSION_HARD_LINE_BREAK // translate newlines into line breaks
39 EXTENSION_TAB_SIZE_EIGHT // expand tabs to eight spaces instead of four
40 EXTENSION_FOOTNOTES // Pandoc-style footnotes
41)
42
43// These are the possible flag values for the link renderer.
44// Only a single one of these values will be used; they are not ORed together.
45// These are mostly of interest if you are writing a new output format.
46const (
47 LINK_TYPE_NOT_AUTOLINK = iota
48 LINK_TYPE_NORMAL
49 LINK_TYPE_EMAIL
50)
51
52// These are the possible flag values for the ListItem renderer.
53// Multiple flag values may be ORed together.
54// These are mostly of interest if you are writing a new output format.
55const (
56 LIST_TYPE_ORDERED = 1 << iota
57 LIST_ITEM_CONTAINS_BLOCK
58 LIST_ITEM_BEGINNING_OF_LIST
59 LIST_ITEM_END_OF_LIST
60)
61
62// These are the possible flag values for the table cell renderer.
63// Only a single one of these values will be used; they are not ORed together.
64// These are mostly of interest if you are writing a new output format.
65const (
66 TABLE_ALIGNMENT_LEFT = 1 << iota
67 TABLE_ALIGNMENT_RIGHT
68 TABLE_ALIGNMENT_CENTER = (TABLE_ALIGNMENT_LEFT | TABLE_ALIGNMENT_RIGHT)
69)
70
71// The size of a tab stop.
72const (
73 TAB_SIZE_DEFAULT = 4
74 TAB_SIZE_EIGHT = 8
75)
76
77// These are the tags that are recognized as HTML block tags.
78// Any of these can be included in markdown text without special escaping.
79var blockTags = map[string]bool{
80 "p": true,
81 "dl": true,
82 "h1": true,
83 "h2": true,
84 "h3": true,
85 "h4": true,
86 "h5": true,
87 "h6": true,
88 "ol": true,
89 "ul": true,
90 "del": true,
91 "div": true,
92 "ins": true,
93 "pre": true,
94 "form": true,
95 "math": true,
96 "table": true,
97 "iframe": true,
98 "script": true,
99 "fieldset": true,
100 "noscript": true,
101 "blockquote": true,
102
103 // HTML5
104 "video": true,
105 "aside": true,
106 "canvas": true,
107 "figure": true,
108 "footer": true,
109 "header": true,
110 "hgroup": true,
111 "output": true,
112 "article": true,
113 "section": true,
114 "progress": true,
115 "figcaption": true,
116}
117
118// Renderer is the rendering interface.
119// This is mostly of interest if you are implementing a new rendering format.
120//
121// When a byte slice is provided, it contains the (rendered) contents of the
122// element.
123//
124// When a callback is provided instead, it will write the contents of the
125// respective element directly to the output buffer and return true on success.
126// If the callback returns false, the rendering function should reset the
127// output buffer as though it had never been called.
128//
129// Currently Html and Latex implementations are provided
130type Renderer interface {
131 // block-level callbacks
132 BlockCode(out *bytes.Buffer, text []byte, lang string)
133 BlockQuote(out *bytes.Buffer, text []byte)
134 BlockHtml(out *bytes.Buffer, text []byte)
135 Header(out *bytes.Buffer, text func() bool, level int)
136 HRule(out *bytes.Buffer)
137 List(out *bytes.Buffer, text func() bool, flags int)
138 ListItem(out *bytes.Buffer, text []byte, flags int)
139 Paragraph(out *bytes.Buffer, text func() bool)
140 Table(out *bytes.Buffer, header []byte, body []byte, columnData []int)
141 TableRow(out *bytes.Buffer, text []byte)
142 TableCell(out *bytes.Buffer, text []byte, flags int)
143 Footnotes(out *bytes.Buffer, text func() bool)
144 FootnoteItem(out *bytes.Buffer, name, text []byte, flags int)
145
146 // Span-level callbacks
147 AutoLink(out *bytes.Buffer, link []byte, kind int)
148 CodeSpan(out *bytes.Buffer, text []byte)
149 DoubleEmphasis(out *bytes.Buffer, text []byte)
150 Emphasis(out *bytes.Buffer, text []byte)
151 Image(out *bytes.Buffer, link []byte, title []byte, alt []byte)
152 LineBreak(out *bytes.Buffer)
153 Link(out *bytes.Buffer, link []byte, title []byte, content []byte)
154 RawHtmlTag(out *bytes.Buffer, tag []byte)
155 TripleEmphasis(out *bytes.Buffer, text []byte)
156 StrikeThrough(out *bytes.Buffer, text []byte)
157 FootnoteRef(out *bytes.Buffer, ref []byte, id int)
158
159 // Low-level callbacks
160 Entity(out *bytes.Buffer, entity []byte)
161 NormalText(out *bytes.Buffer, text []byte)
162
163 // Header and footer
164 DocumentHeader(out *bytes.Buffer)
165 DocumentFooter(out *bytes.Buffer)
166}
167
168// Callback functions for inline parsing. One such function is defined
169// for each character that triggers a response when parsing inline data.
170type inlineParser func(p *parser, out *bytes.Buffer, data []byte, offset int) int
171
172// Parser holds runtime state used by the parser.
173// This is constructed by the Markdown function.
174type parser struct {
175 r Renderer
176 refs map[string]*reference
177 inlineCallback [256]inlineParser
178 flags int
179 nesting int
180 maxNesting int
181 insideLink bool
182
183 // Footnotes need to be ordered as well as available to quickly check for
184 // presence. If a ref is also a footnote, it's stored both in refs and here
185 // in notes. Slice is nil if footnotes not enabled.
186 notes []*reference
187}
188
189//
190//
191// Public interface
192//
193//
194
195// MarkdownBasic is a convenience function for simple rendering.
196// It processes markdown input with no extensions enabled.
197func MarkdownBasic(input []byte) []byte {
198 // set up the HTML renderer
199 htmlFlags := HTML_USE_XHTML
200 renderer := HtmlRenderer(htmlFlags, "", "")
201
202 // set up the parser
203 extensions := 0
204
205 return Markdown(input, renderer, extensions)
206}
207
208// Call Markdown with most useful extensions enabled
209// MarkdownCommon is a convenience function for simple rendering.
210// It processes markdown input with common extensions enabled, including:
211//
212// * Smartypants processing with smart fractions and LaTeX dashes
213//
214// * Intra-word emphasis suppression
215//
216// * Tables
217//
218// * Fenced code blocks
219//
220// * Autolinking
221//
222// * Strikethrough support
223//
224// * Strict header parsing
225func MarkdownCommon(input []byte) []byte {
226 // set up the HTML renderer
227 htmlFlags := 0
228 htmlFlags |= HTML_USE_XHTML
229 htmlFlags |= HTML_USE_SMARTYPANTS
230 htmlFlags |= HTML_SMARTYPANTS_FRACTIONS
231 htmlFlags |= HTML_SMARTYPANTS_LATEX_DASHES
232 htmlFlags |= HTML_SKIP_SCRIPT
233 renderer := HtmlRenderer(htmlFlags, "", "")
234
235 // set up the parser
236 extensions := 0
237 extensions |= EXTENSION_NO_INTRA_EMPHASIS
238 extensions |= EXTENSION_TABLES
239 extensions |= EXTENSION_FENCED_CODE
240 extensions |= EXTENSION_AUTOLINK
241 extensions |= EXTENSION_STRIKETHROUGH
242 extensions |= EXTENSION_SPACE_HEADERS
243
244 return Markdown(input, renderer, extensions)
245}
246
247// Markdown is the main rendering function.
248// It parses and renders a block of markdown-encoded text.
249// The supplied Renderer is used to format the output, and extensions dictates
250// which non-standard extensions are enabled.
251//
252// To use the supplied Html or LaTeX renderers, see HtmlRenderer and
253// LatexRenderer, respectively.
254func Markdown(input []byte, renderer Renderer, extensions int) []byte {
255 // no point in parsing if we can't render
256 if renderer == nil {
257 return nil
258 }
259
260 // fill in the render structure
261 p := new(parser)
262 p.r = renderer
263 p.flags = extensions
264 p.refs = make(map[string]*reference)
265 p.maxNesting = 16
266 p.insideLink = false
267
268 // register inline parsers
269 p.inlineCallback['*'] = emphasis
270 p.inlineCallback['_'] = emphasis
271 if extensions&EXTENSION_STRIKETHROUGH != 0 {
272 p.inlineCallback['~'] = emphasis
273 }
274 p.inlineCallback['`'] = codeSpan
275 p.inlineCallback['\n'] = lineBreak
276 p.inlineCallback['['] = link
277 p.inlineCallback['<'] = leftAngle
278 p.inlineCallback['\\'] = escape
279 p.inlineCallback['&'] = entity
280
281 if extensions&EXTENSION_AUTOLINK != 0 {
282 p.inlineCallback[':'] = autoLink
283 }
284
285 if extensions&EXTENSION_FOOTNOTES != 0 {
286 p.notes = make([]*reference, 0)
287 }
288
289 first := firstPass(p, input)
290 second := secondPass(p, first)
291
292 return second
293}
294
295// first pass:
296// - extract references
297// - expand tabs
298// - normalize newlines
299// - copy everything else
300func firstPass(p *parser, input []byte) []byte {
301 var out bytes.Buffer
302 tabSize := TAB_SIZE_DEFAULT
303 if p.flags&EXTENSION_TAB_SIZE_EIGHT != 0 {
304 tabSize = TAB_SIZE_EIGHT
305 }
306 beg, end := 0, 0
307 for beg < len(input) { // iterate over lines
308 if end = isReference(p, input[beg:], tabSize); end > 0 {
309 beg += end
310 } else { // skip to the next line
311 end = beg
312 for end < len(input) && input[end] != '\n' && input[end] != '\r' {
313 end++
314 }
315
316 // add the line body if present
317 if end > beg {
318 expandTabs(&out, input[beg:end], tabSize)
319 }
320 out.WriteByte('\n')
321
322 if end < len(input) && input[end] == '\r' {
323 end++
324 }
325 if end < len(input) && input[end] == '\n' {
326 end++
327 }
328
329 beg = end
330 }
331 }
332
333 // empty input?
334 if out.Len() == 0 {
335 out.WriteByte('\n')
336 }
337
338 return out.Bytes()
339}
340
341// second pass: actual rendering
342func secondPass(p *parser, input []byte) []byte {
343 var output bytes.Buffer
344
345 p.r.DocumentHeader(&output)
346 p.block(&output, input)
347
348 if p.flags&EXTENSION_FOOTNOTES != 0 && len(p.notes) > 0 {
349 p.r.Footnotes(&output, func() bool {
350 flags := LIST_ITEM_BEGINNING_OF_LIST
351 for _, ref := range p.notes {
352 var buf bytes.Buffer
353 if ref.hasBlock {
354 flags |= LIST_ITEM_CONTAINS_BLOCK
355 p.block(&buf, ref.title)
356 } else {
357 p.inline(&buf, ref.title)
358 }
359 p.r.FootnoteItem(&output, ref.link, buf.Bytes(), flags)
360 flags &^= LIST_ITEM_BEGINNING_OF_LIST | LIST_ITEM_CONTAINS_BLOCK
361 }
362
363 return true
364 })
365 }
366
367 p.r.DocumentFooter(&output)
368
369 if p.nesting != 0 {
370 panic("Nesting level did not end at zero")
371 }
372
373 return output.Bytes()
374}
375
376//
377// Link references
378//
379// This section implements support for references that (usually) appear
380// as footnotes in a document, and can be referenced anywhere in the document.
381// The basic format is:
382//
383// [1]: http://www.google.com/ "Google"
384// [2]: http://www.github.com/ "Github"
385//
386// Anywhere in the document, the reference can be linked by referring to its
387// label, i.e., 1 and 2 in this example, as in:
388//
389// This library is hosted on [Github][2], a git hosting site.
390//
391// Actual footnotes as specified in Pandoc and supported by some other Markdown
392// libraries such as php-markdown are also taken care of. They look like this:
393//
394// This sentence needs a bit of further explanation.[^note]
395//
396// [^note]: This is the explanation.
397//
398// Footnotes should be placed at the end of the document in an ordered list.
399// Inline footnotes such as:
400//
401// Inline footnotes^[Not supported.] also exist.
402//
403// are not yet supported.
404
405// References are parsed and stored in this struct.
406type reference struct {
407 link []byte
408 title []byte
409 noteId int // 0 if not a footnote ref
410 hasBlock bool
411}
412
413// Check whether or not data starts with a reference link.
414// If so, it is parsed and stored in the list of references
415// (in the render struct).
416// Returns the number of bytes to skip to move past it,
417// or zero if the first line is not a reference.
418func isReference(p *parser, data []byte, tabSize int) int {
419 if len(data) >= 5 {
420 }
421 // up to 3 optional leading spaces
422 if len(data) < 4 {
423 return 0
424 }
425 i := 0
426 for i < 3 && data[i] == ' ' {
427 i++
428 }
429
430 noteId := 0
431
432 // id part: anything but a newline between brackets
433 if data[i] != '[' {
434 return 0
435 }
436 i++
437 if p.flags&EXTENSION_FOOTNOTES != 0 {
438 if data[i] == '^' {
439 noteId = len(p.notes) + 1
440 i++
441 }
442 }
443 idOffset := i
444 for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' {
445 i++
446 }
447 if i >= len(data) || data[i] != ']' {
448 return 0
449 }
450 idEnd := i
451
452 // spacer: colon (space | tab)* newline? (space | tab)*
453 i++
454 if i >= len(data) || data[i] != ':' {
455 return 0
456 }
457 i++
458 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
459 i++
460 }
461 if i < len(data) && (data[i] == '\n' || data[i] == '\r') {
462 i++
463 if i < len(data) && data[i] == '\n' && data[i-1] == '\r' {
464 i++
465 }
466 }
467 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
468 i++
469 }
470 if i >= len(data) {
471 return 0
472 }
473
474 var (
475 linkOffset, linkEnd int
476 titleOffset, titleEnd int
477 lineEnd int
478 raw []byte
479 hasBlock bool
480 )
481
482 if p.flags&EXTENSION_FOOTNOTES != 0 && noteId > 0 {
483 linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize)
484 lineEnd = linkEnd
485 } else {
486 linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i)
487 }
488 if lineEnd == 0 {
489 return 0
490 }
491
492 // a valid ref has been found
493
494 ref := &reference{
495 noteId: noteId,
496 hasBlock: hasBlock,
497 }
498
499 if noteId > 0 {
500 // reusing the link field for the id since footnotes don't have links
501 ref.link = data[idOffset:idEnd]
502 // if footnote, it's not really a title, it's the contained text
503 ref.title = raw
504 p.notes = append(p.notes, ref)
505 } else {
506 ref.link = data[linkOffset:linkEnd]
507 ref.title = data[titleOffset:titleEnd]
508 }
509
510 // id matches are case-insensitive
511 id := string(bytes.ToLower(data[idOffset:idEnd]))
512 p.refs[id] = ref
513 return lineEnd
514}
515
516func scanLinkRef(p *parser, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) {
517 // link: whitespace-free sequence, optionally between angle brackets
518 if data[i] == '<' {
519 i++
520 }
521 linkOffset = i
522 for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' {
523 i++
524 }
525 linkEnd = i
526 if data[linkOffset] == '<' && data[linkEnd-1] == '>' {
527 linkOffset++
528 linkEnd--
529 }
530
531 // optional spacer: (space | tab)* (newline | '\'' | '"' | '(' )
532 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
533 i++
534 }
535 if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' {
536 return
537 }
538
539 // compute end-of-line
540 if i >= len(data) || data[i] == '\r' || data[i] == '\n' {
541 lineEnd = i
542 }
543 if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' {
544 lineEnd++
545 }
546
547 // optional (space|tab)* spacer after a newline
548 if lineEnd > 0 {
549 i = lineEnd + 1
550 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
551 i++
552 }
553 }
554
555 // optional title: any non-newline sequence enclosed in '"() alone on its line
556 if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') {
557 i++
558 titleOffset = i
559
560 // look for EOL
561 for i < len(data) && data[i] != '\n' && data[i] != '\r' {
562 i++
563 }
564 if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' {
565 titleEnd = i + 1
566 } else {
567 titleEnd = i
568 }
569
570 // step back
571 i--
572 for i > titleOffset && (data[i] == ' ' || data[i] == '\t') {
573 i--
574 }
575 if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') {
576 lineEnd = titleEnd
577 titleEnd = i
578 }
579 }
580
581 return
582}
583
584// The first bit of this logic is the same as (*parser).listItem, but the rest
585// is much simpler. This function simply finds the entire block and shifts it
586// over by one tab if it is indeed a block (just returns the line if it's not).
587// blockEnd is the end of the section in the input buffer, and contents is the
588// extracted text that was shifted over one tab. It will need to be rendered at
589// the end of the document.
590func scanFootnote(p *parser, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) {
591 if i == 0 {
592 return
593 }
594
595 // skip leading whitespace on first line
596 for data[i] == ' ' {
597 i++
598 }
599
600 blockStart = i
601
602 // find the end of the line
603 blockEnd = i
604 for i < len(data) && data[i-1] != '\n' {
605 i++
606 }
607
608 // get working buffer
609 var raw bytes.Buffer
610
611 // put the first line into the working buffer
612 raw.Write(data[blockEnd:i])
613 blockEnd = i
614
615 // process the following lines
616 containsBlankLine := false
617
618gatherLines:
619 for blockEnd < len(data) {
620 i++
621
622 // find the end of this line
623 for i < len(data) && data[i-1] != '\n' {
624 i++
625 }
626
627 // if it is an empty line, guess that it is part of this item
628 // and move on to the next line
629 if p.isEmpty(data[blockEnd:i]) > 0 {
630 containsBlankLine = true
631 blockEnd = i
632 continue
633 }
634
635 n := 0
636 if n = isIndented(data[blockEnd:i], indentSize); n == 0 {
637 // this is the end of the block.
638 // we don't want to include this last line in the index.
639 break gatherLines
640 }
641
642 // if there were blank lines before this one, insert a new one now
643 if containsBlankLine {
644 raw.WriteByte('\n')
645 containsBlankLine = false
646 }
647
648 // get rid of that first tab, write to buffer
649 raw.Write(data[blockEnd+n : i])
650 hasBlock = true
651
652 blockEnd = i
653 }
654
655 if data[blockEnd-1] != '\n' {
656 raw.WriteByte('\n')
657 }
658
659 contents = raw.Bytes()
660
661 return
662}
663
664//
665//
666// Miscellaneous helper functions
667//
668//
669
670// Test if a character is a punctuation symbol.
671// Taken from a private function in regexp in the stdlib.
672func ispunct(c byte) bool {
673 for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
674 if c == r {
675 return true
676 }
677 }
678 return false
679}
680
681// Test if a character is a whitespace character.
682func isspace(c byte) bool {
683 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
684}
685
686// Test if a character is a letter or a digit.
687// TODO: check when this is looking for ASCII alnum and when it should use unicode
688func isalnum(c byte) bool {
689 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
690}
691
692// Replace tab characters with spaces, aligning to the next TAB_SIZE column.
693// always ends output with a newline
694func expandTabs(out *bytes.Buffer, line []byte, tabSize int) {
695 // first, check for common cases: no tabs, or only tabs at beginning of line
696 i, prefix := 0, 0
697 slowcase := false
698 for i = 0; i < len(line); i++ {
699 if line[i] == '\t' {
700 if prefix == i {
701 prefix++
702 } else {
703 slowcase = true
704 break
705 }
706 }
707 }
708
709 // no need to decode runes if all tabs are at the beginning of the line
710 if !slowcase {
711 for i = 0; i < prefix*tabSize; i++ {
712 out.WriteByte(' ')
713 }
714 out.Write(line[prefix:])
715 return
716 }
717
718 // the slow case: we need to count runes to figure out how
719 // many spaces to insert for each tab
720 column := 0
721 i = 0
722 for i < len(line) {
723 start := i
724 for i < len(line) && line[i] != '\t' {
725 _, size := utf8.DecodeRune(line[i:])
726 i += size
727 column++
728 }
729
730 if i > start {
731 out.Write(line[start:i])
732 }
733
734 if i >= len(line) {
735 break
736 }
737
738 for {
739 out.WriteByte(' ')
740 column++
741 if column%tabSize == 0 {
742 break
743 }
744 }
745
746 i++
747 }
748}
749
750// Find if a line counts as indented or not.
751// Returns number of characters the indent is (0 = not indented).
752func isIndented(data []byte, indentSize int) int {
753 if len(data) == 0 {
754 return 0
755 }
756 if data[0] == '\t' {
757 return 1
758 }
759 if len(data) < indentSize {
760 return 0
761 }
762 for i := 0; i < indentSize; i++ {
763 if data[i] != ' ' {
764 return 0
765 }
766 }
767 return indentSize
768}
769
770// Create a url-safe slug for fragments
771func slugify(in []byte) []byte {
772 if len(in) == 0 {
773 return in
774 }
775 out := make([]byte, 0, len(in))
776 sym := false
777
778 for _, ch := range in {
779 if isalnum(ch) {
780 sym = false
781 out = append(out, ch)
782 } else if sym {
783 continue
784 } else {
785 out = append(out, '-')
786 sym = true
787 }
788 }
789 var a, b int
790 var ch byte
791 for a, ch = range out {
792 if ch != '-' {
793 break
794 }
795 }
796 for b = len(out) - 1; b > 0; b-- {
797 if out[b] != '-' {
798 break
799 }
800 }
801 return out[a : b+1]
802}