From da65bb16f06ebde6c91599004144bae99a442e1b Mon Sep 17 00:00:00 2001 From: Konstantin Nazarov Date: Mon, 26 Jul 2021 20:57:07 +0000 Subject: [PATCH] Implement links --- README.md | 1 + markdown.awk | 48 ++++++++++++++++++++++++++++++++++++++---------- test.sh | 9 +++++++++ 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0e3c506..d7f437a 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Here's a list of supported markdown primitives - Blockquotes - Lists, both bulleted and numbered - Inline html (partial) +- Links ## License diff --git a/markdown.awk b/markdown.awk index 61fcd23..a0fcc2d 100644 --- a/markdown.awk +++ b/markdown.awk @@ -185,6 +185,29 @@ function is_escape_sequence(str, i, sstr) { return match(sstr, /^\\[`\\*_{}\[\]()>#.!+-]/); } +function extract_link(str, i, sstr) { + sstr=substr(str, i, length(str) - i + 1); + + if (!match(sstr, /^\[([^\[\]]*)\]\( *([^() ]*)( +"([^"]*)")? *\)/, arr)) + return ""; + + return substr(str, i, RLENGTH); +} + +function parse_link(str, arr) { + if (!match(str, /^\[([^\[\]]*)\]\( *([^() ]*)( +"([^"]*)")? *\)/, arr)) + return ""; + + if (arr[4] == "") { + return "" arr[1] "" + } + return "" arr[1] "" +} + +function is_link(str, i) { + return extract_link(str, i) != ""; +} + function escape_text(str) { gsub(/&/, "\\&", str); gsub(/" escape_text(substr(str, i+3, end - i - 3)) ""; @@ -221,7 +244,7 @@ function parse_line(str, result, end, i) { i=i+2; } } - else if (substr(str, i, 1) == "`") { + else if (c == "`" && substr(str, i, 1) == "`") { end = find(str, "`", i+1); if (end != 0) { result = result "" escape_text(substr(str, i+1, end - i - 1)) ""; @@ -231,22 +254,27 @@ function parse_line(str, result, end, i) { result = result "`"; } } - else if (is_html_tag(str, i)) { + else if (c == "<" && is_html_tag(str, i)) { tag = extract_html_tag(str, i); result = result tag; i = i + length(tag) - 1; } - else if (is_escape_sequence(str, i)) { + else if (c == "\\" && is_escape_sequence(str, i)) { result = result escape_text(substr(str, i+1, 1)); i = i + 1; } + else if (c == "[" && is_link(str, i)) { + link = extract_link(str, i); + result = result parse_link(link); + i = i + length(link) - 1; + } else { - if (substr(str, i, 1) == "\n") { + if (c == "\n") { if (length(result) > 0) result = result " "; } else { - result = result escape_text(substr(str, i, 1)); + result = result escape_text(c); } } } diff --git a/test.sh b/test.sh index 2ce956e..7ae2765 100755 --- a/test.sh +++ b/test.sh @@ -387,5 +387,14 @@ This shouldn't be escaped: \* This shouldn't be escaped: \* EOF +check <<-"EOF" +Spimple link: [foo](/bar) + +Link with title: [foo](/bar "baz") +--- +

Spimple link: foo

+

Link with title: foo

+EOF + echo echo "All tests passed"