IndentedTextWriterExtensions.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.CodeDom.Compiler;
  2. namespace Terminal.Gui.Analyzers.Internal;
  3. /// <summary>
  4. /// Just a simple set of extension methods to increment and decrement the indentation
  5. /// level of an <see cref="IndentedTextWriter"/> via push and pop terms, and to avoid having
  6. /// explicit values all over the place.
  7. /// </summary>
  8. public static class IndentedTextWriterExtensions
  9. {
  10. /// <summary>
  11. /// Decrements <see cref="IndentedTextWriter.Indent"/> by 1, but only if it is greater than 0.
  12. /// </summary>
  13. /// <returns>
  14. /// The resulting indentation level of the <see cref="IndentedTextWriter"/>.
  15. /// </returns>
  16. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  17. public static int Pop (this IndentedTextWriter w, string endScopeDelimiter = "}")
  18. {
  19. if (w.Indent > 0)
  20. {
  21. w.Indent--;
  22. w.WriteLine (endScopeDelimiter);
  23. }
  24. return w.Indent;
  25. }
  26. /// <summary>
  27. /// Decrements <see cref="IndentedTextWriter.Indent"/> by 1 and then writes a closing curly brace.
  28. /// </summary>
  29. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  30. public static void PopCurly (this IndentedTextWriter w, bool withSemicolon = false)
  31. {
  32. w.Indent--;
  33. if (withSemicolon)
  34. {
  35. w.WriteLine ("};");
  36. }
  37. else
  38. {
  39. w.WriteLine ('}');
  40. }
  41. }
  42. /// <summary>
  43. /// Increments <see cref="IndentedTextWriter.Indent"/> by 1, with optional parameters to customize the scope push.
  44. /// </summary>
  45. /// <param name="w">An instance of an <see cref="IndentedTextWriter"/>.</param>
  46. /// <param name="declaration">
  47. /// The first line to be written before indenting and before the optional <paramref name="scopeDelimiter"/> line or
  48. /// null if not needed.
  49. /// </param>
  50. /// <param name="scopeDelimiter">
  51. /// An opening delimiter to write. Written before the indentation and after <paramref name="declaration"/> (if provided). Default is an opening curly brace.
  52. /// </param>
  53. /// <remarks>Calling with no parameters will write an opening curly brace and a line break at the current indentation and then increment.</remarks>
  54. [MethodImpl (MethodImplOptions.AggressiveInlining)]
  55. public static void Push (this IndentedTextWriter w, string? declaration = null, char scopeDelimiter = '{')
  56. {
  57. if (declaration is { Length: > 0 })
  58. {
  59. w.WriteLine (declaration);
  60. }
  61. w.WriteLine (scopeDelimiter);
  62. w.Indent++;
  63. }
  64. }