From 5ff9ee0235a7e1004904cef2a4d96003b872cd6e Mon Sep 17 00:00:00 2001 From: Konstantin Nazarov Date: Sun, 13 Mar 2022 01:26:32 +0000 Subject: [PATCH] Add support for tables --- markdown.awk | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ test.sh | 17 +++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/markdown.awk b/markdown.awk index 398a415..293002f 100755 --- a/markdown.awk +++ b/markdown.awk @@ -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="\n\n"; + for (i=2; i<=num_cols+1; i++) { + res = res "\n"; + } + res = res "\n" + + for (i=3; i<=length(lines); i++) { + line = lines[i]; + split(line, cols, "|"); + res=res "\n"; + for (i=2; i<=num_cols+1; i++) { + res = res "\n"; + } + res=res"\n"; + } + res=res "
"strip(cols[i])"
"strip(cols[i])"
" + 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); } diff --git a/test.sh b/test.sh index 751da04..2bc1eef 100755 --- a/test.sh +++ b/test.sh @@ -486,5 +486,22 @@ not metadata: 3

this: 1 is: 2 not metadata: 3

EOF +check <<-"EOF" +|foo|bar| +|---|---| +|1 |2 | +--- + + + + + + + + + +
foobar
12
+EOF + echo echo "All tests passed"