1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 | package Torello.Java; import java.util.regex.*; import java.util.stream.IntStream; import Torello.Java.Function.IntCharFunction; import Torello.JavaDoc.StaticFunctional; import Torello.JavaDoc.Excuse; /** * A class for indenting, unindenting and trimming textual-strings. * * <BR /><BR /><EMBED CLASS='external-html' DATA-FILE-ID=STRINDENT> */ @StaticFunctional(Excused="INDENTATION_COUNTER", Excuses=Excuse.DEBUGGING) public class StrIndent { private StrIndent() { } // the indent(String, n, tabOrSpace) method uses this array as a parameter to StrReplace private static final char[] cArrIndent = { '\n' }; // This matches lines of text that contain only blank / white-space characters private static final Pattern EMPTY_LINE = Pattern.compile("^[ \t]+\n", Pattern.MULTILINE); // The 'setCodeIndent' uses all of these (but *ONLY* if "DEBUGGING_INDENTATION" is set to TRUE) private static int INDENTATION_COUNTER = 0; private static final boolean DEBUGGING_INDENTATION = false; private static final String STR_FORMAT_EX_MESSAGE = "One of the lines of code for the method-body as-a-string that was passed contained " + "a tab '\\t' character. Source-Code String's that are passed to this method must have" + "been de-tabified."; // Used by 'setCodeIndent_WithTabsPolicyRelative' // This needs to be a long-array, because there might be lines with lots of initial indentation. private static final char[] SPACES = new char[200]; static { java.util.Arrays.fill(SPACES, ' '); } /** * Replaces sub-strings that contain a newline character followed by only white-space with * only the new-line character itself. * * @param s Any Java {@code String}, but preferrably one which contains newline characters * ({@code '\n'}), and white-space characters immediately followng the newline, but not other * ASCII nor UNICODE. * * @return The same String with each instance of {@code ^[ \t]+\n} replaced by {@code '\n'}. */ public static String trimWhiteSpaceOnlyLines(String s) { Matcher m = EMPTY_LINE.matcher(s); return m.replaceAll("\n"); } /** * Will iterate through <I>each line of text</I> within the input {@code String}-parameter * {@code 's'}, and right-trim the lines. "Right Trim" means to remove all white-space * characters that occur <I><B>after</I></B> the last non-white-space character on the line. * (Does not remove the new-line character ({@code '\n'}) itself). * * <BR /><BR /><B>NOTE:</B> Any line of text which contains only white-space characters is * reduced to a single new-line character. * * @param s Any Java {@code String}, preferrably one with several new-line characters. * * @return The same text, but only after having any 'trailing white-space' characters removed * from each line of text. */ public static String rightTrimAll(String s) { // 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); } /** * Will iterate through <I>each line of text</I> within the input {@code String}-parameter * {@code 's'}, and left-trim the lines. "Left Trim" means to remove all white-space * characters that occur <I><B>before</I></B> the last non-white-space character on the line. * (Does not remove the new-line character ({@code '\n'}) itself). * * <BR /><BR /><B>NOTE:</B> Any line of text which contains only white-space characters is * reduced to a single new-line character. * * @param s Any Java {@code String}, preferrably one with several new-line characters. * * @return The same text, but only after having any 'leading white-space' characters removed * from each line of text. */ public static String leftTrimAll(String s) { 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); } /** * This method expects to receive a method body, constructor body, or other callable body as a * {@code String}; it will remove the beginning and ending braces <CODE>('{'</CODE> & * <CODE>'}')</CODE>, and beginning & ending empty lines. This is to prepare the * method for code hiliting, used internally by the package {@code Torello.JavaDoc}. * * @param callableAsStr This should be a method body. Make sure <B>**NOT TO INCLUDE**</B> the * method signature at the beginning of the method. The first non-white-space character should * be the open braces character <CODE>('{')</CODE>, and the last non-white-space should be * the closing braces character <CODE>('&#125')</CODE>. * * @return A method body {@code String} that can be hilited using the code-hiliting mechanism * of the "JavaDoc Package." * * @throws CallableBodyException If the input parameter {@code String} does not begin and end * with the curly-braces. */ public static String chompCallableBraces(String callableAsStr) { callableAsStr = callableAsStr.trim(); if (callableAsStr.charAt(0) != '{') throw new CallableBodyException( "Passed callable does not begin with a squiggly-brace '{', but rather a: '" + callableAsStr.charAt(0) + "'\n" + callableAsStr ); if (callableAsStr.charAt(callableAsStr.length() - 1) != '}') throw new CallableBodyException( "Passed callable does not end with a squiggly-brace '}', but rather a: '" + callableAsStr.charAt(0) + "'\n"+ callableAsStr ); // This Version does a single "String.substring(...)", meaning it is more efficient // because it is not doing any extra String copies at all. // // NOTE: There is an auto-pre-increment (and pre-decrement), in both of the while loops. // Therefore, sPos starts at 'zero' - even though the open-curly-brace is the // character at position 0, and the closed-curly-brace is at position length-1. int sPos = 0; int ePos = callableAsStr.length() - 1; int first = 1; // The character after the '{' (open-curly-brace) char tempCh = 0; // temp-var // If the callable-braces are on their own line, skip that first line. // If they are **NOTE** on their own first line, the first character returned will be // the first character of source-code. while ((sPos < ePos) && Character.isWhitespace(tempCh = callableAsStr.charAt(++sPos))) if (tempCh == '\n') { first = sPos + 1; break; } // Check for the "bizarre case" that the method body just doesn't contain any code. // This means that *EVERY CHARACTER* that was checked was white-space. Return a single // space character, and be done with it. if (sPos == ePos) return " "; // When this loop terminates, 'ePos' will be pointing to the first non-white-space // character at the tail end of the source-code / String (callableAsStr is a String of // source-code used in the JavaDoc package) while ((ePos > sPos) && Character.isWhitespace(callableAsStr.charAt(--ePos))); // Starts at the 'first-white-space' character in the first line of code, and ends at the // last non-white-space character in source-code String 'callableAsStr' return callableAsStr.substring(first, ePos + 1); } /** * Accepts a method body as a {@code String} and left-shifts or right-shifts each line * of text (each {@code 'Line of Code' - LOC}) so that the indentation is consistent with * the requested-indentation input-parameter. * * <BR /><BR /><B>NOTE:</B> The lines of code contained by input-parameter {@code 'codeAsStr'} * must contain leading white-space <I><B STYLE='color: red;'>without any tab ({@code '\t'}) * characters.</B></I> 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 {@code ASCII 0x20} (space-bar characters) from the beginning * of each line of text. A leading tab-character {@code ASCII 0x09} will generate an exception * throw. * * @param codeAsStr A method body. It is expected to be the internal part of a chunk of * source code. * * @param 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. * * @return An updated method-body as a {@code String}. * * @throws StringFormatException This exception shall throw whenever a line of text contained * by the input {@code String} has a {@code '\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 {@code '\t'} gets interpreted by the editor, it is required to replace * these characters first before invoking this method. */ public static String setCodeIndent(String codeAsStr, int requestedIndent) { if (requestedIndent < 0) throw new IllegalArgumentException ("The requested indent passed to this method was a negative value: " + requestedIndent); else if (requestedIndent > 80) throw new IllegalArgumentException ("The requested indent passed to this method was greater than 80: " + requestedIndent); // Source-Code-String to char-array char[] cArr = codeAsStr.toCharArray(); // Code "Starts With New Line '\n'" boolean swNL = cArr[0] == '\n'; // Code "Ends With New Line" boolean ewNL = cArr[cArr.length - 1] == '\n'; // Location of each '\n' in the code int[] nlPosArr = StrIndexOf.all(codeAsStr, '\n'); // Unless the first character in the code is '\n', numLines - num '\n' + 1 int numLines = nlPosArr.length + (swNL ? 0 : 1); // Length of "Leading White Space" for each line of code int[] wsLenArr = new int[numLines]; // TRUE / FALSE for "only white-space" lines of code boolean[] isOnlyWSArr = new boolean[numLines]; // Amount of White-Space for the LEAST-INDENTED Line of Code int minIndent = Integer.MAX_VALUE; // These three variables are loop-control and temporary variables. int wsCount = 0; // "White Space Count" - amount of WS on each line int outArrPos = 0; // There are two parallel "Output Arrays", this the index int lastPos = 0; // Temp Var for the last-index in a line of code int i; // Simple Loop Control Variable int j; // Simple Loop Control Variable // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Compute amount of "leading white space" (indentation) for the first LOC in input-String // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Count the leading white-space in the first line of text - unless the first character // in the code was a '\n' (newline) if (! swNL) { // The array-index in array cArr of the last character in the first line of text. // If the input code-String is just a single line of code without any newline '\n' // characters, then this value is the length of the code-string. Otherwise, this // value is assigned the cArr index/position of the first newline '\n' character. lastPos = (nlPosArr.length > 0) ? nlPosArr[0] : cArr.length; // The loop iterate until we reach the end of the first line of code/text, or // we reach a character that is not white-space. for (i=0; (i < lastPos) && Character.isWhitespace(cArr[i]); i++) if (cArr[i] == '\t') throw new StringFormatException(STR_FORMAT_EX_MESSAGE); else wsCount++; // Amount of "Leading" white-space (indentation) for first LOC wsLenArr[0] = wsCount; // Was the first line only white-space? isOnlyWSArr[0] = (i == lastPos); // 'minIndent' was initialized to Integer.MAX_VALUE minIndent = wsCount; outArrPos++; } // **************************************************************************************** // Compute the amount of "leading white space" (indentation) for each LOC in input-String // **************************************************************************************** // // This loop will iterate each line of code inside the input source-code character-array // The length (number of characters) for the "leading white-space" (Which may also be called // indentation) for each LOC is stored in an integer-array called "wsLenArr" // When this loop encounters a line that is blank (contains only white-space), it is noted // in a boolean array "isOnlyWSArr" // // NOTE: The previous loop did the *EXACT SAME THING*, but ONLY for the first line of code // in the input-string. This is because the loop-control variables are slightly // different for the first line of code. for (i=0; i < nlPosArr.length; i++) { wsCount = 0; lastPos = (i < (nlPosArr.length-1)) ? nlPosArr[i+1] : cArr.length; for (j = (nlPosArr[i]+1); (j < lastPos) && Character.isWhitespace(cArr[j]); j++) if (cArr[j] == '\t') throw new StringFormatException(STR_FORMAT_EX_MESSAGE); else wsCount++; // Amount of "Leading" white-space (indentation) for current LOC wsLenArr[outArrPos] = wsCount; // Is the current LOC only white-space? isOnlyWSArr[outArrPos] = (j == lastPos); // Check if this line is the "reigning champion" of minimum of white-space indentation // Blank lines (lines with 'only white-space') cannot be factored into the // "minimum indentation" computation if (wsCount < minIndent) if (! isOnlyWSArr[outArrPos]) minIndent = wsCount; outArrPos++; } // **************************************************************************************** // Now we will shorten or extend the amount of indentation for the input code snippet. // **************************************************************************************** // // *** Keep Here for Reference *** // int[] nlPosArr // Location of each '\n' in the code // int[] wsLenArr // Length of "Leading White Space" for each line of code // boolean[] isOnlyWSArr // TRUE / FALSE for "only white-space" lines of code int diff = requestedIndent - minIndent; int delta = 0; // Intended to store the change in "Source Code as a String" LENGTH // after performing the indentation changes int nextNLPos = 0; // Position of the next newline int srcPos = 0; // index/pointer to the input "Source Code as a String" char-array int destPos = 0; // index/pointer to (output) indentation-change output char-array int nlPosArrPos = 0; // index/pointer to the "New Line Position Array" int otherArrPos = 0; // index/pointer to the other 2 position arrays // a.k.a: "White-Space-Length Array" and the // "Is Only White-Space Array" if (diff == 0) return codeAsStr; for (i=0; i < wsLenArr.length; i++) if (! isOnlyWSArr[i]) delta += diff; char[] outArr = new char[cArr.length + delta]; if (diff > 0) return indent(codeAsStr, diff, true, true); else { // We are removing white-space, start at end, work backwards srcPos = cArr.length - 1; // The "output array", therefore, also starts at end of char-array destPos = outArr.length - 1; // The "Where are the newlines array" index-pointer nlPosArrPos = nlPosArr.length - 1; otherArrPos = wsLenArr.length - 1; // The number of "lines of text" and "number of new-lines" // are *NOT NECESSARILY* identical. The former might be // longer by *PRECISELY ONE* array-element. for (; otherArrPos >= 0; otherArrPos--) { // Check if the first character in the Source-Code String is a newline. nextNLPos = (nlPosArrPos >= 0) ? nlPosArr[nlPosArrPos--] : -1; // Lines of Source Code that are only white-space shall simply be copied to // the destination/output char-array. if (isOnlyWSArr[otherArrPos]) while (srcPos >= nextNLPos) outArr[destPos--] = cArr[srcPos--]; else { // Copy the line of source code int numChars = srcPos - nextNLPos - wsLenArr[otherArrPos]; while (numChars-- > 0) outArr[destPos--] = cArr[srcPos--]; // Insert the exact amount of space-characters indentation numChars = wsLenArr[otherArrPos] + diff; while (numChars-- > 0) outArr[destPos--] = ' '; // Skip over the original indentation (white-space) from the input line // of source-code. srcPos -= (wsLenArr[otherArrPos] + 1); // Make sure to insert a new-line (since this character WASN'T copied) if (destPos >= 0) outArr[destPos--] = '\n'; } } } // **************************************************************************************** // Debug Println - This code isn't executed without the little debug-flag being set. // **************************************************************************************** // The returned code block is ready; convert to a String String ret = new String(outArr); // Do not delete. Writing the debugging information takes a lot of thought. // If there is ever an error, this code is quite important. if (! DEBUGGING_INDENTATION) return ret; try { StringBuilder sb = new StringBuilder(); sb.append( "swNL:\t\t\t\t" + swNL + '\n' + "ewNL:\t\t\t\t" + ewNL + '\n' + "numLines:\t\t\t" + numLines + '\n' + "minIndent:\t\t\t" + minIndent + '\n' + "requestedIndent:\t" + requestedIndent + '\n' + "diff:\t\t\t\t" + diff + '\n' + "delta:\t\t\t\t" + delta + '\n' + "nlPosArr:\n\t" ); for (i=0; i < nlPosArr.length; i++) sb.append(nlPosArr[i] + ", "); sb.append("\nwsLenArr:\n\t"); for (i=0; i < wsLenArr.length; i++) sb.append(wsLenArr[i] + ", "); sb.append("\nisOnlyWSArr:\n\t"); for (i=0; i < isOnlyWSArr.length; i++) sb.append(isOnlyWSArr[i] + ", "); sb.append("\n"); FileRW.writeFile( sb.toString() + "\n\n****************************************************\n\n" + codeAsStr + "\n\n****************************************************\n\n" + ret, "TEMP/method" + StringParse.zeroPad10e2(++INDENTATION_COUNTER) + ".txt" ); if (INDENTATION_COUNTER == 5) System.exit(0); } catch (Exception e) { e.printStackTrace(); System.out.println(e + "\n\nFatal Error. Exiting."); System.exit(0); } return ret; } /** * Convenience Method. * <BR />Invokes: {@link #setCodeIndent(String, int)} * <BR />Converts: All {@code '\t'} to the specified number of spaces in parameter * {@code SPACES}. * <BR /><B STYLE='color: red'>NOTE:</B> Exception-Checking is <B STYLE='color: red'>NOT</B> * done on input */ public static String setCodeIndent_WithTabsPolicyAbsolute (String codeAsStr, int requestedIndent, String SPACES) { return setCodeIndent(codeAsStr.replace("\t", SPACES), requestedIndent); } /** * 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. * * <BR /><BR />To do this, first, the number of spaces that preceed the * <B STYLE='color: red;'>least-indented</B> 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 {@code 'requestedIndent'}) is greater-than or less-than the computed * least-indented line. * * <EMBED CLASS='external-html' DATA-FILE-ID=SI_REL_TABS> * * @param codeAsStr Any Java source-code block, as a {@code java.lang.String} * * @param requestedIndent The number of spaces that the code should have as indentation. * Note, that in the JavaDoc Upgrader code, this number is always {@code '1'}. * * @param spacesPerTab If tabs are found inside this {@code String}, then they are replaced * with an appropriate number of space characters, according to a relative tab-policy, as * described above. * * @return A properly shifted-indented Java source-code block. */ public static String setCodeIndent_WithTabsPolicyRelative (String codeAsStr, int requestedIndent, int spacesPerTab) { char[] code = codeAsStr.toCharArray(); IntStream.Builder b = IntStream.builder(); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // First find all of the line-breaks / new-lines. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // NOTE: If the first character is not a new-line, then the first line is presumed to begin // at String-index '-1' // // Afterwards, convert the Stream to 'nlPos' array. Build two other arrays if (code[0] != '\n') b.accept(-1); for (int i=0; i < code.length; i++) if (code[i] == '\n') b.accept(i); int[] nlPos = b.build().toArray(); int[] wsLen = new int[nlPos.length]; int[] fcPos = new int[nlPos.length]; int maxIndent = 0; int minIndent = Integer.MAX_VALUE; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Compute how much white-space is currently at the start of each line // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // NOTE: Since this method calculates what the user is looking at in his code-editor, the // tabs-policy needs to be included in the calculation. // // Once the amount of white-space at the start of each line is computed, it will be easy // to shift the entire source-code left or right. Note that in the JavaDoc Upgrader Tool, // this is always shifted until the **LEAST INDENTED** line is indented by 1... // // REMEMBER: Shifting everything left must be a shift of an **EQUAL NUMBER OF SPACES** for // each line that is shifted. for (int i=0; i < wsLen.length; i++) { int END = (i == (nlPos.length - 1)) ? code.length : nlPos[i+1]; boolean hasCode = false; INNER: for (int j = (nlPos[i] + 1); j < END; j++) if (! Character.isWhitespace(code[j])) { fcPos[i] = j; hasCode = true; break INNER; } if (! hasCode) fcPos[i] = wsLen[i] = -1; else { // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // wsLen[i] = computeEffectiveLeadingWhiteSpace(code, nlPos[i] + 1, spacesPerTab); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // NOTE: The contents of everything within this 'else' branch is nothing more than // an inline block-copy of the method named in the comment above. Hopefully // inlining the method will speed this up a little bit. // // The values that would be passed before the method was inlined, here, are also // noted in the above comment. // // ALSO: The 'i' loop-variable was changed to a 'j' (to avoid conflicting with the // outer-loop 'i'). The "ret" was changed to "whiteSpaceChars" int whiteSpaceChars = 0; int relativeCount = 0; wsLen[i] = -1; EFFECTIVE_LEADING_WS: for (int j = (nlPos[i] + 1) /* lineFirstCharacterPos */; j < code.length; j++) if (! Character.isWhitespace(code[j])) { wsLen[j] = whiteSpaceChars; // return ret; break EFFECTIVE_LEADING_WS; } else switch (code[j]) { case ' ' : whiteSpaceChars++; relativeCount = (relativeCount + 1) % spacesPerTab; break; case '\t' : whiteSpaceChars += (spacesPerTab - relativeCount); relativeCount = 0; break; case '\r' : case '\f' : break; case '\n' : break EFFECTIVE_LEADING_WS; // return -1; default: throw new UnreachableError(); } // return -1; <== Not needed, the array-location is initialized to -1 } if (wsLen[i] == -1) continue; if (wsLen[i] > maxIndent) maxIndent = wsLen[i]; if (wsLen[i] < minIndent) minIndent = wsLen[i]; } // This is the amount of space to shift each line. int delta = requestedIndent - minIndent; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // NOW: Rebuild the source-code string, making sure to shift each line. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** StringBuilder sb = new StringBuilder(); for (int i=0; i < wsLen.length; i++) // The array "White-Space-Length" will have a '-1' if the entire line is nothing but // white-space. In such cases, simply append a '\n' - there is no reason to add extra // spaces. The code hilited just ignores it. if (wsLen[i] == -1) sb.append('\n'); // Otherwise append the leading white-space, and then the line-of-code. else { // First append the white-space at the beginning of the line. int numSpaces = wsLen[i] + delta; sb.append(SPACES, 0, numSpaces); // Now append the line of code. Since there may be tabs after the first // non-white-space character, this is a little complicated... // // NOTE: This could be inlined, but this method just does too much... // // The char[]-Array 'code' has the code. The text of the source-code begins at // array-index 'First-Character-Position' (fcPos). This method needs the parameter // 'numSpaces' to make sure the tabs stay properly-relativised... sb.append(lineOfCodeAsStr(code, numSpaces, fcPos[i], spacesPerTab)); } // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // FINISHED: Return the Source-Code String // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** return sb.toString(); } /** * 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. * * <BR /><BR /><B STYLE='color: red;'>IMPORTANT:</B> 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. * * @param code A Java source-code {@code String}, that has been converted into a Java * {@code char[]}-Array. The line of code whose leading white-space is being computed may be * located anywhere in the array. * * <BR /><BR /><B>NOTE:</B> These types of arrays are easily creaated by invoking the * {@code java.lang.String} method {@code 'toCharArray()'} * * @param lineFirstCharacterPos The array-index to be considered as the first character of * non-new-line character data. * * @param spacesPerTab The number of spaces that a tab-character ({@code '\t'}) intends to * represent. * * <BR /><BR />When {@code FALSE} is passed to this parameter, a tab-character will represent * a {@code String} of space-characters whose length is equal to the number of space-characters * that remain until the next modulo-{@code spacesPerTab} boundary. * * @return The number of space-characters ({@code ' '}) that should preceede the line of source * code. * * <BR /><BR /><B STYLE='color: red'>NOTE:</B> If this line of source-code is a white-space * <B STYLE='color: red;'>ONLY</B> line, then {@code -1} will be returned. */ public static int computeEffectiveLeadingWhiteSpace (char[] code, int lineFirstCharacterPos, int spacesPerTab) { 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; } /** * Replaces tab-characters ({@code '\t'}) in a single-line of source-code with a * relative-number of space-characters ({@code ' '}). * * <EMBED CLASS='external-html' DATA-FILE-ID=SI_REL_TABS> * * <BR /><BR /><B STYLE='color: red;'>IMPORTANT:</B> 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. * * @param 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. * * <BR /><BR /><B>NOTE:</B> These types of arrays are easily creaated by invoking the * {@code java.lang.String} method {@code 'toCharArray()'} * * @param numLeadingSpaces The number of spaces that have been placed before the start of this * line of code. This is needed because <B STYLE='color: red;'>relative</B>-tabs are computed * based on integral-multiples of the tab-width ({@code 'spacesPerTab'}). * * <BR /><BR />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. <I>After converting * tab-characters ({@code '\t'}) to spaces ({@code ' '}), this number will often change.</I> * * @param 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 * <B STYLE='color: red;'>does not</B> contain white-space. * * @param spacesPerTab The number of spaces that are used to replaces tab-characters. Since * this method performs relative tab-replacement, this constitutes the * <B STYLE='color: red;'>maximum</B> number of space characters that will be used to replace * a tab. * * @return A line of code, as a {@code String}, without any leading white-space, and one in * which all tab-characters have been replaced by spaces. */ public static String lineOfCodeAsStr (char[] code, int numLeadingSpaces, int fcPos, int spacesPerTab) { StringBuilder sb = new StringBuilder(); // Loop Control Variables int possibleEndingWhiteSpaceCount = 0; int relativePos = numLeadingSpaces % spacesPerTab; int i = fcPos; while ((i < code.length) && (code[i] != '\n')) { if (code[i] == '\t') while (relativePos < 4) { sb.append(' '); relativePos++; possibleEndingWhiteSpaceCount++; } else if ((code[i] == ' ') || (code[i] == '\r') || (code[i] == '\f')) { sb.append(' '); relativePos++; possibleEndingWhiteSpaceCount++; } else { sb.append(code[i]); relativePos++; possibleEndingWhiteSpaceCount=0;} i++; relativePos %= 4; } if (i < code.length) { if (possibleEndingWhiteSpaceCount > 0) { sb.setCharAt(sb.length() - possibleEndingWhiteSpaceCount, '\n'); return sb.substring(0, sb.length() - possibleEndingWhiteSpaceCount + 1); } else return sb.append('\n').toString(); } return (possibleEndingWhiteSpaceCount > 0) ? sb.substring(0, sb.length() - possibleEndingWhiteSpaceCount) : sb.toString(); } /** * This performs a variation of "indentation" on a Java {@code String} - simply put - it * replaces each new-line character ({@code '\n'}) with a {@code String} that begins with a * new-line, and is followed by {@code 'n'} blank white-space characters {@code ' '}. * * If the input {@code String} parameter {@code 's'} is of zero-length, then the zero-length * {@code String} is returned. If the final character in the input {@code String} is a * new-line, that new-line is not padded. * * @param s Any {@code java.lang.String} - preferably one that contains new-line characters. * * @param n The number of white-space characters to use when pre-pending white-space to each * line of text in input-parameter {@code 's'} * * @return A new {@code java.lang.String} where each line of text has been indented by * {@code 'n'} blank white-space characters. If the text ends with a new-line, that line of * text is not indented. * * @throws NException If parameter {@code 'n'} is less than one. */ public static String indent(String s, int n) { 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; } /** * Identical to {@link #indent(String, int)}, but pre-pends a {@code TAB} character {@code 'n'} * times, rather than a space-character {@code ' '}. * * @param s Any {@code java.lang.String} - preferably one that contains new-line characters. * * @param n The number of tab ({@code '\t'}) characters to use when pre-pending to each line of * text within input-parameter {@code 's'} * * @return A new {@code java.lang.String} where each line of text has been indented by * {@code 'n'} tab characters. If the text ends with a new-line, that line of text is not * indented. * * @throws NException If parameter {@code 'n'} is less than one. */ public static String indentTabs(String s, int n) { 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; } /** * 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 <I>does not indent lines of text that only contain white-space!</I> * * <DIV CLASS=EXAMPLE>{@code * // ***************************** * // 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. * }</DIV> * * @param s Any {@code java.lang.String} - preferably one that contains new-line characters. * * @param n The number of tab ({@code '\t'}) characters to use when pre-pending to each line of * text in input-parameter {@code 's'} * * @param spaceOrTab When this parameter is passed <B>{@code TRUE}</B>, the space character * {@code ' '} is used for indentation. When <B>{@code FALSE}</B>, the tab-character * {@code '\t'} is used. * * @return A new {@code java.lang.String} where each line of text has been indented by * {@code 'n'} characters of spaces or tabs, dependent upon the value of parameter * {@code 'spaceOrTab'}. * * <BR /><BR />The returned {@code String} differs from the returns of the other two * {@code '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, * <I>is not idented</I>. Succinctly, only lines containing non-white-space characters are * actually indented. * * @throws NException If parameter {@code 'n'} is less than one. */ public static String indent (final String s, int n, boolean spaceOrTab, boolean trimBlankLines) { 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; } /** * Throws a new {@code ToDoException} * * @return Will (one day) return an unindented String. */ public static String unIndent( String s, int n, boolean trimBlankLines, boolean rightTrimLines, boolean throwOnTab, boolean throwOnNotEnough, boolean dontThrowOnWhiteSpaceOnlyLines ) { 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(); } /** * Performs an indenting of {@code 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). * * @param s Any instance of {@code java.lang.String}. * @param n The number of space-characters to insert after each newline {@code '\n'} character. * @param spaceOrTab When {@code TRUE}, then there shall be {@code 'n'}-number of space * characters ({@code ' '}) inserted at the beginning of each line of text. When * {@code FALSE}, then this function will insert {@code 'n'} tab characters. * @param trimBlankLines When {@code TRUE}, requests that blank lines be trimmed to only * a single newline ({@code '\n'}) character. * @return The indented {@code String} */ public static String indentAfter2ndLine (String s, int n, boolean spaceOrTab, boolean trimBlankLines) { 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); } /** * 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 {@code 4} spaces, then if a line in a * source-code file had three leading tab-characters, then those three leading * {@code char '\t'} would be replaced with {@code 12} leading space characters {@code ' '}. * * @param javaSrcFileAsStr A Java Source-Code File, loaded as a {@code String}. * * @param numSpacesPerTab This identifies the number of spaces a {@code char '\t'} is supposed * to represent in any source-code editor's settings. In Google Cloud Server, the default * value is '4' spaces. */ public static String tabsToSpace(String javaSrcFileAsStr, int numSpacesPerTab) { 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(); } } |