all repos — grayfriday @ 29f02f7d01e2575258da122cb38ad3c15c544b4e

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
378	if extensions&Autolink != 0 {
379		p.inlineCallback[':'] = autoLink
380	}
381
382	if extensions&Footnotes != 0 {
383		p.notes = make([]*reference, 0)
384	}
385
386	first := firstPass(p, input)
387	second := secondPass(p, first)
388	return second
389}
390
391// first pass:
392// - extract references
393// - expand tabs
394// - normalize newlines
395// - copy everything else
396func firstPass(p *parser, input []byte) []byte {
397	var out bytes.Buffer
398	tabSize := TabSizeDefault
399	if p.flags&TabSizeEight != 0 {
400		tabSize = TabSizeDouble
401	}
402	beg, end := 0, 0
403	lastFencedCodeBlockEnd := 0
404	for beg < len(input) { // iterate over lines
405		if end = isReference(p, input[beg:], tabSize); end > 0 {
406			beg += end
407		} else { // skip to the next line
408			end = beg
409			for end < len(input) && input[end] != '\n' && input[end] != '\r' {
410				end++
411			}
412
413			if p.flags&FencedCode != 0 {
414				// track fenced code block boundaries to suppress tab expansion
415				// inside them:
416				if beg >= lastFencedCodeBlockEnd {
417					if i := p.fencedCode(&out, input[beg:], false); i > 0 {
418						lastFencedCodeBlockEnd = beg + i
419					}
420				}
421			}
422
423			// add the line body if present
424			if end > beg {
425				if end < lastFencedCodeBlockEnd { // Do not expand tabs while inside fenced code blocks.
426					out.Write(input[beg:end])
427				} else {
428					expandTabs(&out, input[beg:end], tabSize)
429				}
430			}
431			out.WriteByte('\n')
432
433			if end < len(input) && input[end] == '\r' {
434				end++
435			}
436			if end < len(input) && input[end] == '\n' {
437				end++
438			}
439
440			beg = end
441		}
442	}
443
444	// empty input?
445	if out.Len() == 0 {
446		out.WriteByte('\n')
447	}
448
449	return out.Bytes()
450}
451
452// second pass: actual rendering
453func secondPass(p *parser, input []byte) []byte {
454	var output bytes.Buffer
455
456	p.r.DocumentHeader(&output)
457	p.block(&output, input)
458
459	if p.flags&Footnotes != 0 && len(p.notes) > 0 {
460		p.r.BeginFootnotes(&output)
461		flags := ListItemBeginningOfList
462		for i := 0; i < len(p.notes); i += 1 {
463			ref := p.notes[i]
464			var buf bytes.Buffer
465			if ref.hasBlock {
466				flags |= ListItemContainsBlock
467				p.block(&buf, ref.title)
468			} else {
469				p.inline(&buf, ref.title)
470			}
471			p.r.FootnoteItem(&output, ref.link, buf.Bytes(), flags)
472			flags &^= ListItemBeginningOfList | ListItemContainsBlock
473		}
474		p.r.EndFootnotes(&output)
475	}
476
477	p.r.DocumentFooter(&output)
478
479	if p.nesting != 0 {
480		panic("Nesting level did not end at zero")
481	}
482
483	return output.Bytes()
484}
485
486//
487// Link references
488//
489// This section implements support for references that (usually) appear
490// as footnotes in a document, and can be referenced anywhere in the document.
491// The basic format is:
492//
493//    [1]: http://www.google.com/ "Google"
494//    [2]: http://www.github.com/ "Github"
495//
496// Anywhere in the document, the reference can be linked by referring to its
497// label, i.e., 1 and 2 in this example, as in:
498//
499//    This library is hosted on [Github][2], a git hosting site.
500//
501// Actual footnotes as specified in Pandoc and supported by some other Markdown
502// libraries such as php-markdown are also taken care of. They look like this:
503//
504//    This sentence needs a bit of further explanation.[^note]
505//
506//    [^note]: This is the explanation.
507//
508// Footnotes should be placed at the end of the document in an ordered list.
509// Inline footnotes such as:
510//
511//    Inline footnotes^[Not supported.] also exist.
512//
513// are not yet supported.
514
515// References are parsed and stored in this struct.
516type reference struct {
517	link     []byte
518	title    []byte
519	noteId   int // 0 if not a footnote ref
520	hasBlock bool
521	text     []byte
522}
523
524func (r *reference) String() string {
525	return fmt.Sprintf("{link: %q, title: %q, text: %q, noteId: %d, hasBlock: %v}",
526		r.link, r.title, r.text, r.noteId, r.hasBlock)
527}
528
529// Check whether or not data starts with a reference link.
530// If so, it is parsed and stored in the list of references
531// (in the render struct).
532// Returns the number of bytes to skip to move past it,
533// or zero if the first line is not a reference.
534func isReference(p *parser, data []byte, tabSize int) int {
535	// up to 3 optional leading spaces
536	if len(data) < 4 {
537		return 0
538	}
539	i := 0
540	for i < 3 && data[i] == ' ' {
541		i++
542	}
543
544	noteId := 0
545
546	// id part: anything but a newline between brackets
547	if data[i] != '[' {
548		return 0
549	}
550	i++
551	if p.flags&Footnotes != 0 {
552		if i < len(data) && data[i] == '^' {
553			// we can set it to anything here because the proper noteIds will
554			// be assigned later during the second pass. It just has to be != 0
555			noteId = 1
556			i++
557		}
558	}
559	idOffset := i
560	for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' {
561		i++
562	}
563	if i >= len(data) || data[i] != ']' {
564		return 0
565	}
566	idEnd := i
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}