-
Notifications
You must be signed in to change notification settings - Fork 0
/
IndentedStringBuilder.cs
97 lines (82 loc) · 2.56 KB
/
IndentedStringBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Text;
namespace DTZ.Utilities
{
public class IndentedStringBuilder
{
private const int SpacesPerIndent = 2;
private readonly StringBuilder _sb;
private string _completeIndentationString = "";
private int _indent;
private bool _newline;
public IndentedStringBuilder()
{
_sb = new StringBuilder();
}
public int Length
{
get { return _sb.Length; }
}
public void Append(string value)
{
int i = value.IndexOf("\r\n", StringComparison.Ordinal);
if (i < 0) // No newline
InternalAppend(value, false);
else if (i == value.Length - 2) // Ends with newline
InternalAppend(value, true);
else
{
InternalAppend(value.Substring(0, i + 2), true);
Append(value.Substring(i + 2));
}
}
private void InternalAppend(string value, bool endsInCr)
{
if (_newline)
_sb.Append(_completeIndentationString);
_sb.Append(value);
_newline = endsInCr;
}
public void AppendLine()
{
Append(Environment.NewLine);
}
public void AppendLine(string value)
{
Append(value);
AppendLine();
}
public void AppendFormat(string format, params object[] objects)
{
Append(string.Format(format, objects));
}
public DecreaseIndentOnDispose IncreaseIndent()
{
_indent++;
_completeIndentationString = new string(' ', SpacesPerIndent*_indent);
return new DecreaseIndentOnDispose(this);
}
public void DecreaseIndent()
{
if (_indent <= 0) return;
_indent--;
_completeIndentationString = new string(' ', SpacesPerIndent*_indent);
}
public override string ToString()
{
return _sb.ToString();
}
}
public class DecreaseIndentOnDispose : IDisposable
{
private readonly IndentedStringBuilder _indentedStringBuilder;
public DecreaseIndentOnDispose(IndentedStringBuilder indentedStringBuilder)
{
_indentedStringBuilder = indentedStringBuilder;
}
public void Dispose()
{
_indentedStringBuilder.DecreaseIndent();
}
}
}