all repos — grayfriday @ 6a7bd0d6e94723d834195ff891099d70b5bb23cf

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