> codebench_TOOL: HomeLOCAL-ONLY⌘K Switch

YAML Block Scalars: Line Breaks in Literal and Folded Text, With Chomping

Write a maintenance notice in YAML, then inspect its parsed JSON to see what literal style, folded style, and chomping do to the string.

·13 min readAbout the maintainer
The same two source lines, Search is paused. and Saved links still work., produce a newline with literal style or a space with folded style.

A documentation team keeps a maintenance notice in YAML. During a search outage, a status banner should display two sentences as one paragraph. A plain text version of the notice also includes a short indented list, where each line has to stay on its own. An editor wraps a long sentence in the YAML file for review, and suddenly the exported notice has an extra line break. Later, a blank line appears above the footer even though nobody edited the footer. Both surprises originate in the notice field, but they require different fixes.

A YAML block scalar is a way to write one value across several source lines. The first symbol in its header decides how to treat breaks inside the text: | is literal and > is folded. An optional - or + changes how the value ends. These decisions are independent. A maintainer can make the notice read as prose without adding a newline at the end, or preserve all its internal lines while keeping exactly one final newline. To tell which decision needs changing, inspect the string the parser returns, not just how it looks in the file.

Start with two source lines

Open the YAML Validator, paste this mapping into the input on the left, and select Validate. The output on the right is JSON. A successful validation tells you the YAML was accepted; the output tells you what you actually wrote. Both fields hold the same words and punctuation. The only meaningful difference in the headers is the first symbol: both carry the same - suffix so neither value ends in a newline.

literal: |-
  Search is paused.
  Saved links still work.
folded: >-
  Search is paused.
  Saved links still work.
{
  "literal": "Search is paused.\nSaved links still work.",
  "folded": "Search is paused. Saved links still work."
}

The literal value contains a line feed immediately after the first period. The folded value has an ordinary space there instead. The two leading spaces on each content line mark the extent of the block and are not part of either value. In this mapping, folded starts at the same indentation as literal, so it is a separate key, not another line of the message. If you reindent the content of a block consistently, the basic indent can change without changing the value. Indenting a single line further than its neighbors is a different edit, as the next exercise shows.

For the status banner, the folded result is the better fit. It leaves wrapping to the display, rather than choosing a visual line length in the configuration file. For a fixed two line message in a plain text export, use the literal result. Do not make this choice based on what a browser does with the literal string in an ordinary HTML paragraph. HTML can collapse a newline and a space to the same apparent gap. The strings still differ, even when the banner makes them look identical.

Try rewrapping the second sentence after links, without adding a blank line. With folded style the new source break becomes the same space that was already between links and still, so the parsed text stays the same. With literal style the same edit inserts another line feed. This is a useful review distinction: reflowing normal prose under > need not change its value, but reflowing the content under | can change the exported notice even if not a single word changes.

Follow the boundaries inside a folded block

The team now adds a second paragraph and a compact list for the plain text export. It wants to keep the paragraphs distinct but still wrap their source lines for review. Folded style can do both. Keep ordinary prose at the base indent, put a blank source line between paragraphs, and give the two list lines two extra spaces. These are just lines of text inside the scalar, not YAML sequence items. The format key is back at the outer indentation, outside the notice.

notice: >-
  Search is paused.
  Saved links still work.

  While search is offline:
    Use saved links.
    Open the index.
  Search will return shortly.
format: text
{
  "notice": "Search is paused. Saved links still work.\nWhile search is offline:\n  Use saved links.\n  Open the index.\nSearch will return shortly.",
  "format": "text"
}

Trace the breaks from top to bottom. Between the first two lines, both at the base indent, YAML folds the break to a space. The one empty line after the first paragraph produces one line feed before While, not two. Next come the lines with extra indentation. The breaks before, between, and after those lines stay as line feeds. The two spaces before each list entry stay too. After the last sentence, - strips the ending. It has no effect on any of the breaks you just traced.

In the folded notice, an ordinary break becomes a space, one blank source line becomes one line feed, breaks around and between more-indented lines stay as line feeds, and the strip suffix removes the ending.
Read the folded notice one boundary at a time. The rules that protect the list are separate from the rule that removes the final newline.

A useful distinction for the export: a paragraph boundary in the folded result is not necessarily a visible blank row. If the plain text design calls for an empty row between the opening paragraph and the list introduction, add a second blank source line there and validate again. The ordinary paragraphs in this example will then be separated by two line feeds. If you instead change >- to |-, you preserve every interior source break: the opening sentences split again, and the original single blank source line becomes a visible empty row. Choose whether the source layout itself is the format, or just a way to write the format.

There is a trap in treating the extra indent as cosmetic. Suppose an editor aligns Open the index. with the prose instead of with Use saved links.. Now the break before Open still touches a more indented line, but the break between Open and Search will return shortly. touches two ordinary lines. That second break folds to a space, joining the list entry with the closing sentence. The indentation also disappears from Open in the output. Check both boundaries of an edited line, not just the first character on that line.

Here the first nonempty content line establishes the base indent because there is no explicit indentation indicator in the header. That works for a notice that opens with ordinary prose. But what if the team needs a compact fallback notice containing just the two indented instructions? If both source lines start with four spaces, automatic detection treats all four as structural indentation. Neither line in the result begins with a space. That is valid YAML, so the validator will not flag it as a mistake.

Specify the baseline explicitly when the value starts with meaningful indentation. Compare these two versions of the fallback. The first detects the indent. The second uses 2 to set the content indent to two spaces in this top level mapping. Both use literal style to preserve the interior break and strip to remove the ending. The leading spaces on the source lines are identical; only the digit changes.

automatic: |-
    Use saved links.
    Open the index.
explicit: |2-
    Use saved links.
    Open the index.
{
  "automatic": "Use saved links.\nOpen the index.",
  "explicit": "  Use saved links.\n  Open the index."
}

In the explicit version, YAML consumes two spaces as indentation and delivers the other two as text on each line. This is not a command to indent the output by two spaces. If the source content already has two leading spaces, there is nothing left after the structural indent is removed. If you nest the mapping, read the digit relative to the enclosing indentation level, not as a column number on the screen. For the original notice, the prose still provides a natural baseline; the fallback is where the digit earns its place.

Decide what the notice ends with

The export joins the notice and footer in plain text. It can insert its own separator between them. If it inserts one line feed and the notice already ends with one, the footer begins after two line feeds instead of one. If the separator is omitted and the notice has been stripped, the footer begins on the same line as the last sentence. To separate the parser's behavior from the exporter's, test all three endings on the same text. Here the source contains one empty line following each instance of Saved links still work.. Each empty line is followed by another key so it cannot disappear when you copy the final line of the example.

clip: >
  Saved links still work.

strip: >-
  Saved links still work.

keep: >+
  Saved links still work.

format: text
{
  "clip": "Saved links still work.\n",
  "strip": "Saved links still work.",
  "keep": "Saved links still work.\n\n",
  "format": "text"
}

Clip is the default when there is no suffix. It preserves the last content line's terminating break when present, and discards subsequent trailing empty lines. Strip, written -, discards both the terminating break and those trailing empty lines. Keep, written +, preserves both. In this sample, keep ends with two line feeds: one terminates the sentence, and the other terminates the empty line. Clip keeps only the first, while strip keeps neither. The same three choices work with |, |-, and |+. Try replacing the folded headers with those literal equivalents here. There is no internal break in any of these values, so the outputs stay the same.

The exact end of the source matters. At end of file with no final line terminator, don't infer a portable result from what one implementation shows: the npm yaml parser used here can still return a final line feed with clip or keep. A formatting step that adds empty lines after a kept notice can also change the value, even if the text on every nonempty line stays identical. The next key in the exercise gives you a visible boundary for counting the breaks. When diagnosing a real file that ends with a scalar, inspect the parsed string using the same parser as the exporter.

For the export, give one layer ownership of the separator. If the exporter joins notice and footer with a newline, use strip for the notice. If it expects the notice to supply its own terminator, clip is appropriate when the source actually has one. Use keep only when the trailing blank lines are part of the intended output. Otherwise a harmless looking end of file cleanup can become a formatting regression. This decision belongs in the field's contract, next to whether the exporter will append a footer at all.

Use the three parsed endings to predict what happens when the export appends the same footer, Documentation team. With strip and one separator, the footer starts on the next line. With clip and the same separator, there is one empty row before the footer. With keep and the same separator, there are two. If an editor asks for one empty row, prefer making that a decision in the export layout rather than requiring authors to leave an invisible extra line in YAML. The separator belongs to the layout, while the notice belongs to the content.

The banner has no footer, so the text should also stand alone. In particular, do not remove whitespace from every line to make the banner and the export agree. That would erase the list indentation the plain text version relies on. If the banner only needs the opening paragraph, give that paragraph its own field and let the export combine it with the rest. Splitting the full notice at the first line feed would tie the banner to a boundary that might move the next time an author adds another paragraph.

When a footer is optional, add the separator only when there is a footer to join. If the plain text file itself must end with a newline, apply that policy to the assembled file. It should not depend on whether the notice or the footer happened to be the last field.

Read the JSON as a representation

The validator's JSON panel shows \n for a line feed inside a string. That does not mean a backslash and an n are present in the notice. JSON cannot put an unescaped line feed inside a quoted string, so the serializer writes those two visible characters to represent one character in the value. A physical newline between JSON properties is different again: it is whitespace in the serialization, not part of a property value. It helps to read the quoted value rather than counting rows in the pretty printed JSON.

To see both cases side by side, compare the literal block with a source break against the second block, where the editor typed a backslash and an n. Backslashes do not introduce escapes in a YAML block scalar. The third field uses a YAML double quoted scalar as a control: that style interprets the typed escape and produces the same value as the first field.

lineBreak: |-
  Search is paused.
  Saved links still work.
typedEscape: |-
  Search is paused.\nSaved links still work.
quoted: "Search is paused.\nSaved links still work."
{
  "lineBreak": "Search is paused.\nSaved links still work.",
  "typedEscape": "Search is paused.\\nSaved links still work.",
  "quoted": "Search is paused.\nSaved links still work."
}

In the middle property, the two backslashes in the JSON escape a single literal backslash. The n that follows it is ordinary text. After JSON decoding, a plain text renderer will print that middle message on one line with a visible \n, while the other two messages break after the first sentence. A consumer should decode the JSON normally, not search and replace every apparent \n. That would turn intentional text in the middle field into a line break and could also misread backslashes that belonged to the original value.

If the export still looks wrong, compare the string immediately after YAML parsing with the string handed to the renderer. An actual line feed in the parsed value that later disappears points to a downstream transformation or a display that collapses whitespace. A visible backslash in the parsed value points to the input style or to an already serialized string passed along as text. This check narrows the problem without guessing from a screenshot. It also handles Windows source files: YAML normalizes line breaks in scalar content to line feeds, so you need not expect a carriage return in the value just because the editor saved the source with CRLF.

Review the notice at the string boundary

Start the review with the expected parsed notice, before asking whether the source looks tidy. Check three places: an ordinary wrap in the opening sentences, both sides of the indented list, and the final character before the footer is attached. A whitespace insensitive snapshot of the rendered banner is a poor check for any of these. A comparison against an exact string catches the lost indentation and the unexpected trailing break as well as the inadvertent join between list text and prose. Keep an expected value that includes a paragraph break, not only a single sentence where the choice of block style has nothing to do.

A useful regression check is to rewrap one sentence inside the opening paragraph and confirm that its parsed value is unchanged. Then remove one of the list's extra indents and confirm that the value changes. Those two edits look similar in a text diff, but the first is a presentation choice and the second modifies the data. For a third check, hold the notice and footer text constant and verify the separator after concatenation. That makes it clear whether the parser or the join operation added the extra break. If the banner and the export diverge only after this point, change the rendering or joining code rather than compensating in the YAML.

The formal rules and examples are in the YAML 1.2.2 specification's sections on block indentation, block chomping, literal style, and folded style. Use the validator to see how those rules apply to the exact text you are about to ship. For this notice, >- handles ordinary prose wraps, protects the indented lines, and leaves the footer separator to the exporter. If the source breaks themselves become part of the design, switch to |- and keep the same ending policy.

#yaml#configuration#strings
> codebench $Ctrl+Enter Run