1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package Torello.Java;

// When you take this stuff for granted ... well ... Yes, somebody out there has written a
// String-Package that includes a "Wrap" Feature.
// 
// This stuff is so tedious, that I started to feel pain in my fingers just trying to write it
// today.

class Wrap
{
    static String wrap(
            final String    s,
            final int       firstLineLen,
            final int       lineLen
        )
    {
        if (firstLineLen <= 0) throw new IllegalArgumentException(
            "You have passed [" + firstLineLen + "] to firstLineLen.  " +
            "This value may not be zero or negative."
        );

        if (lineLen <= 0) throw new IllegalArgumentException(
            "You have passed [" + lineLen + "] to lineLen.  " +
            "This value may not be zero or negative."
        );

        final StringBuilder sb  = new StringBuilder();
        final int           LEN = s.length();

        if (LEN == 0) return s;

        boolean firstLine   = true;
        int     start       = 0;
        int     end         = 0;
        int     curLineLen  = 1;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Here we go magic
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        for (int pos=0; pos < LEN; pos++, curLineLen++)
        {
            final String insertStr;
            final char c = s.charAt(pos);

            /*
            System.out.println(
                "CUR LOOP VALUES: " +
                "c=" + WrapHelpers.PRINTABLE_C(c) + ", pos=" + pos + ", start=" + start + ", " +
                "curLineLen=" + curLineLen
            );
            */


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Check for invalid characters.  There is just no good way to handle this garbage
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            if (    (c == '\t')
                ||  (c == '\r')
                ||  (c == '\f')
            )

                throw new StringFormatException(
                    "Input String contains '" + WrapHelpers.PRINTABLE_C(c) + "' at " +
                    "String-Location " + pos
                );


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // '\n' NEWLINE ==> Append everything to the left of it **BUT** do a Right-Trim too!
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            else if (c == '\n')
            {
                /*
                System.out.println(
                    "CASE: Found a New-Line, No Over-run yet!" +
                    WrapHelpers.SP(start, pos)
                );
                */

                firstLine = false;

                end         = WrapHelpers.backupSpaces_AKA_RightTrimCurLine(s, start, pos-1);
                insertStr   = s.substring(start, end);
                start       = pos + 1;
            }


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Any other character...
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            else 
            {
                // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                // First, check if "curLineLen" is OVER-BOARD ==> IF NOT, CONTINUE IMMEDIATELY
                // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

                if (firstLine)
                {
                    if (curLineLen <= firstLineLen) continue;
                    else                            firstLine = false;
                }

                else if (curLineLen <= lineLen) continue;


                // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                // "curLineLen" IS NOW TOO-LONG  ==>  Time to do some "Wrapping"
                // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                //
                // CASE 1: (**EASY**) Space-Char is located at the "Over-run"

                if (c == ' ')
                {
                    /*
                    System.out.println(
                        "CASE: Break is on a Space-Character" +
                        WrapHelpers.SP(start, pos)
                    );
                    */

                    end         = WrapHelpers.backupSpaces_AKA_RightTrimCurLine(s, start, pos);
                    insertStr   = s.substring(start, end);
                    start       = WrapHelpers.skipSpacesTowardsNextLine(s, pos, LEN);


                    // IMPORTANT: If there is a bunch of spaces, and then a new-line character...
                    //            (This is a little unlikely, but a bug I found while testing)
                    //            And actually, this "deviates" from the expected behavior...
                    // 
                    // The "insertStr" is padded with a new-line '\n' character, and therefore
                    // we cannot 'add' a SECOND-NEWLINE-CHARACTER !!  Remember, this special case
                    // can only "crop up" when there is a bunch of white-space, and then the line
                    // in questions closing-new line!
                    // 
                    // Specifically, if the "over-run" location occurs on a White-Space Character,
                    // but the only characters after the over-run location contain more spaces,
                    // THEN-AND-ONLY-THEN is this line necessary.
                    // 
                    // This linc **COULD** theoretically be inserted into the method
                    // "skipSpacesTowardsNextLine" - but that method's name explains what it does
                    // pretty clearly.

                    if ((start < LEN) && (s.charAt(start) == '\n')) start++;
                }

                // CASE 2: A printable non-space character is at the "Over-run"
                else 
                {
                    // System.out.println("CASE: non-space char found @ the over-run location");


                    // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                    // Find the first white-space TOWARDS LEFT
                    // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                    // 
                    // Currently, a Printable-Non-Space Character is located

                    final int firstLeftWS = WrapHelpers.firstLeftWhiteSpace(s, start, pos);
                    // System.out.println("    firstLeftWS: " + firstLeftWS);


                    // CASE 1:  There was no White-Space WHAT-SO-EVER between 'start' AND 'pos' !!
                    //          Break the Current Word at the current pos and wrap
                    // 
                    // This is the case where there was some "Really Long Word" that went from start
                    // all the way to the over-run situation.  This Really Long Word needs to be
                    // broken up, there is no other way (other than to allow over-run)

                    if (firstLeftWS == -1)
                    {
                        /*
                        System.out.println(
                            "    SUB-CASE: (firstLeftWS == -1)" +
                            WrapHelpers.SP(start, pos)
                        );
                        */

                        insertStr = s.substring(start, pos);
                        start = pos;
                    }


                    // CASE 2: There was at least one Space-Character towards the left, which
                    //         occurs **AFTER** 'start' (a.k.a. between 'start' and 'pos')
                    // 
                    // This case has TWO SUB-CASES !!!
                    // 
                    //      SUB-CASE 1: There is only space before the word that starts before
                    //                  the over-run / 'pos'.  Seems extremely unlikely.
                    //                  SPECIFICALLY - There was 'start', then a bunch of
                    //                  white-space, then a really long word!
                    // 
                    //      SUB-CASE 2: There are multiple words before the word that causes the
                    //                  over-run.  This, theoretically, should be the most
                    //                  common "Over-run Case"!  Easy to handle: wrap the very last
                    //                  word onto the next line!

                    else
                    {
                        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                        // This situation has two possible ways to handle it, explained above
                        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

                        final int mostLeftWS =
                            WrapHelpers.lastLeftWhiteSpace(s, start, firstLeftWS);
    
                        // System.out.println("    mostLeftWS: " + mostLeftWS);


                        // One very long White-Sace, followed by one very long word.
                        // ==> BREAK UP THAT WORD.  NO OTHER OPTIONS!

                        if (mostLeftWS == start)
                        {
                            /*
                            System.out.println(
                                "    SUB-CASE: mostLeftWS == start" +
                                WrapHelpers.SP(start, pos)
                            );
                            */

                            insertStr = s.substring(start, pos);
                            start = pos;
                        }


                        // Theoretically, this is the most common of the "over-run" cases.  Some
                        // words, but the very last word needs to be wrapped to the next line.

                        else
                        {
                            /*
                            System.out.println(
                                "    SUB-CASE: else MOST COMMON OVER-RUN CASE!" +
                                WrapHelpers.SP(start, pos)
                            );
                            */

                            insertStr = s.substring(start, mostLeftWS);
                            start = firstLeftWS + 1;
                        }
                    }
                }
            }

            /*
            System.out.println(
                "    INSERTING:\n" +
                "        insertStr: [" + insertStr.replace("\n", "\\n") + "]\n" +
                "        start=" + start + ", end=" + end
            );
            */


            // FINISH THIS LATER
            // if (wrapped && indentWrappedLines)
            // {
            //     sb.append("    ");
            //     wrapped = false;
            // }

            sb.append(insertStr + '\n');

            // Because of the Loop's Post-Increment, subract one from 'start' here
            pos = start - 1;

            // No characters added to the current line yet!
            curLineLen  = 0;

            /*
            System.out.println(
                "*** *** *** *** *** ***\n" +
                "INSERTED NEW SUBSTRING!\n" +
                "*** *** *** *** *** ***\n"
            );
            */
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // The "Tail" or the "Trailing-Write"
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        final String lastInsertStr;

        if (s.charAt(LEN-1) == ' ')
        {
            end = WrapHelpers.backupSpaces_AKA_RightTrimCurLine(s, start, LEN-1);
            lastInsertStr = s.substring(start, end);
        }

        else lastInsertStr = s.substring(start);

        /*
        System.out.println(
            "LAST-INSERTING STR IS:\n" +
            "    lastInsertStr: [" + lastInsertStr.replace("\n", "\\n") + "]\n" +
            "    start=" + start
        );
        */

        if (lastInsertStr.length() > 0) sb.append(lastInsertStr);

        else
        {
            if (    (! WrapHelpers.lastLineIsNewLine(s, LEN))
                &&  (sb.length() > 0)
                &&  (sb.charAt(sb.length() - 1) == '\n')
            )
                sb.deleteCharAt(sb.length() - 1);
        }

        return sb.toString();
    }
}