1
0
html/escape.go

77 lines
1.3 KiB
Go
Raw Normal View History

2025-10-05 20:06:39 +02:00
package html
import (
"bytes"
2025-11-01 21:23:56 +01:00
"code.squareroundforest.org/arpio/textedit"
2025-10-05 21:25:53 +02:00
"io"
2025-10-05 20:06:39 +02:00
)
2025-10-05 21:25:53 +02:00
const unicodeNBSP = 0xa0
2025-10-05 20:06:39 +02:00
2025-11-01 21:23:56 +01:00
func escapeEdit(nonbreakSpaces bool) func(rune, []rune) ([]rune, []rune) {
return func(r rune, state []rune) ([]rune, []rune) {
var rr []rune
switch r {
case ' ':
if !nonbreakSpaces {
return []rune{r}, nil
}
2025-10-05 20:06:39 +02:00
2025-11-01 21:23:56 +01:00
if len(state) == 0 {
return nil, []rune{' '}
}
2025-10-05 20:06:39 +02:00
2025-11-01 21:23:56 +01:00
return []rune(" "), []rune(" ")
2025-10-05 20:06:39 +02:00
case '<':
2025-11-01 21:23:56 +01:00
rr = []rune("&lt;")
2025-10-05 20:06:39 +02:00
case '>':
2025-11-01 21:23:56 +01:00
rr = []rune("&gt;")
2025-10-05 20:06:39 +02:00
case '&':
2025-11-01 21:23:56 +01:00
rr = []rune("&amp;")
2025-10-05 20:06:39 +02:00
case unicodeNBSP:
2025-11-01 21:23:56 +01:00
rr = []rune("&nbsp;")
2025-10-05 20:06:39 +02:00
default:
2025-11-01 21:23:56 +01:00
rr = []rune{r}
2025-10-05 20:06:39 +02:00
}
2025-11-01 21:23:56 +01:00
return append(state, rr...), nil
2025-10-05 20:06:39 +02:00
}
2025-11-01 21:23:56 +01:00
}
2025-10-05 20:06:39 +02:00
2025-11-01 21:23:56 +01:00
func escapeReleaseState(state []rune) []rune {
return state
}
2025-10-05 20:06:39 +02:00
2025-11-01 21:23:56 +01:00
func newEscapeWriter(out io.Writer, nonbreakSpaces bool) *textedit.Writer {
return textedit.New(
out,
textedit.Func(
escapeEdit(nonbreakSpaces),
escapeReleaseState,
),
)
2025-10-05 20:06:39 +02:00
}
2025-10-06 23:49:11 +02:00
2025-10-29 21:04:07 +01:00
func escape(s string, nonbreakSpaces bool) string {
2025-10-06 23:49:11 +02:00
var b bytes.Buffer
2025-10-29 21:04:07 +01:00
w := newEscapeWriter(&b, nonbreakSpaces)
2025-10-06 23:49:11 +02:00
w.Write([]byte(s))
w.Flush()
return b.String()
}
func escapeAttribute(value string) string {
2025-11-01 21:23:56 +01:00
var b bytes.Buffer
w := textedit.New(
&b,
textedit.Replace(
"&", "&amp;",
"\"", "&quot;",
),
)
w.Write([]byte(value))
2025-11-03 03:02:50 +01:00
w.Flush()
2025-11-01 21:23:56 +01:00
return b.String()
2025-10-06 23:49:11 +02:00
}