// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using System.Collections.Generic; using System.Text; using UnityEngine; namespace ScriptTemplates { /// /// Helps you to build script files with support for automatically indenting source code. /// public sealed class ScriptBuilder { private StringBuilder _sb = new StringBuilder(); private int _indentLevel = 0; private string _indent = ""; private string _indentChars = "\t"; private string _indentCharsNewLine = "\n"; /// /// Gets or sets sequence of characters to use when indenting text. /// /// /// Changing this value will not affect text which has already been appended. /// public string IndentChars { get { return _indentChars; } set { int restoreIndent = _indentLevel; _indentLevel = -1; _indentChars = value; IndentLevel = restoreIndent; } } /// /// Gets or sets current indent level within script. /// public int IndentLevel { get { return _indentLevel; } set { value = Mathf.Max(0, value); if (value != _indentLevel) { if (value < _indentLevel) _sb.Length -= _indentChars.Length; _indentLevel = value; _indent = ""; for (int i = 0; i < value; ++i) _indent += _indentChars; _indentCharsNewLine = "\n" + _indent; } } } /// /// Clear output and start over. /// /// /// This method also resets indention to 0. /// public void Clear() { _sb.Length = 0; IndentLevel = 0; } /// /// Append text to script and begin new line. /// /// Text. public void AppendLine(string text) { Append(text); _sb.Append(_indentCharsNewLine); } /// /// Append blank line to script. /// public void AppendLine() { _sb.Append(_indentCharsNewLine); } /// /// Append text to script. /// /// Text. public void Append(string text) { _sb.Append(text.Replace("\n", _indentCharsNewLine)); } /// /// Begin namespace scope and automatically indent. /// /// Text. public void BeginNamespace(string text) { Append(text); _sb.AppendLine(); ++IndentLevel; _sb.Append(_indentCharsNewLine); } /// /// End namespace scope and unindent. /// /// Text. public void EndNamespace(string text) { --IndentLevel; _sb.Append(text.Replace("\n", _indentCharsNewLine)); _sb.AppendLine(); _sb.Append(_indent); AppendLine(); } /// /// Get generated source code as string. /// /// /// The string. /// public override string ToString() { return _sb.ToString().Trim() + "\n"; } } }