From 43428e759d9fbc5a319c2b929bfb4469938cc386 Mon Sep 17 00:00:00 2001 From: clsr Date: Thu, 23 Dec 2021 01:54:47 +0000 Subject: Add EscapeAll and escape all spaces in links --- simpletext.go | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) (limited to 'simpletext.go') diff --git a/simpletext.go b/simpletext.go index 4d86d6d..00d82ec 100644 --- a/simpletext.go +++ b/simpletext.go @@ -70,7 +70,9 @@ func CollapseWhitespace(raw string) string { var escapeRe = regexp.MustCompile(`[\t\n\f\r\\\x00]|^ | $| `) -// Escape escapes whitespace, backslash and and U+0000 within s. +// Escape escapes whitespace, backslash and U+0000 within s. +// +// Only leading, trailing or multiple consecutive spaces are escaped. func Escape(s string) string { return escapeRe.ReplaceAllStringFunc(s, func(match string) string { switch match { @@ -115,6 +117,34 @@ func EscapeSpace(s string) string { }) } +var escapeAllRe = regexp.MustCompile(`[\t\n\f\r\\\x00 ]`) + +// EscapeAll escapes all whitespace, backslash and and U+0000 within s. +// +// Unlike Escape, all spaces are escaped, not just ones that would be collapsed +// into one. +func EscapeAll(s string) string { + return escapeAllRe.ReplaceAllStringFunc(s, func(match string) string { + switch match { + case "\t": + return `\t` + case "\n": + return `\n` + case "\f": + return `\f` + case "\r": + return `\r` + case "\\": + return `\\` + case "\x00": + return `\x00` + case " ": + return `\ ` + } + return match // this shouldn't happen + }) +} + var escapeNonspaceRe = regexp.MustCompile(`[\f\r\\\x00]`) // EscapeNonspace works like Escape, except it does not escape spaces, tabs and -- cgit