1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
// Copyright 2015 The Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package markdown
import (
"strings"
"gitlab.com/golang-commonmark/linkify"
)
func isLinkOpen(s string) bool { return isLetter(s[1]) }
func isLinkClose(s string) bool { return s[1] == '/' }
func ruleLinkify(s *StateCore) {
blockTokens := s.Tokens
if !s.Md.Linkify {
return
}
for _, tok := range blockTokens {
if tok, ok := tok.(*Inline); ok {
tokens := tok.Children
htmlLinkLevel := 0
for i := len(tokens) - 1; i >= 0; i-- {
currentTok := tokens[i]
if _, ok := currentTok.(*LinkClose); ok {
i--
for tokens[i].Level() != currentTok.Level() {
if _, ok := tokens[i].(*LinkOpen); ok {
break
}
i--
}
continue
}
if currentTok, ok := currentTok.(*HTMLInline); ok {
if isLinkOpen(currentTok.Content) && htmlLinkLevel > 0 {
htmlLinkLevel--
}
if isLinkClose(currentTok.Content) {
htmlLinkLevel++
}
}
if htmlLinkLevel > 0 {
continue
}
if currentTok, ok := currentTok.(*Text); ok {
text := currentTok.Content
links := linkify.Links(text)
if len(links) == 0 {
continue
}
var nodes []Token
level := currentTok.Lvl
lastPos := 0
for _, ln := range links {
urlText := text[ln.Start:ln.End]
url := urlText
if ln.Scheme == "" {
url = "http://" + url
} else if ln.Scheme == "mailto:" && !strings.HasPrefix(url, "mailto:") {
url = "mailto:" + url
}
url = normalizeLink(url)
if !validateLink(url) {
continue
}
if ln.Scheme == "" {
urlText = strings.TrimPrefix(normalizeLinkText("http://"+urlText), "http://")
} else if ln.Scheme == "mailto:" && !strings.HasPrefix(urlText, "mailto:") {
urlText = strings.TrimPrefix(normalizeLinkText("mailto:"+urlText), "mailto:")
} else {
urlText = normalizeLinkText(urlText)
}
pos := ln.Start
if pos > lastPos {
tok := Text{
Content: text[lastPos:pos],
Lvl: level,
}
nodes = append(nodes, &tok)
}
nodes = append(nodes, &LinkOpen{
Href: url,
Lvl: level,
})
nodes = append(nodes, &Text{
Content: urlText,
Lvl: level + 1,
})
nodes = append(nodes, &LinkClose{
Lvl: level,
})
lastPos = ln.End
}
if lastPos < len(text) {
tok := Text{
Content: text[lastPos:],
Lvl: level,
}
nodes = append(nodes, &tok)
}
children := make([]Token, len(tokens)+len(nodes)-1)
copy(children, tokens[:i])
copy(children[i:], nodes)
copy(children[i+len(nodes):], tokens[i+1:])
tok.Children = children
tokens = children
}
}
}
}
}
|