]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/lib/markdown.qh
Merge branch 'master' into Mario/wepent_experimental
[xonotic/xonotic-data.pk3dir.git] / qcsrc / lib / markdown.qh
1 #include "test.qh"
2
3 /**
4  * handle string spacing as markdown:
5  *   - two spaces escape a linebreak (otherwise text wraps)
6  *   - two linebreaks become a paragraph (remain unchanged)
7  */
8 string markdown(string s)
9 {
10         string buf = "";
11         int lines = 0;
12         int spaces = 0;
13         FOREACH_CHAR(s, true, {
14                 switch (it) {
15                         default:
16                                 for (; spaces > 0; --spaces) {
17                                         buf = strcat(buf, " ");
18                                 }
19                                 buf = strcat(buf, chr2str(it));
20                                 break;
21                         case ' ':
22                                 spaces += 1;
23                                 break;
24                         case '\n':
25                                 lines += 1;
26                                 if (lines > 1) {
27                                         lines = 0;
28                                         spaces = 0;
29                                         buf = strcat(buf, "\n\n");
30                                         break;
31                                 }
32                                 if (spaces < 2) {
33                                         spaces = 1;
34                                 } else {
35                                         spaces = 0;
36                                         buf = strcat(buf, "\n");
37                                 }
38                                 break;
39                 }
40         });
41         return buf;
42 }
43
44 TEST(Markdown, LineWrap)
45 {
46         #define X(expect, in) MACRO_BEGIN \
47                 string out = markdown(in); \
48                 EXPECT_TRUE(expect == out); \
49                 LOG_INFO(expect); \
50                 LOG_INFO(out); \
51         MACRO_END
52
53         // identity
54         X("lorem ipsum", "lorem ipsum");
55         // trim trailing space
56         X("lorem ipsum", "lorem ipsum ");
57         // allow manual input wrapping
58         X("lorem ipsum", "lorem\nipsum");
59         // line break
60         X("lorem\nipsum", "lorem  \nipsum");
61         // paragraph
62         X("lorem\n\nipsum", "lorem\n\nipsum");
63         SUCCEED();
64         #undef X
65 }