blob: 663a9d65111bad8857dd750d27a8a0e42dd54a83 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.justif;
2
3import java.util.*;
4
5
6public class Justif {
7 int []tabs;
8
9 public Justif(int width, int ... tabs) {
10 this.tabs = tabs;
11 }
12
13 /**
14 * Routine to wrap a stringbuffer. Basically adds line endings but has the
15 * following control characters:
16 * <ul>
17 * <li>Space at the beginnng of a line is repeated when wrapped for indent.</li>
18 * <li>A tab will mark the current position and wrapping will return to that
19 * position</li>
20 * <li>A form feed in a tabbed colum will break but stay in the column</li>
21 * </ul>
22 *
23 * @param sb
24 */
25 public void wrap(StringBuilder sb) {
26 List<Integer> indents = new ArrayList<Integer>();
27
28 int indent = 0;
29 int linelength = 0;
30 int lastSpace = 0;
31 int r = 0;
32 boolean begin = true;
33
34 while (r < sb.length()) {
35 switch (sb.charAt(r++)) {
36 case '\n':
37 linelength = 0;
38
39 indent = indents.isEmpty() ? 0 : indents.remove(0);
40 begin = true;
41 lastSpace = 0;
42 break;
43
44 case ' ':
45 if (begin)
46 indent++;
47 lastSpace = r - 1;
48 linelength++;
49 break;
50
51 case '\t':
52 indents.add(indent);
53 indent = linelength;
54 sb.deleteCharAt(--r);
55
56 if (r < sb.length()) {
57 char digit = sb.charAt(r);
58 if (Character.isDigit(digit)) {
59 sb.deleteCharAt(r--);
60
61 int column = (digit - '0');
62 if (column < tabs.length)
63 indent = tabs[column];
64 else
65 indent = column * 8;
66
67 int diff = indent - linelength;
68 if (diff > 0) {
69 for (int i=0; i<diff; i++) {
70 sb.insert(r, ' ');
71 }
72 r += diff;
73 linelength += diff;
74 }
75 }
76 }
77 break;
78
79 case '\f':
80 linelength = 100000; // force a break
81 lastSpace = r-1;
82
83 //$FALL-THROUGH$
84
85 default:
86 linelength++;
87 begin = false;
88 if (lastSpace != 0 && linelength > 60) {
89 sb.setCharAt(lastSpace, '\n');
90 linelength = 0;
91
92 for (int i = 0; i < indent; i++) {
93 sb.insert(lastSpace + 1, ' ');
94 linelength++;
95 }
96 r += indent;
97 lastSpace = 0;
98 }
99 }
100 }
101 }
102
103
104}