all repos — grayfriday @ 58c4ddd4312ed3590e02b837c785cef03554e530

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