all repos — grayfriday @ da0664143874c5ec373f1dc400bd412688002f96

blackfriday fork with a few changes

markdown.go (view raw)

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