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 "fmt"
24 "strings"
25 "unicode/utf8"
26)
27
28const VERSION = "1.4"
29
30type Extensions int
31
32// These are the supported markdown parsing extensions.
33// OR these values together to select multiple extensions.
34const (
35 NoExtensions Extensions = 0
36 NoIntraEmphasis Extensions = 1 << iota // Ignore emphasis markers inside words
37 Tables // Render tables
38 FencedCode // Render fenced code blocks
39 Autolink // Detect embedded URLs that are not explicitly marked
40 Strikethrough // Strikethrough text using ~~test~~
41 LaxHTMLBlocks // Loosen up HTML block parsing rules
42 SpaceHeaders // Be strict about prefix header rules
43 HardLineBreak // Translate newlines into line breaks
44 TabSizeEight // Expand tabs to eight spaces instead of four
45 Footnotes // Pandoc-style footnotes
46 NoEmptyLineBeforeBlock // No need to insert an empty line to start a (code, quote, ordered list, unordered list) block
47 HeaderIDs // specify header IDs with {#id}
48 Titleblock // Titleblock ala pandoc
49 AutoHeaderIDs // Create the header ID from the text
50 BackslashLineBreak // Translate trailing backslashes into line breaks
51 DefinitionLists // Render definition lists
52 Smartypants // Enable smart punctuation substitutions
53 SmartypantsFractions // Enable smart fractions (with Smartypants)
54 SmartypantsDashes // Enable smart dashes (with Smartypants)
55 SmartypantsLatexDashes // Enable LaTeX-style dashes (with Smartypants)
56 SmartypantsAngledQuotes // Enable angled double quotes (with Smartypants) for double quotes rendering
57
58 CommonHtmlFlags HTMLFlags = UseXHTML
59
60 CommonExtensions Extensions = NoIntraEmphasis | Tables | FencedCode |
61 Autolink | Strikethrough | SpaceHeaders | HeaderIDs |
62 BackslashLineBreak | DefinitionLists | Smartypants |
63 SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes
64)
65
66var DefaultOptions = Options{
67 Extensions: CommonExtensions,
68}
69
70type LinkType int
71
72// These are the possible flag values for the link renderer.
73// Only a single one of these values will be used; they are not ORed together.
74// These are mostly of interest if you are writing a new output format.
75const (
76 LinkTypeNotAutolink LinkType = iota
77 LinkTypeNormal
78 LinkTypeEmail
79)
80
81type ListType int
82
83// These are the possible flag values for the ListItem renderer.
84// Multiple flag values may be ORed together.
85// These are mostly of interest if you are writing a new output format.
86const (
87 ListTypeOrdered ListType = 1 << iota
88 ListTypeDefinition
89 ListTypeTerm
90
91 ListItemContainsBlock
92 ListItemBeginningOfList
93 ListItemEndOfList
94)
95
96type CellAlignFlags int
97
98// These are the possible flag values for the table cell renderer.
99// Only a single one of these values will be used; they are not ORed together.
100// These are mostly of interest if you are writing a new output format.
101const (
102 TableAlignmentLeft = 1 << iota
103 TableAlignmentRight
104 TableAlignmentCenter = (TableAlignmentLeft | TableAlignmentRight)
105)
106
107// The size of a tab stop.
108const (
109 TabSizeDefault = 4
110 TabSizeDouble = 8
111)
112
113// blockTags is a set of tags that are recognized as HTML block tags.
114// Any of these can be included in markdown text without special escaping.
115var blockTags = map[string]struct{}{
116 "blockquote": struct{}{},
117 "del": struct{}{},
118 "div": struct{}{},
119 "dl": struct{}{},
120 "fieldset": struct{}{},
121 "form": struct{}{},
122 "h1": struct{}{},
123 "h2": struct{}{},
124 "h3": struct{}{},
125 "h4": struct{}{},
126 "h5": struct{}{},
127 "h6": struct{}{},
128 "iframe": struct{}{},
129 "ins": struct{}{},
130 "math": struct{}{},
131 "noscript": struct{}{},
132 "ol": struct{}{},
133 "pre": struct{}{},
134 "p": struct{}{},
135 "script": struct{}{},
136 "style": struct{}{},
137 "table": struct{}{},
138 "ul": struct{}{},
139
140 // HTML5
141 "address": struct{}{},
142 "article": struct{}{},
143 "aside": struct{}{},
144 "canvas": struct{}{},
145 "figcaption": struct{}{},
146 "figure": struct{}{},
147 "footer": struct{}{},
148 "header": struct{}{},
149 "hgroup": struct{}{},
150 "main": struct{}{},
151 "nav": struct{}{},
152 "output": struct{}{},
153 "progress": struct{}{},
154 "section": struct{}{},
155 "video": struct{}{},
156}
157
158// Renderer is the rendering interface.
159// This is mostly of interest if you are implementing a new rendering format.
160//
161// When a byte slice is provided, it contains the (rendered) contents of the
162// element.
163//
164// When a callback is provided instead, it will write the contents of the
165// respective element directly to the output buffer and return true on success.
166// If the callback returns false, the rendering function should reset the
167// output buffer as though it had never been called.
168//
169// Currently Html and Latex implementations are provided
170type Renderer interface {
171 // block-level callbacks
172 BlockCode(text []byte, lang string)
173 BlockQuote(text []byte)
174 BlockHtml(text []byte)
175 BeginHeader(level int, id string)
176 EndHeader(level int, id string, header []byte)
177 HRule()
178 BeginList(flags ListType)
179 EndList(flags ListType)
180 ListItem(text []byte, flags ListType)
181 BeginParagraph()
182 EndParagraph()
183 Table(header []byte, body []byte, columnData []CellAlignFlags)
184 TableRow(text []byte)
185 TableHeaderCell(out *bytes.Buffer, text []byte, flags CellAlignFlags)
186 TableCell(out *bytes.Buffer, text []byte, flags CellAlignFlags)
187 BeginFootnotes()
188 EndFootnotes()
189 FootnoteItem(name, text []byte, flags ListType)
190 TitleBlock(text []byte)
191
192 // Span-level callbacks
193 AutoLink(link []byte, kind LinkType)
194 CodeSpan(text []byte)
195 DoubleEmphasis(text []byte)
196 Emphasis(text []byte)
197 Image(link []byte, title []byte, alt []byte)
198 LineBreak()
199 Link(link []byte, title []byte, content []byte)
200 RawHtmlTag(tag []byte)
201 TripleEmphasis(text []byte)
202 StrikeThrough(text []byte)
203 FootnoteRef(ref []byte, id int)
204
205 // Low-level callbacks
206 Entity(entity []byte)
207 NormalText(text []byte)
208
209 // Header and footer
210 DocumentHeader()
211 DocumentFooter()
212
213 Write(b []byte) (int, error)
214
215 Render(ast *Node) []byte
216}
217
218// Callback functions for inline parsing. One such function is defined
219// for each character that triggers a response when parsing inline data.
220type inlineParser func(p *parser, data []byte, offset int) int
221
222// Parser holds runtime state used by the parser.
223// This is constructed by the Markdown function.
224type parser struct {
225 refOverride ReferenceOverrideFunc
226 refs map[string]*reference
227 inlineCallback [256]inlineParser
228 flags Extensions
229 nesting int
230 maxNesting int
231 insideLink bool
232
233 // Footnotes need to be ordered as well as available to quickly check for
234 // presence. If a ref is also a footnote, it's stored both in refs and here
235 // in notes. Slice is nil if footnotes not enabled.
236 notes []*reference
237
238 doc *Node
239 tip *Node // = doc
240 oldTip *Node
241 lastMatchedContainer *Node // = doc
242 allClosed bool
243 currBlock *Node // a block node currently being parsed by inline parser
244}
245
246func (p *parser) getRef(refid string) (ref *reference, found bool) {
247 if p.refOverride != nil {
248 r, overridden := p.refOverride(refid)
249 if overridden {
250 if r == nil {
251 return nil, false
252 }
253 return &reference{
254 link: []byte(r.Link),
255 title: []byte(r.Title),
256 noteId: 0,
257 hasBlock: false,
258 text: []byte(r.Text)}, true
259 }
260 }
261 // refs are case insensitive
262 ref, found = p.refs[strings.ToLower(refid)]
263 return ref, found
264}
265
266func (p *parser) finalize(block *Node) {
267 above := block.Parent
268 block.open = false
269 p.tip = above
270}
271
272func (p *parser) addChild(node NodeType, offset uint32) *Node {
273 for !p.tip.canContain(node) {
274 p.finalize(p.tip)
275 }
276 newNode := NewNode(node)
277 newNode.content = []byte{}
278 p.tip.appendChild(newNode)
279 p.tip = newNode
280 return newNode
281}
282
283func (p *parser) closeUnmatchedBlocks() {
284 if !p.allClosed {
285 for p.oldTip != p.lastMatchedContainer {
286 parent := p.oldTip.Parent
287 p.finalize(p.oldTip)
288 p.oldTip = parent
289 }
290 p.allClosed = true
291 }
292}
293
294//
295//
296// Public interface
297//
298//
299
300// Reference represents the details of a link.
301// See the documentation in Options for more details on use-case.
302type Reference struct {
303 // Link is usually the URL the reference points to.
304 Link string
305 // Title is the alternate text describing the link in more detail.
306 Title string
307 // Text is the optional text to override the ref with if the syntax used was
308 // [refid][]
309 Text string
310}
311
312// ReferenceOverrideFunc is expected to be called with a reference string and
313// return either a valid Reference type that the reference string maps to or
314// nil. If overridden is false, the default reference logic will be executed.
315// See the documentation in Options for more details on use-case.
316type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool)
317
318// Options represents configurable overrides and callbacks (in addition to the
319// extension flag set) for configuring a Markdown parse.
320type Options struct {
321 // Extensions is a flag set of bit-wise ORed extension bits. See the
322 // Extensions flags defined in this package.
323 Extensions Extensions
324
325 // ReferenceOverride is an optional function callback that is called every
326 // time a reference is resolved.
327 //
328 // In Markdown, the link reference syntax can be made to resolve a link to
329 // a reference instead of an inline URL, in one of the following ways:
330 //
331 // * [link text][refid]
332 // * [refid][]
333 //
334 // Usually, the refid is defined at the bottom of the Markdown document. If
335 // this override function is provided, the refid is passed to the override
336 // function first, before consulting the defined refids at the bottom. If
337 // the override function indicates an override did not occur, the refids at
338 // the bottom will be used to fill in the link details.
339 ReferenceOverride ReferenceOverrideFunc
340}
341
342// MarkdownBasic is a convenience function for simple rendering.
343// It processes markdown input with no extensions enabled.
344func MarkdownBasic(input []byte) []byte {
345 // set up the HTML renderer
346 htmlFlags := UseXHTML
347 renderer := HTMLRenderer(htmlFlags, CommonExtensions, "", "")
348
349 // set up the parser
350 return MarkdownOptions(input, renderer, Options{Extensions: 0})
351}
352
353// Call Markdown with most useful extensions enabled
354// MarkdownCommon is a convenience function for simple rendering.
355// It processes markdown input with common extensions enabled, including:
356//
357// * Smartypants processing with smart fractions and LaTeX dashes
358//
359// * Intra-word emphasis suppression
360//
361// * Tables
362//
363// * Fenced code blocks
364//
365// * Autolinking
366//
367// * Strikethrough support
368//
369// * Strict header parsing
370//
371// * Custom Header IDs
372func MarkdownCommon(input []byte) []byte {
373 // set up the HTML renderer
374 renderer := HTMLRenderer(CommonHtmlFlags, CommonExtensions, "", "")
375 return MarkdownOptions(input, renderer, DefaultOptions)
376}
377
378// Markdown is the main rendering function.
379// It parses and renders a block of markdown-encoded text.
380// The supplied Renderer is used to format the output, and extensions dictates
381// which non-standard extensions are enabled.
382//
383// To use the supplied Html or LaTeX renderers, see HtmlRenderer and
384// LatexRenderer, respectively.
385func Markdown(input []byte, renderer Renderer, extensions Extensions) []byte {
386 return MarkdownOptions(input, renderer, Options{
387 Extensions: extensions})
388}
389
390// MarkdownOptions is just like Markdown but takes additional options through
391// the Options struct.
392func MarkdownOptions(input []byte, renderer Renderer, opts Options) []byte {
393 // no point in parsing if we can't render
394 if renderer == nil {
395 return nil
396 }
397 return renderer.Render(Parse(input, opts))
398}
399
400func Parse(input []byte, opts Options) *Node {
401 extensions := opts.Extensions
402
403 // fill in the render structure
404 p := new(parser)
405 p.flags = extensions
406 p.refOverride = opts.ReferenceOverride
407 p.refs = make(map[string]*reference)
408 p.maxNesting = 16
409 p.insideLink = false
410
411 docNode := NewNode(Document)
412 p.doc = docNode
413 p.tip = docNode
414 p.oldTip = docNode
415 p.lastMatchedContainer = docNode
416 p.allClosed = true
417
418 // register inline parsers
419 p.inlineCallback['*'] = emphasis
420 p.inlineCallback['_'] = emphasis
421 if extensions&Strikethrough != 0 {
422 p.inlineCallback['~'] = emphasis
423 }
424 p.inlineCallback['`'] = codeSpan
425 p.inlineCallback['\n'] = lineBreak
426 p.inlineCallback['['] = link
427 p.inlineCallback['<'] = leftAngle
428 p.inlineCallback['\\'] = escape
429 p.inlineCallback['&'] = entity
430 p.inlineCallback['!'] = maybeImage
431 p.inlineCallback['^'] = maybeInlineFootnote
432
433 if extensions&Autolink != 0 {
434 p.inlineCallback['h'] = maybeAutoLink
435 p.inlineCallback['m'] = maybeAutoLink
436 p.inlineCallback['f'] = maybeAutoLink
437 p.inlineCallback['H'] = maybeAutoLink
438 p.inlineCallback['M'] = maybeAutoLink
439 p.inlineCallback['F'] = maybeAutoLink
440 }
441
442 if extensions&Footnotes != 0 {
443 p.notes = make([]*reference, 0)
444 }
445
446 first := firstPass(p, input)
447 secondPass(p, first)
448 // Walk the tree and finish up some of unfinished blocks
449 for p.tip != nil {
450 p.finalize(p.tip)
451 }
452 // Walk the tree again and process inline markdown in each block
453 p.doc.Walk(func(node *Node, entering bool) {
454 if node.Type == Paragraph || node.Type == Header || node.Type == TableCell {
455 p.currBlock = node
456 p.inline(node.content)
457 node.content = nil
458 }
459 })
460 p.parseRefsToAST()
461 return p.doc
462}
463
464func (p *parser) parseRefsToAST() {
465 if p.flags&Footnotes == 0 || len(p.notes) == 0 {
466 return
467 }
468 p.tip = p.doc
469 finalizeHtmlBlock(p.addBlock(HTMLBlock, []byte(`<div class="footnotes">`)))
470 p.addBlock(HorizontalRule, nil)
471 block := p.addBlock(List, nil)
472 block.ListFlags = ListTypeOrdered
473 flags := ListItemBeginningOfList
474 // Note: this loop is intentionally explicit, not range-form. This is
475 // because the body of the loop will append nested footnotes to p.notes and
476 // we need to process those late additions. Range form would only walk over
477 // the fixed initial set.
478 for i := 0; i < len(p.notes); i++ {
479 ref := p.notes[i]
480 block := p.addBlock(Item, nil)
481 block.ListFlags = ListTypeOrdered
482 block.RefLink = ref.link
483 if ref.hasBlock {
484 flags |= ListItemContainsBlock
485 p.block(ref.title)
486 } else {
487 p.currBlock = block
488 p.inline(ref.title)
489 }
490 flags &^= ListItemBeginningOfList | ListItemContainsBlock
491 }
492 above := block.Parent
493 finalizeList(block)
494 p.tip = above
495 finalizeHtmlBlock(p.addBlock(HTMLBlock, []byte("</div>")))
496 block.Walk(func(node *Node, entering bool) {
497 if node.Type == Paragraph || node.Type == Header {
498 p.currBlock = node
499 p.inline(node.content)
500 node.content = nil
501 }
502 })
503}
504
505// first pass:
506// - extract references
507// - expand tabs
508// - normalize newlines
509// - copy everything else
510func firstPass(p *parser, input []byte) []byte {
511 var out bytes.Buffer
512 tabSize := TabSizeDefault
513 if p.flags&TabSizeEight != 0 {
514 tabSize = TabSizeDouble
515 }
516 beg, end := 0, 0
517 lastFencedCodeBlockEnd := 0
518 for beg < len(input) { // iterate over lines
519 if end = isReference(p, input[beg:], tabSize); end > 0 {
520 beg += end
521 } else { // skip to the next line
522 end = beg
523 for end < len(input) && input[end] != '\n' && input[end] != '\r' {
524 end++
525 }
526
527 if p.flags&FencedCode != 0 {
528 // track fenced code block boundaries to suppress tab expansion
529 // inside them:
530 if beg >= lastFencedCodeBlockEnd {
531 if i := p.fencedCode(input[beg:], false); i > 0 {
532 lastFencedCodeBlockEnd = beg + i
533 }
534 }
535 }
536
537 // add the line body if present
538 if end > beg {
539 if end < lastFencedCodeBlockEnd { // Do not expand tabs while inside fenced code blocks.
540 out.Write(input[beg:end])
541 } else {
542 expandTabs(&out, input[beg:end], tabSize)
543 }
544 }
545 out.WriteByte('\n')
546
547 if end < len(input) && input[end] == '\r' {
548 end++
549 }
550 if end < len(input) && input[end] == '\n' {
551 end++
552 }
553
554 beg = end
555 }
556 }
557
558 // empty input?
559 if out.Len() == 0 {
560 out.WriteByte('\n')
561 }
562
563 return out.Bytes()
564}
565
566// second pass: actual rendering
567func secondPass(p *parser, input []byte) {
568 p.block(input)
569
570 if p.flags&Footnotes != 0 && len(p.notes) > 0 {
571 flags := ListItemBeginningOfList
572 for i := 0; i < len(p.notes); i += 1 {
573 ref := p.notes[i]
574 if ref.hasBlock {
575 flags |= ListItemContainsBlock
576 p.block(ref.title)
577 } else {
578 p.inline(ref.title)
579 }
580 flags &^= ListItemBeginningOfList | ListItemContainsBlock
581 }
582 }
583
584 if p.nesting != 0 {
585 panic("Nesting level did not end at zero")
586 }
587}
588
589//
590// Link references
591//
592// This section implements support for references that (usually) appear
593// as footnotes in a document, and can be referenced anywhere in the document.
594// The basic format is:
595//
596// [1]: http://www.google.com/ "Google"
597// [2]: http://www.github.com/ "Github"
598//
599// Anywhere in the document, the reference can be linked by referring to its
600// label, i.e., 1 and 2 in this example, as in:
601//
602// This library is hosted on [Github][2], a git hosting site.
603//
604// Actual footnotes as specified in Pandoc and supported by some other Markdown
605// libraries such as php-markdown are also taken care of. They look like this:
606//
607// This sentence needs a bit of further explanation.[^note]
608//
609// [^note]: This is the explanation.
610//
611// Footnotes should be placed at the end of the document in an ordered list.
612// Inline footnotes such as:
613//
614// Inline footnotes^[Not supported.] also exist.
615//
616// are not yet supported.
617
618// References are parsed and stored in this struct.
619type reference struct {
620 link []byte
621 title []byte
622 noteId int // 0 if not a footnote ref
623 hasBlock bool
624 text []byte
625}
626
627func (r *reference) String() string {
628 return fmt.Sprintf("{link: %q, title: %q, text: %q, noteId: %d, hasBlock: %v}",
629 r.link, r.title, r.text, r.noteId, r.hasBlock)
630}
631
632// Check whether or not data starts with a reference link.
633// If so, it is parsed and stored in the list of references
634// (in the render struct).
635// Returns the number of bytes to skip to move past it,
636// or zero if the first line is not a reference.
637func isReference(p *parser, data []byte, tabSize int) int {
638 // up to 3 optional leading spaces
639 if len(data) < 4 {
640 return 0
641 }
642 i := 0
643 for i < 3 && data[i] == ' ' {
644 i++
645 }
646
647 noteId := 0
648
649 // id part: anything but a newline between brackets
650 if data[i] != '[' {
651 return 0
652 }
653 i++
654 if p.flags&Footnotes != 0 {
655 if i < len(data) && data[i] == '^' {
656 // we can set it to anything here because the proper noteIds will
657 // be assigned later during the second pass. It just has to be != 0
658 noteId = 1
659 i++
660 }
661 }
662 idOffset := i
663 for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' {
664 i++
665 }
666 if i >= len(data) || data[i] != ']' {
667 return 0
668 }
669 idEnd := i
670
671 // spacer: colon (space | tab)* newline? (space | tab)*
672 i++
673 if i >= len(data) || data[i] != ':' {
674 return 0
675 }
676 i++
677 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
678 i++
679 }
680 if i < len(data) && (data[i] == '\n' || data[i] == '\r') {
681 i++
682 if i < len(data) && data[i] == '\n' && data[i-1] == '\r' {
683 i++
684 }
685 }
686 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
687 i++
688 }
689 if i >= len(data) {
690 return 0
691 }
692
693 var (
694 linkOffset, linkEnd int
695 titleOffset, titleEnd int
696 lineEnd int
697 raw []byte
698 hasBlock bool
699 )
700
701 if p.flags&Footnotes != 0 && noteId != 0 {
702 linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize)
703 lineEnd = linkEnd
704 } else {
705 linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i)
706 }
707 if lineEnd == 0 {
708 return 0
709 }
710
711 // a valid ref has been found
712
713 ref := &reference{
714 noteId: noteId,
715 hasBlock: hasBlock,
716 }
717
718 if noteId > 0 {
719 // reusing the link field for the id since footnotes don't have links
720 ref.link = data[idOffset:idEnd]
721 // if footnote, it's not really a title, it's the contained text
722 ref.title = raw
723 } else {
724 ref.link = data[linkOffset:linkEnd]
725 ref.title = data[titleOffset:titleEnd]
726 }
727
728 // id matches are case-insensitive
729 id := string(bytes.ToLower(data[idOffset:idEnd]))
730
731 p.refs[id] = ref
732
733 return lineEnd
734}
735
736func scanLinkRef(p *parser, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) {
737 // link: whitespace-free sequence, optionally between angle brackets
738 if data[i] == '<' {
739 i++
740 }
741 linkOffset = i
742 for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' {
743 i++
744 }
745 if i == len(data) {
746 return
747 }
748 linkEnd = i
749 if data[linkOffset] == '<' && data[linkEnd-1] == '>' {
750 linkOffset++
751 linkEnd--
752 }
753
754 // optional spacer: (space | tab)* (newline | '\'' | '"' | '(' )
755 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
756 i++
757 }
758 if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' {
759 return
760 }
761
762 // compute end-of-line
763 if i >= len(data) || data[i] == '\r' || data[i] == '\n' {
764 lineEnd = i
765 }
766 if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' {
767 lineEnd++
768 }
769
770 // optional (space|tab)* spacer after a newline
771 if lineEnd > 0 {
772 i = lineEnd + 1
773 for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
774 i++
775 }
776 }
777
778 // optional title: any non-newline sequence enclosed in '"() alone on its line
779 if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') {
780 i++
781 titleOffset = i
782
783 // look for EOL
784 for i < len(data) && data[i] != '\n' && data[i] != '\r' {
785 i++
786 }
787 if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' {
788 titleEnd = i + 1
789 } else {
790 titleEnd = i
791 }
792
793 // step back
794 i--
795 for i > titleOffset && (data[i] == ' ' || data[i] == '\t') {
796 i--
797 }
798 if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') {
799 lineEnd = titleEnd
800 titleEnd = i
801 }
802 }
803
804 return
805}
806
807// The first bit of this logic is the same as (*parser).listItem, but the rest
808// is much simpler. This function simply finds the entire block and shifts it
809// over by one tab if it is indeed a block (just returns the line if it's not).
810// blockEnd is the end of the section in the input buffer, and contents is the
811// extracted text that was shifted over one tab. It will need to be rendered at
812// the end of the document.
813func scanFootnote(p *parser, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) {
814 if i == 0 || len(data) == 0 {
815 return
816 }
817
818 // skip leading whitespace on first line
819 for i < len(data) && data[i] == ' ' {
820 i++
821 }
822
823 blockStart = i
824
825 // find the end of the line
826 blockEnd = i
827 for i < len(data) && data[i-1] != '\n' {
828 i++
829 }
830
831 // get working buffer
832 var raw bytes.Buffer
833
834 // put the first line into the working buffer
835 raw.Write(data[blockEnd:i])
836 blockEnd = i
837
838 // process the following lines
839 containsBlankLine := false
840
841gatherLines:
842 for blockEnd < len(data) {
843 i++
844
845 // find the end of this line
846 for i < len(data) && data[i-1] != '\n' {
847 i++
848 }
849
850 // if it is an empty line, guess that it is part of this item
851 // and move on to the next line
852 if p.isEmpty(data[blockEnd:i]) > 0 {
853 containsBlankLine = true
854 blockEnd = i
855 continue
856 }
857
858 n := 0
859 if n = isIndented(data[blockEnd:i], indentSize); n == 0 {
860 // this is the end of the block.
861 // we don't want to include this last line in the index.
862 break gatherLines
863 }
864
865 // if there were blank lines before this one, insert a new one now
866 if containsBlankLine {
867 raw.WriteByte('\n')
868 containsBlankLine = false
869 }
870
871 // get rid of that first tab, write to buffer
872 raw.Write(data[blockEnd+n : i])
873 hasBlock = true
874
875 blockEnd = i
876 }
877
878 if data[blockEnd-1] != '\n' {
879 raw.WriteByte('\n')
880 }
881
882 contents = raw.Bytes()
883
884 return
885}
886
887//
888//
889// Miscellaneous helper functions
890//
891//
892
893// Test if a character is a punctuation symbol.
894// Taken from a private function in regexp in the stdlib.
895func ispunct(c byte) bool {
896 for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
897 if c == r {
898 return true
899 }
900 }
901 return false
902}
903
904// Test if a character is a whitespace character.
905func isspace(c byte) bool {
906 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
907}
908
909// Test if a character is letter.
910func isletter(c byte) bool {
911 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
912}
913
914// Test if a character is a letter or a digit.
915// TODO: check when this is looking for ASCII alnum and when it should use unicode
916func isalnum(c byte) bool {
917 return (c >= '0' && c <= '9') || isletter(c)
918}
919
920// Replace tab characters with spaces, aligning to the next TAB_SIZE column.
921// always ends output with a newline
922func expandTabs(out *bytes.Buffer, line []byte, tabSize int) {
923 // first, check for common cases: no tabs, or only tabs at beginning of line
924 i, prefix := 0, 0
925 slowcase := false
926 for i = 0; i < len(line); i++ {
927 if line[i] == '\t' {
928 if prefix == i {
929 prefix++
930 } else {
931 slowcase = true
932 break
933 }
934 }
935 }
936
937 // no need to decode runes if all tabs are at the beginning of the line
938 if !slowcase {
939 for i = 0; i < prefix*tabSize; i++ {
940 out.WriteByte(' ')
941 }
942 out.Write(line[prefix:])
943 return
944 }
945
946 // the slow case: we need to count runes to figure out how
947 // many spaces to insert for each tab
948 column := 0
949 i = 0
950 for i < len(line) {
951 start := i
952 for i < len(line) && line[i] != '\t' {
953 _, size := utf8.DecodeRune(line[i:])
954 i += size
955 column++
956 }
957
958 if i > start {
959 out.Write(line[start:i])
960 }
961
962 if i >= len(line) {
963 break
964 }
965
966 for {
967 out.WriteByte(' ')
968 column++
969 if column%tabSize == 0 {
970 break
971 }
972 }
973
974 i++
975 }
976}
977
978// Find if a line counts as indented or not.
979// Returns number of characters the indent is (0 = not indented).
980func isIndented(data []byte, indentSize int) int {
981 if len(data) == 0 {
982 return 0
983 }
984 if data[0] == '\t' {
985 return 1
986 }
987 if len(data) < indentSize {
988 return 0
989 }
990 for i := 0; i < indentSize; i++ {
991 if data[i] != ' ' {
992 return 0
993 }
994 }
995 return indentSize
996}
997
998// Create a url-safe slug for fragments
999func slugify(in []byte) []byte {
1000 if len(in) == 0 {
1001 return in
1002 }
1003 out := make([]byte, 0, len(in))
1004 sym := false
1005
1006 for _, ch := range in {
1007 if isalnum(ch) {
1008 sym = false
1009 out = append(out, ch)
1010 } else if sym {
1011 continue
1012 } else {
1013 out = append(out, '-')
1014 sym = true
1015 }
1016 }
1017 var a, b int
1018 var ch byte
1019 for a, ch = range out {
1020 if ch != '-' {
1021 break
1022 }
1023 }
1024 for b = len(out) - 1; b > 0; b-- {
1025 if out[b] != '-' {
1026 break
1027 }
1028 }
1029 return out[a : b+1]
1030}