all repos — grayfriday @ c9f5708bd5bc263527a4893542d3a0668a19a065

blackfriday fork with a few changes

inline.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 inline elements.
  12//
  13
  14package blackfriday
  15
  16import (
  17	"bytes"
  18	"regexp"
  19	"strconv"
  20)
  21
  22var (
  23	urlRe    = `((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+`
  24	anchorRe = regexp.MustCompile(`^(<a\shref="` + urlRe + `"(\stitle="[^"<>]+")?\s?>` + urlRe + `<\/a>)`)
  25)
  26
  27// Functions to parse text within a block
  28// Each function returns the number of chars taken care of
  29// data is the complete block being rendered
  30// offset is the number of valid chars before the current cursor
  31
  32func (p *parser) inline(out *bytes.Buffer, data []byte) {
  33	// this is called recursively: enforce a maximum depth
  34	if p.nesting >= p.maxNesting {
  35		return
  36	}
  37	p.nesting++
  38
  39	i, end := 0, 0
  40	for i < len(data) {
  41		// copy inactive chars into the output
  42		for end < len(data) && p.inlineCallback[data[end]] == nil {
  43			end++
  44		}
  45
  46		p.r.NormalText(out, data[i:end])
  47
  48		if end >= len(data) {
  49			break
  50		}
  51		i = end
  52
  53		// call the trigger
  54		handler := p.inlineCallback[data[end]]
  55		if consumed := handler(p, out, data, i); consumed == 0 {
  56			// no action from the callback; buffer the byte for later
  57			end = i + 1
  58		} else {
  59			// skip past whatever the callback used
  60			i += consumed
  61			end = i
  62		}
  63	}
  64
  65	p.nesting--
  66}
  67
  68// single and double emphasis parsing
  69func emphasis(p *parser, out *bytes.Buffer, data []byte, offset int) int {
  70	data = data[offset:]
  71	c := data[0]
  72	ret := 0
  73
  74	if len(data) > 2 && data[1] != c {
  75		// whitespace cannot follow an opening emphasis;
  76		// strikethrough only takes two characters '~~'
  77		if c == '~' || isspace(data[1]) {
  78			return 0
  79		}
  80		if ret = helperEmphasis(p, out, data[1:], c); ret == 0 {
  81			return 0
  82		}
  83
  84		return ret + 1
  85	}
  86
  87	if len(data) > 3 && data[1] == c && data[2] != c {
  88		if isspace(data[2]) {
  89			return 0
  90		}
  91		if ret = helperDoubleEmphasis(p, out, data[2:], c); ret == 0 {
  92			return 0
  93		}
  94
  95		return ret + 2
  96	}
  97
  98	if len(data) > 4 && data[1] == c && data[2] == c && data[3] != c {
  99		if c == '~' || isspace(data[3]) {
 100			return 0
 101		}
 102		if ret = helperTripleEmphasis(p, out, data, 3, c); ret == 0 {
 103			return 0
 104		}
 105
 106		return ret + 3
 107	}
 108
 109	return 0
 110}
 111
 112func codeSpan(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 113	data = data[offset:]
 114
 115	nb := 0
 116
 117	// count the number of backticks in the delimiter
 118	for nb < len(data) && data[nb] == '`' {
 119		nb++
 120	}
 121
 122	// find the next delimiter
 123	i, end := 0, 0
 124	for end = nb; end < len(data) && i < nb; end++ {
 125		if data[end] == '`' {
 126			i++
 127		} else {
 128			i = 0
 129		}
 130	}
 131
 132	// no matching delimiter?
 133	if i < nb && end >= len(data) {
 134		return 0
 135	}
 136
 137	// trim outside whitespace
 138	fBegin := nb
 139	for fBegin < end && data[fBegin] == ' ' {
 140		fBegin++
 141	}
 142
 143	fEnd := end - nb
 144	for fEnd > fBegin && data[fEnd-1] == ' ' {
 145		fEnd--
 146	}
 147
 148	// render the code span
 149	if fBegin != fEnd {
 150		p.r.CodeSpan(out, data[fBegin:fEnd])
 151	}
 152
 153	return end
 154
 155}
 156
 157// newline preceded by two spaces becomes <br>
 158// newline without two spaces works when EXTENSION_HARD_LINE_BREAK is enabled
 159func lineBreak(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 160	// remove trailing spaces from out
 161	outBytes := out.Bytes()
 162	end := len(outBytes)
 163	eol := end
 164	for eol > 0 && outBytes[eol-1] == ' ' {
 165		eol--
 166	}
 167	out.Truncate(eol)
 168
 169	precededByTwoSpaces := offset >= 2 && data[offset-2] == ' ' && data[offset-1] == ' '
 170	precededByBackslash := offset >= 1 && data[offset-1] == '\\' // see http://spec.commonmark.org/0.18/#example-527
 171	precededByBackslash = precededByBackslash && p.flags&EXTENSION_BACKSLASH_LINE_BREAK != 0
 172
 173	// should there be a hard line break here?
 174	if p.flags&EXTENSION_HARD_LINE_BREAK == 0 && !precededByTwoSpaces && !precededByBackslash {
 175		return 0
 176	}
 177
 178	if precededByBackslash && eol > 0 {
 179		out.Truncate(eol - 1)
 180	}
 181	p.r.LineBreak(out)
 182	return 1
 183}
 184
 185type linkType int
 186
 187const (
 188	linkNormal linkType = iota
 189	linkImg
 190	linkDeferredFootnote
 191	linkInlineFootnote
 192)
 193
 194// '[': parse a link or an image or a footnote
 195func link(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 196	// no links allowed inside regular links, footnote, and deferred footnotes
 197	if p.insideLink && (offset > 0 && data[offset-1] == '[' || len(data)-1 > offset && data[offset+1] == '^') {
 198		return 0
 199	}
 200
 201	// [text] == regular link
 202	// ![alt] == image
 203	// ^[text] == inline footnote
 204	// [^refId] == deferred footnote
 205	var t linkType
 206	if offset > 0 && data[offset-1] == '!' {
 207		t = linkImg
 208	} else if p.flags&EXTENSION_FOOTNOTES != 0 {
 209		if offset > 0 && data[offset-1] == '^' {
 210			t = linkInlineFootnote
 211		} else if len(data)-1 > offset && data[offset+1] == '^' {
 212			t = linkDeferredFootnote
 213		}
 214	}
 215
 216	data = data[offset:]
 217
 218	var (
 219		i                       = 1
 220		noteId                  int
 221		title, link, altContent []byte
 222		textHasNl               = false
 223	)
 224
 225	if t == linkDeferredFootnote {
 226		i++
 227	}
 228
 229	// look for the matching closing bracket
 230	for level := 1; level > 0 && i < len(data); i++ {
 231		switch {
 232		case data[i] == '\n':
 233			textHasNl = true
 234
 235		case data[i-1] == '\\':
 236			continue
 237
 238		case data[i] == '[':
 239			level++
 240
 241		case data[i] == ']':
 242			level--
 243			if level <= 0 {
 244				i-- // compensate for extra i++ in for loop
 245			}
 246		}
 247	}
 248
 249	if i >= len(data) {
 250		return 0
 251	}
 252
 253	txtE := i
 254	i++
 255
 256	// skip any amount of whitespace or newline
 257	// (this is much more lax than original markdown syntax)
 258	for i < len(data) && isspace(data[i]) {
 259		i++
 260	}
 261
 262	// inline style link
 263	switch {
 264	case i < len(data) && data[i] == '(':
 265		// skip initial whitespace
 266		i++
 267
 268		for i < len(data) && isspace(data[i]) {
 269			i++
 270		}
 271
 272		linkB := i
 273
 274		// look for link end: ' " )
 275	findlinkend:
 276		for i < len(data) {
 277			switch {
 278			case data[i] == '\\':
 279				i += 2
 280
 281			case data[i] == ')' || data[i] == '\'' || data[i] == '"':
 282				break findlinkend
 283
 284			default:
 285				i++
 286			}
 287		}
 288
 289		if i >= len(data) {
 290			return 0
 291		}
 292		linkE := i
 293
 294		// look for title end if present
 295		titleB, titleE := 0, 0
 296		if data[i] == '\'' || data[i] == '"' {
 297			i++
 298			titleB = i
 299
 300		findtitleend:
 301			for i < len(data) {
 302				switch {
 303				case data[i] == '\\':
 304					i += 2
 305
 306				case data[i] == ')':
 307					break findtitleend
 308
 309				default:
 310					i++
 311				}
 312			}
 313
 314			if i >= len(data) {
 315				return 0
 316			}
 317
 318			// skip whitespace after title
 319			titleE = i - 1
 320			for titleE > titleB && isspace(data[titleE]) {
 321				titleE--
 322			}
 323
 324			// check for closing quote presence
 325			if data[titleE] != '\'' && data[titleE] != '"' {
 326				titleB, titleE = 0, 0
 327				linkE = i
 328			}
 329		}
 330
 331		// remove whitespace at the end of the link
 332		for linkE > linkB && isspace(data[linkE-1]) {
 333			linkE--
 334		}
 335
 336		// remove optional angle brackets around the link
 337		if data[linkB] == '<' {
 338			linkB++
 339		}
 340		if data[linkE-1] == '>' {
 341			linkE--
 342		}
 343
 344		// build escaped link and title
 345		if linkE > linkB {
 346			link = data[linkB:linkE]
 347		}
 348
 349		if titleE > titleB {
 350			title = data[titleB:titleE]
 351		}
 352
 353		i++
 354
 355	// reference style link
 356	case i < len(data)-1 && data[i] == '[' && data[i+1] != '^':
 357		var id []byte
 358		altContentConsidered := false
 359
 360		// look for the id
 361		i++
 362		linkB := i
 363		for i < len(data) && data[i] != ']' {
 364			i++
 365		}
 366		if i >= len(data) {
 367			return 0
 368		}
 369		linkE := i
 370
 371		// find the reference
 372		if linkB == linkE {
 373			if textHasNl {
 374				var b bytes.Buffer
 375
 376				for j := 1; j < txtE; j++ {
 377					switch {
 378					case data[j] != '\n':
 379						b.WriteByte(data[j])
 380					case data[j-1] != ' ':
 381						b.WriteByte(' ')
 382					}
 383				}
 384
 385				id = b.Bytes()
 386			} else {
 387				id = data[1:txtE]
 388				altContentConsidered = true
 389			}
 390		} else {
 391			id = data[linkB:linkE]
 392		}
 393
 394		// find the reference with matching id
 395		lr, ok := p.getRef(string(id))
 396		if !ok {
 397			return 0
 398
 399		}
 400
 401		// keep link and title from reference
 402		link = lr.link
 403		title = lr.title
 404		if altContentConsidered {
 405			altContent = lr.text
 406		}
 407		i++
 408
 409	// shortcut reference style link or reference or inline footnote
 410	default:
 411		var id []byte
 412
 413		// craft the id
 414		if textHasNl {
 415			var b bytes.Buffer
 416
 417			for j := 1; j < txtE; j++ {
 418				switch {
 419				case data[j] != '\n':
 420					b.WriteByte(data[j])
 421				case data[j-1] != ' ':
 422					b.WriteByte(' ')
 423				}
 424			}
 425
 426			id = b.Bytes()
 427		} else {
 428			if t == linkDeferredFootnote {
 429				id = data[2:txtE] // get rid of the ^
 430			} else {
 431				id = data[1:txtE]
 432			}
 433		}
 434
 435		if t == linkInlineFootnote {
 436			// create a new reference
 437			noteId = len(p.notes) + 1
 438
 439			var fragment []byte
 440			if len(id) > 0 {
 441				if len(id) < 16 {
 442					fragment = make([]byte, len(id))
 443				} else {
 444					fragment = make([]byte, 16)
 445				}
 446				copy(fragment, slugify(id))
 447			} else {
 448				fragment = append([]byte("footnote-"), []byte(strconv.Itoa(noteId))...)
 449			}
 450
 451			ref := &reference{
 452				noteId:   noteId,
 453				hasBlock: false,
 454				link:     fragment,
 455				title:    id,
 456			}
 457
 458			p.notes = append(p.notes, ref)
 459
 460			link = ref.link
 461			title = ref.title
 462		} else {
 463			// find the reference with matching id
 464			lr, ok := p.getRef(string(id))
 465			if !ok {
 466				return 0
 467			}
 468
 469			if t == linkDeferredFootnote {
 470				lr.noteId = len(p.notes) + 1
 471				p.notes = append(p.notes, lr)
 472			}
 473
 474			// keep link and title from reference
 475			link = lr.link
 476			// if inline footnote, title == footnote contents
 477			title = lr.title
 478			noteId = lr.noteId
 479		}
 480
 481		// rewind the whitespace
 482		i = txtE + 1
 483	}
 484
 485	// build content: img alt is escaped, link content is parsed
 486	var content bytes.Buffer
 487	if txtE > 1 {
 488		if t == linkImg {
 489			content.Write(data[1:txtE])
 490		} else {
 491			// links cannot contain other links, so turn off link parsing temporarily
 492			insideLink := p.insideLink
 493			p.insideLink = true
 494			p.inline(&content, data[1:txtE])
 495			p.insideLink = insideLink
 496		}
 497	}
 498
 499	var uLink []byte
 500	if t == linkNormal || t == linkImg {
 501		if len(link) > 0 {
 502			var uLinkBuf bytes.Buffer
 503			unescapeText(&uLinkBuf, link)
 504			uLink = uLinkBuf.Bytes()
 505		}
 506
 507		// links need something to click on and somewhere to go
 508		if len(uLink) == 0 || (t == linkNormal && content.Len() == 0) {
 509			return 0
 510		}
 511	}
 512
 513	// call the relevant rendering function
 514	switch t {
 515	case linkNormal:
 516		if len(altContent) > 0 {
 517			p.r.Link(out, uLink, title, altContent)
 518		} else {
 519			p.r.Link(out, uLink, title, content.Bytes())
 520		}
 521
 522	case linkImg:
 523		outSize := out.Len()
 524		outBytes := out.Bytes()
 525		if outSize > 0 && outBytes[outSize-1] == '!' {
 526			out.Truncate(outSize - 1)
 527		}
 528
 529		p.r.Image(out, uLink, title, content.Bytes())
 530
 531	case linkInlineFootnote:
 532		outSize := out.Len()
 533		outBytes := out.Bytes()
 534		if outSize > 0 && outBytes[outSize-1] == '^' {
 535			out.Truncate(outSize - 1)
 536		}
 537
 538		p.r.FootnoteRef(out, link, noteId)
 539
 540	case linkDeferredFootnote:
 541		p.r.FootnoteRef(out, link, noteId)
 542
 543	default:
 544		return 0
 545	}
 546
 547	return i
 548}
 549
 550func (p *parser) inlineHtmlComment(out *bytes.Buffer, data []byte) int {
 551	if len(data) < 5 {
 552		return 0
 553	}
 554	if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' {
 555		return 0
 556	}
 557	i := 5
 558	// scan for an end-of-comment marker, across lines if necessary
 559	for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') {
 560		i++
 561	}
 562	// no end-of-comment marker
 563	if i >= len(data) {
 564		return 0
 565	}
 566	return i + 1
 567}
 568
 569// '<' when tags or autolinks are allowed
 570func leftAngle(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 571	data = data[offset:]
 572	altype := LINK_TYPE_NOT_AUTOLINK
 573	end := tagLength(data, &altype)
 574	if size := p.inlineHtmlComment(out, data); size > 0 {
 575		end = size
 576	}
 577	if end > 2 {
 578		if altype != LINK_TYPE_NOT_AUTOLINK {
 579			var uLink bytes.Buffer
 580			unescapeText(&uLink, data[1:end+1-2])
 581			if uLink.Len() > 0 {
 582				p.r.AutoLink(out, uLink.Bytes(), altype)
 583			}
 584		} else {
 585			p.r.RawHtmlTag(out, data[:end])
 586		}
 587	}
 588
 589	return end
 590}
 591
 592// '\\' backslash escape
 593var escapeChars = []byte("\\`*_{}[]()#+-.!:|&<>~")
 594
 595func escape(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 596	data = data[offset:]
 597
 598	if len(data) > 1 {
 599		if bytes.IndexByte(escapeChars, data[1]) < 0 {
 600			return 0
 601		}
 602
 603		p.r.NormalText(out, data[1:2])
 604	}
 605
 606	return 2
 607}
 608
 609func unescapeText(ob *bytes.Buffer, src []byte) {
 610	i := 0
 611	for i < len(src) {
 612		org := i
 613		for i < len(src) && src[i] != '\\' {
 614			i++
 615		}
 616
 617		if i > org {
 618			ob.Write(src[org:i])
 619		}
 620
 621		if i+1 >= len(src) {
 622			break
 623		}
 624
 625		ob.WriteByte(src[i+1])
 626		i += 2
 627	}
 628}
 629
 630// '&' escaped when it doesn't belong to an entity
 631// valid entities are assumed to be anything matching &#?[A-Za-z0-9]+;
 632func entity(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 633	data = data[offset:]
 634
 635	end := 1
 636
 637	if end < len(data) && data[end] == '#' {
 638		end++
 639	}
 640
 641	for end < len(data) && isalnum(data[end]) {
 642		end++
 643	}
 644
 645	if end < len(data) && data[end] == ';' {
 646		end++ // real entity
 647	} else {
 648		return 0 // lone '&'
 649	}
 650
 651	p.r.Entity(out, data[:end])
 652
 653	return end
 654}
 655
 656func linkEndsWithEntity(data []byte, linkEnd int) bool {
 657	entityRanges := htmlEntity.FindAllIndex(data[:linkEnd], -1)
 658	if entityRanges != nil && entityRanges[len(entityRanges)-1][1] == linkEnd {
 659		return true
 660	}
 661	return false
 662}
 663
 664func autoLink(p *parser, out *bytes.Buffer, data []byte, offset int) int {
 665	// quick check to rule out most false hits on ':'
 666	if p.insideLink || len(data) < offset+3 || data[offset+1] != '/' || data[offset+2] != '/' {
 667		return 0
 668	}
 669
 670	// Now a more expensive check to see if we're not inside an anchor element
 671	anchorStart := offset
 672	offsetFromAnchor := 0
 673	for anchorStart > 0 && data[anchorStart] != '<' {
 674		anchorStart--
 675		offsetFromAnchor++
 676	}
 677
 678	anchorStr := anchorRe.Find(data[anchorStart:])
 679	if anchorStr != nil {
 680		out.Write(anchorStr[offsetFromAnchor:])
 681		return len(anchorStr) - offsetFromAnchor
 682	}
 683
 684	// scan backward for a word boundary
 685	rewind := 0
 686	for offset-rewind > 0 && rewind <= 7 && isletter(data[offset-rewind-1]) {
 687		rewind++
 688	}
 689	if rewind > 6 { // longest supported protocol is "mailto" which has 6 letters
 690		return 0
 691	}
 692
 693	origData := data
 694	data = data[offset-rewind:]
 695
 696	if !isSafeLink(data) {
 697		return 0
 698	}
 699
 700	linkEnd := 0
 701	for linkEnd < len(data) && !isEndOfLink(data[linkEnd]) {
 702		linkEnd++
 703	}
 704
 705	// Skip punctuation at the end of the link
 706	if (data[linkEnd-1] == '.' || data[linkEnd-1] == ',') && data[linkEnd-2] != '\\' {
 707		linkEnd--
 708	}
 709
 710	// But don't skip semicolon if it's a part of escaped entity:
 711	if data[linkEnd-1] == ';' && data[linkEnd-2] != '\\' && !linkEndsWithEntity(data, linkEnd) {
 712		linkEnd--
 713	}
 714
 715	// See if the link finishes with a punctuation sign that can be closed.
 716	var copen byte
 717	switch data[linkEnd-1] {
 718	case '"':
 719		copen = '"'
 720	case '\'':
 721		copen = '\''
 722	case ')':
 723		copen = '('
 724	case ']':
 725		copen = '['
 726	case '}':
 727		copen = '{'
 728	default:
 729		copen = 0
 730	}
 731
 732	if copen != 0 {
 733		bufEnd := offset - rewind + linkEnd - 2
 734
 735		openDelim := 1
 736
 737		/* Try to close the final punctuation sign in this same line;
 738		 * if we managed to close it outside of the URL, that means that it's
 739		 * not part of the URL. If it closes inside the URL, that means it
 740		 * is part of the URL.
 741		 *
 742		 * Examples:
 743		 *
 744		 *      foo http://www.pokemon.com/Pikachu_(Electric) bar
 745		 *              => http://www.pokemon.com/Pikachu_(Electric)
 746		 *
 747		 *      foo (http://www.pokemon.com/Pikachu_(Electric)) bar
 748		 *              => http://www.pokemon.com/Pikachu_(Electric)
 749		 *
 750		 *      foo http://www.pokemon.com/Pikachu_(Electric)) bar
 751		 *              => http://www.pokemon.com/Pikachu_(Electric))
 752		 *
 753		 *      (foo http://www.pokemon.com/Pikachu_(Electric)) bar
 754		 *              => foo http://www.pokemon.com/Pikachu_(Electric)
 755		 */
 756
 757		for bufEnd >= 0 && origData[bufEnd] != '\n' && openDelim != 0 {
 758			if origData[bufEnd] == data[linkEnd-1] {
 759				openDelim++
 760			}
 761
 762			if origData[bufEnd] == copen {
 763				openDelim--
 764			}
 765
 766			bufEnd--
 767		}
 768
 769		if openDelim == 0 {
 770			linkEnd--
 771		}
 772	}
 773
 774	// we were triggered on the ':', so we need to rewind the output a bit
 775	if out.Len() >= rewind {
 776		out.Truncate(len(out.Bytes()) - rewind)
 777	}
 778
 779	var uLink bytes.Buffer
 780	unescapeText(&uLink, data[:linkEnd])
 781
 782	if uLink.Len() > 0 {
 783		p.r.AutoLink(out, uLink.Bytes(), LINK_TYPE_NORMAL)
 784	}
 785
 786	return linkEnd - rewind
 787}
 788
 789func isEndOfLink(char byte) bool {
 790	return isspace(char) || char == '<'
 791}
 792
 793var validUris = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")}
 794var validPaths = [][]byte{[]byte("/"), []byte("./"), []byte("../")}
 795
 796func isSafeLink(link []byte) bool {
 797	for _, path := range validPaths {
 798		if len(link) >= len(path) && bytes.Equal(link[:len(path)], path) {
 799			if len(link) == len(path) {
 800				return true
 801			} else if isalnum(link[len(path)]) {
 802				return true
 803			}
 804		}
 805	}
 806
 807	for _, prefix := range validUris {
 808		// TODO: handle unicode here
 809		// case-insensitive prefix test
 810		if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) {
 811			return true
 812		}
 813	}
 814
 815	return false
 816}
 817
 818// return the length of the given tag, or 0 is it's not valid
 819func tagLength(data []byte, autolink *int) int {
 820	var i, j int
 821
 822	// a valid tag can't be shorter than 3 chars
 823	if len(data) < 3 {
 824		return 0
 825	}
 826
 827	// begins with a '<' optionally followed by '/', followed by letter or number
 828	if data[0] != '<' {
 829		return 0
 830	}
 831	if data[1] == '/' {
 832		i = 2
 833	} else {
 834		i = 1
 835	}
 836
 837	if !isalnum(data[i]) {
 838		return 0
 839	}
 840
 841	// scheme test
 842	*autolink = LINK_TYPE_NOT_AUTOLINK
 843
 844	// try to find the beginning of an URI
 845	for i < len(data) && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-') {
 846		i++
 847	}
 848
 849	if i > 1 && i < len(data) && data[i] == '@' {
 850		if j = isMailtoAutoLink(data[i:]); j != 0 {
 851			*autolink = LINK_TYPE_EMAIL
 852			return i + j
 853		}
 854	}
 855
 856	if i > 2 && i < len(data) && data[i] == ':' {
 857		*autolink = LINK_TYPE_NORMAL
 858		i++
 859	}
 860
 861	// complete autolink test: no whitespace or ' or "
 862	switch {
 863	case i >= len(data):
 864		*autolink = LINK_TYPE_NOT_AUTOLINK
 865	case *autolink != 0:
 866		j = i
 867
 868		for i < len(data) {
 869			if data[i] == '\\' {
 870				i += 2
 871			} else if data[i] == '>' || data[i] == '\'' || data[i] == '"' || isspace(data[i]) {
 872				break
 873			} else {
 874				i++
 875			}
 876
 877		}
 878
 879		if i >= len(data) {
 880			return 0
 881		}
 882		if i > j && data[i] == '>' {
 883			return i + 1
 884		}
 885
 886		// one of the forbidden chars has been found
 887		*autolink = LINK_TYPE_NOT_AUTOLINK
 888	}
 889
 890	// look for something looking like a tag end
 891	for i < len(data) && data[i] != '>' {
 892		i++
 893	}
 894	if i >= len(data) {
 895		return 0
 896	}
 897	return i + 1
 898}
 899
 900// look for the address part of a mail autolink and '>'
 901// this is less strict than the original markdown e-mail address matching
 902func isMailtoAutoLink(data []byte) int {
 903	nb := 0
 904
 905	// address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@'
 906	for i := 0; i < len(data); i++ {
 907		if isalnum(data[i]) {
 908			continue
 909		}
 910
 911		switch data[i] {
 912		case '@':
 913			nb++
 914
 915		case '-', '.', '_':
 916			break
 917
 918		case '>':
 919			if nb == 1 {
 920				return i + 1
 921			} else {
 922				return 0
 923			}
 924		default:
 925			return 0
 926		}
 927	}
 928
 929	return 0
 930}
 931
 932// look for the next emph char, skipping other constructs
 933func helperFindEmphChar(data []byte, c byte) int {
 934	i := 1
 935
 936	for i < len(data) {
 937		for i < len(data) && data[i] != c && data[i] != '`' && data[i] != '[' {
 938			i++
 939		}
 940		if i >= len(data) {
 941			return 0
 942		}
 943		if data[i] == c {
 944			return i
 945		}
 946
 947		// do not count escaped chars
 948		if i != 0 && data[i-1] == '\\' {
 949			i++
 950			continue
 951		}
 952
 953		if data[i] == '`' {
 954			// skip a code span
 955			tmpI := 0
 956			i++
 957			for i < len(data) && data[i] != '`' {
 958				if tmpI == 0 && data[i] == c {
 959					tmpI = i
 960				}
 961				i++
 962			}
 963			if i >= len(data) {
 964				return tmpI
 965			}
 966			i++
 967		} else if data[i] == '[' {
 968			// skip a link
 969			tmpI := 0
 970			i++
 971			for i < len(data) && data[i] != ']' {
 972				if tmpI == 0 && data[i] == c {
 973					tmpI = i
 974				}
 975				i++
 976			}
 977			i++
 978			for i < len(data) && (data[i] == ' ' || data[i] == '\n') {
 979				i++
 980			}
 981			if i >= len(data) {
 982				return tmpI
 983			}
 984			if data[i] != '[' && data[i] != '(' { // not a link
 985				if tmpI > 0 {
 986					return tmpI
 987				} else {
 988					continue
 989				}
 990			}
 991			cc := data[i]
 992			i++
 993			for i < len(data) && data[i] != cc {
 994				if tmpI == 0 && data[i] == c {
 995					return i
 996				}
 997				i++
 998			}
 999			if i >= len(data) {
1000				return tmpI
1001			}
1002			i++
1003		}
1004	}
1005	return 0
1006}
1007
1008func helperEmphasis(p *parser, out *bytes.Buffer, data []byte, c byte) int {
1009	i := 0
1010
1011	// skip one symbol if coming from emph3
1012	if len(data) > 1 && data[0] == c && data[1] == c {
1013		i = 1
1014	}
1015
1016	for i < len(data) {
1017		length := helperFindEmphChar(data[i:], c)
1018		if length == 0 {
1019			return 0
1020		}
1021		i += length
1022		if i >= len(data) {
1023			return 0
1024		}
1025
1026		if i+1 < len(data) && data[i+1] == c {
1027			i++
1028			continue
1029		}
1030
1031		if data[i] == c && !isspace(data[i-1]) {
1032
1033			if p.flags&EXTENSION_NO_INTRA_EMPHASIS != 0 {
1034				if !(i+1 == len(data) || isspace(data[i+1]) || ispunct(data[i+1])) {
1035					continue
1036				}
1037			}
1038
1039			var work bytes.Buffer
1040			p.inline(&work, data[:i])
1041			p.r.Emphasis(out, work.Bytes())
1042			return i + 1
1043		}
1044	}
1045
1046	return 0
1047}
1048
1049func helperDoubleEmphasis(p *parser, out *bytes.Buffer, data []byte, c byte) int {
1050	i := 0
1051
1052	for i < len(data) {
1053		length := helperFindEmphChar(data[i:], c)
1054		if length == 0 {
1055			return 0
1056		}
1057		i += length
1058
1059		if i+1 < len(data) && data[i] == c && data[i+1] == c && i > 0 && !isspace(data[i-1]) {
1060			var work bytes.Buffer
1061			p.inline(&work, data[:i])
1062
1063			if work.Len() > 0 {
1064				// pick the right renderer
1065				if c == '~' {
1066					p.r.StrikeThrough(out, work.Bytes())
1067				} else {
1068					p.r.DoubleEmphasis(out, work.Bytes())
1069				}
1070			}
1071			return i + 2
1072		}
1073		i++
1074	}
1075	return 0
1076}
1077
1078func helperTripleEmphasis(p *parser, out *bytes.Buffer, data []byte, offset int, c byte) int {
1079	i := 0
1080	origData := data
1081	data = data[offset:]
1082
1083	for i < len(data) {
1084		length := helperFindEmphChar(data[i:], c)
1085		if length == 0 {
1086			return 0
1087		}
1088		i += length
1089
1090		// skip whitespace preceded symbols
1091		if data[i] != c || isspace(data[i-1]) {
1092			continue
1093		}
1094
1095		switch {
1096		case i+2 < len(data) && data[i+1] == c && data[i+2] == c:
1097			// triple symbol found
1098			var work bytes.Buffer
1099
1100			p.inline(&work, data[:i])
1101			if work.Len() > 0 {
1102				p.r.TripleEmphasis(out, work.Bytes())
1103			}
1104			return i + 3
1105		case (i+1 < len(data) && data[i+1] == c):
1106			// double symbol found, hand over to emph1
1107			length = helperEmphasis(p, out, origData[offset-2:], c)
1108			if length == 0 {
1109				return 0
1110			} else {
1111				return length - 2
1112			}
1113		default:
1114			// single symbol found, hand over to emph2
1115			length = helperDoubleEmphasis(p, out, origData[offset-1:], c)
1116			if length == 0 {
1117				return 0
1118			} else {
1119				return length - 1
1120			}
1121		}
1122	}
1123	return 0
1124}