/src/kilim/analysis/Utils.java

http://github.com/kilim/kilim · Java · 78 lines · 54 code · 12 blank · 12 comment · 8 complexity · 63722cb0f9e369946863448fd2d5612e MD5 · raw file

  1. /* Copyright (c) 2006, Sriram Srinivasan
  2. *
  3. * You may distribute this software under the terms of the license
  4. * specified in the file "License"
  5. */
  6. package kilim.analysis;
  7. /**
  8. * Simple string utils for pretty printing support
  9. *
  10. */
  11. public class Utils {
  12. public static String indentStr = "";
  13. public static String spaces = " ";
  14. public static void indentWith(String s) {
  15. indentStr = indentStr + s;
  16. }
  17. public static void indent(int numSpaces) {
  18. indentWith(spaces.substring(0, numSpaces));
  19. }
  20. public static void dedent(int numSpaces) {
  21. indentStr = indentStr.substring(0, indentStr.length() - numSpaces);
  22. }
  23. public static String format(String s) {
  24. if (indentStr.length() == 0)
  25. return s;
  26. int i = s.indexOf('\n'); // i is always the index of newline
  27. if (i >= 0) {
  28. StringBuffer sb = new StringBuffer(100);
  29. sb.append(indentStr); // leading indent
  30. int prev = 0; // prev value of i in loop
  31. do {
  32. // copy from prev to i (including \n)
  33. sb.append(s, prev, i + 1);
  34. // add indentation wherever \n occurs
  35. sb.append(indentStr);
  36. prev = i + 1;
  37. if (prev >= s.length())
  38. break;
  39. i = s.indexOf('\n', prev);
  40. } while (i != -1);
  41. // copy left over chars from the last segment
  42. sb.append(s, prev, s.length());
  43. return sb.toString();
  44. } else {
  45. return indentStr + s;
  46. }
  47. }
  48. public static void resetIndentation() {
  49. indentStr = "";
  50. }
  51. public static void p(String s) {
  52. System.out.print(format(s));
  53. }
  54. public static void pn(String s) {
  55. System.out.println(format(s));
  56. }
  57. public static void pn(int i) {
  58. System.out.println(format("" + i));
  59. }
  60. public static void pn() {
  61. System.out.println();
  62. }
  63. public static void pn(Object o) {
  64. pn((o == null) ? "null" : o.toString());
  65. }
  66. }