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