Add support for space-indented code blocks

This commit is contained in:
Konstantin Nazarov 2021-07-10 22:34:39 +00:00
parent fe2635e6bf
commit e15d8a56ef
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
2 changed files with 61 additions and 34 deletions

View file

@ -4,7 +4,7 @@ BEGIN {
} }
function parse_header(str) { function parse_header(str) {
match($0, /#+/); match(str, /#+/);
hnum = RLENGTH; hnum = RLENGTH;
content = parse_line(substr(str, hnum + 1, length(str) - hnum )); content = parse_line(substr(str, hnum + 1, length(str) - hnum ));
@ -225,10 +225,35 @@ function parse_blockquote(str, i, lines, line, buf, result) {
return result; return result;
} }
function parse_code(str, i, lines, result) {
if (match(str, /^```.*```$/)) {
gsub(/^```/, "", str);
gsub(/\n```$/, "", str);
return "<pre><code>" str "</code></pre>";
}
if (match(str, /^ /)) {
result = "";
split(str, lines, "\n");
for (i in lines) {
line = lines[i];
gsub(/^ /, "", line);
result = result "\n" line;
}
gsub(/^\n/, "", result);
return "<pre><code>" result "</code></pre>";
}
return "";
}
function parse_block(str) { function parse_block(str) {
if (str == "") if (str == "")
return ""; return "";
if (match(str, /^```\n.*```$/) || match(str, /^ /)) {
return parse_code(str);
}
if (substr(str, 1, 1) == "#") { if (substr(str, 1, 1) == "#") {
return parse_header(str); return parse_header(str);
} }
@ -243,48 +268,40 @@ function parse_block(str) {
} }
} }
function parse_body(str) { function line_continues(body, line) {
print(parse_block(str)); if (match(body, /^ /) && match(line, /^ /))
} return 1;
/^#/ { if (match(body, /^```\n/) && !match(body, /\n```$/))
if (body != "") { return 1;
parse_body(body);
}
parse_body($0);
body = "";
next;
}
/^$/ { if (match(body, /^#* /))
if (body == "") return 0;
next;
if (startswith(body, "```") == 1) { if (line != "")
body = body "\n"; return 1;
next;
}
parse_body(body); return 0;
body = "";
next;
}
/```/ {
if (startswith(body, "```") == 1) {
print "<pre><code>" substr(body, 4, length(body)-3) "</code></pre>";
body = "";
next;
}
} }
// { // {
body = join_lines(body, $0, "\n") if (line_continues(body, $0)) {
if (body != "")
body = body "\n" $0;
else
body = $0;
next;
}
if (body != "")
print parse_block(body);
body = $0;
next; next;
} }
END { END {
if (body != "") { if (body != "")
parse_body(body); print parse_block(body);
}
} }

10
test.sh
View file

@ -127,6 +127,16 @@ second line of code
<p>``` first line of code second line of code</p> <p>``` first line of code second line of code</p>
EOF EOF
check <<-"EOF"
code
indented by
spaces
---
<pre><code>code
indented by
spaces</code></pre>
EOF
check <<-"EOF" check <<-"EOF"
asdf asdf