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