using System; namespace mustache { /// /// Removes unnecessary whitespace from static text. /// internal sealed class Trimmer { private bool hasHeader; private bool hasFooter; private bool hasTag; private bool canTrim; /// /// Initializes a new instance of a Trimmer. /// public Trimmer() { hasTag = false; canTrim = true; } /// /// Processes the given text, creating a StaticGenerator and adding it to the current compound generator. /// /// The compound generator to add the static generator to. /// Gets whether we're encountered the header tag. /// The static text to trim. public void AddStaticGeneratorBeforeTag(CompoundGenerator generator, bool isHeader, string value) { string trimmed = processLines(value); hasHeader |= isHeader; hasFooter |= hasHeader && !isHeader; addStaticGenerator(generator, trimmed); } /// /// Processes the given text, creating a StaticGenerator and adding it to the current compound generator. /// /// The compound generator to add the static generator to. /// Specifies whether the tag results in output. /// The static text to trim. public void AddStaticGenerator(CompoundGenerator generator, bool isOutput, string value) { string trimmed = processLines(value); canTrim &= !isOutput; addStaticGenerator(generator, trimmed); } private string processLines(string value) { string trimmed = value; int newline = value.IndexOf(Environment.NewLine); if (newline == -1) { canTrim &= String.IsNullOrWhiteSpace(value); } else { // finish processing the previous line if (canTrim && hasTag && (!hasHeader || !hasFooter)) { string lineEnd = trimmed.Substring(0, newline); if (String.IsNullOrWhiteSpace(lineEnd)) { trimmed = trimmed.Substring(newline + Environment.NewLine.Length); } } // start processing the next line hasTag = false; hasHeader = false; hasFooter = false; int lastNewline = value.LastIndexOf(Environment.NewLine); string lineStart = value.Substring(lastNewline + Environment.NewLine.Length); canTrim = String.IsNullOrWhiteSpace(lineStart); } return trimmed; } private static void addStaticGenerator(CompoundGenerator generator, string trimmed) { if (trimmed.Length > 0) { StaticGenerator leading = new StaticGenerator(trimmed); generator.AddGenerator(leading); } } } }