all repos — grayfriday @ ef087889f49d63f4ada853a7b255072f85ec970f

blackfriday fork with a few changes

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(out *bytes.Buffer, text []byte, lang string)
164	BlockQuote(out *bytes.Buffer, text []byte)
165	BlockHtml(out *bytes.Buffer, text []byte)
166	BeginHeader(out *bytes.Buffer, level int, id string) int
167	EndHeader(out *bytes.Buffer, level int, id string, tocMarker int)
168	HRule(out *bytes.Buffer)
169	BeginList(out *bytes.Buffer, flags ListType)
170	EndList(out *bytes.Buffer, flags ListType)
171	ListItem(out *bytes.Buffer, text []byte, flags ListType)
172	BeginParagraph(out *bytes.Buffer)
173	EndParagraph(out *bytes.Buffer)
174	Table(out *bytes.Buffer, header []byte, body []byte, columnData []int)
175	TableRow(out *bytes.Buffer, text []byte)
176	TableHeaderCell(out *bytes.Buffer, text []byte, flags int)
177	TableCell(out *bytes.Buffer, text []byte, flags int)
178	BeginFootnotes(out *bytes.Buffer)
179	EndFootnotes(out *bytes.Buffer)
180	FootnoteItem(out *bytes.Buffer, name, text []byte, flags ListType)
181	TitleBlock(out *bytes.Buffer, text []byte)
182
183	// Span-level callbacks
184	AutoLink(out *bytes.Buffer, link []byte, kind LinkType)
185	CodeSpan(out *bytes.Buffer, text []byte)
186	DoubleEmphasis(out *bytes.Buffer, text []byte)
187	Emphasis(out *bytes.Buffer, text []byte)
188	Image(out *bytes.Buffer, link []byte, title []byte, alt []byte)
189	LineBreak(out *bytes.Buffer)
190	Link(out *bytes.Buffer, link []byte, title []byte, content []byte)
191	RawHtmlTag(out *bytes.Buffer, tag []byte)
192	TripleEmphasis(out *bytes.Buffer, text []byte)
193	StrikeThrough(out *bytes.Buffer, text []byte)
194	FootnoteRef(out *bytes.Buffer, ref []byte, id int)
195
196	// Low-level callbacks
197	Entity(out *bytes.Buffer, entity []byte)
198	NormalText(out *bytes.Buffer, text []byte)
199
200	// Header and footer
201	DocumentHeader(out *bytes.Buffer)
202	DocumentFooter(out *bytes.Buffer)
203
204	GetFlags() HtmlFlags
205}
206
207// Callback functions for inline parsing. One such function is defined
208// for each character that triggers a response when parsing inline data.
209type inlineParser func(p *parser, out *bytes.Buffer, data []byte, offset int) int
210
211// Parser holds runtime state used by the parser.
212// This is constructed by the Markdown function.
213type parser struct {
214	r              Renderer
215	refOverride    ReferenceOverrideFunc
216	refs           map[string]*reference
217	inlineCallback [256]inlineParser
218	flags          Extensions
219	nesting        int
220	maxNesting     int
221	insideLink     bool
222
223	// Footnotes need to be ordered as well as available to quickly check for
224	// presence. If a ref is also a footnote, it's stored both in refs and here
225	// in notes. Slice is nil if footnotes not enabled.
226	notes []*reference
227}
228
229func (p *parser) getRef(refid string) (ref *reference, found bool) {
230	if p.refOverride != nil {
231		r, overridden := p.refOverride(refid)
232		if overridden {
233			if r == nil {
234				return nil, false
235			}
236			return &reference{
237				link:     []byte(r.Link),
238				title:    []byte(r.Title),
239				noteId:   0,
240				hasBlock: false,
241				text:     []byte(r.Text)}, true
242		}
243	}
244	// refs are case insensitive
245	ref, found = p.refs[strings.ToLower(refid)]
246	return ref, found
247}
248
249//
250//
251// Public interface
252//
253//
254
255// Reference represents the details of a link.
256// See the documentation in Options for more details on use-case.
257type Reference struct {
258	// Link is usually the URL the reference points to.
259	Link string
260	// Title is the alternate text describing the link in more detail.
261	Title string
262	// Text is the optional text to override the ref with if the syntax used was
263	// [refid][]
264	Text string
265}
266
267// ReferenceOverrideFunc is expected to be called with a reference string and
268// return either a valid Reference type that the reference string maps to or
269// nil. If overridden is false, the default reference logic will be executed.
270// See the documentation in Options for more details on use-case.
271type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool)
272
273// Options represents configurable overrides and callbacks (in addition to the
274// extension flag set) for configuring a Markdown parse.
275type Options struct {
276	// Extensions is a flag set of bit-wise ORed extension bits. See the
277	// Extensions flags defined in this package.
278	Extensions Extensions
279
280	// ReferenceOverride is an optional function callback that is called every
281	// time a reference is resolved.
282	//
283	// In Markdown, the link reference syntax can be made to resolve a link to
284	// a reference instead of an inline URL, in one of the following ways:
285	//
286	//  * [link text][refid]
287	//  * [refid][]
288	//
289	// Usually, the refid is defined at the bottom of the Markdown document. If
290	// this override function is provided, the refid is passed to the override
291	// function first, before consulting the defined refids at the bottom. If
292	// the override function indicates an override did not occur, the refids at
293	// the bottom will be used to fill in the link details.
294	ReferenceOverride ReferenceOverrideFunc
295}
296
297// MarkdownBasic is a convenience function for simple rendering.
298// It processes markdown input with no extensions enabled.
299func MarkdownBasic(input []byte) []byte {
300	// set up the HTML renderer
301	htmlFlags := UseXHTML
302	renderer := HtmlRenderer(htmlFlags, "", "")
303
304	// set up the parser
305	return MarkdownOptions(input, renderer, Options{Extensions: 0})
306}
307
308// Call Markdown with most useful extensions enabled
309// MarkdownCommon is a convenience function for simple rendering.
310// It processes markdown input with common extensions enabled, including:
311//
312// * Smartypants processing with smart fractions and LaTeX dashes
313//
314// * Intra-word emphasis suppression
315//
316// * Tables
317//
318// * Fenced code blocks
319//
320// * Autolinking
321//
322// * Strikethrough support
323//
324// * Strict header parsing
325//
326// * Custom Header IDs
327func MarkdownCommon(input []byte) []byte {
328	// set up the HTML renderer
329	renderer := HtmlRenderer(commonHtmlFlags, "", "")
330	return MarkdownOptions(input, renderer, Options{
331		Extensions: commonExtensions})
332}
333
334// Markdown is the main rendering function.
335// It parses and renders a block of markdown-encoded text.
336// The supplied Renderer is used to format the output, and extensions dictates
337// which non-standard extensions are enabled.
338//
339// To use the supplied Html or LaTeX renderers, see HtmlRenderer and
340// LatexRenderer, respectively.
341func Markdown(input []byte, renderer Renderer, extensions Extensions) []byte {
342	return MarkdownOptions(input, renderer, Options{
343		Extensions: extensions})
344}
345
346// MarkdownOptions is just like Markdown but takes additional options through
347// the Options struct.
348func MarkdownOptions(input []byte, renderer Renderer, opts Options) []byte {
349	// no point in parsing if we can't render
350	if renderer == nil {
351		return nil
352	}
353
354	extensions := opts.Extensions
355
356	// fill in the render structure
357	p := new(parser)
358	p.r = renderer
359	p.flags = extensions
360	p.refOverride = opts.ReferenceOverride
361	p.refs = make(map[string]*reference)
362	p.maxNesting = 16
363	p.insideLink = false
364
365	// register inline parsers
366	p.inlineCallback['*'] = emphasis
367	p.inlineCallback['_'] = emphasis
368	if extensions&Strikethrough != 0 {
369		p.inlineCallback['~'] = emphasis
370	}
371	p.inlineCallback['`'] = codeSpan
372	p.inlineCallback['\n'] = lineBreak
373	p.inlineCallback['['] = link
374	p.inlineCallback['<'] = leftAngle
375	p.inlineCallback['\\'] = escape
376	p.inlineCallback['&'] = entity
377	p.inlineCallback['!'] = maybeImage
378	p.inlineCallback['^'] = maybeInlineFootnote
379
380	if extensions&Autolink != 0 {
381		p.inlineCallback[':'] = autoLink
382	}
383
384	if extensions&Footnotes != 0 {
385		p.notes = make([]*reference, 0)
386	}
387
388	first := firstPass(p, input)
389	second := secondPass(p, first)
390	return second
391}
392
393// first pass:
394// - extract references
395// - expand tabs
396// - normalize newlines
397// - copy everything else
398func firstPass(p *parser, input []byte) []byte {
399	var out bytes.Buffer
400	tabSize := TabSizeDefault
401	if p.flags&TabSizeEight != 0 {
402		tabSize = TabSizeDouble
403	}
404	beg, end := 0, 0
405	lastFencedCodeBlockEnd := 0
406	for beg < len(input) { // iterate over lines
407		if end = isReference(p, input[beg:], tabSize); end > 0 {
408			beg += end
409		} else { // skip to the next line
410			end = beg
411			for end < len(input) && input[end] != '\n' && input[end] != '\r' {
412				end++
413			}
414
415			if p.flags&FencedCode != 0 {
416				// track fenced code block boundaries to suppress tab expansion
417				// inside them:
418				if beg >= lastFencedCodeBlockEnd {
419					if i := p.fencedCode(&out, input[beg:], false); i > 0 {
420						lastFencedCodeBlockEnd = beg + i
421					}
422				}
423			}
424
425			// add the line body if present
426			if end > beg {
427				if end < lastFencedCodeBlockEnd { // Do not expand tabs while inside fenced code blocks.
428					out.Write(input[beg:end])
429				} else {
430					expandTabs(&out, input[beg:end], tabSize)
431				}
432			}
433			out.WriteByte('\n')
434
435			if end < len(input) && input[end] == '\r' {
436				end++
437			}
438			if end < len(input) && input[end] == '\n' {
439				end++
440			}
441
442			beg = end
443		}
444	}
445
446	// empty input?
447	if out.Len() == 0 {
448		out.WriteByte('\n')
449	}
450
451	return out.Bytes()
452}
453
454// second pass: actual rendering
455func secondPass(p *parser, input []byte) []byte {
456	var output bytes.Buffer
457
458	p.r.DocumentHeader(&output)
459	p.block(&output, input)
460
461	if p.flags&Footnotes != 0 && len(p.notes) > 0 {
462		p.r.BeginFootnotes(&output)
463		flags := ListItemBeginningOfList
464		for i := 0; i < len(p.notes); i += 1 {
465			ref := p.notes[i]
466			var buf bytes.Buffer
467			if ref.hasBlock {
468				flags |= ListItemContainsBlock
469				p.block(&buf, ref.title)
470			} else {
471				p.inline(&buf, ref.title)
472			}
473			p.r.FootnoteItem(&output, ref.link, buf.Bytes(), flags)
474			flags &^= ListItemBeginningOfList | ListItemContainsBlock
475		}
476		p.r.EndFootnotes(&output)
477	}
478
479	p.r.DocumentFooter(&output)
480
481	if p.nesting != 0 {
482		panic("Nesting level did not end at zero")
483	}
484
485	return output.Bytes()
486}
487
488//
489// Link references
490//
491// This section implements support for references that (usually) appear
492// as footnotes in a document, and can be referenced anywhere in the document.
493// The basic format is:
494//
495//    [1]: http://www.google.com/ "Google"
496//    [2]: http://www.github.com/ "Github"
497//
498// Anywhere in the document, the reference can be linked by referring to its
499// label, i.e., 1 and 2 in this example, as in:
500//
501//    This library is hosted on [Github][2], a git hosting site.
502//
503// Actual footnotes as specified in Pandoc and supported by some other Markdown
504// libraries such as php-markdown are also taken care of. They look like this:
505//
506//    This sentence needs a bit of further explanation.[^note]
507//
508//    [^note]: This is the explanation.
509//
510// Footnotes should be placed at the end of the document in an ordered list.
511// Inline footnotes such as:
512//
513//    Inline footnotes^[Not supported.] also exist.
514//
515// are not yet supported.
516
517// References are parsed and stored in this struct.
518type reference struct {
519	link     []byte
520	title    []byte
521	noteId   int // 0 if not a footnote ref
522	hasBlock bool
523	text     []byte
524}
525
526func (r *reference) String() string {
527	return fmt.Sprintf("{link: %q, title: %q, text: %q, noteId: %d, hasBlock: %v}",
528		r.link, r.title, r.text, r.noteId, r.hasBlock)
529}
530
531// Check whether or not data starts with a reference link.
532// If so, it is parsed and stored in the list of references
533// (in the render struct).
534// Returns the number of bytes to skip to move past it,
535// or zero if the first line is not a reference.
536func isReference(p *parser, data []byte, tabSize int) int {
537	// up to 3 optional leading spaces
538	if len(data) < 4 {
539		return 0
540	}
541	i := 0
542	for i < 3 && data[i] == ' ' {
543		i++
544	}
545
546	noteId := 0
547
548	// id part: anything but a newline between brackets
549	if data[i] != '[' {
550		return 0
551	}
552	i++
553	if p.flags&Footnotes != 0 {
554		if i < len(data) && data[i] == '^' {
555			// we can set it to anything here because the proper noteIds will
556			// be assigned later during the second pass. It just has to be != 0
557			noteId = 1
558			i++
559		}
560	}
561	idOffset := i
562	for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' {
563		i++
564	}
565	if i >= len(data) || data[i] != ']' {
566		return 0
567	}
568	idEnd := i
569
570	// spacer: colon (space | tab)* newline? (space | tab)*
571	i++
572	if i >= len(data) || data[i] != ':' {
573		return 0
574	}
575	i++
576	for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
577		i++
578	}
579	if i < len(data) && (data[i] == '\n' || data[i] == '\r') {
580		i++
581		if i < len(data) && data[i] == '\n' && data[i-1] == '\r' {
582			i++
583		}
584	}
585	for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
586		i++
587	}
588	if i >= len(data) {
589		return 0
590	}
591
592	var (
593		linkOffset, linkEnd   int
594		titleOffset, titleEnd int
595		lineEnd               int
596		raw                   []byte
597		hasBlock              bool
598	)
599
600	if p.flags&Footnotes != 0 && noteId != 0 {
601		linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize)
602		lineEnd = linkEnd
603	} else {
604		linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i)
605	}
606	if lineEnd == 0 {
607		return 0
608	}
609
610	// a valid ref has been found
611
612	ref := &reference{
613		noteId:   noteId,
614		hasBlock: hasBlock,
615	}
616
617	if noteId > 0 {
618		// reusing the link field for the id since footnotes don't have links
619		ref.link = data[idOffset:idEnd]
620		// if footnote, it's not really a title, it's the contained text
621		ref.title = raw
622	} else {
623		ref.link = data[linkOffset:linkEnd]
624		ref.title = data[titleOffset:titleEnd]
625	}
626
627	// id matches are case-insensitive
628	id := string(bytes.ToLower(data[idOffset:idEnd]))
629
630	p.refs[id] = ref
631
632	return lineEnd
633}
634
635func scanLinkRef(p *parser, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) {
636	// link: whitespace-free sequence, optionally between angle brackets
637	if data[i] == '<' {
638		i++
639	}
640	linkOffset = i
641	for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' {
642		i++
643	}
644	if i == len(data) {
645		return
646	}
647	linkEnd = i
648	if data[linkOffset] == '<' && data[linkEnd-1] == '>' {
649		linkOffset++
650		linkEnd--
651	}
652
653	// optional spacer: (space | tab)* (newline | '\'' | '"' | '(' )
654	for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
655		i++
656	}
657	if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' {
658		return
659	}
660
661	// compute end-of-line
662	if i >= len(data) || data[i] == '\r' || data[i] == '\n' {
663		lineEnd = i
664	}
665	if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' {
666		lineEnd++
667	}
668
669	// optional (space|tab)* spacer after a newline
670	if lineEnd > 0 {
671		i = lineEnd + 1
672		for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
673			i++
674		}
675	}
676
677	// optional title: any non-newline sequence enclosed in '"() alone on its line
678	if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') {
679		i++
680		titleOffset = i
681
682		// look for EOL
683		for i < len(data) && data[i] != '\n' && data[i] != '\r' {
684			i++
685		}
686		if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' {
687			titleEnd = i + 1
688		} else {
689			titleEnd = i
690		}
691
692		// step back
693		i--
694		for i > titleOffset && (data[i] == ' ' || data[i] == '\t') {
695			i--
696		}
697		if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') {
698			lineEnd = titleEnd
699			titleEnd = i
700		}
701	}
702
703	return
704}
705
706// The first bit of this logic is the same as (*parser).listItem, but the rest
707// is much simpler. This function simply finds the entire block and shifts it
708// over by one tab if it is indeed a block (just returns the line if it's not).
709// blockEnd is the end of the section in the input buffer, and contents is the
710// extracted text that was shifted over one tab. It will need to be rendered at
711// the end of the document.
712func scanFootnote(p *parser, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) {
713	if i == 0 || len(data) == 0 {
714		return
715	}
716
717	// skip leading whitespace on first line
718	for i < len(data) && data[i] == ' ' {
719		i++
720	}
721
722	blockStart = i
723
724	// find the end of the line
725	blockEnd = i
726	for i < len(data) && data[i-1] != '\n' {
727		i++
728	}
729
730	// get working buffer
731	var raw bytes.Buffer
732
733	// put the first line into the working buffer
734	raw.Write(data[blockEnd:i])
735	blockEnd = i
736
737	// process the following lines
738	containsBlankLine := false
739
740gatherLines:
741	for blockEnd < len(data) {
742		i++
743
744		// find the end of this line
745		for i < len(data) && data[i-1] != '\n' {
746			i++
747		}
748
749		// if it is an empty line, guess that it is part of this item
750		// and move on to the next line
751		if p.isEmpty(data[blockEnd:i]) > 0 {
752			containsBlankLine = true
753			blockEnd = i
754			continue
755		}
756
757		n := 0
758		if n = isIndented(data[blockEnd:i], indentSize); n == 0 {
759			// this is the end of the block.
760			// we don't want to include this last line in the index.
761			break gatherLines
762		}
763
764		// if there were blank lines before this one, insert a new one now
765		if containsBlankLine {
766			raw.WriteByte('\n')
767			containsBlankLine = false
768		}
769
770		// get rid of that first tab, write to buffer
771		raw.Write(data[blockEnd+n : i])
772		hasBlock = true
773
774		blockEnd = i
775	}
776
777	if data[blockEnd-1] != '\n' {
778		raw.WriteByte('\n')
779	}
780
781	contents = raw.Bytes()
782
783	return
784}
785
786//
787//
788// Miscellaneous helper functions
789//
790//
791
792// Test if a character is a punctuation symbol.
793// Taken from a private function in regexp in the stdlib.
794func ispunct(c byte) bool {
795	for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
796		if c == r {
797			return true
798		}
799	}
800	return false
801}
802
803// Test if a character is a whitespace character.
804func isspace(c byte) bool {
805	return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
806}
807
808// Test if a character is letter.
809func isletter(c byte) bool {
810	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
811}
812
813// Test if a character is a letter or a digit.
814// TODO: check when this is looking for ASCII alnum and when it should use unicode
815func isalnum(c byte) bool {
816	return (c >= '0' && c <= '9') || isletter(c)
817}
818
819// Replace tab characters with spaces, aligning to the next TAB_SIZE column.
820// always ends output with a newline
821func expandTabs(out *bytes.Buffer, line []byte, tabSize int) {
822	// first, check for common cases: no tabs, or only tabs at beginning of line
823	i, prefix := 0, 0
824	slowcase := false
825	for i = 0; i < len(line); i++ {
826		if line[i] == '\t' {
827			if prefix == i {
828				prefix++
829			} else {
830				slowcase = true
831				break
832			}
833		}
834	}
835
836	// no need to decode runes if all tabs are at the beginning of the line
837	if !slowcase {
838		for i = 0; i < prefix*tabSize; i++ {
839			out.WriteByte(' ')
840		}
841		out.Write(line[prefix:])
842		return
843	}
844
845	// the slow case: we need to count runes to figure out how
846	// many spaces to insert for each tab
847	column := 0
848	i = 0
849	for i < len(line) {
850		start := i
851		for i < len(line) && line[i] != '\t' {
852			_, size := utf8.DecodeRune(line[i:])
853			i += size
854			column++
855		}
856
857		if i > start {
858			out.Write(line[start:i])
859		}
860
861		if i >= len(line) {
862			break
863		}
864
865		for {
866			out.WriteByte(' ')
867			column++
868			if column%tabSize == 0 {
869				break
870			}
871		}
872
873		i++
874	}
875}
876
877// Find if a line counts as indented or not.
878// Returns number of characters the indent is (0 = not indented).
879func isIndented(data []byte, indentSize int) int {
880	if len(data) == 0 {
881		return 0
882	}
883	if data[0] == '\t' {
884		return 1
885	}
886	if len(data) < indentSize {
887		return 0
888	}
889	for i := 0; i < indentSize; i++ {
890		if data[i] != ' ' {
891			return 0
892		}
893	}
894	return indentSize
895}
896
897// Create a url-safe slug for fragments
898func slugify(in []byte) []byte {
899	if len(in) == 0 {
900		return in
901	}
902	out := make([]byte, 0, len(in))
903	sym := false
904
905	for _, ch := range in {
906		if isalnum(ch) {
907			sym = false
908			out = append(out, ch)
909		} else if sym {
910			continue
911		} else {
912			out = append(out, '-')
913			sym = true
914		}
915	}
916	var a, b int
917	var ch byte
918	for a, ch = range out {
919		if ch != '-' {
920			break
921		}
922	}
923	for b = len(out) - 1; b > 0; b-- {
924		if out[b] != '-' {
925			break
926		}
927	}
928	return out[a : b+1]
929}