all repos — grayfriday @ d4c83fb4daf75cf9c60ab1267955617919f61558

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