all repos — grayfriday @ 2bbed304fbd05594bb4dd76154add618f70d1e7c

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