all repos — grayfriday @ 5e8b222b6980d15fae51c859ca79b97cc679168d

blackfriday fork with a few changes

block.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// Functions to parse block-level elements.
  12//
  13
  14package blackfriday
  15
  16import (
  17	"bytes"
  18
  19	"github.com/shurcooL/go/github_flavored_markdown/sanitized_anchor_name"
  20)
  21
  22// Parse block-level data.
  23// Note: this function and many that it calls assume that
  24// the input buffer ends with a newline.
  25func (p *parser) block(out *bytes.Buffer, data []byte) {
  26	if len(data) == 0 || data[len(data)-1] != '\n' {
  27		panic("block input is missing terminating newline")
  28	}
  29
  30	// this is called recursively: enforce a maximum depth
  31	if p.nesting >= p.maxNesting {
  32		return
  33	}
  34	p.nesting++
  35
  36	// parse out one block-level construct at a time
  37	for len(data) > 0 {
  38		// prefixed header:
  39		//
  40		// # Header 1
  41		// ## Header 2
  42		// ...
  43		// ###### Header 6
  44		if p.isPrefixHeader(data) {
  45			data = data[p.prefixHeader(out, data):]
  46			continue
  47		}
  48
  49		// block of preformatted HTML:
  50		//
  51		// <div>
  52		//     ...
  53		// </div>
  54		if data[0] == '<' {
  55			if i := p.html(out, data, true); i > 0 {
  56				data = data[i:]
  57				continue
  58			}
  59		}
  60
  61		// title block
  62		//
  63		// % stuff
  64		// % more stuff
  65		// % even more stuff
  66		if p.flags&EXTENSION_TITLEBLOCK != 0 {
  67			if data[0] == '%' {
  68				if i := p.titleBlock(out, data, true); i > 0 {
  69					data = data[i:]
  70					continue
  71				}
  72			}
  73		}
  74
  75		// blank lines.  note: returns the # of bytes to skip
  76		if i := p.isEmpty(data); i > 0 {
  77			data = data[i:]
  78			continue
  79		}
  80
  81		// indented code block:
  82		//
  83		//     func max(a, b int) int {
  84		//         if a > b {
  85		//             return a
  86		//         }
  87		//         return b
  88		//      }
  89		if p.codePrefix(data) > 0 {
  90			data = data[p.code(out, data):]
  91			continue
  92		}
  93
  94		// fenced code block:
  95		//
  96		// ``` go
  97		// func fact(n int) int {
  98		//     if n <= 1 {
  99		//         return n
 100		//     }
 101		//     return n * fact(n-1)
 102		// }
 103		// ```
 104		if p.flags&EXTENSION_FENCED_CODE != 0 {
 105			if i := p.fencedCode(out, data, true); i > 0 {
 106				data = data[i:]
 107				continue
 108			}
 109		}
 110
 111		// horizontal rule:
 112		//
 113		// ------
 114		// or
 115		// ******
 116		// or
 117		// ______
 118		if p.isHRule(data) {
 119			p.r.HRule(out)
 120			var i int
 121			for i = 0; data[i] != '\n'; i++ {
 122			}
 123			data = data[i:]
 124			continue
 125		}
 126
 127		// block quote:
 128		//
 129		// > A big quote I found somewhere
 130		// > on the web
 131		if p.quotePrefix(data) > 0 {
 132			data = data[p.quote(out, data):]
 133			continue
 134		}
 135
 136		// table:
 137		//
 138		// Name  | Age | Phone
 139		// ------|-----|---------
 140		// Bob   | 31  | 555-1234
 141		// Alice | 27  | 555-4321
 142		if p.flags&EXTENSION_TABLES != 0 {
 143			if i := p.table(out, data); i > 0 {
 144				data = data[i:]
 145				continue
 146			}
 147		}
 148
 149		// an itemized/unordered list:
 150		//
 151		// * Item 1
 152		// * Item 2
 153		//
 154		// also works with + or -
 155		if p.uliPrefix(data) > 0 {
 156			data = data[p.list(out, data, 0):]
 157			continue
 158		}
 159
 160		// a numbered/ordered list:
 161		//
 162		// 1. Item 1
 163		// 2. Item 2
 164		if p.oliPrefix(data) > 0 {
 165			data = data[p.list(out, data, LIST_TYPE_ORDERED):]
 166			continue
 167		}
 168
 169		// anything else must look like a normal paragraph
 170		// note: this finds underlined headers, too
 171		data = data[p.paragraph(out, data):]
 172	}
 173
 174	p.nesting--
 175}
 176
 177func (p *parser) isPrefixHeader(data []byte) bool {
 178	if data[0] != '#' {
 179		return false
 180	}
 181
 182	if p.flags&EXTENSION_SPACE_HEADERS != 0 {
 183		level := 0
 184		for level < 6 && data[level] == '#' {
 185			level++
 186		}
 187		if data[level] != ' ' {
 188			return false
 189		}
 190	}
 191	return true
 192}
 193
 194func (p *parser) prefixHeader(out *bytes.Buffer, data []byte) int {
 195	level := 0
 196	for level < 6 && data[level] == '#' {
 197		level++
 198	}
 199	i, end := 0, 0
 200	for i = level; data[i] == ' '; i++ {
 201	}
 202	for end = i; data[end] != '\n'; end++ {
 203	}
 204	skip := end
 205	id := ""
 206	if p.flags&EXTENSION_HEADER_IDS != 0 {
 207		j, k := 0, 0
 208		// find start/end of header id
 209		for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ {
 210		}
 211		for k = j + 1; k < end && data[k] != '}'; k++ {
 212		}
 213		// extract header id iff found
 214		if j < end && k < end {
 215			id = string(data[j+2 : k])
 216			end = j
 217			skip = k + 1
 218			for end > 0 && data[end-1] == ' ' {
 219				end--
 220			}
 221		}
 222	}
 223	for end > 0 && data[end-1] == '#' {
 224		end--
 225	}
 226	for end > 0 && data[end-1] == ' ' {
 227		end--
 228	}
 229	if end > i {
 230		if id == "" && p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
 231			id = sanitized_anchor_name.Create(string(data[i:end]))
 232		}
 233		work := func() bool {
 234			p.inline(out, data[i:end])
 235			return true
 236		}
 237		p.r.Header(out, work, level, id)
 238	}
 239	return skip
 240}
 241
 242func (p *parser) isUnderlinedHeader(data []byte) int {
 243	// test of level 1 header
 244	if data[0] == '=' {
 245		i := 1
 246		for data[i] == '=' {
 247			i++
 248		}
 249		for data[i] == ' ' {
 250			i++
 251		}
 252		if data[i] == '\n' {
 253			return 1
 254		} else {
 255			return 0
 256		}
 257	}
 258
 259	// test of level 2 header
 260	if data[0] == '-' {
 261		i := 1
 262		for data[i] == '-' {
 263			i++
 264		}
 265		for data[i] == ' ' {
 266			i++
 267		}
 268		if data[i] == '\n' {
 269			return 2
 270		} else {
 271			return 0
 272		}
 273	}
 274
 275	return 0
 276}
 277
 278func (p *parser) titleBlock(out *bytes.Buffer, data []byte, doRender bool) int {
 279	if data[0] != '%' {
 280		return 0
 281	}
 282	splitData := bytes.Split(data, []byte("\n"))
 283	var i int
 284	for idx, b := range splitData {
 285		if !bytes.HasPrefix(b, []byte("%")) {
 286			i = idx // - 1
 287			break
 288		}
 289	}
 290
 291	data = bytes.Join(splitData[0:i], []byte("\n"))
 292	p.r.TitleBlock(out, data)
 293
 294	return len(data)
 295}
 296
 297func (p *parser) html(out *bytes.Buffer, data []byte, doRender bool) int {
 298	var i, j int
 299
 300	// identify the opening tag
 301	if data[0] != '<' {
 302		return 0
 303	}
 304	curtag, tagfound := p.htmlFindTag(data[1:])
 305
 306	// handle special cases
 307	if !tagfound {
 308		// check for an HTML comment
 309		if size := p.htmlComment(out, data, doRender); size > 0 {
 310			return size
 311		}
 312
 313		// check for an <hr> tag
 314		if size := p.htmlHr(out, data, doRender); size > 0 {
 315			return size
 316		}
 317
 318		// no special case recognized
 319		return 0
 320	}
 321
 322	// look for an unindented matching closing tag
 323	// followed by a blank line
 324	found := false
 325	/*
 326		closetag := []byte("\n</" + curtag + ">")
 327		j = len(curtag) + 1
 328		for !found {
 329			// scan for a closing tag at the beginning of a line
 330			if skip := bytes.Index(data[j:], closetag); skip >= 0 {
 331				j += skip + len(closetag)
 332			} else {
 333				break
 334			}
 335
 336			// see if it is the only thing on the line
 337			if skip := p.isEmpty(data[j:]); skip > 0 {
 338				// see if it is followed by a blank line/eof
 339				j += skip
 340				if j >= len(data) {
 341					found = true
 342					i = j
 343				} else {
 344					if skip := p.isEmpty(data[j:]); skip > 0 {
 345						j += skip
 346						found = true
 347						i = j
 348					}
 349				}
 350			}
 351		}
 352	*/
 353
 354	// if not found, try a second pass looking for indented match
 355	// but not if tag is "ins" or "del" (following original Markdown.pl)
 356	if !found && curtag != "ins" && curtag != "del" {
 357		i = 1
 358		for i < len(data) {
 359			i++
 360			for i < len(data) && !(data[i-1] == '<' && data[i] == '/') {
 361				i++
 362			}
 363
 364			if i+2+len(curtag) >= len(data) {
 365				break
 366			}
 367
 368			j = p.htmlFindEnd(curtag, data[i-1:])
 369
 370			if j > 0 {
 371				i += j - 1
 372				found = true
 373				break
 374			}
 375		}
 376	}
 377
 378	if !found {
 379		return 0
 380	}
 381
 382	// the end of the block has been found
 383	if doRender {
 384		// trim newlines
 385		end := i
 386		for end > 0 && data[end-1] == '\n' {
 387			end--
 388		}
 389		p.r.BlockHtml(out, data[:end])
 390	}
 391
 392	return i
 393}
 394
 395// HTML comment, lax form
 396func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int {
 397	if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' {
 398		return 0
 399	}
 400
 401	i := 5
 402
 403	// scan for an end-of-comment marker, across lines if necessary
 404	for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') {
 405		i++
 406	}
 407	i++
 408
 409	// no end-of-comment marker
 410	if i >= len(data) {
 411		return 0
 412	}
 413
 414	// needs to end with a blank line
 415	if j := p.isEmpty(data[i:]); j > 0 {
 416		size := i + j
 417		if doRender {
 418			// trim trailing newlines
 419			end := size
 420			for end > 0 && data[end-1] == '\n' {
 421				end--
 422			}
 423			p.r.BlockHtml(out, data[:end])
 424		}
 425		return size
 426	}
 427
 428	return 0
 429}
 430
 431// HR, which is the only self-closing block tag considered
 432func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int {
 433	if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') {
 434		return 0
 435	}
 436	if data[3] != ' ' && data[3] != '/' && data[3] != '>' {
 437		// not an <hr> tag after all; at least not a valid one
 438		return 0
 439	}
 440
 441	i := 3
 442	for data[i] != '>' && data[i] != '\n' {
 443		i++
 444	}
 445
 446	if data[i] == '>' {
 447		i++
 448		if j := p.isEmpty(data[i:]); j > 0 {
 449			size := i + j
 450			if doRender {
 451				// trim newlines
 452				end := size
 453				for end > 0 && data[end-1] == '\n' {
 454					end--
 455				}
 456				p.r.BlockHtml(out, data[:end])
 457			}
 458			return size
 459		}
 460	}
 461
 462	return 0
 463}
 464
 465func (p *parser) htmlFindTag(data []byte) (string, bool) {
 466	i := 0
 467	for isalnum(data[i]) {
 468		i++
 469	}
 470	key := string(data[:i])
 471	if blockTags[key] {
 472		return key, true
 473	}
 474	return "", false
 475}
 476
 477func (p *parser) htmlFindEnd(tag string, data []byte) int {
 478	// assume data[0] == '<' && data[1] == '/' already tested
 479
 480	// check if tag is a match
 481	closetag := []byte("</" + tag + ">")
 482	if !bytes.HasPrefix(data, closetag) {
 483		return 0
 484	}
 485	i := len(closetag)
 486
 487	// check that the rest of the line is blank
 488	skip := 0
 489	if skip = p.isEmpty(data[i:]); skip == 0 {
 490		return 0
 491	}
 492	i += skip
 493	skip = 0
 494
 495	if i >= len(data) {
 496		return i
 497	}
 498
 499	if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
 500		return i
 501	}
 502	if skip = p.isEmpty(data[i:]); skip == 0 {
 503		// following line must be blank
 504		return 0
 505	}
 506
 507	return i + skip
 508}
 509
 510func (p *parser) isEmpty(data []byte) int {
 511	// it is okay to call isEmpty on an empty buffer
 512	if len(data) == 0 {
 513		return 0
 514	}
 515
 516	var i int
 517	for i = 0; i < len(data) && data[i] != '\n'; i++ {
 518		if data[i] != ' ' && data[i] != '\t' {
 519			return 0
 520		}
 521	}
 522	return i + 1
 523}
 524
 525func (p *parser) isHRule(data []byte) bool {
 526	i := 0
 527
 528	// skip up to three spaces
 529	for i < 3 && data[i] == ' ' {
 530		i++
 531	}
 532
 533	// look at the hrule char
 534	if data[i] != '*' && data[i] != '-' && data[i] != '_' {
 535		return false
 536	}
 537	c := data[i]
 538
 539	// the whole line must be the char or whitespace
 540	n := 0
 541	for data[i] != '\n' {
 542		switch {
 543		case data[i] == c:
 544			n++
 545		case data[i] != ' ':
 546			return false
 547		}
 548		i++
 549	}
 550
 551	return n >= 3
 552}
 553
 554func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (skip int, marker string) {
 555	i, size := 0, 0
 556	skip = 0
 557
 558	// skip up to three spaces
 559	for i < 3 && data[i] == ' ' {
 560		i++
 561	}
 562
 563	// check for the marker characters: ~ or `
 564	if data[i] != '~' && data[i] != '`' {
 565		return
 566	}
 567
 568	c := data[i]
 569
 570	// the whole line must be the same char or whitespace
 571	for data[i] == c {
 572		size++
 573		i++
 574	}
 575
 576	// the marker char must occur at least 3 times
 577	if size < 3 {
 578		return
 579	}
 580	marker = string(data[i-size : i])
 581
 582	// if this is the end marker, it must match the beginning marker
 583	if oldmarker != "" && marker != oldmarker {
 584		return
 585	}
 586
 587	if syntax != nil {
 588		syn := 0
 589
 590		for data[i] == ' ' {
 591			i++
 592		}
 593
 594		syntaxStart := i
 595
 596		if data[i] == '{' {
 597			i++
 598			syntaxStart++
 599
 600			for data[i] != '}' && data[i] != '\n' {
 601				syn++
 602				i++
 603			}
 604
 605			if data[i] != '}' {
 606				return
 607			}
 608
 609			// strip all whitespace at the beginning and the end
 610			// of the {} block
 611			for syn > 0 && isspace(data[syntaxStart]) {
 612				syntaxStart++
 613				syn--
 614			}
 615
 616			for syn > 0 && isspace(data[syntaxStart+syn-1]) {
 617				syn--
 618			}
 619
 620			i++
 621		} else {
 622			for !isspace(data[i]) {
 623				syn++
 624				i++
 625			}
 626		}
 627
 628		language := string(data[syntaxStart : syntaxStart+syn])
 629		*syntax = &language
 630	}
 631
 632	for data[i] == ' ' {
 633		i++
 634	}
 635	if data[i] != '\n' {
 636		return
 637	}
 638
 639	skip = i + 1
 640	return
 641}
 642
 643func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int {
 644	var lang *string
 645	beg, marker := p.isFencedCode(data, &lang, "")
 646	if beg == 0 || beg >= len(data) {
 647		return 0
 648	}
 649
 650	var work bytes.Buffer
 651
 652	for {
 653		// safe to assume beg < len(data)
 654
 655		// check for the end of the code block
 656		fenceEnd, _ := p.isFencedCode(data[beg:], nil, marker)
 657		if fenceEnd != 0 {
 658			beg += fenceEnd
 659			break
 660		}
 661
 662		// copy the current line
 663		end := beg
 664		for data[end] != '\n' {
 665			end++
 666		}
 667		end++
 668
 669		// did we reach the end of the buffer without a closing marker?
 670		if end >= len(data) {
 671			return 0
 672		}
 673
 674		// verbatim copy to the working buffer
 675		if doRender {
 676			work.Write(data[beg:end])
 677		}
 678		beg = end
 679	}
 680
 681	syntax := ""
 682	if lang != nil {
 683		syntax = *lang
 684	}
 685
 686	if doRender {
 687		p.r.BlockCode(out, work.Bytes(), syntax)
 688	}
 689
 690	return beg
 691}
 692
 693func (p *parser) table(out *bytes.Buffer, data []byte) int {
 694	var header bytes.Buffer
 695	i, columns := p.tableHeader(&header, data)
 696	if i == 0 {
 697		return 0
 698	}
 699
 700	var body bytes.Buffer
 701
 702	for i < len(data) {
 703		pipes, rowStart := 0, i
 704		for ; data[i] != '\n'; i++ {
 705			if data[i] == '|' {
 706				pipes++
 707			}
 708		}
 709
 710		if pipes == 0 {
 711			i = rowStart
 712			break
 713		}
 714
 715		// include the newline in data sent to tableRow
 716		i++
 717		p.tableRow(&body, data[rowStart:i], columns, false)
 718	}
 719
 720	p.r.Table(out, header.Bytes(), body.Bytes(), columns)
 721
 722	return i
 723}
 724
 725// check if the specified position is preceeded by an odd number of backslashes
 726func isBackslashEscaped(data []byte, i int) bool {
 727	backslashes := 0
 728	for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' {
 729		backslashes++
 730	}
 731	return backslashes&1 == 1
 732}
 733
 734func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) {
 735	i := 0
 736	colCount := 1
 737	for i = 0; data[i] != '\n'; i++ {
 738		if data[i] == '|' && !isBackslashEscaped(data, i) {
 739			colCount++
 740		}
 741	}
 742
 743	// doesn't look like a table header
 744	if colCount == 1 {
 745		return
 746	}
 747
 748	// include the newline in the data sent to tableRow
 749	header := data[:i+1]
 750
 751	// column count ignores pipes at beginning or end of line
 752	if data[0] == '|' {
 753		colCount--
 754	}
 755	if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) {
 756		colCount--
 757	}
 758
 759	columns = make([]int, colCount)
 760
 761	// move on to the header underline
 762	i++
 763	if i >= len(data) {
 764		return
 765	}
 766
 767	if data[i] == '|' && !isBackslashEscaped(data, i) {
 768		i++
 769	}
 770	for data[i] == ' ' {
 771		i++
 772	}
 773
 774	// each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3
 775	// and trailing | optional on last column
 776	col := 0
 777	for data[i] != '\n' {
 778		dashes := 0
 779
 780		if data[i] == ':' {
 781			i++
 782			columns[col] |= TABLE_ALIGNMENT_LEFT
 783			dashes++
 784		}
 785		for data[i] == '-' {
 786			i++
 787			dashes++
 788		}
 789		if data[i] == ':' {
 790			i++
 791			columns[col] |= TABLE_ALIGNMENT_RIGHT
 792			dashes++
 793		}
 794		for data[i] == ' ' {
 795			i++
 796		}
 797
 798		// end of column test is messy
 799		switch {
 800		case dashes < 3:
 801			// not a valid column
 802			return
 803
 804		case data[i] == '|' && !isBackslashEscaped(data, i):
 805			// marker found, now skip past trailing whitespace
 806			col++
 807			i++
 808			for data[i] == ' ' {
 809				i++
 810			}
 811
 812			// trailing junk found after last column
 813			if col >= colCount && data[i] != '\n' {
 814				return
 815			}
 816
 817		case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount:
 818			// something else found where marker was required
 819			return
 820
 821		case data[i] == '\n':
 822			// marker is optional for the last column
 823			col++
 824
 825		default:
 826			// trailing junk found after last column
 827			return
 828		}
 829	}
 830	if col != colCount {
 831		return
 832	}
 833
 834	p.tableRow(out, header, columns, true)
 835	size = i + 1
 836	return
 837}
 838
 839func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) {
 840	i, col := 0, 0
 841	var rowWork bytes.Buffer
 842
 843	if data[i] == '|' && !isBackslashEscaped(data, i) {
 844		i++
 845	}
 846
 847	for col = 0; col < len(columns) && i < len(data); col++ {
 848		for data[i] == ' ' {
 849			i++
 850		}
 851
 852		cellStart := i
 853
 854		for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' {
 855			i++
 856		}
 857
 858		cellEnd := i
 859
 860		// skip the end-of-cell marker, possibly taking us past end of buffer
 861		i++
 862
 863		for cellEnd > cellStart && data[cellEnd-1] == ' ' {
 864			cellEnd--
 865		}
 866
 867		var cellWork bytes.Buffer
 868		p.inline(&cellWork, data[cellStart:cellEnd])
 869
 870		if header {
 871			p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col])
 872		} else {
 873			p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col])
 874		}
 875	}
 876
 877	// pad it out with empty columns to get the right number
 878	for ; col < len(columns); col++ {
 879		if header {
 880			p.r.TableHeaderCell(&rowWork, nil, columns[col])
 881		} else {
 882			p.r.TableCell(&rowWork, nil, columns[col])
 883		}
 884	}
 885
 886	// silently ignore rows with too many cells
 887
 888	p.r.TableRow(out, rowWork.Bytes())
 889}
 890
 891// returns blockquote prefix length
 892func (p *parser) quotePrefix(data []byte) int {
 893	i := 0
 894	for i < 3 && data[i] == ' ' {
 895		i++
 896	}
 897	if data[i] == '>' {
 898		if data[i+1] == ' ' {
 899			return i + 2
 900		}
 901		return i + 1
 902	}
 903	return 0
 904}
 905
 906// parse a blockquote fragment
 907func (p *parser) quote(out *bytes.Buffer, data []byte) int {
 908	var raw bytes.Buffer
 909	beg, end := 0, 0
 910	for beg < len(data) {
 911		end = beg
 912		for data[end] != '\n' {
 913			end++
 914		}
 915		end++
 916
 917		if pre := p.quotePrefix(data[beg:]); pre > 0 {
 918			// skip the prefix
 919			beg += pre
 920		} else if p.isEmpty(data[beg:]) > 0 &&
 921			(end >= len(data) ||
 922				(p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0)) {
 923			// blockquote ends with at least one blank line
 924			// followed by something without a blockquote prefix
 925			break
 926		}
 927
 928		// this line is part of the blockquote
 929		raw.Write(data[beg:end])
 930		beg = end
 931	}
 932
 933	var cooked bytes.Buffer
 934	p.block(&cooked, raw.Bytes())
 935	p.r.BlockQuote(out, cooked.Bytes())
 936	return end
 937}
 938
 939// returns prefix length for block code
 940func (p *parser) codePrefix(data []byte) int {
 941	if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' {
 942		return 4
 943	}
 944	return 0
 945}
 946
 947func (p *parser) code(out *bytes.Buffer, data []byte) int {
 948	var work bytes.Buffer
 949
 950	i := 0
 951	for i < len(data) {
 952		beg := i
 953		for data[i] != '\n' {
 954			i++
 955		}
 956		i++
 957
 958		blankline := p.isEmpty(data[beg:i]) > 0
 959		if pre := p.codePrefix(data[beg:i]); pre > 0 {
 960			beg += pre
 961		} else if !blankline {
 962			// non-empty, non-prefixed line breaks the pre
 963			i = beg
 964			break
 965		}
 966
 967		// verbatim copy to the working buffeu
 968		if blankline {
 969			work.WriteByte('\n')
 970		} else {
 971			work.Write(data[beg:i])
 972		}
 973	}
 974
 975	// trim all the \n off the end of work
 976	workbytes := work.Bytes()
 977	eol := len(workbytes)
 978	for eol > 0 && workbytes[eol-1] == '\n' {
 979		eol--
 980	}
 981	if eol != len(workbytes) {
 982		work.Truncate(eol)
 983	}
 984
 985	work.WriteByte('\n')
 986
 987	p.r.BlockCode(out, work.Bytes(), "")
 988
 989	return i
 990}
 991
 992// returns unordered list item prefix
 993func (p *parser) uliPrefix(data []byte) int {
 994	i := 0
 995
 996	// start with up to 3 spaces
 997	for i < 3 && data[i] == ' ' {
 998		i++
 999	}
1000
1001	// need a *, +, or - followed by a space
1002	if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
1003		data[i+1] != ' ' {
1004		return 0
1005	}
1006	return i + 2
1007}
1008
1009// returns ordered list item prefix
1010func (p *parser) oliPrefix(data []byte) int {
1011	i := 0
1012
1013	// start with up to 3 spaces
1014	for i < 3 && data[i] == ' ' {
1015		i++
1016	}
1017
1018	// count the digits
1019	start := i
1020	for data[i] >= '0' && data[i] <= '9' {
1021		i++
1022	}
1023
1024	// we need >= 1 digits followed by a dot and a space
1025	if start == i || data[i] != '.' || data[i+1] != ' ' {
1026		return 0
1027	}
1028	return i + 2
1029}
1030
1031// parse ordered or unordered list block
1032func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int {
1033	i := 0
1034	flags |= LIST_ITEM_BEGINNING_OF_LIST
1035	work := func() bool {
1036		for i < len(data) {
1037			skip := p.listItem(out, data[i:], &flags)
1038			i += skip
1039
1040			if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 {
1041				break
1042			}
1043			flags &= ^LIST_ITEM_BEGINNING_OF_LIST
1044		}
1045		return true
1046	}
1047
1048	p.r.List(out, work, flags)
1049	return i
1050}
1051
1052// Parse a single list item.
1053// Assumes initial prefix is already removed if this is a sublist.
1054func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int {
1055	// keep track of the indentation of the first line
1056	itemIndent := 0
1057	for itemIndent < 3 && data[itemIndent] == ' ' {
1058		itemIndent++
1059	}
1060
1061	i := p.uliPrefix(data)
1062	if i == 0 {
1063		i = p.oliPrefix(data)
1064	}
1065	if i == 0 {
1066		return 0
1067	}
1068
1069	// skip leading whitespace on first line
1070	for data[i] == ' ' {
1071		i++
1072	}
1073
1074	// find the end of the line
1075	line := i
1076	for data[i-1] != '\n' {
1077		i++
1078	}
1079
1080	// get working buffer
1081	var raw bytes.Buffer
1082
1083	// put the first line into the working buffer
1084	raw.Write(data[line:i])
1085	line = i
1086
1087	// process the following lines
1088	containsBlankLine := false
1089	sublist := 0
1090
1091gatherlines:
1092	for line < len(data) {
1093		i++
1094
1095		// find the end of this line
1096		for data[i-1] != '\n' {
1097			i++
1098		}
1099
1100		// if it is an empty line, guess that it is part of this item
1101		// and move on to the next line
1102		if p.isEmpty(data[line:i]) > 0 {
1103			containsBlankLine = true
1104			line = i
1105			continue
1106		}
1107
1108		// calculate the indentation
1109		indent := 0
1110		for indent < 4 && line+indent < i && data[line+indent] == ' ' {
1111			indent++
1112		}
1113
1114		chunk := data[line+indent : i]
1115
1116		// evaluate how this line fits in
1117		switch {
1118		// is this a nested list item?
1119		case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) ||
1120			p.oliPrefix(chunk) > 0:
1121
1122			if containsBlankLine {
1123				*flags |= LIST_ITEM_CONTAINS_BLOCK
1124			}
1125
1126			// to be a nested list, it must be indented more
1127			// if not, it is the next item in the same list
1128			if indent <= itemIndent {
1129				break gatherlines
1130			}
1131
1132			// is this the first item in the the nested list?
1133			if sublist == 0 {
1134				sublist = raw.Len()
1135			}
1136
1137		// is this a nested prefix header?
1138		case p.isPrefixHeader(chunk):
1139			// if the header is not indented, it is not nested in the list
1140			// and thus ends the list
1141			if containsBlankLine && indent < 4 {
1142				*flags |= LIST_ITEM_END_OF_LIST
1143				break gatherlines
1144			}
1145			*flags |= LIST_ITEM_CONTAINS_BLOCK
1146
1147		// anything following an empty line is only part
1148		// of this item if it is indented 4 spaces
1149		// (regardless of the indentation of the beginning of the item)
1150		case containsBlankLine && indent < 4:
1151			*flags |= LIST_ITEM_END_OF_LIST
1152			break gatherlines
1153
1154		// a blank line means this should be parsed as a block
1155		case containsBlankLine:
1156			raw.WriteByte('\n')
1157			*flags |= LIST_ITEM_CONTAINS_BLOCK
1158		}
1159
1160		// if this line was preceeded by one or more blanks,
1161		// re-introduce the blank into the buffer
1162		if containsBlankLine {
1163			containsBlankLine = false
1164			raw.WriteByte('\n')
1165		}
1166
1167		// add the line into the working buffer without prefix
1168		raw.Write(data[line+indent : i])
1169
1170		line = i
1171	}
1172
1173	rawBytes := raw.Bytes()
1174
1175	// render the contents of the list item
1176	var cooked bytes.Buffer
1177	if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 {
1178		// intermediate render of block li
1179		if sublist > 0 {
1180			p.block(&cooked, rawBytes[:sublist])
1181			p.block(&cooked, rawBytes[sublist:])
1182		} else {
1183			p.block(&cooked, rawBytes)
1184		}
1185	} else {
1186		// intermediate render of inline li
1187		if sublist > 0 {
1188			p.inline(&cooked, rawBytes[:sublist])
1189			p.block(&cooked, rawBytes[sublist:])
1190		} else {
1191			p.inline(&cooked, rawBytes)
1192		}
1193	}
1194
1195	// render the actual list item
1196	cookedBytes := cooked.Bytes()
1197	parsedEnd := len(cookedBytes)
1198
1199	// strip trailing newlines
1200	for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' {
1201		parsedEnd--
1202	}
1203	p.r.ListItem(out, cookedBytes[:parsedEnd], *flags)
1204
1205	return line
1206}
1207
1208// render a single paragraph that has already been parsed out
1209func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) {
1210	if len(data) == 0 {
1211		return
1212	}
1213
1214	// trim leading spaces
1215	beg := 0
1216	for data[beg] == ' ' {
1217		beg++
1218	}
1219
1220	// trim trailing newline
1221	end := len(data) - 1
1222
1223	// trim trailing spaces
1224	for end > beg && data[end-1] == ' ' {
1225		end--
1226	}
1227
1228	work := func() bool {
1229		p.inline(out, data[beg:end])
1230		return true
1231	}
1232	p.r.Paragraph(out, work)
1233}
1234
1235func (p *parser) paragraph(out *bytes.Buffer, data []byte) int {
1236	// prev: index of 1st char of previous line
1237	// line: index of 1st char of current line
1238	// i: index of cursor/end of current line
1239	var prev, line, i int
1240
1241	// keep going until we find something to mark the end of the paragraph
1242	for i < len(data) {
1243		// mark the beginning of the current line
1244		prev = line
1245		current := data[i:]
1246		line = i
1247
1248		// did we find a blank line marking the end of the paragraph?
1249		if n := p.isEmpty(current); n > 0 {
1250			p.renderParagraph(out, data[:i])
1251			return i + n
1252		}
1253
1254		// an underline under some text marks a header, so our paragraph ended on prev line
1255		if i > 0 {
1256			if level := p.isUnderlinedHeader(current); level > 0 {
1257				// render the paragraph
1258				p.renderParagraph(out, data[:prev])
1259
1260				// ignore leading and trailing whitespace
1261				eol := i - 1
1262				for prev < eol && data[prev] == ' ' {
1263					prev++
1264				}
1265				for eol > prev && data[eol-1] == ' ' {
1266					eol--
1267				}
1268
1269				// render the header
1270				// this ugly double closure avoids forcing variables onto the heap
1271				work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool {
1272					return func() bool {
1273						pp.inline(o, d)
1274						return true
1275					}
1276				}(out, p, data[prev:eol])
1277
1278				id := ""
1279				if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
1280					id = sanitized_anchor_name.Create(string(data[prev:eol]))
1281				}
1282
1283				p.r.Header(out, work, level, id)
1284
1285				// find the end of the underline
1286				for data[i] != '\n' {
1287					i++
1288				}
1289				return i
1290			}
1291		}
1292
1293		// if the next line starts a block of HTML, then the paragraph ends here
1294		if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
1295			if data[i] == '<' && p.html(out, current, false) > 0 {
1296				// rewind to before the HTML block
1297				p.renderParagraph(out, data[:i])
1298				return i
1299			}
1300		}
1301
1302		// if there's a prefixed header or a horizontal rule after this, paragraph is over
1303		if p.isPrefixHeader(current) || p.isHRule(current) {
1304			p.renderParagraph(out, data[:i])
1305			return i
1306		}
1307
1308		// if there's a list after this, paragraph is over
1309		if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 {
1310			if p.uliPrefix(current) != 0 ||
1311				p.oliPrefix(current) != 0 ||
1312				p.quotePrefix(current) != 0 ||
1313				p.codePrefix(current) != 0 {
1314				p.renderParagraph(out, data[:i])
1315				return i
1316			}
1317		}
1318
1319		// otherwise, scan to the beginning of the next line
1320		for data[i] != '\n' {
1321			i++
1322		}
1323		i++
1324	}
1325
1326	p.renderParagraph(out, data[:i])
1327	return i
1328}