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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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 WrapToIndentationPlus
{
    static String wrap(
            final String    s,
            final int       firstLineLen,
            final int       lineLen,
            final int       extraSpaces
        )
    {
        if (firstLineLen < 0) throw new IllegalArgumentException(
            "You have passed [" + firstLineLen + "] to firstLineLen.  " +
            "This value may not be negative."
        );

        // Maybe this is stupid - I am not sure right now.
        if (firstLineLen > 1000) throw new IllegalArgumentException(
            "You have passed [" + firstLineLen + "] to firstLineLen.  " +
            "This value may not be be greater than 1000."
        );

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

        // Maybe this is stupid - I am not sure right now.
        if (lineLen > 1000) throw new IllegalArgumentException(
            "You have passed [" + lineLen + "] to lineLen.  " +
            "This value may not be be greater than 1000."
        );

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

        if (extraSpaces > 1000) throw new IllegalArgumentException(
            "You have passed [" + extraSpaces + "] to lineLen.  " +
            "This value may not be be greater than 1000."
        );


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


        // These two fields are the "Main Difference" between this class, and the class
        // "WrapToIndentation" (without the word 'Plus' at the end!)
        // 
        // YES, there is a copy made of the "extraSpaces" input Parameter!  BECAUSE it is a final
        // constant that never changes throughout the entire life of this method-invocation,
        // therefore it looks better in ALL-CAPS, so that's why.

        final String    EXTRA_SPACE         = StringParse.nChars(' ', extraSpaces);
        final int       NUM_EXTRA_SPACES    = extraSpaces;

        if (LEN == 0) return s;

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


        // These keep track of the previous Line-Insert Operation so that when a line is broken up
        // by the "Wrap" Logic, the number of space-characters that are inserted at the beginning
        // of the Inserted-Line is directly equal to the number of Space-Characters that were 
        // inserted into the line directly above it.
    
        String  prevLineIndentation = "";
        boolean prevLineHadOverrun  = false;

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

        for (int pos=0; pos < LEN; pos++, curLineLen++)
        {
            // These are both assigned inside the loop (and assigned only once)
            final String    insertStr;
            final boolean   hadOverrun;

            // Assigned here
            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;
                hadOverrun  = 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 are 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 question reaches its closing-new line!
                    // 
                    // Specifically, if the "over-run" location occurs on a White-Space Character,
                    // but the only characters after the over-run location are just more spaces,
                    // THEN-AND-ONLY-THEN is the next if-branch (below) necessary.
                    // 
                    // This if-statement **COULD** theoretically be inserted into the method
                    // "skipSpacesTowardsNextLine" - but that method's name explains what it does
                    // pretty clearly.  As such, it seems better to keep the 'start++' here
                    // 
                    // NOTE: the subsequent line `hadOverrun = false` was just added after the 
                    //       writing of the above comment.
                    // 
                    // In all cases that have run past the LOC:
                    // 
                    // if (curLineLen <= lineLen) continue;
                    // 
                    // 'hadOverrun' MUST be TRUE!!  **EXCEPT** for this one particular situation
                    // where White-Space Characters are the only overrun.

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


                    // There was an overrun, and since the next non-space character **AFTER**
                    // the overrun was not a new-line '\n', then it must either be End-Of-String, 
                    // or Wrap is about to happen (meaning that there **WAS** an overrun!)
                    // 
                    // Note that if the above loop terminated because the end of the string was
                    // reached, then it really doesn't matter what is assigned to this variable.
                    // It's not going to be used!
                    // 
                    // NOTE: For that reason, the next line very-well could be:
                    // 
                    // else hadOverrun = (start < LEN);
                    // 
                    // **BUT** it is completely irrelevant

                    else hadOverrun = true;
                }

                // CASE 2: A printable non-space character is at the "Over-run"
                else 
                {
                    // No matter what happens, an artificially added line-break is about to be
                    // inserted into the User's String.  At this point in this Loop-Body, there is
                    // now (with certainty) going to be a brand-new / "extra" new-line '\n'
                    // character inserted, that actually/really wasn't present within the original
                    // String that the user passed to this method.  That part is a given.
                    // 
                    // From this point forward, the only decision to make is **WHERE** that break 
                    // is going to occur, and if / when the Right-Trim of space is going to happen.

                    hadOverrun = true;

                    // 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
            );
            */


            // ??? Decembet 2024: I no longer know what this if-statement was supposed to be about
            // 
            // FINISH THIS LATER ???
            // 
            // if (wrapped && indentWrappedLines)
            // {
            //     sb.append("    ");
            //     wrapped = false;
            // }


            // The first 'if-statement' branch below means that the line being appended was
            // actually a line which was broken-off from the previous line.  It is important to
            // note that any line which was broken off from the previous one **BECAUSE** of a 
            // Wrap-Operation will not contain **ANY** leading space characters.
            // 
            // December 2024: The above statement is true (I remember writing this 2 months ago)
            // because 'insertStr' is extracted from the User's Input-String in a precise way such
            // that any and all Space-Characters are skipped immediately before the Sub-String 
            // Operation which builds 'insertStr' can be applied.

            if (prevLineHadOverrun)
                sb.append(prevLineIndentation + EXTRA_SPACE + insertStr + '\n');

            else
            {
                sb.append(insertStr + '\n');
                prevLineIndentation = WrapHelpers.getIndentationAmount(insertStr);
            }
 

            // At the end of the loop, after the most recent line of text has been inserted into
            // the output StringBuilder, the 'currentLineLen' has to be zero.  
            // 
            // If, however, a Line-Break / Overrun occured, then for the purposes of the 
            // calculations in this loop (above, at top), then 'curLineLen' has to be initialized
            // with the number of Space-Characters (' ') that are going to be inserted the next
            // time a String Line-Of-Text is inserted into the StringBuilder

            curLineLen  = hadOverrun ? (NUM_EXTRA_SPACES + prevLineIndentation.length()) : 0;


            // There is a 'hadOverrun' and a 'prevLineHadOverrun'
            // Both of these values need to be maintained in memory, simultaneously.
            // This is hopefully obvious

            prevLineHadOverrun = hadOverrun;

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

            /*
            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)
        {
            if (prevLineHadOverrun) sb.append(prevLineIndentation + EXTRA_SPACE + lastInsertStr);
            else                    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();
    }
}