From e8ab5cb157b6c4fee13e739b09df83e73f5dfbee Mon Sep 17 00:00:00 2001 From: TimePath Date: Tue, 9 Feb 2016 20:33:36 +1100 Subject: [PATCH] Markdown: basic spacing support --- qcsrc/lib/_all.inc | 1 + qcsrc/lib/markdown.qh | 65 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 qcsrc/lib/markdown.qh diff --git a/qcsrc/lib/_all.inc b/qcsrc/lib/_all.inc index 307b4bd08..9aaf52449 100644 --- a/qcsrc/lib/_all.inc +++ b/qcsrc/lib/_all.inc @@ -49,6 +49,7 @@ #include "linkedlist.qh" #include "log.qh" #include "map.qh" +#include "markdown.qh" #include "math.qh" #include "misc.qh" #include "net.qh" diff --git a/qcsrc/lib/markdown.qh b/qcsrc/lib/markdown.qh new file mode 100644 index 000000000..63a4182b4 --- /dev/null +++ b/qcsrc/lib/markdown.qh @@ -0,0 +1,65 @@ +#include "test.qh" + +/** + * handle string spacing as markdown: + * - two spaces escape a linebreak (otherwise text wraps) + * - two linebreaks become a paragraph (remain unchanged) + */ +string markdown(string s) +{ + string buf = ""; + int lines = 0; + int spaces = 0; + FOREACH_CHAR(s, true, { + switch (it) { + default: + for (; spaces > 0; --spaces) { + buf = strcat(buf, " "); + } + buf = strcat(buf, chr2str(it)); + break; + case ' ': + spaces += 1; + break; + case '\n': + lines += 1; + if (lines > 1) { + lines = 0; + spaces = 0; + buf = strcat(buf, "\n\n"); + break; + } + if (spaces < 2) { + spaces = 1; + } else { + spaces = 0; + buf = strcat(buf, "\n"); + } + break; + } + }); + return buf; +} + +TEST(Markdown, LineWrap) +{ + #define X(expect, in) MACRO_BEGIN \ + string out = markdown(in); \ + EXPECT_TRUE(expect == out); \ + LOG_INFO(expect); \ + LOG_INFO(out); \ + MACRO_END + + // identity + X("lorem ipsum", "lorem ipsum"); + // trim trailing space + X("lorem ipsum", "lorem ipsum "); + // allow manual input wrapping + X("lorem ipsum", "lorem\nipsum"); + // line break + X("lorem\nipsum", "lorem \nipsum"); + // paragraph + X("lorem\n\nipsum", "lorem\n\nipsum"); + SUCCEED(); + #undef X +} -- 2.39.2