Package Torello.Java
Class StrIndent
- java.lang.Object
-
- Torello.Java.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
. Theindent
methods right shift (add / append) each line of text within an input-String
by pre-pending tabs or space characters.
Hi-Lited Source-Code:- View Here: Torello/Java/StrIndent.java
- Open New Browser-Tab: Torello/Java/StrIndent.java
File Size: 21,378 Bytes Line Count: 464 '\n' Characters Found
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
- 1 Field(s), 1 declared static, 1 declared final
-
-
Method Summary
Basic Text Indentation Modifier and Type Method Description static String
indent(String s, int n)
This performs a variation of "indentation" on a JavaString
- simply put - it replaces each new-line character ('\n'
) with aString
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)
static String
indentAfter2ndLine(String s, int n, boolean spaceOrTab, boolean trimBlankLines)
Performs an indenting ofString
of text, but does not indent the first line.static String
indentTabs(String s, int n)
Identical toindent(String, int)
, but pre-pends aTAB
character'n'
times, rather than a space-character' '
.String-Trim Text Methods Modifier and Type Method Description static String
leftTrimAll(String s)
Will iterate through each line of text within the inputString
-parameter's'
, and left-trim the lines.static String
rightTrimAll(String s)
Will iterate through each line of text within the inputString
-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 Description static String
chompCallableBraces(String callableAsStr)
This method expects to receive a method body, constructor body, or other callable body as aString
; 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 aString
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 Description static String
unIndent(String s, int n, boolean trimBlankLines, boolean rightTrimLines, boolean throwOnTab, boolean throwOnNotEnough, boolean dontThrowOnWhiteSpaceOnlyLines)
Throws a newToDoException
-
-
-
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 JavaString
, 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 inputString
-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 JavaString
, 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:
return RightTrimAll.run(s);
-
leftTrimAll
public static java.lang.String leftTrimAll(java.lang.String s)
Will iterate through each line of text within the inputString
-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 JavaString
, 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:
return LeftTrimAll.run(s);
-
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 aString
; 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 packageTorello.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('}')
.- Returns:
- A method body
String
that can be hilited using the code-hiliting mechanism of the "JavaDoc Package." - Throws:
CallableBodyException
- If the input parameterString
does not begin and end with the curly-braces.- Code:
- Exact Method Body:
return ChompCallableBraces.run(callableAsStr);
-
setCodeIndent
public static java.lang.String setCodeIndent(java.lang.String codeAsStr, int requestedIndent)
Accepts a method body as aString
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 leadingASCII 0x20
(space-bar characters) from the beginning of each line of text. A leading tab-characterASCII 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 inputString
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:
return SetCodeIndent.run(codeAsStr, requestedIndent);
-
setCodeIndent_WithTabsPolicyAbsolute
public static java.lang.String setCodeIndent_WithTabsPolicyAbsolute (java.lang.String codeAsStr, int requestedIndent, java.lang.String SPACES)
Convenience Method
See Documentation:setCodeIndent(String, int)
Converts: All'\t'
to the specified number of spaces in parameterSPACES
.
NOTE: Exception-Checking is NOT done on input- Code:
- Exact Method Body:
return SetCodeIndent.run(codeAsStr.replace("\t", SPACES), requestedIndent);
-
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 thespacesPerTab
-characters in the line.
For instance, if a tab-character were found at character-index10
in the input array, and if'spacesPerTab'
were passed4
, then precisely2
space-characters would be inserted - since12
is the next integral-multiple of4
.- Parameters:
codeAsStr
- Any Java source-code block, as ajava.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 thisString
, 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:
return SetCodeIndentTabsPolicy.run(codeAsStr, requestedIndent, spacesPerTab);
-
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-codeString
, that has been converted into a Javachar[]
-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 thejava.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.
WhenFALSE
is passed to this parameter, a tab-character will represent aString
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 thespacesPerTab
-characters in the line.
For instance, if a tab-character were found at character-index10
in the input array, and if'spacesPerTab'
were passed4
, then precisely2
space-characters would be inserted - since12
is the next integral-multiple of4
.
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 thejava.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:
return LOCAsStr.run(code, numLeadingSpaces, fcPos, spacesPerTab);
-
indent
public static java.lang.String indent(java.lang.String s, int n)
This performs a variation of "indentation" on a JavaString
- simply put - it replaces each new-line character ('\n'
) with aString
that begins with a new-line, and is followed by'n'
blank white-space characters' '
. If the inputString
parameter's'
is of zero-length, then the zero-lengthString
is returned. If the final character in the inputString
is a new-line, that new-line is not padded.- Parameters:
s
- Anyjava.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 toindent(String, int)
, but pre-pends aTAB
character'n'
times, rather than a space-character' '
.- Parameters:
s
- Anyjava.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
- Anyjava.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 passedTRUE
, the space character' '
is used for indentation. WhenFALSE
, 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 returnedString
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:
return Indent.run(s, n, spaceOrTab, trimBlankLines);
-
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 newToDoException
- 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 ofString
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 ofjava.lang.String
.n
- The number of space-characters to insert after each newline'\n'
character.spaceOrTab
- WhenTRUE
, then there shall be'n'
-number of space characters (' '
) inserted at the beginning of each line of text. WhenFALSE
, then this function will insert'n'
tab characters.trimBlankLines
- WhenTRUE
, 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 represent4
spaces, then if a line in a source-code file had three leading tab-characters, then those three leadingchar '\t'
would be replaced with12
leading space characters' '
.- Parameters:
javaSrcFileAsStr
- A Java Source-Code File, loaded as aString
.numSpacesPerTab
- This identifies the number of spaces achar '\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();
-
-