all repos — grayfriday @ 257ccba98f905c39b0163a224c8f73eddd09fd93

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