Add support for tables

This commit is contained in:
Konstantin Nazarov 2022-03-13 01:26:32 +00:00
parent 131ea53f4a
commit 5ff9ee0235
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
2 changed files with 75 additions and 0 deletions

View file

@ -68,6 +68,11 @@ function lstrip(str) {
return str;
}
function strip(str) {
gsub(/^ *\n*| *\n*$/, "", str);
return str;
}
function escape_special() {
}
@ -429,10 +434,63 @@ function is_metadata(str, i, lines, line) {
return 1;
}
function col_count(str, i, count) {
count = 0;
for (i=1; i<=length(str); i++) {
if (substr(str, i, 1) == "|")
count++;
}
return count-1;
}
function is_table(str, i, lines, line) {
split(str, lines, "\n");
num_cols = col_count(lines[1]);
if (!match(lines[2], /^([[:space:]]*\|[[:space:]]*-{3,}[[:space:]])*\|[[:space:]]*/)) {
return 0;
}
for (i=2; i<=length(lines); i++) {
line = lines[i];
if (col_count(line) != num_cols)
return 0;
}
return 1;
}
function parse_table(str, num_cols, lines, line, cols, i, j) {
split(str, lines, "\n");
num_cols = col_count(lines[1]);
split(lines[1], cols, "|");
res="<table>\n<tr>\n";
for (i=2; i<=num_cols+1; i++) {
res = res "<th>"strip(cols[i])"</th>\n";
}
res = res "</tr>\n"
for (i=3; i<=length(lines); i++) {
line = lines[i];
split(line, cols, "|");
res=res "<tr>\n";
for (i=2; i<=num_cols+1; i++) {
res = res "<td>"strip(cols[i])"</td>\n";
}
res=res"</tr>\n";
}
res=res "</table>"
return res;
}
function parse_block(str) {
if (str == "")
return "";
if (match(str, /^[[:space:]]*\|.*/) && is_table(str)) {
return parse_table(str);
}
if (match(str, /^```\n.*```$/) || match(str, /^ /)) {
return parse_code(str);
}

17
test.sh
View file

@ -486,5 +486,22 @@ not metadata: 3
<p>this: 1 is: 2 not metadata: 3</p>
EOF
check <<-"EOF"
|foo|bar|
|---|---|
|1 |2 |
---
<table>
<tr>
<th>foo</th>
<th>bar</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
EOF
echo
echo "All tests passed"