Skip to content

Instantly share code, notes, and snippets.

@yankooliveira
Created April 1, 2021 23:20
Show Gist options
  • Save yankooliveira/27e683dc6f95f2484cdbce54798e36cf to your computer and use it in GitHub Desktop.
Save yankooliveira/27e683dc6f95f2484cdbce54798e36cf to your computer and use it in GitHub Desktop.
If you have the terrible idea of making a prototype using CodeDOM and explicit snippets like I did, this helps controlling indentation. I'm pretty sure there's a smarter way, but it's not like I think before I type when I make prototypes ๐Ÿ˜…
using System.Text;
namespace deVoid.Utils {
// Uses an internal StringBuilder instance and automatically keeps tracks of indentation.
public class CodeSnippetBuilder {
public int IndentLevel {
get { return _indentLevel; }
set {
if (value < 0) {
value = 0;
}
if (value > _indentLevel) {
int delta = value - _indentLevel;
for (int i = 0; i < delta; i++) {
_stringBuilder.Append(Tab);
}
}
_indentLevel = value;
}
}
// IndentLevel * Tabs are added whenever AppendLine is called, or when IndentLevel *increases*.
public readonly string Tab = " ";
private int _indentLevel;
private StringBuilder _stringBuilder = new StringBuilder();
public CodeSnippetBuilder(StringBuilder builder = null, string existingSnippet = "", string tabbing = " ") {
if (builder != null) {
_stringBuilder = builder;
}
if (!string.IsNullOrEmpty(existingSnippet)) {
_stringBuilder.Append(existingSnippet);
}
if (!string.IsNullOrEmpty(tabbing)) {
Tab = tabbing;
}
}
public CodeSnippetBuilder AppendLine() {
_stringBuilder.AppendLine();
for (int i = 0; i < IndentLevel; i++) {
_stringBuilder.Append(Tab);
}
return this;
}
public CodeSnippetBuilder Append(string snippet) {
_stringBuilder.Append(snippet);
return this;
}
public override string ToString() {
return _stringBuilder.ToString();
}
public void Clear() {
_stringBuilder.Clear();
IndentLevel = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment