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 field. It is very similar to the Java-Bean @Stateless Annotation.
  • 1 Constructor(s), 1 declared private, zero-argument constructor
  • 11 Method(s), 11 declared static
  • 5 Field(s), 5 declared static, 4 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 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 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 HTML.Tools.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
        
         // When this loop terminates, 'first' will be pointing to the first character in the first
         // line of code in the source-code / String.
         //
         // NOTE: the 'first' position *CANNOT* point to the first non-white-space character in the
         //       source-code String (callableAsStr) *BECAUSE* white-space before source code is
         //       actually "indentation".  Only white-space at the end of a line of source-code 
         //       can be 'trimmed' using String.trim().
        
         while ((sPos < ePos) && Character.isWhitespace(tempCh = callableAsStr.charAt(++sPos)))
             if (tempCh == '\n') first = sPos + 1;
        
         // 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 setCodeIndent(callableAsStr.substring(first, ePos + 1), 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
         // ****************************************************************************************
        
         // 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)
             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;
        
      • 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();