Package Torello.Java

Class StrIndent


  • public class StrIndent
    extends java.lang.Object
    A class for indenting, unindenting and trimming textual-strings.

    This class performs several text-indentation and code-indentation functions. The specifics of indenting text (or un-indenting) is somewhat varied, and better explained in each of the methods themselves. The one function 'chompCallableBraces' is used by the JavaDoc tool of this JAR Package, and really just prepares a method body for syntax hilighting.

    The trim-left and right methods remove white-space from each line of text contained within an input-String. The indent methods right shift (add / append) each line of text within an input-String by pre-pending tabs or space characters.



    Stateless Class:
    This class neither contains any program-state, nor can it be instantiated. The @StaticFunctional Annotation may also be called 'The Spaghetti Report'. Static-Functional classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's @Stateless Annotation.

    • 1 Constructor(s), 1 declared private, zero-argument constructor
    • 15 Method(s), 15 declared static
    • 6 Field(s), 6 declared static, 5 declared final
    • Fields excused from final modifier (with explanation):
      Field 'INDENTATION_COUNTER' is not final. Reason: DEBUGGING


    • Method Summary

       
      Basic Text Indentation
      Modifier and Type Method
      static String indent​(String s, int n)
      This performs a variation of "indentation" on a Java String - simply put - it replaces each new-line character ('\n') with a String that begins with a new-line, and is followed by 'n' blank white-space characters ' '.
      static String indent​(String s, int n, boolean spaceOrTab, boolean trimBlankLines)
      This method replaces all '\n' characters with pre-pended white-space indentation, similar to the other two methods of the same name.
      static String indentAfter2ndLine​(String s, int n, boolean spaceOrTab, boolean trimBlankLines)
      Performs an indenting of String of text, but does not indent the first line.
      static String indentTabs​(String s, int n)
      Identical to indent(String, int), but pre-pends a TAB character 'n' times, rather than a space-character ' '.
       
      String-Trim Text Methods
      Modifier and Type Method
      static String leftTrimAll​(String s)
      Will iterate through each line of text within the input String-parameter 's', and left-trim the lines.
      static String rightTrimAll​(String s)
      Will iterate through each line of text within the input String-parameter 's', and right-trim the lines.
      static String trimWhiteSpaceOnlyLines​(String s)
      Replaces sub-strings that contain a newline character followed by only white-space with only the new-line character itself.
       
      Source Code Indentation
      Modifier and Type Method
      static String chompCallableBraces​(String callableAsStr)
      This method expects to receive a method body, constructor body, or other callable body as a String; it will remove the beginning and ending braces ('{' & '}'), and beginning & ending empty lines.
      static int computeEffectiveLeadingWhiteSpace​(char[] code, int lineFirstCharacterPos, int spacesPerTab)
      Helper Method for calculating the number of space characters to be used at the beginning of a line of code, all the while obeying a particular tabs-policy.
      static String lineOfCodeAsStr​(char[] code, int numLeadingSpaces, int fcPos, int spacesPerTab)
      Replaces tab-characters ('\t') in a single-line of source-code with a relative-number of space-characters (' ').
      static String setCodeIndent​(String codeAsStr, int requestedIndent)
      Accepts a method body as a String and left-shifts or right-shifts each line of text (each 'Line of Code' - LOC) so that the indentation is consistent with the requested-indentation input-parameter.
      static String setCodeIndent_WithTabsPolicyAbsolute​(String codeAsStr, int requestedIndent, String SPACES)
      Convenience Method.
      static String setCodeIndent_WithTabsPolicyRelative​(String codeAsStr, int requestedIndent, int spacesPerTab)
      Adjusts code-indentation using a relative-sized tab-policy.
      static String tabsToSpace​(String javaSrcFileAsStr, int numSpacesPerTab)
      This will replaced leading tabs for each line of text in a source code file with a specified number of spaces.
       
      Unindent Text
      Modifier and Type Method
      static String unIndent​(String s, int n, boolean trimBlankLines, boolean rightTrimLines, boolean throwOnTab, boolean throwOnNotEnough, boolean dontThrowOnWhiteSpaceOnlyLines)
      Throws a new ToDoException
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • trimWhiteSpaceOnlyLines

        🡇     🗕  🗗  🗖
        public static java.lang.String trimWhiteSpaceOnlyLines​(java.lang.String s)
        Replaces sub-strings that contain a newline character followed by only white-space with only the new-line character itself.
        Parameters:
        s - Any Java String, but preferrably one which contains newline characters ('\n'), and white-space characters immediately followng the newline, but not other ASCII nor UNICODE.
        Returns:
        The same String with each instance of ^[ \t]+\n replaced by '\n'.
        Code:
        Exact Method Body:
         Matcher m = EMPTY_LINE.matcher(s);
         return m.replaceAll("\n");
        
      • rightTrimAll

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String rightTrimAll​(java.lang.String s)
        Will iterate through each line of text within the input String-parameter 's', and right-trim the lines. "Right Trim" means to remove all white-space characters that occur after the last non-white-space character on the line. (Does not remove the new-line character ('\n') itself).

        NOTE: Any line of text which contains only white-space characters is reduced to a single new-line character.
        Parameters:
        s - Any Java String, preferrably one with several new-line characters.
        Returns:
        The same text, but only after having any 'trailing white-space' characters removed from each line of text.
        Code:
        Exact Method Body:
         // SPECIAL-CASE: There is
         if (s.length() == 0) return s;
        
         char[]  cArr        = s.toCharArray();
         int     targetPos   = 0;
         int     nlPos       = 0;
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Set up the Loop Variables 'nlPos' and 'targetPos'
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         // SKIP: Skip past all leading new-lines.  They don't need to be moved at all in the loop!
         for (nlPos=0; (nlPos < cArr.length) && (cArr[nlPos] == '\n'); nlPos++);
        
         // SPECIAL-CASE: The String had **ONLY** new-lines in it...
         if (nlPos == cArr.length) return s;
        
         // IF THERE WERE LEADING NEWLINES:
         // AFTER-LOOP:  'nlPos' will be pointing at the character IMMEDIATELY-AFTER the last
         //              leading newline.
         // NOTE:        IF there WERE NOT leading newlines, 'nlPos' is ZERO,
         //              which is just fine for assigning to 'targetPos' anyway!
         targetPos = nlPos;
        
         // Continue to initialize 'nlPos' and 'targetPos'
         // PART ONE: Find the FIRST new-line AFTER the first CONTENT-CONTAINING line.
         // PART TWO: Set 'targetPos' to the last character that is non-white-space.  'targetPos'
         //           will be incremented-by-one later to point to white-space.
         while ((++nlPos < cArr.length) && (cArr[nlPos] != '\n'))
             if (! Character.isWhitespace(cArr[nlPos]))
                 targetPos = nlPos;
        
         // Now increment 'targetPos' because in MOST-CASES it will be pointing to the last
         // non-white-space character in the first line.  (and we *CANNOT* clobber that character!)
         // HOWEVER: if 'targetPos' is still pointing at White-Space (after the previous loop),
         //          then it must be that the ENTIRE-FIRST-LINE was BLANK!
         if (! Character.isWhitespace(cArr[targetPos])) targetPos++;
        
         // SPECIAL-CASE: The first CONTENT-FUL LINE is the ONLY-LINE in the text.
         //          ===> Return the input-String.
         //               **BUT** make sure to right-trim that CONTENT-FUL line.
         if (nlPos == cArr.length) return s.substring(0, targetPos);
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Now do the 'Shifting Loop'
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         while (nlPos < cArr.length)
         {
             int nextNLPos               = nlPos + 1;
             int lastNonWhiteSpacePos    = nlPos;
             int sourcePos               = nlPos;
        
             // Compute 'nextNLPos' and 'lastNonWhiteSpacePos': In the Example *SUBSTRING* Below:
             // "...\nHello, How are you?   \n..."
             //
             // NEW-LINE-POS was set to the first '\n' you see in the above-String
             // The '?' is the LAST-NON-WHITE-SPACE
             // The '\n' after that is the NEXT-NEWLINE-POS
             while ((nextNLPos < cArr.length) && (cArr[nextNLPos] != '\n'))
             {
                 if (! Character.isWhitespace(cArr[nextNLPos]))
                     lastNonWhiteSpacePos = nextNLPos;
                 nextNLPos++;
             }
        
             // Shift all characters BEGINNING with the OLD new-line position (since 'sourcePos')
             // is initiliazed with 'nlPos') ... 
             // 
             // AGAIN: Shift all characters beginning with 'nlPos' UP-TO-AND-INCLUDING
             // 'lastNonWhiteSpacePos' for the NEXT line of text to the appropriate position.
             while (sourcePos <= lastNonWhiteSpacePos) cArr[targetPos++] = cArr[sourcePos++];
        
             // The next loop-iteration will start with the next line in the text.
             nlPos = nextNLPos;
         }
        
         return new String(cArr, 0, targetPos);
        
      • leftTrimAll

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String leftTrimAll​(java.lang.String s)
        Will iterate through each line of text within the input String-parameter 's', and left-trim the lines. "Left Trim" means to remove all white-space characters that occur before the last non-white-space character on the line. (Does not remove the new-line character ('\n') itself).

        NOTE: Any line of text which contains only white-space characters is reduced to a single new-line character.
        Parameters:
        s - Any Java String, preferrably one with several new-line characters.
        Returns:
        The same text, but only after having any 'leading white-space' characters removed from each line of text.
        Code:
        Exact Method Body:
         char[] cArr = s.toCharArray();
        
         // LEFT TRIM is easier on the mind.  There are only two variables needed for this one.
         int targetPos = 0;
         int sourcePos = 0;
        
         // Make sure to skip completely any and all leading new-line characters.
         while ((targetPos < cArr.length) && (cArr[targetPos] == '\n')) targetPos++;
        
         // If there were **ONLY** leading new-line characters, return the original string
         if (targetPos == cArr.length) return s;
        
         // Re-initialize 'sourcePos'
         sourcePos = targetPos;
        
         while (sourcePos < cArr.length)
         {
             // When this loop begins, sourcePos is pointing at the first character of text
             // in the very-next line-of-text to process.
             //
             // NORMAL EXECUTION:    This loop advances 'sourcePos' to the first non-white-space
             //                      character in the line.
             // WS-ONLY LINES CASE:  This loop advances 'sourcePos' to the next line ('\n')
             // LAST-LINE CASE:      Advances 'sourcePos' to cArr.length
             while (     (sourcePos < cArr.length)
                     &&  Character.isWhitespace(cArr[sourcePos])
                     &&  (cArr[sourcePos] != '\n')
                 )
                 sourcePos++;
        
             // Left Shift the String to 'erase' all leading white-space characters in the
             // current line of text.
             while ((sourcePos < cArr.length) && (cArr[sourcePos] != '\n'))
                 cArr[targetPos++] = cArr[sourcePos++];
        
             // The loop that is directly above this statement BREAKS when '\n' is reached,
             // so unless the end of the String has been reached, shift one more of the characters
             // NOTE: If a character is shifted, below, it will always be the '\n' character
             if (sourcePos < cArr.length) cArr[targetPos++] = cArr[sourcePos++];
         }
        
         return new String(cArr, 0, targetPos);
        
      • chompCallableBraces

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String chompCallableBraces​
                    (java.lang.String callableAsStr)
        
        This method expects to receive a method body, constructor body, or other callable body as a String; it will remove the beginning and ending braces ('{' & '}'), and beginning & ending empty lines. This is to prepare the method for code hiliting, used internally by the package Torello.JavaDoc.
        Parameters:
        callableAsStr - This should be a method body. Make sure **NOT TO INCLUDE** the method signature at the beginning of the method. The first non-white-space character should be the open braces character ('{'), and the last non-white-space should be the closing braces character ('&#125').
        Returns:
        A method body String that can be hilited using the code-hiliting mechanism of the "JavaDoc Package."
        Throws:
        CallableBodyException - If the input parameter String does not begin and end with the curly-braces.
        Code:
        Exact Method Body:
         callableAsStr = callableAsStr.trim();
        
         if (callableAsStr.charAt(0) != '{') throw new CallableBodyException(
             "Passed callable does not begin with a squiggly-brace '{', but rather a: '" + 
             callableAsStr.charAt(0) + "'\n" + callableAsStr
         );
        
         if (callableAsStr.charAt(callableAsStr.length() - 1) != '}') throw new CallableBodyException(
             "Passed callable does not end with a squiggly-brace '}', but rather a: '" + 
             callableAsStr.charAt(0) + "'\n"+ callableAsStr
         );
        
         // This Version does a single "String.substring(...)", meaning it is more efficient
         // because it is not doing any extra String copies at all.
         //
         // NOTE: There is an auto-pre-increment (and pre-decrement), in both of the while loops.
         //       Therefore, sPos starts at 'zero' - even though the open-curly-brace is the 
         //       character at position 0, and the closed-curly-brace is at position length-1.
        
         int     sPos    = 0;
         int     ePos    = callableAsStr.length() - 1;
         int     first   = 1;    // The character after the '{' (open-curly-brace)
         char    tempCh  = 0;    // temp-var
        
         // If the callable-braces are on their own line, skip that first line.
         // If they are **NOTE** on their own first line, the first character returned will be
         // the first character of source-code.
        
         while ((sPos < ePos) && Character.isWhitespace(tempCh = callableAsStr.charAt(++sPos)))
        
             if (tempCh == '\n')
             {
                 first = sPos + 1;
                 break;
             }
        
         // Check for the "bizarre case" that the method body just doesn't contain any code.
         // This means that *EVERY CHARACTER* that was checked was white-space.  Return a single
         // space character, and be done with it.
        
         if (sPos == ePos) return " ";
        
         // When this loop terminates, 'ePos' will be pointing to the first non-white-space
         // character at the tail end of the source-code / String (callableAsStr is a String of
         // source-code used in the JavaDoc package)
        
         while ((ePos > sPos) && Character.isWhitespace(callableAsStr.charAt(--ePos)));
                
         // Starts at the 'first-white-space' character in the first line of code, and ends at the
         // last non-white-space character in source-code String 'callableAsStr'
        
         return callableAsStr.substring(first, ePos + 1);
        
      • setCodeIndent

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String setCodeIndent​(java.lang.String codeAsStr,
                                                     int requestedIndent)
        Accepts a method body as a String and left-shifts or right-shifts each line of text (each 'Line of Code' - LOC) so that the indentation is consistent with the requested-indentation input-parameter.

        NOTE: The lines of code contained by input-parameter 'codeAsStr' must contain leading white-space without any tab ('\t') characters. The reasoning here is that tabs can be interpreted in many different ways, and therefore it is required to replace them before invoking this method. This method merely adds or removes leading ASCII 0x20 (space-bar characters) from the beginning of each line of text. A leading tab-character ASCII 0x09 will generate an exception throw.
        Parameters:
        codeAsStr - A method body. It is expected to be the internal part of a chunk of source code.
        requestedIndent - The requested amount of indentation for the method-body. The line of code that contains the shortest amount of indentation (white-space) will be calculated, and then all LOC's shall be left-shifted (or right-shifted) according to that LOC which contained the least amount of leading white-space.
        Returns:
        An updated method-body as a String.
        Throws:
        StringFormatException - This exception shall throw whenever a line of text contained by the input String has a '\t' (tab-character) before the first non-white-space character on that line of text. Code that contains tab-characters is invariably "auto-indented" by the Code-Editor when loaded into the GUI, and the amount of indentation applied for each tab-character is usually configurable. Because there are many variants of how tab's '\t' gets interpreted by the editor, it is required to replace these characters first before invoking this method.
        Code:
        Exact Method Body:
         if (requestedIndent < 0) throw new IllegalArgumentException
             ("The requested indent passed to this method was a negative value: " + requestedIndent);
        
         else if (requestedIndent > 80) throw new IllegalArgumentException
             ("The requested indent passed to this method was greater than 80: " + requestedIndent);
        
         // Source-Code-String to char-array
         char[] cArr = codeAsStr.toCharArray();
        
         // Code "Starts With New Line '\n'"
         boolean swNL = cArr[0] == '\n';
        
         // Code "Ends With New Line"            
         boolean ewNL = cArr[cArr.length - 1] == '\n';
        
         // Location of each '\n' in the code
         int[] nlPosArr = StrIndexOf.all(codeAsStr, '\n');
        
         // Unless the first character in the code is '\n', numLines - num '\n' + 1
         int numLines = nlPosArr.length + (swNL ? 0 : 1);
        
         // Length of "Leading White Space" for each line of code
         int[] wsLenArr = new int[numLines];
        
         // TRUE / FALSE for "only white-space" lines of code
         boolean[] isOnlyWSArr = new boolean[numLines];
        
         // Amount of White-Space for the LEAST-INDENTED Line of Code
         int minIndent = Integer.MAX_VALUE;
        
         // These three variables are loop-control and temporary variables.
         int wsCount     = 0;    // "White Space Count" - amount of WS on each line
         int outArrPos   = 0;    // There are two parallel "Output Arrays", this the index
         int lastPos     = 0;    // Temp Var for the last-index in a line of code
        
         int i;                  // Simple Loop Control Variable
         int j;                  // Simple Loop Control Variable
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Compute amount of "leading white space" (indentation) for the first LOC in input-String
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         // Count the leading white-space in the first line of text - unless the first character
         // in the code was a '\n' (newline)
        
         if (! swNL)
         {
             // The array-index in array cArr of the last character in the first line of text.
             // If the input code-String is just a single line of code without any newline '\n'
             // characters, then this value is the length of the code-string.  Otherwise, this
             // value is assigned the cArr index/position of the first newline '\n' character.
        
             lastPos = (nlPosArr.length > 0) ? nlPosArr[0] : cArr.length;
        
             // The loop iterate until we reach the end of the first line of code/text, or
             // we reach a character that is not white-space.
        
             for (i=0; (i < lastPos) && Character.isWhitespace(cArr[i]); i++)
                 if (cArr[i] == '\t')    throw new StringFormatException(STR_FORMAT_EX_MESSAGE);
                 else                    wsCount++;
        
             // Amount of "Leading" white-space (indentation) for first LOC
             wsLenArr[0] = wsCount;
        
             // Was the first line only white-space?
             isOnlyWSArr[0] = (i == lastPos);
        
             // 'minIndent' was initialized to Integer.MAX_VALUE
             minIndent = wsCount;
        
             outArrPos++;
         }
        
        
         // ****************************************************************************************
         // Compute the amount of "leading white space" (indentation) for each LOC in input-String
         // ****************************************************************************************
         //
         // This loop will iterate each line of code inside the input source-code character-array
         // The length (number of characters) for the "leading white-space" (Which may also be called
         // indentation) for each LOC is stored in an integer-array called "wsLenArr"
         // When this loop encounters a line that is blank (contains only white-space), it is noted
         // in a boolean array "isOnlyWSArr"
         //
         // NOTE: The previous loop did the *EXACT SAME THING*, but ONLY for the first line of code
         //       in the input-string.  This is because the loop-control variables are slightly
         //       different for the first line of code.
        
         for (i=0; i < nlPosArr.length; i++)
         {
             wsCount = 0;
             lastPos = (i < (nlPosArr.length-1)) ? nlPosArr[i+1] : cArr.length;
        
             for (j = (nlPosArr[i]+1); (j < lastPos) && Character.isWhitespace(cArr[j]); j++)
                 if (cArr[j] == '\t')    throw new StringFormatException(STR_FORMAT_EX_MESSAGE);
                 else                    wsCount++;
        
             // Amount of "Leading" white-space (indentation) for current LOC
             wsLenArr[outArrPos] = wsCount;
        
             // Is the current LOC only white-space?
             isOnlyWSArr[outArrPos] = (j == lastPos);
        
             // Check if this line is the "reigning champion" of minimum of white-space indentation
             // Blank lines (lines with 'only white-space') cannot be factored into the
             // "minimum indentation" computation
        
             if (wsCount < minIndent) if (! isOnlyWSArr[outArrPos]) minIndent = wsCount;
                    
             outArrPos++;
         }
        
        
         // ****************************************************************************************
         // Now we will shorten or extend the amount of indentation for the input code snippet.
         // ****************************************************************************************
         //
         // *** Keep Here for Reference ***
         // int[]        nlPosArr    // Location of each '\n' in the code
         // int[]        wsLenArr    // Length of "Leading White Space" for each line of code
         // boolean[]    isOnlyWSArr // TRUE / FALSE for "only white-space" lines of code
        
         int diff        = requestedIndent - minIndent;
         int delta       = 0;    // Intended to store the change in "Source Code as a String" LENGTH
                                 // after performing the indentation changes
         int nextNLPos   = 0;    // Position of the next newline
         int srcPos      = 0;    // index/pointer to the input "Source Code as a String" char-array
         int destPos     = 0;    // index/pointer to (output) indentation-change output char-array
         int nlPosArrPos = 0;    // index/pointer to the "New Line Position Array"
         int otherArrPos = 0;    // index/pointer to the other 2 position arrays
                                 // a.k.a:   "White-Space-Length Array" and the
                                 //          "Is Only White-Space Array"
        
         if (diff == 0) return codeAsStr;
        
         for (i=0; i < wsLenArr.length; i++) if (! isOnlyWSArr[i]) delta += diff;
        
         char[]  outArr  = new char[cArr.length + delta];
        
         if (diff > 0)
             return indent(codeAsStr, diff, true, true);
         else
         {
             // We are removing white-space, start at end, work backwards
             srcPos = cArr.length - 1;
        
             // The "output array", therefore, also starts at end of char-array
             destPos     = outArr.length - 1;
        
             // The "Where are the newlines array" index-pointer
             nlPosArrPos = nlPosArr.length - 1;
        
             otherArrPos = wsLenArr.length - 1;
                 // The number of "lines of text" and "number of new-lines"
                 // are *NOT NECESSARILY* identical.  The former might be
                 // longer by *PRECISELY ONE* array-element.
        
             for (; otherArrPos >= 0; otherArrPos--)
             {
                 // Check if the first character in the Source-Code String is a newline.
                 nextNLPos = (nlPosArrPos >= 0) ? nlPosArr[nlPosArrPos--] : -1;
        
                 // Lines of Source Code that are only white-space shall simply be copied to
                 // the destination/output char-array.
                 if (isOnlyWSArr[otherArrPos])
                     while (srcPos >= nextNLPos) outArr[destPos--] = cArr[srcPos--];
        
                 else
                 {
                     // Copy the line of source code
                     int numChars = srcPos - nextNLPos - wsLenArr[otherArrPos];
                     while (numChars-- > 0) outArr[destPos--] = cArr[srcPos--];
        
                     // Insert the exact amount of space-characters indentation
                     numChars = wsLenArr[otherArrPos] + diff;
                     while (numChars-- > 0) outArr[destPos--] = ' ';
        
                     // Skip over the original indentation (white-space) from the input line
                     // of source-code.
                     srcPos -= (wsLenArr[otherArrPos] + 1);
        
                     // Make sure to insert a new-line (since this character WASN'T copied)
                     if (destPos >= 0) outArr[destPos--] = '\n';
                 }
             }
         }
        
        
         // ****************************************************************************************
         // Debug Println - This code isn't executed without the little debug-flag being set.
         // ****************************************************************************************
        
         // The returned code block is ready; convert to a String
         String ret = new String(outArr);
        
         // Do not delete.  Writing the debugging information takes a lot of thought.
         // If there is ever an error, this code is quite important.
        
         if (! DEBUGGING_INDENTATION) return ret;
        
         try
         {
             StringBuilder sb = new StringBuilder();
        
             sb.append(
                 "swNL:\t\t\t\t"         + swNL              + '\n' +
                 "ewNL:\t\t\t\t"         + ewNL              + '\n' +
                 "numLines:\t\t\t"       + numLines          + '\n' +
                 "minIndent:\t\t\t"      + minIndent         + '\n' +
                 "requestedIndent:\t"    + requestedIndent   + '\n' +
                 "diff:\t\t\t\t"         + diff              + '\n' +
                 "delta:\t\t\t\t"        + delta             + '\n' +
                 "nlPosArr:\n\t"
             );
        
             for (i=0; i < nlPosArr.length; i++) sb.append(nlPosArr[i] + ", ");
             sb.append("\nwsLenArr:\n\t");
             for (i=0; i < wsLenArr.length; i++) sb.append(wsLenArr[i] + ", ");
             sb.append("\nisOnlyWSArr:\n\t");
             for (i=0; i < isOnlyWSArr.length; i++) sb.append(isOnlyWSArr[i] + ", ");
             sb.append("\n");
        
             FileRW.writeFile(
                 sb.toString() + "\n\n****************************************************\n\n" + 
                 codeAsStr + "\n\n****************************************************\n\n" +
                 ret,
                 "TEMP/method" + StringParse.zeroPad10e2(++INDENTATION_COUNTER) + ".txt"
             );
        
             if (INDENTATION_COUNTER == 5) System.exit(0);
        
         } catch (Exception e)
         {
             e.printStackTrace();
             System.out.println(e + "\n\nFatal Error. Exiting.");
             System.exit(0);
         }
        
         return ret;
        
      • setCodeIndent_WithTabsPolicyRelative

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String setCodeIndent_WithTabsPolicyRelative​
                    (java.lang.String codeAsStr,
                     int requestedIndent,
                     int spacesPerTab)
        
        Adjusts code-indentation using a relative-sized tab-policy. This method performs the equivalent of shifting the entire text-block, proportionately, to the left or right.

        To do this, first, the number of spaces that preceed the least-indented line is computed, and afterwards, every line in the text is shifted by an identical number of space-characters. The number of spaces that are either added or removed from each line is dependent on whether the requested indentation (parameter 'requestedIndent') is greater-than or less-than the computed least-indented line.

        The term relative used to mean that whenever a tab is encountered, the number of spaces added is equal to the distance to the next integral-multiple of the spacesPerTab-characters in the line.
        For instance, if a tab-character were found at character-index 10 in the input array, and if 'spacesPerTab' were passed 4, then precisely 2 space-characters would be inserted - since 12 is the next integral-multiple of 4.
        Parameters:
        codeAsStr - Any Java source-code block, as a java.lang.String
        requestedIndent - The number of spaces that the code should have as indentation. Note, that in the JavaDoc Upgrader code, this number is always '1'.
        spacesPerTab - If tabs are found inside this String, then they are replaced with an appropriate number of space characters, according to a relative tab-policy, as described above.
        Returns:
        A properly shifted-indented Java source-code block.
        Code:
        Exact Method Body:
         char[]              code    = codeAsStr.toCharArray();
         IntStream.Builder   b       = IntStream.builder();
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // First find all of the line-breaks / new-lines.
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         //
         // NOTE: If the first character is not a new-line, then the first line is presumed to begin
         //       at String-index '-1'
         //
         // Afterwards, convert the Stream to 'nlPos' array.  Build two other arrays
        
         if (code[0] != '\n') b.accept(-1);
        
         for (int i=0; i < code.length; i++) if (code[i] == '\n') b.accept(i);
        
         int[]   nlPos       = b.build().toArray();
         int[]   wsLen       = new int[nlPos.length];
         int[]   fcPos       = new int[nlPos.length];
         int     maxIndent   = 0;
         int     minIndent   = Integer.MAX_VALUE;
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Compute how much white-space is currently at the start of each line
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         //
         // NOTE: Since this method calculates what the user is looking at in his code-editor, the
         //       tabs-policy needs to be included in the calculation.
         //
         // Once the amount of white-space at the start of each line is computed, it will be easy
         // to shift the entire source-code left or right.  Note that in the JavaDoc Upgrader Tool,
         // this is always shifted until the **LEAST INDENTED** line is indented by 1...
         //
         // REMEMBER: Shifting everything left must be a shift of an **EQUAL NUMBER OF SPACES** for
         //           each line that is shifted.
        
         for (int i=0; i < wsLen.length; i++)
         {
             int     END     = (i == (nlPos.length - 1)) ? code.length : nlPos[i+1];
             boolean hasCode = false;
        
             INNER:
             for (int j = (nlPos[i] + 1); j < END; j++)
        
                 if (! Character.isWhitespace(code[j]))
                 {
                     fcPos[i]    = j;
                     hasCode     = true;
        
                     break INNER;
                 }
        
             if (! hasCode) fcPos[i] = wsLen[i] = -1;
        
             else
             {
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 // wsLen[i] = computeEffectiveLeadingWhiteSpace(code, nlPos[i] + 1, spacesPerTab);
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 //
                 // NOTE: The contents of everything within this 'else' branch is nothing more than
                 //       an inline block-copy of the method named in the comment above.  Hopefully
                 //       inlining the method will speed this up a little bit.
                 //
                 // The values that would be passed before the method was inlined, here, are also
                 // noted in the above comment.
                 //
                 // ALSO: The 'i' loop-variable was changed to a 'j' (to avoid conflicting with the
                 //       outer-loop 'i').  The "ret" was changed to "whiteSpaceChars"
        
                 int whiteSpaceChars = 0;
                 int relativeCount   = 0;
        
                 wsLen[i] = -1;
        
                 EFFECTIVE_LEADING_WS:
                 for (int j = (nlPos[i] + 1) /* lineFirstCharacterPos */; j < code.length; j++)
        
                     if (! Character.isWhitespace(code[j])) 
                     {
                         wsLen[j] = whiteSpaceChars; // return ret;
                         break EFFECTIVE_LEADING_WS;
                     }
        
                     else switch (code[j])
                     {
                         case ' ' : 
                             whiteSpaceChars++;
                             relativeCount = (relativeCount + 1) % spacesPerTab;
                             break;
        
                         case '\t' :
                             whiteSpaceChars += (spacesPerTab - relativeCount);
                             relativeCount = 0;
                             break;
        
                         case '\r' : 
                         case '\f' : break;
                         case '\n' : break EFFECTIVE_LEADING_WS; // return -1;
                         default: throw new UnreachableError();
                     }
        
                 // return -1;  <== Not needed, the array-location is initialized to -1
             }
        
             if (wsLen[i] == -1)        continue;
             if (wsLen[i] > maxIndent)  maxIndent = wsLen[i];
             if (wsLen[i] < minIndent)  minIndent = wsLen[i];
         }
        
         // This is the amount of space to shift each line.
         int delta = requestedIndent - minIndent;
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // NOW: Rebuild the source-code string, making sure to shift each line.
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         StringBuilder sb = new StringBuilder();
        
         for (int i=0; i < wsLen.length; i++)
        
             // The array "White-Space-Length" will have a '-1' if the entire line is nothing but
             // white-space.  In such cases, simply append a '\n' - there is no reason to add extra
             // spaces.  The code hilited just ignores it.
        
             if (wsLen[i] == -1) sb.append('\n');
        
             // Otherwise append the leading white-space, and then the line-of-code.
             else
             {
                 // First append the white-space at the beginning of the line.
                 int numSpaces = wsLen[i] + delta;
        
                 sb.append(SPACES, 0, numSpaces);
        
                 // Now append the line of code.  Since there may be tabs after the first
                 // non-white-space character, this is a little complicated...
                 //
                 // NOTE: This could be inlined, but this method just does too much...
                 //
                 // The char[]-Array 'code' has the code.  The text of the source-code begins at
                 // array-index 'First-Character-Position' (fcPos).  This method needs the parameter
                 // 'numSpaces' to make sure the tabs stay properly-relativised...
        
                 sb.append(lineOfCodeAsStr(code, numSpaces, fcPos[i], spacesPerTab));
             }
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // FINISHED: Return the Source-Code String
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         return sb.toString();
        
      • computeEffectiveLeadingWhiteSpace

        🡅  🡇     🗕  🗗  🗖
        public static int computeEffectiveLeadingWhiteSpace​
                    (char[] code,
                     int lineFirstCharacterPos,
                     int spacesPerTab)
        
        Helper Method for calculating the number of space characters to be used at the beginning of a line of code, all the while obeying a particular tabs-policy.

        IMPORTANT: None of the parameters to this method will be checked for errors. This method is often used inside of a loop, and improper input should be presumed to cause indeterminate results.
        Parameters:
        code - A Java source-code String, that has been converted into a Java char[]-Array. The line of code whose leading white-space is being computed may be located anywhere in the array.

        NOTE: These types of arrays are easily creaated by invoking the java.lang.String method 'toCharArray()'
        lineFirstCharacterPos - The array-index to be considered as the first character of non-new-line character data.
        spacesPerTab - The number of spaces that a tab-character ('\t') intends to represent.

        When FALSE is passed to this parameter, a tab-character will represent a String of space-characters whose length is equal to the number of space-characters that remain until the next modulo-spacesPerTab boundary.
        Returns:
        The number of space-characters (' ') that should preceede the line of source code.

        NOTE: If this line of source-code is a white-space ONLY line, then -1 will be returned.
        Code:
        Exact Method Body:
         int ret = 0;
         int relativeCount = 0;
        
         for (int i=lineFirstCharacterPos; i < code.length; i++)
        
             if (! Character.isWhitespace(code[i])) return ret;
        
             else switch (code[i])
             {
                 case ' ' : 
                     ret++;
                     relativeCount = (relativeCount + 1) % spacesPerTab;
                     break;
        
                 case '\t' :
                     ret += (spacesPerTab - relativeCount);
                     relativeCount = 0;
                     break;
        
                 case '\r' : 
                 case '\f' : break;
                 case '\n' : return -1;
                 default: throw new UnreachableError();
             }
        
         return -1;
        
      • lineOfCodeAsStr

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String lineOfCodeAsStr​(char[] code,
                                                       int numLeadingSpaces,
                                                       int fcPos,
                                                       int spacesPerTab)
        Replaces tab-characters ('\t') in a single-line of source-code with a relative-number of space-characters (' ').

        The term relative used to mean that whenever a tab is encountered, the number of spaces added is equal to the distance to the next integral-multiple of the spacesPerTab-characters in the line.
        For instance, if a tab-character were found at character-index 10 in the input array, and if 'spacesPerTab' were passed 4, then precisely 2 space-characters would be inserted - since 12 is the next integral-multiple of 4.

        IMPORTANT: None of the parameters to this method will be checked for errors. This method is often used inside of a loop, and improper input should be presumed to cause indeterminate results.
        Parameters:
        code - This should be the source-code, converted to a character-array. The specific line in the source-code being properly space-adjusted may be located anywhere in this array.

        NOTE: These types of arrays are easily creaated by invoking the java.lang.String method 'toCharArray()'
        numLeadingSpaces - The number of spaces that have been placed before the start of this line of code. This is needed because relative-tabs are computed based on integral-multiples of the tab-width ('spacesPerTab').

        This method is a helper & example method that may be used in conjunction with properly indenting source-code. Note that the number of leading-spaces may not be identicaly to the actual number of white-space characters in the array. After converting tab-characters ('\t') to spaces (' '), this number will often change.
        fcPos - This parameter should contain the location of the first source-code character in the line of code. This parameter should be an array-index that does not contain white-space.
        spacesPerTab - The number of spaces that are used to replaces tab-characters. Since this method performs relative tab-replacement, this constitutes the maximum number of space characters that will be used to replace a tab.
        Returns:
        A line of code, as a String, without any leading white-space, and one in which all tab-characters have been replaced by spaces.
        Code:
        Exact Method Body:
         StringBuilder sb = new StringBuilder();
        
         // Loop Control Variables
         int possibleEndingWhiteSpaceCount   = 0;
         int relativePos                     = numLeadingSpaces % spacesPerTab;
         int i                               = fcPos;
        
         while ((i < code.length) && (code[i] != '\n'))
         {
             if (code[i] == '\t')
                 while (relativePos < 4)
                     { sb.append(' '); relativePos++; possibleEndingWhiteSpaceCount++; }
        
             else if ((code[i] == ' ') || (code[i] == '\r') || (code[i] == '\f'))
             { sb.append(' '); relativePos++; possibleEndingWhiteSpaceCount++; }
        
             else
             { sb.append(code[i]); relativePos++; possibleEndingWhiteSpaceCount=0;}
        
             i++;
             relativePos %= 4;
         }
        
         if (i < code.length)
         {
             if (possibleEndingWhiteSpaceCount > 0)
             {
                 sb.setCharAt(sb.length() - possibleEndingWhiteSpaceCount, '\n');
                 return sb.substring(0, sb.length() - possibleEndingWhiteSpaceCount + 1);
             }
             else return sb.append('\n').toString();
         }
        
         return (possibleEndingWhiteSpaceCount > 0)
             ? sb.substring(0, sb.length() - possibleEndingWhiteSpaceCount)
             : sb.toString();
        
      • indent

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String indent​(java.lang.String s,
                                              int n)
        This performs a variation of "indentation" on a Java String - simply put - it replaces each new-line character ('\n') with a String that begins with a new-line, and is followed by 'n' blank white-space characters ' '. If the input String parameter 's' is of zero-length, then the zero-length String is returned. If the final character in the input String is a new-line, that new-line is not padded.
        Parameters:
        s - Any java.lang.String - preferably one that contains new-line characters.
        n - The number of white-space characters to use when pre-pending white-space to each line of text in input-parameter 's'
        Returns:
        A new java.lang.String where each line of text has been indented by 'n' blank white-space characters. If the text ends with a new-line, that line of text is not indented.
        Throws:
        NException - If parameter 'n' is less than one.
        Code:
        Exact Method Body:
         if (n < 1) throw new NException(
             "The value passed to parameter 'n' was [" + n + "], but this is expected to be an " +
             "integer greater than or equal to 1."
         );
        
         if (s.length() == 0) return "";
        
         String  padding         = String.format("%1$" + n + "s", " ");
         boolean lastIsNewLine   = s.charAt(s.length() - 1) == '\n';
        
         s = padding + s.replace("\n", "\n" + padding);
        
         return lastIsNewLine
             ? s.substring(0, s.length() - padding.length())
             : s;
        
      • indentTabs

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String indentTabs​(java.lang.String s,
                                                  int n)
        Identical to indent(String, int), but pre-pends a TAB character 'n' times, rather than a space-character ' '.
        Parameters:
        s - Any java.lang.String - preferably one that contains new-line characters.
        n - The number of tab ('\t') characters to use when pre-pending to each line of text within input-parameter 's'
        Returns:
        A new java.lang.String where each line of text has been indented by 'n' tab characters. If the text ends with a new-line, that line of text is not indented.
        Throws:
        NException - If parameter 'n' is less than one.
        Code:
        Exact Method Body:
         if (n < 1) throw new NException(
             "The value passed to parameter 'n' was [" + n + "], but this is expected to be an " +
             "integer greater than or equal to 1."
         );
        
         if (s.length() == 0) return "";
        
         String  padding         = String.format("%1$"+ n + "s", "\t");
         boolean lastIsNewLine   = s.charAt(s.length() - 1) == '\n';
        
         s = padding + s.replace("\n", "\n" + padding);
        
         return lastIsNewLine
             ? s.substring(0, s.length() - padding.length())
             : s;
        
      • indent

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String indent​(java.lang.String s,
                                              int n,
                                              boolean spaceOrTab,
                                              boolean trimBlankLines)
        This method replaces all '\n' characters with pre-pended white-space indentation, similar to the other two methods of the same name. The difference, here, and the other two functions is this one does not indent lines of text that only contain white-space!

        Example:
         // *****************************
         // VERSION 1: Identical Output
         String s1 = "Hello World!";
         
         System.out.println(indent(s1, 4));
         System.out.println(indent(s1, 4, true, true));
         // Both Print: "    Hello World!"
         
         // *****************************
         // VERSION 2: Output's differ
         String s2 = "Hello World!\n\nSincerely,\n\nCorporate Headquarters.\n";
        
         System.out.println(indent(s2, 4));
         // Prints: "    Hello World!\n    \n    Sincerely,\n    \n    Corporate Headquarters.\n"
        
         System.out.println(indent(s2, 4, true, true));
         // Prints: "    Hello World!\n\n    Sincerely,\n\n    Corporate Headquarters.\n"
         // NOTICE: Blank lines are not indented.
        
        Parameters:
        s - Any java.lang.String - preferably one that contains new-line characters.
        n - The number of tab ('\t') characters to use when pre-pending to each line of text in input-parameter 's'
        spaceOrTab - When this parameter is passed TRUE, the space character ' ' is used for indentation. When FALSE, the tab-character '\t' is used.
        Returns:
        A new java.lang.String where each line of text has been indented by 'n' characters of spaces or tabs, dependent upon the value of parameter 'spaceOrTab'.

        The returned String differs from the returns of the other two 'indent' methods in that any new-line that contains only white-space, or any new-line that is empty and is immediately-followed-by another newline, is not idented. Succinctly, only lines containing non-white-space characters are actually indented.
        Throws:
        NException - If parameter 'n' is less than one.
        Code:
        Exact Method Body:
         if (n < 1) throw new NException(
             "The value passed to parameter 'n' was [" + n + "], but this is expected to be an " +
             "integer greater than or equal to 1."
         );
        
         if (s.length() == 0) return "";
        
         final String padding = String.format("%1$"+ n + "s", spaceOrTab ? " " : "\t");
        
         // This replacement-function does a 'look-ahead'.  If the next character after a newline
         // character '\n' is *also* a '\n', then the first '\n' is left alone (not indented)
         IntCharFunction<String> replFunc = (int i, char c) ->
         {
             while (i < (s.length() - 1))
             {
                 c = s.charAt(++i);
                 if (c == '\n')                  return "\n";
                 if ((c != ' ') && (c != '\t'))  return "\n" + padding;
             }
        
             return "\n";
         };
        
         // NOTE: private static final char[] cArrIndent = { '\n' };
         String ret = StrReplace.r(s, cArrIndent, replFunc);
        
         if (trimBlankLines) ret = trimWhiteSpaceOnlyLines(ret);
        
         // Indent the first line of text - insert the padding before the final returned string.
         // NOTE: This is somewhat inefficient, because the whole array needs to be copied again.
         //       Perhaps switching to RegEx and matching '^' is better (because of this reason).
         // Special Case:    The first character, itself, is a new-line.
         return (ret.charAt(0) != '\n') ? (padding + ret) : ret;
        
      • unIndent

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String unIndent​
                    (java.lang.String s,
                     int n,
                     boolean trimBlankLines,
                     boolean rightTrimLines,
                     boolean throwOnTab,
                     boolean throwOnNotEnough,
                     boolean dontThrowOnWhiteSpaceOnlyLines)
        
        Throws a new ToDoException
        Returns:
        Will (one day) return an unindented String.
        Code:
        Exact Method Body:
         if (n < 1) throw new NException(
             "The value that was passed to parameter 'n' was [" + n + "], but unfortunately this " +
             "expected to be a positive integer, greater than zero."
         );
        
         char[] cArr = s.toCharArray();
         throw new ToDoException();
        
      • indentAfter2ndLine

        🡅  🡇     🗕  🗗  🗖
        public static java.lang.String indentAfter2ndLine​(java.lang.String s,
                                                          int n,
                                                          boolean spaceOrTab,
                                                          boolean trimBlankLines)
        Performs an indenting of String of text, but does not indent the first line. This is used quit frequently by code-generators that need to assign or invoke something, and want to make sure that subsequent lines of piece of code are indented (after the first line of text).
        Parameters:
        s - Any instance of java.lang.String.
        n - The number of space-characters to insert after each newline '\n' character.
        spaceOrTab - When TRUE, then there shall be 'n'-number of space characters (' ') inserted at the beginning of each line of text. When FALSE, then this function will insert 'n' tab characters.
        trimBlankLines - When TRUE, requests that blank lines be trimmed to only a single newline ('\n') character.
        Returns:
        The indented String
        Code:
        Exact Method Body:
         int pos = s.indexOf('\n'); // If there are no newlines, then return the original string.
         if (pos == -1) return s;
        
         pos++;
         return // return the first string, as is, and then indent subsequent lines.
             s.substring(0, pos) + 
             indent(s.substring(pos), n, spaceOrTab, trimBlankLines);
        
      • tabsToSpace

        🡅     🗕  🗗  🗖
        public static java.lang.String tabsToSpace​
                    (java.lang.String javaSrcFileAsStr,
                     int numSpacesPerTab)
        
        This will replaced leading tabs for each line of text in a source code file with a specified number of spaces. If tabs are supposed to represent 4 spaces, then if a line in a source-code file had three leading tab-characters, then those three leading char '\t' would be replaced with 12 leading space characters ' '.
        Parameters:
        javaSrcFileAsStr - A Java Source-Code File, loaded as a String.
        numSpacesPerTab - This identifies the number of spaces a char '\t' is supposed to represent in any source-code editor's settings. In Google Cloud Server, the default value is '4' spaces.
        Code:
        Exact Method Body:
         String spaces   = StringParse.nChars(' ', numSpacesPerTab);
         String[] lines  = javaSrcFileAsStr.split("\n");
        
         for (String line:lines) System.out.println("LINE: " + line);
        
         for (int i=0; i < lines.length; i++)
         {
             int numTabs = 0;
        
             while ((numTabs < lines[i].length()) && (lines[i].charAt(numTabs) == '\t'))
                 numTabs++;
        
             if (numTabs == 0)
                 lines[i] = lines[i] + '\n';
             else
                 lines[i] = StringParse.nStrings(spaces, numTabs) +
                 lines[i].substring(numTabs) + '\n';
         }
        
         StringBuilder sb = new StringBuilder();
        
         for (String line : lines) sb.append(line);
        
         return sb.toString();