2016-09-10 13:33:37 +02:00
|
|
|
package blackfriday
|
|
|
|
|
|
|
|
import (
|
|
|
|
"html"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2016-10-08 16:58:30 +02:00
|
|
|
var htmlEscaper = [256][]byte{
|
|
|
|
'&': []byte("&"),
|
|
|
|
'<': []byte("<"),
|
|
|
|
'>': []byte(">"),
|
|
|
|
'"': []byte("""),
|
2016-09-10 13:33:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func escapeHTML(w io.Writer, s []byte) {
|
2018-09-06 11:05:43 +02:00
|
|
|
escapeEntities(w, s, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
func escapeAllHTML(w io.Writer, s []byte) {
|
|
|
|
escapeEntities(w, s, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
func escapeEntities(w io.Writer, s []byte, escapeValidEntities bool) {
|
2016-09-10 13:33:37 +02:00
|
|
|
var start, end int
|
|
|
|
for end < len(s) {
|
2016-10-08 16:58:30 +02:00
|
|
|
escSeq := htmlEscaper[s[end]]
|
|
|
|
if escSeq != nil {
|
2018-07-26 05:48:47 +02:00
|
|
|
isEntity, entityEnd := nodeIsEntity(s, end)
|
2018-09-06 11:05:43 +02:00
|
|
|
if isEntity && !escapeValidEntities {
|
2018-07-26 05:48:47 +02:00
|
|
|
w.Write(s[start : entityEnd+1])
|
|
|
|
start = entityEnd + 1
|
|
|
|
} else {
|
|
|
|
w.Write(s[start:end])
|
|
|
|
w.Write(escSeq)
|
|
|
|
start = end + 1
|
|
|
|
}
|
2016-09-10 13:33:37 +02:00
|
|
|
}
|
|
|
|
end++
|
|
|
|
}
|
|
|
|
if start < len(s) && end <= len(s) {
|
|
|
|
w.Write(s[start:end])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-26 05:48:47 +02:00
|
|
|
func nodeIsEntity(s []byte, end int) (isEntity bool, endEntityPos int) {
|
|
|
|
isEntity = false
|
|
|
|
endEntityPos = end + 1
|
|
|
|
|
|
|
|
if s[end] == '&' {
|
|
|
|
for endEntityPos < len(s) {
|
|
|
|
if s[endEntityPos] == ';' {
|
2018-09-06 11:05:43 +02:00
|
|
|
if entities[string(s[end:endEntityPos+1])] {
|
|
|
|
isEntity = true
|
|
|
|
break
|
|
|
|
}
|
2018-07-26 05:48:47 +02:00
|
|
|
}
|
|
|
|
if !isalnum(s[endEntityPos]) && s[endEntityPos] != '&' && s[endEntityPos] != '#' {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
endEntityPos++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return isEntity, endEntityPos
|
|
|
|
}
|
|
|
|
|
2016-09-10 13:33:37 +02:00
|
|
|
func escLink(w io.Writer, text []byte) {
|
|
|
|
unesc := html.UnescapeString(string(text))
|
|
|
|
escapeHTML(w, []byte(unesc))
|
|
|
|
}
|