Formatter.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Text;
  2. internal static class Formatter
  3. {
  4. public static string Indent = " ";
  5. public static void AppendIndent(StringBuilder sb, int count)
  6. {
  7. while (count > 0)
  8. {
  9. sb.Append(Indent);
  10. count--;
  11. }
  12. }
  13. public static bool IsEscaped(StringBuilder sb, int index)
  14. {
  15. bool escaped = false;
  16. while (index > 0 && sb[--index] == '\\')
  17. {
  18. escaped = !escaped;
  19. }
  20. return escaped;
  21. }
  22. public static string PrettyPrint(string input)
  23. {
  24. StringBuilder output = new StringBuilder(input.Length * 2);
  25. char? quote = null;
  26. int depth = 0;
  27. for (int i = 0; i < input.Length; i++)
  28. {
  29. char ch = input[i];
  30. switch (ch)
  31. {
  32. case '[':
  33. case '{':
  34. output.Append(ch);
  35. if (!quote.HasValue)
  36. {
  37. output.AppendLine();
  38. AppendIndent(output, ++depth);
  39. }
  40. break;
  41. case ']':
  42. case '}':
  43. if (quote.HasValue)
  44. {
  45. output.Append(ch);
  46. break;
  47. }
  48. output.AppendLine();
  49. AppendIndent(output, --depth);
  50. output.Append(ch);
  51. break;
  52. case '"':
  53. case '\'':
  54. output.Append(ch);
  55. if (quote.HasValue)
  56. {
  57. if (!IsEscaped(output, i))
  58. {
  59. quote = null;
  60. }
  61. }
  62. else
  63. {
  64. quote = ch;
  65. }
  66. break;
  67. case ',':
  68. output.Append(ch);
  69. if (!quote.HasValue)
  70. {
  71. output.AppendLine();
  72. AppendIndent(output, depth);
  73. }
  74. break;
  75. case ':':
  76. if (quote.HasValue)
  77. {
  78. output.Append(ch);
  79. }
  80. else
  81. {
  82. output.Append(" : ");
  83. }
  84. break;
  85. default:
  86. if (quote.HasValue || !char.IsWhiteSpace(ch))
  87. {
  88. output.Append(ch);
  89. }
  90. break;
  91. }
  92. }
  93. return output.ToString();
  94. }
  95. }