Removed trailing whitespaces in tilemanager source files (yes I know that code needs...
[supertux.git] / tools / tilemanager / LispWriter.cs
1 using System;
2 using System.IO;
3 using System.Collections;
4
5 public class LispWriter {
6     private TextWriter stream;
7     private int IndentDepth;
8     private Stack lists = new Stack();
9
10     public LispWriter(TextWriter stream) {
11         this.stream = stream;
12     }
13
14     public void WriteComment(string comment) {
15         stream.WriteLine("; " + comment);
16     }
17
18     public void StartList(string name) {
19         indent();
20         stream.WriteLine("(" + name);
21         IndentDepth += 2;
22         lists.Push(name);
23     }
24
25     public void EndList(string name) {
26         if(lists.Count == 0)
27             throw new Exception("Trying to close list while none is open");
28         string back = (string) lists.Pop();
29         if(name != back)
30             throw new Exception(
31                     String.Format("Trying to close {0} which is not open", name));
32
33         IndentDepth -= 2;
34         indent();
35         stream.WriteLine(")");
36     }
37
38     public void Write(string name, object value) {
39         indent();
40         stream.Write("(" + name);
41         if(value is string) {
42             stream.Write(" \"" + value.ToString() + "\"");
43         } else if(value is IEnumerable) {
44             foreach(object o in (IEnumerable) value) {
45                 stream.Write(" ");
46                 WriteValue(o);
47             }
48         } else {
49             stream.Write(" ");
50             WriteValue(value);
51         }
52         stream.WriteLine(")");
53     }
54
55     private void WriteValue(object val) {
56         if(val is bool) {
57             stream.Write((bool) val ? "#t" : "#f");
58         } else if(val is int || val is float) {
59             stream.Write(val.ToString());
60         } else {
61             stream.Write("\"" + val.ToString() + "\"");
62         }
63     }
64
65     public void WriteVerbatimLine(string line) {
66         indent();
67         stream.WriteLine(line);
68     }
69
70     private void indent() {
71         for(int i = 0; i < IndentDepth; ++i)
72             stream.Write(" ");
73     }
74 }