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