all repos — grayfriday @ 2a07386455d11afe616a6184c03e88a1c969316b

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