Advertisement
Guest User

Colums

a guest
Feb 24th, 2014
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. package joptsimple.internal;
  2.  
  3. import java.text.BreakIterator;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Locale;
  7.  
  8. class Columns
  9. {
  10. private static final int INDENT_WIDTH = 2;
  11. private final int optionWidth;
  12. private final int descriptionWidth;
  13.  
  14. Columns(int optionWidth, int descriptionWidth)
  15. {
  16. this.optionWidth = optionWidth;
  17. this.descriptionWidth = descriptionWidth;
  18. }
  19.  
  20. List<Row> fit(Row row) {
  21. List options = piecesOf(row.option, this.optionWidth);
  22. List descriptions = piecesOf(row.description, this.descriptionWidth);
  23.  
  24. List rows = new ArrayList();
  25. for (int i = 0; i < Math.max(options.size(), descriptions.size()); i++) {
  26. rows.add(new Row(itemOrEmpty(options, i), itemOrEmpty(descriptions, i)));
  27. }
  28. return rows;
  29. }
  30.  
  31. private static String itemOrEmpty(List<String> items, int index) {
  32. return index >= items.size() ? "" : (String)items.get(index);
  33. }
  34.  
  35. private List<String> piecesOf(String raw, int width) {
  36. List pieces = new ArrayList();
  37.  
  38. for (String each : raw.trim().split(Strings.LINE_SEPARATOR)) {
  39. pieces.addAll(piecesOfEmbeddedLine(each, width));
  40. }
  41. return pieces;
  42. }
  43.  
  44. private List<String> piecesOfEmbeddedLine(String line, int width) {
  45. List pieces = new ArrayList();
  46.  
  47. BreakIterator words = BreakIterator.getLineInstance(Locale.US);
  48. words.setText(line);
  49.  
  50. StringBuilder nextPiece = new StringBuilder();
  51.  
  52. int start = words.first();
  53. for (int end = words.next(); end != -1; end = words.next()) {
  54. nextPiece = processNextWord(line, nextPiece, start, end, width, pieces);
  55.  
  56. start = end;
  57. }
  58.  
  59. if (nextPiece.length() > 0) {
  60. pieces.add(nextPiece.toString());
  61. }
  62. return pieces;
  63. }
  64.  
  65. private StringBuilder processNextWord(String source, StringBuilder nextPiece, int start, int end, int width, List<String> pieces)
  66. {
  67. StringBuilder augmented = nextPiece;
  68.  
  69. String word = source.substring(start, end);
  70. if (augmented.length() + word.length() > width) {
  71. pieces.add(augmented.toString().replaceAll("\\s+$", ""));
  72. augmented = new StringBuilder(Strings.repeat(' ', 2)).append(word);
  73. }
  74. else {
  75. augmented.append(word);
  76. }
  77. return augmented;
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement