Changed the rendering code for templating output
[biaweb2.git] / biawebutil.hpp
1 #ifndef __BIAWEBUTIL__
2 #define __BIAWEBUTIL__
3 #include <string>
4
5 // "discount" markdown library is a C library and hence requires to be wrapped in
6 // extern "C"
7 extern "C" {
8 #include <mkdio.h>
9 }
10
11 // utility functions for Biaweb that don't fit into any class and can be used by
12 // any class
13 namespace biaweb {
14
15 // convert markdown
16 std::string convert_to_markdown (std::string str) {
17 // discount is a C library and it doesn't work well with C++ streams
18 // and there seems no way to get the output of any of these functions
19 // into an std::string.
20 // the only option seems to be to write the output of the markdown()
21 // function to a temporary working file and then read it back into C++
22 // with the normal std::ifstream and feed it into the std::string
23 // till a cleaner solution can be found.
24 MMIOT *doc;
25 doc = mkd_string (str.c_str(), str.size(), 0);
26 FILE *f = fopen (".biaweb.tmp", "w");
27 markdown (doc, f, 0);
28 fclose (f);
29 std::ifstream ftmp (".biaweb.tmp");
30 std::string tmpl ( (std::istreambuf_iterator<char> (ftmp)),
31 (std::istreambuf_iterator<char> ())
32 );
33 ftmp.close ();
34 mkd_cleanup (doc);
35 remove (".biaweb.tmp");
36 return tmpl;
37 }
38
39 // convert a document title to a file title - strip out the non-alpha
40 // chars and spaces
41 std::string convert_title (std::string title)
42 {
43 std::string output;
44 for (char c : title) {
45 if (isalnum (c))
46 output.append (1, c);
47 else if (isspace (c))
48 output.append (1, '_');
49 }
50 return output;
51 }
52
53 // escape HTML special characters
54 std::string escape_html (std::string source)
55 {
56 std::string replace_buf;
57 replace_buf.reserve (source.size());
58 for (char p : source)
59 {
60 switch (p)
61 {
62 case '&' : replace_buf.append ("&amp;"); break;
63 case '<' : replace_buf.append ("&lt;"); break;
64 case '>' : replace_buf.append ("&gt;"); break;
65 case '\"': replace_buf.append ("&quot;"); break;
66 case '\'': replace_buf.append ("&apos;"); break;
67 default : replace_buf.append (1, p);
68 }
69 }
70 return replace_buf;
71 }
72 }
73 #endif