< prev index next >

src/java.base/share/classes/java/lang/String.java

Print this page
rev 54939 : 8223775: String::stripIndent (Preview)

@@ -34,10 +34,11 @@
 import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.Formatter;
+import java.util.List;
 import java.util.Locale;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Spliterator;
 import java.util.StringJoiner;

@@ -2795,15 +2796,10 @@
      */
     public boolean isBlank() {
         return indexOfNonWhitespace() == length();
     }
 
-    private Stream<String> lines(int maxLeading, int maxTrailing) {
-        return isLatin1() ? StringLatin1.lines(value, maxLeading, maxTrailing)
-                          : StringUTF16.lines(value, maxLeading, maxTrailing);
-    }
-
     /**
      * Returns a stream of lines extracted from this string,
      * separated by line terminators.
      * <p>
      * A <i>line terminator</i> is one of the following:

@@ -2831,11 +2827,11 @@
      * @return  the stream of lines extracted from this string
      *
      * @since 11
      */
     public Stream<String> lines() {
-        return lines(0, 0);
+        return isLatin1() ? StringLatin1.lines(value) : StringUTF16.lines(value);
     }
 
     /**
      * Adjusts the indentation of each line of this string based on the value of
      * {@code n}, and normalizes line termination characters.

@@ -2871,16 +2867,14 @@
      * @see Character#isWhitespace(int)
      *
      * @since 12
      */
     public String indent(int n) {
-        return isEmpty() ? "" :  indent(n, false);
+        if (isEmpty()) {
+            return "";
     }
-
-    private String indent(int n, boolean removeBlanks) {
-        Stream<String> stream = removeBlanks ? lines(Integer.MAX_VALUE, Integer.MAX_VALUE)
-                                             : lines();
+        Stream<String> stream = lines();
         if (n > 0) {
             final String spaces = " ".repeat(n);
             stream = stream.map(s -> spaces + s);
         } else if (n == Integer.MIN_VALUE) {
             stream = stream.map(s -> s.stripLeading());

@@ -2899,10 +2893,112 @@
         return isLatin1() ? StringLatin1.lastIndexOfNonWhitespace(value)
                           : StringUTF16.lastIndexOfNonWhitespace(value);
     }
 
     /**
+     * Returns a string whose value is this string, with incidental white space
+     * removed from the beginning and end of every line.
+     * <p>
+     * Incidental white space is often present in a text block to align the
+     * content with the opening delimiter. For example, in the following code,
+     * dots represent incidental white space:
+     * <blockquote><pre>
+     * String html = """
+     * ..............&lt;html&gt;
+     * ..............    &lt;body&gt;
+     * ..............        &lt;p&gt;Hello, world&lt;/p&gt;
+     * ..............    &lt;/body&gt;
+     * ..............&lt;/html&gt;
+     * ..............""";
+     * </pre></blockquote>
+     * This method treats the incidental white space as indentation to be
+     * stripped, producing a string that preserves the relative indentation of
+     * the content. Using | to visualize the start of each line of the string:
+     * <blockquote><pre>
+     * |&lt;html&gt;
+     * |    &lt;body&gt;
+     * |        &lt;p&gt;Hello, world&lt;/p&gt;
+     * |    &lt;/body&gt;
+     * |&lt;/html&gt;
+     * </pre></blockquote>
+     * First, this string is conceptually separated into lines as if by
+     * {@link String#lines()}.
+     * <p>
+     * Then, the <i>minimum indentation</i> (min) is determined as follows.
+     * For each non-blank line (as defined by {@link String#isBlank()}), the
+     * leading {@link Character#isWhitespace(int) white space} characters are
+     * counted. The leading {@link Character#isWhitespace(int) white space}
+     * characters on the last line are are also counted even if blank.
+     * The <i>min</i> value is the smallest of these counts.
+     * <p>
+     * For each non-blank line, <i>min</i> leading white space characters are
+     * removed, and any trailing white space characters are removed.
+     * <p>
+     * Finally, the lines are joined with a line feed character {@code "\n"}
+     * (U+000A) into a single string and returned.
+     *
+     * @apiNote
+     * This method's primary purpose is to shift a block of lines as far as
+     * possible to the left, while preserving relative indentation. Lines
+     * that were indented the least will thus have no leading white space.
+     *
+     * @implNote
+     * This method treats all white space characters as having equal weight.
+     * As long as the indentation on every line is consistently composed
+     * of the same character sequences, then the result will be as described
+     * above.
+     *
+     * @return string with margins removed and line terminators normalized
+     *
+     * @see String#lines()
+     * @see String#isBlank()
+     * @see String#indent(int)
+     * @see Character#isWhitespace(int)
+     *
+     * @since 13
+     *
+     * @deprecated  Preview feature associated with Text Blocks.
+     *              Use at your own risk.
+     */
+    @Deprecated(forRemoval=true, since="13")
+    public String stripIndent() {
+        int length = length();
+        if (length == 0) {
+            return "";
+        }
+        char lastChar = charAt(length - 1);
+        boolean optOut = lastChar == '\n' || lastChar == '\r';
+        List<String> lines = lines().collect(Collectors.toList());
+        final int outdent = optOut ? 0 : outdent(lines);
+        return lines.stream()
+            .map(line -> {
+                int firstNonWhitespace = line.indexOfNonWhitespace();
+                int lastNonWhitespace = line.lastIndexOfNonWhitespace();
+                return firstNonWhitespace > lastNonWhitespace
+                    ? "" : line.substring(Math.min(outdent, firstNonWhitespace), lastNonWhitespace);
+            })
+            .collect(Collectors.joining("\n", "", optOut ? "\n" : ""));
+    }
+
+    private static int outdent(List<String> lines) {
+        // Note: outdent is guaranteed to be zero or positive number.
+        // If there isn't a non-blank line then the last must be blank
+        int outdent = Integer.MAX_VALUE;
+        for (String line : lines) {
+            int leadingWhitespace = line.indexOfNonWhitespace();
+            if (leadingWhitespace != line.length()) {
+                outdent = Integer.min(outdent, leadingWhitespace);
+            }
+        }
+        String lastLine = lines.get(lines.size() - 1);
+        if (lastLine.isBlank()) {
+            outdent = Integer.min(outdent, lastLine.length());
+        }
+        return outdent;
+    }
+
+    /**
      * This method allows the application of a function to {@code this}
      * string. The function should expect a single String argument
      * and produce an {@code R} result.
      * <p>
      * Any exception thrown by {@code f()} will be propagated to the
< prev index next >