• Incidental White Space

    Ideally, a text block would be indented to match the indentation of the surrounding code. For example:

    However, this raises the question of how spaces used for indentation affect the contents of the string. A naïve interpretation would include all of this whitespace in the text block. The consequence would be that reindenting the code would affect the contents of the text block. This is quite likely to be an error.

    To avoid this problem, a text block differentiates incidental white space from essential white space. The Java compiler automatically strips away the incidental white space. The indentation to the left of htmland /html is considered incidental, since these lines are indented the least. Thus, they effectively determine the left margin of the text in the text block. However, the indentation of body relative to htmlis not considered to be incidental white space. Presumably, this relative indentation is intended to be part of the string's contents.

    The example below uses "·" to visualize the incidental white space, with essential white space shown as actual white space.

    After the incidental white space is stripped, the resulting contents of the text block are as follows:

    The algorithm for determining incidental white space is described in JEP 378 in detail. Nevertheless, the net effect is quite simple. The entire contents of the text block is shifted to the left until the line with the least leading white space has no leading white space.

    To preserve some white space and not have it be considered incidental white space, simply shift the content lines of the text block to the right, while keeping the closing triple-quote delimiter at the indentation appropriate for the surrounding code. For example:

    results in the following:

    A text block can opt out of incidental white space stripping by positioning the closing delimiter in the first character position of a source line:

    The result is that there is no incidental white space that is stripped, and the string includes leading white space on each line.

    This technique for controlling the amount of indentation that is preserved only works if the last line of the text block ends with a line terminator. If the last line does not end with a line terminator, you need to use String::indent to control the indentation explicitly. In the following example,

    all of the indentation is treated as incidental and is stripped away:

    To include some indentation in the string's contents, invoke the indent method on the text block:

    This results in: