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 return entityRanges != nil && entityRanges[len(entityRanges)-1][1] == linkEnd
665}
666
667func autoLink(p *parser, out *bytes.Buffer, data []byte, offset int) int {
668 // quick check to rule out most false hits on ':'
669 if p.insideLink || len(data) < offset+3 || data[offset+1] != '/' || data[offset+2] != '/' {
670 return 0
671 }
672
673 // Now a more expensive check to see if we're not inside an anchor element
674 anchorStart := offset
675 offsetFromAnchor := 0
676 for anchorStart > 0 && data[anchorStart] != '<' {
677 anchorStart--
678 offsetFromAnchor++
679 }
680
681 anchorStr := anchorRe.Find(data[anchorStart:])
682 if anchorStr != nil {
683 out.Write(anchorStr[offsetFromAnchor:])
684 return len(anchorStr) - offsetFromAnchor
685 }
686
687 // scan backward for a word boundary
688 rewind := 0
689 for offset-rewind > 0 && rewind <= 7 && isletter(data[offset-rewind-1]) {
690 rewind++
691 }
692 if rewind > 6 { // longest supported protocol is "mailto" which has 6 letters
693 return 0
694 }
695
696 origData := data
697 data = data[offset-rewind:]
698
699 if !isSafeLink(data) {
700 return 0
701 }
702
703 linkEnd := 0
704 for linkEnd < len(data) && !isEndOfLink(data[linkEnd]) {
705 linkEnd++
706 }
707
708 // Skip punctuation at the end of the link
709 if (data[linkEnd-1] == '.' || data[linkEnd-1] == ',') && data[linkEnd-2] != '\\' {
710 linkEnd--
711 }
712
713 // But don't skip semicolon if it's a part of escaped entity:
714 if data[linkEnd-1] == ';' && data[linkEnd-2] != '\\' && !linkEndsWithEntity(data, linkEnd) {
715 linkEnd--
716 }
717
718 // See if the link finishes with a punctuation sign that can be closed.
719 var copen byte
720 switch data[linkEnd-1] {
721 case '"':
722 copen = '"'
723 case '\'':
724 copen = '\''
725 case ')':
726 copen = '('
727 case ']':
728 copen = '['
729 case '}':
730 copen = '{'
731 default:
732 copen = 0
733 }
734
735 if copen != 0 {
736 bufEnd := offset - rewind + linkEnd - 2
737
738 openDelim := 1
739
740 /* Try to close the final punctuation sign in this same line;
741 * if we managed to close it outside of the URL, that means that it's
742 * not part of the URL. If it closes inside the URL, that means it
743 * is part of the URL.
744 *
745 * Examples:
746 *
747 * foo http://www.pokemon.com/Pikachu_(Electric) bar
748 * => http://www.pokemon.com/Pikachu_(Electric)
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 * => foo http://www.pokemon.com/Pikachu_(Electric)
758 */
759
760 for bufEnd >= 0 && origData[bufEnd] != '\n' && openDelim != 0 {
761 if origData[bufEnd] == data[linkEnd-1] {
762 openDelim++
763 }
764
765 if origData[bufEnd] == copen {
766 openDelim--
767 }
768
769 bufEnd--
770 }
771
772 if openDelim == 0 {
773 linkEnd--
774 }
775 }
776
777 // we were triggered on the ':', so we need to rewind the output a bit
778 if out.Len() >= rewind {
779 out.Truncate(len(out.Bytes()) - rewind)
780 }
781
782 var uLink bytes.Buffer
783 unescapeText(&uLink, data[:linkEnd])
784
785 if uLink.Len() > 0 {
786 p.r.AutoLink(out, uLink.Bytes(), LINK_TYPE_NORMAL)
787 }
788
789 return linkEnd - rewind
790}
791
792func isEndOfLink(char byte) bool {
793 return isspace(char) || char == '<'
794}
795
796var validUris = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")}
797var validPaths = [][]byte{[]byte("/"), []byte("./"), []byte("../")}
798
799func isSafeLink(link []byte) bool {
800 for _, path := range validPaths {
801 if len(link) >= len(path) && bytes.Equal(link[:len(path)], path) {
802 if len(link) == len(path) {
803 return true
804 } else if isalnum(link[len(path)]) {
805 return true
806 }
807 }
808 }
809
810 for _, prefix := range validUris {
811 // TODO: handle unicode here
812 // case-insensitive prefix test
813 if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) {
814 return true
815 }
816 }
817
818 return false
819}
820
821// return the length of the given tag, or 0 is it's not valid
822func tagLength(data []byte, autolink *int) int {
823 var i, j int
824
825 // a valid tag can't be shorter than 3 chars
826 if len(data) < 3 {
827 return 0
828 }
829
830 // begins with a '<' optionally followed by '/', followed by letter or number
831 if data[0] != '<' {
832 return 0
833 }
834 if data[1] == '/' {
835 i = 2
836 } else {
837 i = 1
838 }
839
840 if !isalnum(data[i]) {
841 return 0
842 }
843
844 // scheme test
845 *autolink = LINK_TYPE_NOT_AUTOLINK
846
847 // try to find the beginning of an URI
848 for i < len(data) && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-') {
849 i++
850 }
851
852 if i > 1 && i < len(data) && data[i] == '@' {
853 if j = isMailtoAutoLink(data[i:]); j != 0 {
854 *autolink = LINK_TYPE_EMAIL
855 return i + j
856 }
857 }
858
859 if i > 2 && i < len(data) && data[i] == ':' {
860 *autolink = LINK_TYPE_NORMAL
861 i++
862 }
863
864 // complete autolink test: no whitespace or ' or "
865 switch {
866 case i >= len(data):
867 *autolink = LINK_TYPE_NOT_AUTOLINK
868 case *autolink != 0:
869 j = i
870
871 for i < len(data) {
872 if data[i] == '\\' {
873 i += 2
874 } else if data[i] == '>' || data[i] == '\'' || data[i] == '"' || isspace(data[i]) {
875 break
876 } else {
877 i++
878 }
879
880 }
881
882 if i >= len(data) {
883 return 0
884 }
885 if i > j && data[i] == '>' {
886 return i + 1
887 }
888
889 // one of the forbidden chars has been found
890 *autolink = LINK_TYPE_NOT_AUTOLINK
891 }
892
893 // look for something looking like a tag end
894 for i < len(data) && data[i] != '>' {
895 i++
896 }
897 if i >= len(data) {
898 return 0
899 }
900 return i + 1
901}
902
903// look for the address part of a mail autolink and '>'
904// this is less strict than the original markdown e-mail address matching
905func isMailtoAutoLink(data []byte) int {
906 nb := 0
907
908 // address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@'
909 for i := 0; i < len(data); i++ {
910 if isalnum(data[i]) {
911 continue
912 }
913
914 switch data[i] {
915 case '@':
916 nb++
917
918 case '-', '.', '_':
919 break
920
921 case '>':
922 if nb == 1 {
923 return i + 1
924 } else {
925 return 0
926 }
927 default:
928 return 0
929 }
930 }
931
932 return 0
933}
934
935// look for the next emph char, skipping other constructs
936func helperFindEmphChar(data []byte, c byte) int {
937 i := 0
938
939 for i < len(data) {
940 for i < len(data) && data[i] != c && data[i] != '`' && data[i] != '[' {
941 i++
942 }
943 if i >= len(data) {
944 return 0
945 }
946 // do not count escaped chars
947 if i != 0 && data[i-1] == '\\' {
948 i++
949 continue
950 }
951 if data[i] == c {
952 return i
953 }
954
955 if data[i] == '`' {
956 // skip a code span
957 tmpI := 0
958 i++
959 for i < len(data) && data[i] != '`' {
960 if tmpI == 0 && data[i] == c {
961 tmpI = i
962 }
963 i++
964 }
965 if i >= len(data) {
966 return tmpI
967 }
968 i++
969 } else if data[i] == '[' {
970 // skip a link
971 tmpI := 0
972 i++
973 for i < len(data) && data[i] != ']' {
974 if tmpI == 0 && data[i] == c {
975 tmpI = i
976 }
977 i++
978 }
979 i++
980 for i < len(data) && (data[i] == ' ' || data[i] == '\n') {
981 i++
982 }
983 if i >= len(data) {
984 return tmpI
985 }
986 if data[i] != '[' && data[i] != '(' { // not a link
987 if tmpI > 0 {
988 return tmpI
989 } else {
990 continue
991 }
992 }
993 cc := data[i]
994 i++
995 for i < len(data) && data[i] != cc {
996 if tmpI == 0 && data[i] == c {
997 return i
998 }
999 i++
1000 }
1001 if i >= len(data) {
1002 return tmpI
1003 }
1004 i++
1005 }
1006 }
1007 return 0
1008}
1009
1010func helperEmphasis(p *parser, out *bytes.Buffer, data []byte, c byte) int {
1011 i := 0
1012
1013 // skip one symbol if coming from emph3
1014 if len(data) > 1 && data[0] == c && data[1] == c {
1015 i = 1
1016 }
1017
1018 for i < len(data) {
1019 length := helperFindEmphChar(data[i:], c)
1020 if length == 0 {
1021 return 0
1022 }
1023 i += length
1024 if i >= len(data) {
1025 return 0
1026 }
1027
1028 if i+1 < len(data) && data[i+1] == c {
1029 i++
1030 continue
1031 }
1032
1033 if data[i] == c && !isspace(data[i-1]) {
1034
1035 if p.flags&EXTENSION_NO_INTRA_EMPHASIS != 0 {
1036 if !(i+1 == len(data) || isspace(data[i+1]) || ispunct(data[i+1])) {
1037 continue
1038 }
1039 }
1040
1041 var work bytes.Buffer
1042 p.inline(&work, data[:i])
1043 p.r.Emphasis(out, work.Bytes())
1044 return i + 1
1045 }
1046 }
1047
1048 return 0
1049}
1050
1051func helperDoubleEmphasis(p *parser, out *bytes.Buffer, data []byte, c byte) int {
1052 i := 0
1053
1054 for i < len(data) {
1055 length := helperFindEmphChar(data[i:], c)
1056 if length == 0 {
1057 return 0
1058 }
1059 i += length
1060
1061 if i+1 < len(data) && data[i] == c && data[i+1] == c && i > 0 && !isspace(data[i-1]) {
1062 var work bytes.Buffer
1063 p.inline(&work, data[:i])
1064
1065 if work.Len() > 0 {
1066 // pick the right renderer
1067 if c == '~' {
1068 p.r.StrikeThrough(out, work.Bytes())
1069 } else {
1070 p.r.DoubleEmphasis(out, work.Bytes())
1071 }
1072 }
1073 return i + 2
1074 }
1075 i++
1076 }
1077 return 0
1078}
1079
1080func helperTripleEmphasis(p *parser, out *bytes.Buffer, data []byte, offset int, c byte) int {
1081 i := 0
1082 origData := data
1083 data = data[offset:]
1084
1085 for i < len(data) {
1086 length := helperFindEmphChar(data[i:], c)
1087 if length == 0 {
1088 return 0
1089 }
1090 i += length
1091
1092 // skip whitespace preceded symbols
1093 if data[i] != c || isspace(data[i-1]) {
1094 continue
1095 }
1096
1097 switch {
1098 case i+2 < len(data) && data[i+1] == c && data[i+2] == c:
1099 // triple symbol found
1100 var work bytes.Buffer
1101
1102 p.inline(&work, data[:i])
1103 if work.Len() > 0 {
1104 p.r.TripleEmphasis(out, work.Bytes())
1105 }
1106 return i + 3
1107 case (i+1 < len(data) && data[i+1] == c):
1108 // double symbol found, hand over to emph1
1109 length = helperEmphasis(p, out, origData[offset-2:], c)
1110 if length == 0 {
1111 return 0
1112 } else {
1113 return length - 2
1114 }
1115 default:
1116 // single symbol found, hand over to emph2
1117 length = helperDoubleEmphasis(p, out, origData[offset-1:], c)
1118 if length == 0 {
1119 return 0
1120 } else {
1121 return length - 1
1122 }
1123 }
1124 }
1125 return 0
1126}