Properly escape "<", ">" and "&"

This commit is contained in:
Konstantin Nazarov 2021-07-25 15:57:32 +00:00
parent 5fadd96dfc
commit ebd74283ee
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
2 changed files with 48 additions and 3 deletions

View file

@ -65,6 +65,10 @@ function lstrip(str) {
return str; return str;
} }
function escape_special() {
}
function join_lines(first, second, sep) { function join_lines(first, second, sep) {
if (sep == "") if (sep == "")
sep = " "; sep = " ";
@ -152,13 +156,28 @@ function parse_list(str, buf, result, i, ind, line, lines, indent, is_bullet)
return result; return result;
} }
function is_token(str, i, tok) {
return substr(str, i, length(tok)) == tok;
}
function escape_char(char) {
if (char == "<")
return "&lt;";
if (char == ">")
return "&gt;";
if (char == "&")
return "&amp;";
return char;
}
function parse_line(str, result, end, i) { function parse_line(str, result, end, i) {
#print "block '" str "'" #print "block '" str "'"
result = "" result = ""
for (i=1; i<=length(str); i++) { for (i=1; i<=length(str); i++) {
if (substr(str, i, 2) == "**") { if (is_token(str, i, "**")){
end = find(str, "**", i+2); end = find(str, "**", i+2);
if (end != 0) { if (end != 0) {
@ -170,7 +189,7 @@ function parse_line(str, result, end, i) {
i++; i++;
} }
} }
else if (substr(str, i, 3) == "```") { else if (is_token(str, i, "```")) {
end = find(str, "```", i+3); end = find(str, "```", i+3);
if (end != 0) { if (end != 0) {
result = result "<code>" substr(str, i+3, end - i - 3) "</code>"; result = result "<code>" substr(str, i+3, end - i - 3) "</code>";
@ -191,7 +210,7 @@ function parse_line(str, result, end, i) {
result = result " "; result = result " ";
} }
else { else {
result = result substr(str, i, 1); result = result escape_char(substr(str, i, 1));
} }
} }
} }

26
test.sh
View file

@ -265,6 +265,20 @@ check <<-"EOF"
</blockquote> </blockquote>
EOF EOF
check <<-"EOF"
> foo
>
>> bar
>> baz
---
<blockquote>
<p>foo</p>
<blockquote>
<p>bar baz</p>
</blockquote>
</blockquote>
EOF
check <<-"EOF" check <<-"EOF"
> code blocks > code blocks
> in blockquotes > in blockquotes
@ -275,5 +289,17 @@ in blockquotes</code></pre>
</blockquote> </blockquote>
EOF EOF
check <<-"EOF"
foo&bar
1 < 2
2 > 1
---
<p>foo&amp;bar</p>
<p>1 &lt; 2</p>
<p>2 &gt; 1</p>
EOF
echo echo
echo "All tests passed" echo "All tests passed"