all repos — grayfriday @ 7846a310eae14eb4fbb0cc35a00c2b228653719e

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