all repos — grayfriday @ 747587a52d3bf20215a1ea2d40831b367acac37b

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