f37b7339e462f35f1cc5461c60dbb60a8a8a3b4b
[libs/datafile.git] / source / textwriter.cpp
1 #include <msp/io/print.h>
2 #include <msp/strings/utils.h>
3 #include "output.h"
4 #include "statement.h"
5 #include "textwriter.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace DataFile {
11
12 TextWriter::TextWriter(Output &o):
13         WriterMode(o)
14 {
15         float_format.showpoint().precision(7);
16 }
17
18 void TextWriter::set_float_precision(unsigned fp)
19 {
20         float_format.precision(fp/4-1);
21 }
22
23 void TextWriter::write(const Statement &st)
24 {
25         write_(st, 0);
26 }
27
28 void TextWriter::write_(const Statement &st, unsigned level)
29 {
30         string indent(level, '\t');
31
32         out.write(format("%s%s", indent, st.keyword));
33         for(ValueArray::const_iterator i = st.args.begin(); i!=st.args.end(); ++i)
34         {
35                 out.put(' ');
36                 if(i->get_signature()==StringType::signature)
37                         out.write(format("\"%s\"", c_escape(i->get<StringType::Store>(), false)));
38                 else if(i->get_signature()==BoolType::signature)
39                         out.write(i->get<BoolType::Store>() ? "true" : "false");
40                 else if(i->get_signature()==IntType::signature)
41                         out.write(lexical_cast<string>(i->get<IntType::Store>()));
42                 else if(i->get_signature()==FloatType::signature)
43                         out.write(lexical_cast<string>(i->get<FloatType::Store>(), float_format));
44                 else if(i->get_signature()==SymbolType::signature)
45                 {
46                         string name = i->get<SymbolType::Store>().name;
47                         if(isdigit(name[0]))
48                                 out.write("\\"+name);
49                         else
50                                 out.write(name);
51                 }
52         }
53         if(!st.sub.empty())
54         {
55                 out.write(format("\n%s{\n", indent));
56                 for(list<Statement>::const_iterator i = st.sub.begin(); i!=st.sub.end(); ++i)
57                         write_(*i, level+1);
58                 out.write(format("%s}", indent));
59         }
60         out.write(";\n");
61 }
62
63 } // namespace DataFile
64 } // namespace Msp