all repos — grayfriday @ 7a97ffe689e803d08c63679c7f878757fbc1e1f8

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