all repos — grayfriday @ f3ab1849e6b17a1564b9088d01fee399a83cddd7

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