001package Torello.Java; 002 003import Torello.Java.HelperPackages.StrPrint.*; 004 005import Torello.Java.Function.IntTFunction; 006import static Torello.Java.C.*; 007 008// Needed for a few JavaDoc Comments 009import Torello.JavaDoc.Field; 010import Torello.JavaDoc.Constructor; 011import Torello.JavaDoc.Method; 012import Torello.JavaDoc.AnnotationElem; 013 014/** 015 * This class provides several {@code String} printing utilities such as abbreviation and list 016 * printing. 017 */ 018@Torello.JavaDoc.StaticFunctional 019public class StrPrint 020{ 021 private StrPrint() { } 022 023 024 // ******************************************************************************************** 025 // ******************************************************************************************** 026 // HELPER & BASIC 027 // ******************************************************************************************** 028 // ******************************************************************************************** 029 030 031 /** 032 * Converts every line-character ({@code '\n'}) - <I>and any white-space before or after 033 * that character</I>, into the {@code String} - {@code "\\n"} - which is the actual two 034 * character sequence of a back-slash ({@code '\'}), followed by the letter {@code 'n'}. 035 * 036 * <BR /><BR />After new-line characters are replaced, the method will remove any duplicate 037 * spaces that are present in the {@code String}, and reduce them to a single space character 038 * 039 * <BR /><TABLE CLASS=JDBriefTable> 040 * <TR><TH>Input {@code String}</TH><TH>Returned {@code String}</TH></TR> 041 * <TR><TD>"Hello World"</TD><TD>"Hello World"</TD></TR> 042 * <TR><TD>"Hello \t World"</TD><TD>"Hello World"</TD></TR> 043 * <TR><TD>"Hello World\n"</TD><TD>"Hello World\\n"</TD></TR> 044 * <TR><TD>"Hello World \n\t \n"</TD><TD>"Hello World\\n\\n"</TD></TR> 045 * <TR> 046 * <TD>"Hello Today!\nHow Are You?"</TD> 047 * <TD>"Hello Today!\\nHow Are You?"</TD> 048 * </TR> 049 * <TR> 050 * <TD>"Hello,\n Testing 1, 2, 3\n"</TD> 051 * <TD>"Hello,\\nTesting 1, 2, 3\\n"</TD> 052 * </TR> 053 * <TR> 054 * <TD>"Hello,\n Testing 1, 2, 3 \n\t\t\t"</TD> 055 * <TD>"Hello,\\nTesting 1, 2, 3\\n"</TD> 056 * </TR> 057 * <TR><TD>"\n"</TD><TD>"\\n"</TD></TR> 058 * <TR><TD>"\n \t"</TD><TD>"\\n"</TD></TR> 059 * <TR><TD>"\n\t \n\t \n\t "</TD><TD>"\\n\\n\\n"</TD></TR> 060 * </TABLE> 061 * 062 * <BR />This method is used in printing Java Source Code to a terminal - in an abbreviated 063 * way! After this method is finished, java-source-as-text is actually <B><I>still</I></B> 064 * look readable, and can be printed in a table of methods on a page. It is used in the Java 065 * Doc Upgrader tool, and makes printing up <B><I>both</I></B> method-signatures 066 * <B><I>and</I></B> method bodies quite a bit easier. 067 * 068 * <BR /><BR />For a better understanding of the use and application of this function, please 069 * take a look at the <B>{@code 'toString'}</B> methods: <B>{@link Method#toString()}, 070 * {@link Constructor#toString()}, {@link Field#toString()} and 071 * {@link AnnotationElem#toString()}</B> 072 * 073 * <BR /><BR /><B CLASS=JDDescLabel>Regular Expressions:</B> 074 * 075 * <BR />This method uses regular-expressions, rather performing an optimized, in-place, 076 * {@code String} replacement (such as one with a {@code for} or {@code while} loop). This 077 * means that there is a little efficiency sacrificed in the name of brevity. 078 * 079 * <BR /><BR />The replacement used in the {@code String.replaceAll} method was thouroughly 080 * tested. The quadruple-backslash {@code '\n'} <I>is actually necessary!</I> The first 081 * escape used is to communicate with the Java-Compiler, and the second round of escaping is 082 * communicating with the Regular Expression Processor. 083 * 084 * @param s Any {@code java.lang.String}, preferably one with multiple lines of text. 085 * 086 * @return A {@code String}, where each line of text has been "trimmed", and the two 087 * character sequence {@code "\\n"} inserted in-between each line. 088 * 089 * @see #abbrevStartRDSF(String, int, boolean) 090 * @see #abbrevEndRDSF(String, int, boolean) 091 */ 092 public static String newLinesAsText(String s) 093 { 094 return s 095 .replaceAll( 096 // White-Space-Except-Newline, THEN newline, THEN White-SpaceExcept-Newline 097 "[ \t\r\f\b]*\n[ \t\r\f\b]*", 098 099 // Replace Each Occurence of that with: 100 // == COMPILES-TO ==> "\\n" == REG-EX-READS ==> BackSlash and letter 'n' 101 "\\\\n" 102 ) 103 // == COMPILES-TO ==> "\s+" == REG-EX-READS ==> 'spaces' 104 .replaceAll("\\s+", " ") 105 106 // Don't forget about leading and trailing stuff... 107 .trim(); 108 } 109 110 111 // ******************************************************************************************** 112 // ******************************************************************************************** 113 // Abbreviating Text, with "newLinesAsText" - Helper 114 // ******************************************************************************************** 115 // ******************************************************************************************** 116 117 118 /** 119 * Convenience Method. 120 * <BR /><B STYLE='color: red;'>RDSF: Remove Duplicate Spaces First</B> 121 * <BR />Invokes: {@link StringParse#removeDuplicateSpaces(String)} 122 * <BR />Or Invokes: {@link #newLinesAsText(String)} 123 * <BR />Finally: {@link #abbrevStart(String, boolean, int)} 124 */ 125 public static String abbrevStartRDSF 126 (String s, int maxLength, boolean seeEscapedNewLinesAsText) 127 { 128 // false is passed to 'abbrevStart' parameter 'escapeNewLines' because in both scenarios 129 // of this conditional-statement, the new-lines have already been removed by the previous 130 // method call. 131 // 132 // both 'removeDuplicateSpaces' and 'newLinesAsText' remove the new-lines 133 134 return seeEscapedNewLinesAsText 135 ? abbrevStart(newLinesAsText(s), false, maxLength) 136 : abbrevStart(StringParse.removeDuplicateSpaces(s), false, maxLength); 137 } 138 139 /** 140 * Convenience Method. 141 * <BR /><B STYLE='color: red;'>RDSF: Remove Duplicate Spaces First</B> 142 * <BR />Invokes: {@link StringParse#removeDuplicateSpaces(String)} 143 * <BR />Or Invokes: {@link #newLinesAsText(String)} 144 * <BR />Finally: {@link #abbrevEnd(String, boolean, int)} 145 */ 146 public static String abbrevEndRDSF 147 (String s, int maxLength, boolean seeEscapedNewLinesAsText) 148 { 149 // false is passed to 'abbrevStart' parameter 'escapeNewLines' because in both scenarios 150 // of this conditional-statement, the new-lines have already been removed by the previous 151 // method call. 152 // 153 // both 'removeDuplicateSpaces' and 'newLinesAsText' remove the new-lines 154 155 return seeEscapedNewLinesAsText 156 ? abbrevEnd(newLinesAsText(s), false, maxLength) 157 : abbrevEnd(StringParse.removeDuplicateSpaces(s), false, maxLength); 158 } 159 160 /** 161 * Convenience Method. 162 * <BR />Passes: {@code '0'} to parameter {@code 'abbrevPos'}, forcing the abbreviation to 163 * occur at the <B>start</B> of the {@code String} (if long enough to be abbreviated) 164 * @see #abbrev(String, int, boolean, String, int) 165 */ 166 public static String abbrevStart(String s, boolean escNewLines, int maxLength) 167 { return Abbrev.print(s, 0, escNewLines, null, maxLength); } 168 169 /** 170 * This will abbreviate any {@code String} using either the ellipsis ({@code '...'}), or some 171 * other use provided abbreviation-{@code String} - <I>as long as the provided {@code String} 172 * is longer than {@code 'maxLength'}.</I> When {@code 's'} is, indeed, longer than 173 * {@code 'maxLength'} the returned-{@code String} will contain the ellipsis abbreviation 174 * beginning at {@code String}-index {@code 'abbrevPos'}. 175 * 176 * <BR /><BR />You have the option of asking that new-line characters ({@code '\n'}) be 177 * escaped into the two-character {@code String: "\\n"}. This optional is provided so that 178 * the output may fit on a single-line, for readability purposes. It will look somewhat like 179 * an escaped {@code JSON} file, which also substitues {@code '\n'} characters for the 180 * 'escaped' version {@code "\\n"}. <I>Note that when this occurs, the replaced-{@code String} 181 * actually only contains two characters, <B>not three,</B> since the first back-slash your are 182 * looking right here is, itself, an escape character!</I> 183 * 184 * @param s This may be any Java (non-null) {@code String} 185 * 186 * @param abbrevPos This parameter is used to indicate where the abbreviation-{@code String} 187 * should occur - <I>if this {@code String 's'} is long enough to be abbreviated.</I> For 188 * instance, if {@code '0'} (zero) were passed to this parameter, and {@code 's'} were longer 189 * than parameter {@code 'maxLength'}, then an ellipsis would be appended to the beginning of 190 * the returned-{@code 'String'}. (Or, if some other {@code 'abbrevStr'} were specified, that 191 * other abbreviation would be appended to the beginning of the returned-{@code String}) 192 * 193 * @param escapeNewLines <EMBED CLASS='external-html' DATA-FILE-ID=SP_ABBREV_ENL> 194 * @param abbrevStr <EMBED CLASS='external-html' DATA-FILE-ID=SP_ABBREV_STR> 195 * @param maxLength <EMBED CLASS='external-html' DATA-FILE-ID=SP_ABBREV_MXL> 196 * 197 * @return If the input {@code String} has a <I>length less-than {@code 'maxLength'}</I>, then 198 * it is returned, unchanged. If the input contained new-line characters, and you have 199 * requested to escape them, that replacement is performed first (which makes the original 200 * {@code String}} longer). Then, if the {@code String} is longer than {@code 'maxLength'}, 201 * it is abbreviated, and either the default ellipsis <I>or the user-provided 202 * {@code 'abbrevStr'}</I> are inserted at location {@code 'abbrevPos'} and returned. 203 * 204 * <BR /><BR />If, after the new-line escape-replacement, the returned-{@code String} would not 205 * be longer than {@code 'maxLength'}, then that escaped-{@code String} is returned, as is 206 * (without any elliptical-characters). 207 * 208 * @throws IllegalArgumentException If the value for {@code 'maxLength'} is negative, or if it 209 * is less than the length of the abbreviation. 210 * 211 * <BR /><BR />Specifically, if {@code 'maxLength'} isn't even long enough to fit the abbreviation 212 * itself, then this exception will throw. 213 * 214 * <BR /><BR />If the value passed to {@code 'abbrevPos'} is negative or longer than the value 215 * passed to {@code 'maxLength'} minus the length of the ellipsis-{@code String}, then this 216 * exception will also throw. 217 */ 218 public static String abbrev( 219 String s, 220 int abbrevPos, 221 boolean escapeNewLines, 222 String abbrevStr, 223 int maxLength 224 ) 225 { return Abbrev.print(s, abbrevPos, escapeNewLines, abbrevStr, maxLength); } 226 227 /** 228 * Convenience Method. 229 * <BR />Parameter: {@code spaceBeforeAbbrev} set to {@code FALSE} 230 * <BR />Abbreviates: Default ellipsis ({@code '...'}) are placed at the end of the 231 * {@code String} 232 * @see #abbrev(String, boolean, boolean, String, int) 233 */ 234 public static String abbrevEnd(String s, boolean escapeNewLines, int maxLength) 235 { return Abbrev.print(s, false, escapeNewLines, null, maxLength); } 236 237 /** 238 * This will abbreviate any {@code String} using either the ellipsis ({@code '...'}), or some 239 * other use provided abbreviation-{@code String}, if the provided {@code String} is longer 240 * than {@code 'maxLength'}. If the returned-{@code String} is, indeed, abbreviated then the 241 * elliptical-abbreviation {@code String} will be placed <I>at the end of the 242 * returned-{@code String}</I> 243 * 244 * <BR /><BR />You have the option of asking that new-line characters ({@code '\n'}) be 245 * escaped into the two-character {@code String: "\\n"}. This optional is provided so that 246 * the output may fit on a single-line, for readability purposes. It will look somewhat like 247 * an escaped {@code JSON} file, which also substitues {@code '\n'} characters for the 248 * 'escaped' version {@code "\\n"}. <I>Note that when this occurs, the replaced-{@code String} 249 * actually only contains two characters, <B>not three,</B> since the first back-slash your are 250 * looking right here is, itself, an escape character!</I> 251 * 252 * @param s This may be any Java (non-null) {@code String} 253 * 254 * @param spaceBeforeAbbrev This ensures that for whatever variant of ellipsis being used, the 255 * space-character is inserted directly before appending the ellipsis {@code "..."} or the 256 * user-provided {@code 'abbrevStr'}. 257 * 258 * @param escapeNewLines <EMBED CLASS='external-html' DATA-FILE-ID=SP_ABBREV_ENL> 259 * @param abbrevStr <EMBED CLASS='external-html' DATA-FILE-ID=SP_ABBREV_STR> 260 * @param maxLength <EMBED CLASS='external-html' DATA-FILE-ID=SP_ABBREV_MXL> 261 * 262 * @return If the input {@code String} has a <I>length less-than {@code 'maxLength'}</I>, then 263 * it is returned, unchanged. If the input contained new-line characters, and you have 264 * requested to escape them, that replacement is performed first (which makes the original 265 * {@code String}} longer). Then, if the {@code String} is longer than {@code 'maxLength'}, 266 * it is abbreviated, and either the default ellipsis <I>or the user-provided 267 * {@code 'abbrevStr'}</I> are are appended to the end and returned. 268 * 269 * @throws IllegalArgumentException If the value for {@code 'maxLength'} is negative, or if it 270 * is less than the length of the abbreviation plus the value of {@code 'spaceBeforeAbbrev'}. 271 * <BR /><BR />Specifically, if {@code 'maxLength'} isn't even long enough to fit the abbreviation 272 * itself, then this exception will throw. 273 */ 274 public static String abbrev( 275 String s, 276 boolean spaceBeforeAbbrev, 277 boolean escapeNewLines, 278 String abbrevStr, 279 int maxLength 280 ) 281 { return Abbrev.print(s, spaceBeforeAbbrev, escapeNewLines, abbrevStr, maxLength); } 282 283 284 // ******************************************************************************************** 285 // ******************************************************************************************** 286 // Abbreviated List Printing 287 // ******************************************************************************************** 288 // ******************************************************************************************** 289 290 291 /** 292 * Convenience Method. 293 * <BR />Passes: {@code Object.toString()} to {@code 'listItemPrinter'} 294 * @see #printListAbbrev(Iterable, IntTFunction, int, int, boolean, boolean, boolean) 295 */ 296 public static <ELEM> String printListAbbrev( 297 Iterable<ELEM> list, int lineWidth, int indentation, boolean seeEscapedNewLinesAsText, 298 boolean printNulls, boolean showLineNumbers 299 ) 300 { 301 return PrintListAbbrev.print( 302 list, (int i, Object o) -> o.toString(), lineWidth, indentation, 303 seeEscapedNewLinesAsText, printNulls, showLineNumbers 304 ); 305 } 306 307 /** 308 * <EMBED CLASS=defs DATA-LIST_TYPE=Array> 309 * <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_DESCRIPTION> 310 * @param list Any iterable-list of Java Object's 311 * @param listItemPrinter <EMBED CLASS='extenal-html' DATA-FILE-ID=SP_PLA_LIST_ITEM_PR> 312 * @param lineWidth <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_LINE_WIDTH> 313 * @param indentation <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_INDENTATION> 314 * @param seeEscapedNewLinesAsText <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_SEE_ESC_NL> 315 * @param printNulls <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_PRINT_NULLS> 316 * @param showLineNumbers <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_SHOW_LNUMS> 317 * @return <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_RETURNS> 318 * @see StringParse#zeroPad10e2(int) 319 * @see #abbrevEndRDSF(String, int, boolean) 320 * @see StringParse#nChars(char, int) 321 * @see StringParse#trimLeft(String) 322 */ 323 public static <ELEM> String printListAbbrev( 324 Iterable<ELEM> list, 325 IntTFunction<? super ELEM, String> listItemPrinter, 326 int lineWidth, 327 int indentation, 328 boolean seeEscapedNewLinesAsText, 329 boolean printNulls, 330 boolean showLineNumbers 331 ) 332 { 333 return PrintListAbbrev.print( 334 list, listItemPrinter, lineWidth, indentation, seeEscapedNewLinesAsText, 335 printNulls, showLineNumbers 336 ); 337 } 338 339 /** 340 * Convenience Method. 341 * <BR />Passes: {@code Object.toString()} to {@code 'listItemPrinter'} 342 * @see #printListAbbrev(Object[], IntTFunction, int, int, boolean, boolean, boolean)} 343 */ 344 public static <ELEM> String printListAbbrev( 345 ELEM[] arr, 346 int lineWidth, 347 int indentation, 348 boolean seeEscapedNewLinesAsText, 349 boolean printNulls, 350 boolean showLineNumbers 351 ) 352 { 353 return PrintListAbbrev.print( 354 arr, (int i, Object o) -> o.toString(), lineWidth, indentation, 355 seeEscapedNewLinesAsText, printNulls, showLineNumbers 356 ); 357 } 358 359 /** 360 * <EMBED CLASS=defs DATA-LIST_TYPE=Array> 361 * <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_DESCRIPTION> 362 * @param list Any iterable-list of Java Object's 363 * @param listItemPrinter <EMBED CLASS='extenal-html' DATA-FILE-ID=SP_PLA_LIST_ITEM_PR> 364 * @param lineWidth <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_LINE_WIDTH> 365 * @param indentation <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_INDENTATION> 366 * @param seeEscapedNewLinesAsText <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_SEE_ESC_NL> 367 * @param printNulls <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_PRINT_NULLS> 368 * @param showLineNumbers <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_SHOW_LNUMS> 369 * @return <EMBED CLASS='external-html' DATA-FILE-ID=SP_PLA_RETURNS> 370 * @see StringParse#zeroPad10e2(int) 371 * @see #abbrevEndRDSF(String, int, boolean) 372 * @see StringParse#trimLeft(String) 373 */ 374 public static <ELEM> String printListAbbrev( 375 ELEM[] list, 376 IntTFunction<? super ELEM, String> listItemPrinter, 377 int lineWidth, 378 int indentation, 379 boolean seeEscapedNewLinesAsText, 380 boolean printNulls, 381 boolean showLineNumbers 382 ) 383 { 384 return PrintListAbbrev.print( 385 list, listItemPrinter, lineWidth, indentation, seeEscapedNewLinesAsText, 386 printNulls, showLineNumbers 387 ); 388 } 389 390 391 // ******************************************************************************************** 392 // ******************************************************************************************** 393 // Line(s) of Text 394 // ******************************************************************************************** 395 // ******************************************************************************************** 396 397 398 /** 399 * This will return the complete text-lines of character data for the line identified by 400 * token-substring position parameters {@code pos} and {@code len}. This method will search, 401 * in the left-direction (decreasing {@code String} index) for the first new-line character 402 * identified. It will also search, starting at position {@code pos + len}, for the first 403 * new-line character in the right-direction (increasing {@code String} index). 404 * 405 * <BR /><BR />If the token-substring identified by {@code s.substring(pos, len)} itself 406 * contains any new-line characters, these will neither affect the prepended, nor the 407 * post-pended search {@code String}. To be precise, any newline characters between 408 * {@code 'pos'} and {@code 'len'} will be irrelevant to the left-wards and right-wards 409 * newlines searches for new-line characters. 410 * 411 * @param s This may be any valid Java {@code String}. It ought to be some variant of a 412 * text-file. It will be searched for the nearest {@code '\n'} character - <I>in both 413 * directions, left and right</I> - from parameter {@code int 'pos'} and parameter 414 * {@code int 'len'} 415 * 416 * @param pos This is a position in the input-parameter {@code String 's'}. The nearest 417 * {@code '\n'} (new-line) character, <I>to the left</I> of this position, will be found and 418 * identified. If the {@code char} at {@code s.charAt(pos)} is, itself, a {@code '\n'} 419 * (newline) character, then no left-direction search will be performed. The left-most 420 * position of the returned substring would then be {@code pos + 1}. 421 * 422 * @param len The search for the 'right-most' {@code '\n'} (newline-character) will begin at 423 * position {@code 'len'}. If the character at {@code s.charAt(pos + len)} is, itself, a 424 * new-line character, then no right-direction search will be performed. The right-most 425 * position of the returned substring would be {@code pos + len - 1}. 426 * 427 * @param unixColorCode If this {@code String} is null, it will be ignored. If this 428 * {@code String} is non-null, it will be inserted before the "Matching {@code String}" 429 * indicated by the index-boundaries {@code pos} <I>TO</I> {@code pos + len}. 430 * 431 * <BR /><BR /><B>NOTE:</B> No Validity Check shall be performed on this {@code String}, and 432 * the user is not obligated to provide a {@link C} valid UNIX Color-Code {@code String}. 433 * Also, a closing {@code C.RESET} is inserted after the terminus of the match. 434 * 435 * @return The {@code String} demarcated by the first new-line character PLUS 1 436 * <I><B>BEFORE</I></B> index {@code 'pos'}, and the first new-line character MINUS 1 437 * <I><B>AFTER</I></B> index {@code pos + len}. 438 * 439 * <BR /><BR /><B>NOTE:</B> The above does mean, indeed, that the starting and ending 440 * new-lines <B>WILL NOT</B> be included in the returned {@code String}. 441 * 442 * <BR /><BR /><B>ALSO:</B> Also, if there are no new-line characters before position 443 * {@code 'pos'}, then every character beginning at position zero will be included in the 444 * returned {@code String} result. Also, if there are no new-line characters after position 445 * {@code pos + len} then every character after position {@code pos + len} will be appended to 446 * the returned {@code String} result. 447 * 448 * @throws StringIndexOutOfBoundsException If either {@code 'pos'}, or {@code 'pos + len'} are 449 * not within the bounds of the input {@code String 's'} 450 * 451 * @throws IllegalArgumentException If the value passed to parameter {@code 'len'} is zero or 452 * negative. 453 */ 454 public static String lineOrLines(String s, int pos, int len, String unixColorCode) 455 { 456 if ((pos >= s.length()) || (pos < 0)) throw new StringIndexOutOfBoundsException( 457 "The integer passed to parameter 'pos' [" + pos + "], is past the bounds of the end " + 458 "of String 's', which has length [" + s.length() + "]" 459 ); 460 461 if (len <= 0) throw new IllegalArgumentException 462 ("The value passed to parameter 'len' [" + len + "], may not be negative."); 463 464 if ((pos + len) > s.length()) throw new StringIndexOutOfBoundsException( 465 "The total of parameter 'pos' [" + pos + "], and parameter 'len' [" + len + "], is: " + 466 "[" + (pos + len) + "]. Unfortunately, String parameter 's' only has length " + 467 "[" + s.length() + "]" 468 ); 469 470 int linesStart, linesEnd, temp; 471 472 if (pos == 0) linesStart = 0; 473 else if (s.charAt(pos) == '\n') linesStart = pos + 1; 474 else if ((temp = StrIndexOf.left(s, pos, '\n')) != -1) linesStart = temp + 1; 475 else linesStart = 0; 476 477 if ((pos + len) == s.length()) linesEnd = s.length(); 478 else if (s.charAt(pos + len) == '\n') linesEnd = pos + len; 479 else if ((temp = s.indexOf('\n', pos + len)) != -1) linesEnd = temp; 480 else linesEnd = s.length(); 481 482 /* 483 // VERY USEFUL FOR DEBUGGING. DO NOT DELETE... 484 // NOTE: This method is the one that GREP uses. 485 System.out.println("s.charAt(pos)\t\t= " + "[" + s.charAt(pos) + "]"); 486 System.out.println("s.charAt(pos+len)\t= " + "[" + s.charAt(pos+len) + "]"); 487 System.out.println("s.length()\t\t= " + s.length()); 488 System.out.println("pos\t\t\t= " + pos); 489 System.out.println("pos + len\t\t= " + (pos + len)); 490 System.out.println("linesStart\t\t= " + linesStart); 491 System.out.println("linesEnd\t\t= " + linesEnd); 492 */ 493 494 return (unixColorCode != null) 495 ? s.substring(linesStart, pos) + 496 unixColorCode + s.substring(pos, pos + len) + RESET + 497 s.substring(pos + len, linesEnd) 498 : s.substring(linesStart, linesEnd); 499 /* 500 OOPS.... For Posterity, this shall remain, here, but commented 501 s.substring(linesStart, pos) + 502 s.substring(pos, pos + len) + 503 s.substring(pos + len, linesEnd); 504 */ 505 } 506 507 /** 508 * This will return the complete text-line of character data from 'inside' the input-parameter 509 * {@code String s}. The meaning of {@code 'complete text-line'}, in this method, is that any 510 * and all character data between the first {@code '\n'} (new-line character) when scanning 511 * towards <I>the right</I> (increasing {@code String}-index) and the first {@code '\n'} 512 * character when scanning towards <I>the left</I> (decreasing index) constitutes 513 * {@code 'a line'} (of text-data). 514 * 515 * <BR /><BR />This scan shall for the left-most and right-most new-line shall begin at 516 * {@code String}-index parameter {@code pos}. If either the left-direction or 517 * right-direction scan does not find any new-line characters, then start and end indices of 518 * the returned line of text shall be demarcated by input-{@code String} index {@code '0'} and 519 * index {@code String.length()}, <I><B>respectively</B></I> 520 * 521 * @param s This may be any valid Java {@code String}. It ought to be some variant of a 522 * text-file. It will be searched for the nearest {@code '\n'} character - <I>in both 523 * directions, left and right</I> - from parameter {@code int 'pos'}. 524 * 525 * @param pos This is a position in the input-parameter {@code String 's'}. The nearest 526 * new-line character both to the left of this position, and to the right, will be found and 527 * identified. If the character at {@code s.charAt(pos)} is itself a newline {@code '\n'} 528 * character, then <I>an exception shall throw</I>. 529 * 530 * @return The {@code String} identified by the first new-line character PLUS 1 531 * <I><B>BEFORE</I></B> index {@code 'pos'}, and the first new-line character MINUS 1 532 * <I><B>AFTER</I></B> index {@code 'pos + len'}. 533 * 534 * <BR /><BR /><B>NOTE:</B> The above means, that the starting and ending new-lines, 535 * themselves, will not be included in the {@code String} that is returned. 536 * 537 * <BR /><BR /><B>ALSO:</B> Also, if there are no new-line characters before position 538 * {@code 'pos'}, then every character beginning at position zero will be included in the 539 * returned {@code String} result. Also, if there are no new-line characters after position 540 * {@code 'pos + len'} then every character after position {@code 'pos + len'} will be appended 541 * to the returned {@code String} result. 542 * 543 * @throws StringIndexOutOfBoundsException If {@code 'pos'} is not within the bounds of the 544 * input {@code String 's'} 545 * 546 * @throws IllegalArgumentException If the character in {@code String 's'} at position 547 * {@code 'pos'} is a newline {@code '\n'}, itself. 548 */ 549 public static String line(String s, int pos) 550 { 551 if ((pos > s.length()) || (pos < 0)) throw new StringIndexOutOfBoundsException( 552 "The integer passed to parameter 'pos' [" + pos + "], is past the bounds of the end of " + 553 "String 's', which has length [" + s.length() + "]" 554 ); 555 556 if (s.charAt(pos) == '\n') throw new IllegalArgumentException( 557 "The position-index for string-parameter 's' contains, itself, a new line character " + 558 "'\\n.' This is not allowed here." 559 ); 560 561 int lineStart, lineEnd; 562 563 // Prevents StrIndexOf from throwing StringINdexOutOfBounds 564 if (pos == 0) lineStart = 0; 565 566 // Also prevent lineStart equal-to '-1' 567 else if ((lineStart = StrIndexOf.left(s, pos, '\n')) == -1) lineStart = 0; 568 569 // Prevent lineEnd equal to '-1' 570 if ((lineEnd = s.indexOf('\n', pos)) == -1) lineEnd = s.length(); 571 572 // if this is the first line, there was no initial '\n', so don't skip it! 573 return (lineStart == 0) 574 575 // This version returns the String from the position-0 (Pay Attention!) 576 ? s.substring(0, lineEnd) 577 578 // This version simply eliminates the '\n' that is in the directly-preceeding character 579 : s.substring(lineStart + 1, lineEnd); 580 } 581 582 /** 583 * This will retrieve the first {@code 'n'} lines of a {@code String} - where a line is defined 584 * as everything up to and including the next newline {@code '\n'} character. 585 * 586 * @param s Any java {@code String}. 587 * 588 * @param n This is the number of lines of text to retrieve. 589 * 590 * @return a substring of s where the last character in the {@code String} is a {@code '\n'}. 591 * The last character should be the nth {@code '\n'} character found in s. If there is no such 592 * character, then the original {@code String} shall be returned instead. 593 * 594 * @throws NException This exception shall throw if parameter {@code 'n'} is less than 1, or 595 * longer than {@code s.length()}. 596 */ 597 public static String firstNLines(String s, int n) 598 { 599 NException.check(n, s); 600 int pos = StrIndexOf.nth(s, n, '\n'); 601 602 if (pos != -1) return s.substring(0, pos + 1); 603 else return s; 604 } 605 606 /** 607 * This will retrieve the last 'n' lines of a {@code String} - where a line is defined as 608 * everything up to and including the next newline {@code '\n'} character. 609 * 610 * @param s Any java {@code String}. 611 * 612 * @param n This is the number of lines of text to retrieve. 613 * 614 * @return a substring of {@code 's'} where the last character in the {@code String} is a 615 * new-line character {@code '\n'}, and the first character is the character directly before 616 * the nth newline {@code '\n'} found in {@code 's'} - starting the count at the end of the 617 * {@code String}. If there is no such substring, then the original {@code String} shall be 618 * returned. 619 * 620 * @throws NException This exception shall throw if {@code 'n'} is less than 1, or longer 621 * {@code s.length()}. 622 */ 623 public static String lastNLines(String s, int n) 624 { 625 NException.check(n, s); 626 int pos = StrIndexOf.nthFromEnd(s, n, '\n'); 627 628 if (pos != -1) return s.substring(pos + 1); 629 else return s; 630 } 631 632 /** 633 * This is used for "trimming each line" of an input {@code String}. Generally, when dealing 634 * with HTML there may be superfluous white-space that is useful in some places, but not 635 * necessarily when HTML is copied and pasted to other sections of a page (or to another page, 636 * altogether). This will split a {@code String} by new-line characters, and then trim each 637 * line, and afterward rebuild the {@code String} and return it. 638 * 639 * <BR /><BR /><B CLASS=JDDescLabel>CRLF Issues:</B> 640 * 641 * <BR />This will only split the {@code String} using the standard {@code '\n'} character. If 642 * the {@code String} being used uses {@code '\r'} or {@code '\n\r'}, use a different trim 643 * method. 644 * 645 * @param str This may be any {@code String}. It will be split by new-line characters 646 * {@code '\n'} 647 * 648 * @return Returns the rebuilt {@code String}, with each line having a {@code String.trim();} 649 * operation performed. 650 */ 651 public static String trimEachLine(String str) 652 { 653 StringBuilder sb = new StringBuilder(); 654 655 for (String s : str.split("\\n")) 656 657 if ((s = s.trim()).length() == 0) continue; 658 else sb.append(s + '\n'); 659 660 return sb.toString().trim(); 661 } 662 663 /** 664 * Interprets an input {@code String} as one which was read out of a Text-File. Counts the 665 * number of new-line ({@code '\n'}) characters between {@code String} indices {@code '0'} and 666 * {@code 'pos'} 667 * 668 * <BR /><BR />This is intended be the Line-Number where {@code String}-Index parameter 669 * {@code 'pos'} is located inside the {@code 'str'} (presuming {@code 'str'} was retrieved 670 * from a Text-File). 671 * 672 * @param str Any Java {@code String}, preferably one with multiple lines of text. 673 * @param pos Any valid {@code String}-Index that occurs ithin {@code 'str'} 674 * 675 * @return The Line-Number within Text-File parameter {@code 'str'} which contains 676 * {@code String}-Index parameter {@code 'pos'} 677 * 678 * @throws StringIndexOutOfBoundsException If integer-parameter {@code 'pos'} is negative or 679 * past the length of the {@code String}-Parameter {@code 'str'}. 680 * 681 * @see #lineNumberSince(String, int, int, int) 682 */ 683 public static int lineNumber(String str, int pos) 684 { 685 if (pos < 0) throw new StringIndexOutOfBoundsException 686 ("The number provided to index parameter 'pos' : [" + pos + "] is negative."); 687 688 if (pos >= str.length()) throw new StringIndexOutOfBoundsException( 689 "The number provided to index parameter 'pos' : [" + pos + "] is greater than the " + 690 "length of the input String-Parameter 'str' [" + str.length() + "]." 691 ); 692 693 int lineNum = 1; 694 695 for (int i=0; i <= pos; i++) if (str.charAt(i) == '\n') lineNum++; 696 697 return lineNum; 698 } 699 700 /** 701 * This methe may be used, iteratively, inside of a loop for finding the location of any 702 * subsequent {@code String}-Index within a Text-File, based on the information obtained from 703 * a previous Line-Number retrieval. 704 * 705 * <BR /><BR /><B CLASS=JDDescLabel>Use inside For-Loop:</B> 706 * 707 * <BR />This method is designed to be used within a {@code 'for'} or {@code 'while'} loop. 708 * Though it is true that the exception-check which occurs inside this method is superfluous 709 * and redundant, the cost incurred by the two {@code if}-statements is minimal. These checks 710 * are used here, in the code, primarily for readability. 711 * 712 * <BR /><BR />If maximum efficiency is needed, then copy and paste the bottom two lines of 713 * code into your editor, and use that instead, without the exception-checks. 714 * 715 * <BR />In the example below, it should be noted how to use both methods to iterate through 716 * the line numbers in a Text-File, efficiently. 717 * 718 * <DIV CLASS=EXAMPLE>{@code 719 * 720 * int[] posArr = findIndices(myString, "Raindrops on Roses", "Whiskers on Kittens"); 721 * int lineNumber = StrPrint.lineNumber(myString, posArr[0]); 722 * int prevPos = posArr[0]; 723 * 724 * System.out.println("There is a match on line: " + lineNumber); 725 * 726 * for (int i=1; i < posArr.length; i++) 727 * { 728 * lineNumber = StrPrint.lineNumberSince(myString, posArr[i], lineNumber, prevPos); 729 * System.out.println("There is a match on line: " + lineNumber); 730 * 731 * prevPos = posArr[i]; 732 * } 733 * }</DIV> 734 * 735 * @param str Any Java {@code String}. This {@code String} will be interpreted as a Text-File 736 * whose newline characters ({@code '\n'} chars) represent lines of text. 737 * 738 * @param pos Any valid {@code String}-index within {@code 'str'} 739 * 740 * @param prevLineNum This should be the Line-Number that contains the {@code String}-index 741 * {@code 'prevPos'} 742 * 743 * @param prevPos This may be any index contained by {@code String} parameter {@code 'str'}. 744 * It is expected that this parameter be an index that occured on Line-Number 745 * {@code 'prevLineNum'} of the Text-File {@code 'str'} 746 * 747 * @return The Line-Number within Text-File parameter {@code 'str'} that contains 748 * {@code String}-index {@code 'pos'} 749 * 750 * @throws IllegalArgumentException If {@code 'pos'} is less than or equal to 751 * {@code 'prevPos'}, or if {@code 'prevLineNum'} is less than zero. 752 * 753 * @see #lineNumber(String, int) 754 */ 755 public static int lineNumberSince(String str, int pos, int prevLineNum, int prevPos) 756 { 757 if (pos <= prevPos) throw new IllegalArgumentException( 758 "The number provided to index parameter 'pos' : [" + pos + "] is less than or equal " + 759 "to previous-match index-parameter prevPos : [" + prevPos + "]" 760 ); 761 762 if (prevLineNum < 0) throw new IllegalArgumentException( 763 "You have provided a negative number to Line-Number parameter 'prevLineNum' : " + 764 "[" + prevLineNum + "]" 765 ); 766 767 for (int i = (prevPos + 1); i <= pos; i++) if (str.charAt(i) == '\n') prevLineNum++; 768 769 return prevLineNum; 770 } 771 772 773 // ******************************************************************************************** 774 // ******************************************************************************************** 775 // Abbreviation: Line-Length **AND** Number of Lines 776 // ******************************************************************************************** 777 // ******************************************************************************************** 778 779 780 /** 781 * This method allows for printing an abbreviation of a {@code String} such that 782 * <B STYLE='color: red;'><I>BOTH</I></B> the number of lines (height), 783 * <B STYLE='color: red;'><I>AND</I></B> the length of each line of text (width) can both be 784 * abbreviated. There is even a third abbreviation that is possible, and that is where 785 * blank-links can be compacted / flattened first (before the abbreviation process starts). 786 * 787 * <BR /><BR />This method is being used for printing JSON-Response Objects that contain large 788 * HTML-Page {@code String's}. Primarily, if you want to see a message, but do not want 789 * hundreds or even thousands of lines of HTML blasted across your terminal, then this method is 790 * for you! 791 * 792 * <BR /><BR />The package {@code Torello.Browser's} Web-Sockets Communications is making use 793 * of this for printing Chrome-Browser Messages to the terminal. 794 * 795 * @param s Any Java {@code String} 796 * 797 * @param horizAbbrevStr If you have a specific Abbreviation-{@code String} that you would like 798 * to see used in Horizontally-Abbreviated Lines, please pass it here. 799 * 800 * <BR /><BR />Note that this value is directly passed to the {@code 'abbrevStr'} parameters 801 * in the Standard {@code String}-Abbreviation methods. This means that when this parameter is 802 * null, it will be ignored - <I>and if any horizontal (line-length) abbreviattions occur, then 803 * the 'Default-Abbreviation {@code String}' {@code "..."} will be used</I>. 804 * 805 * <BR ><BR />Also note that if parameter {@code 'maxLineLength'} is passed null, then lines of 806 * text will not be shortened. In that case, each line of text will retain its exact length 807 * that occured prior to the internal {@code String.split()} invocation. 808 * 809 * @param maxLineLength If you would like to shorten each line of text which is appended to the 810 * returned {@code String}, then pass a positive value to this parameter. 811 * 812 * <BR /><BR />This parameter may be null, and if it is, it will be ignored. In such cases, 813 * individual lines of text will retain their original length. 814 * 815 * @param maxNumLines This is the maximum number of lines of text that will appear in the 816 * returned {@code String}. Note, under normal operation, if this parameter is passed 817 * {@code '3'}, then there will be exactly three lines of text. Furthermore there will be 818 * exactly {@code '2'} newline {@code '\n'} characters. 819 * 820 * @param compactConsecutiveBlankLines When this parameter is passed {@code TRUE}, any 821 * series of Empty-Lines, or lines only containing White-Space will be compacted to a single 822 * line of text that simply states {@code "[Compacted 10 Blank Lines]"} (or however many 823 * White-Space-Only Lines were actually compacted, if that number isn't {@code '10'}) 824 * 825 * @return The modified {@code String}. 826 * 827 * @throws IllegalArgumentException If parameter {@code 'maxNumLines'} is less than 3. The 828 * returned {@code String} must be long enough to keep the first line, the last line and the 829 * abbreviation note. 830 * 831 * <BR /><BR />This exception will also throw if the internal invocation of the standard 832 * {@code String}-abbreviation method is passed a {@code 'maxLineLength'} that is less than 833 * the minimum line-length requirements for a successful horizontal abbreviation. 834 * 835 * <BR /><BR />Finally, this exception throws if {@code 'maxLineLength'} and 836 * {@code 'maxNumLines'} are both passed null, and {@code 'compactConsecutiveBlankLines'}. 837 * This scenario is considered an error-case because there it would exact a situation where 838 * there is nothing for this method to do. 839 */ 840 public static String widthHeightAbbrev( 841 final String s, 842 final String horizAbbrevStr, 843 final Integer maxLineLength, 844 final Integer maxNumLines, 845 final boolean compactConsecutiveBlankLines 846 ) 847 { 848 return VertAndHorizAbbrev.print 849 (s, horizAbbrevStr, maxLineLength, maxNumLines, compactConsecutiveBlankLines); 850 } 851}