[string] How do I break a string in YAML over multiple lines?

In YAML, I have a string that's very long. I want to keep this within the 80-column (or so) view of my editor, so I'd like to break the string. What's the syntax for this?

In other words, I have this:

Key: 'this is my very very very very very very long string'

and I'd like to have this (or something to this effect):

Key: 'this is my very very very ' +
     'long string'

I'd like to use quotes as above, so I don't need to escape anything within the string.

This question is related to string syntax yaml newline

The answer is


In case you're using YAML and Twig for translations in Symfony, and want to use multi-line translations in Javascript, a carriage return is added right after the translation. So even the following code:

var javascriptVariable = "{{- 'key'|trans -}}";

Which has the following yml translation:

key: >
    This is a
    multi line 
    translation.

Will still result into the following code in html:

var javascriptVariable = "This is a multi line translation.
";

So, the minus sign in Twig does not solve this. The solution is to add this minus sign after the greater than sign in yml:

key: >-
    This is a
    multi line 
    translation.

Will have the proper result, multi line translation on one line in Twig:

var javascriptVariable = "This is a multi line translation.";

For situations were the string might contain spaces or not, I prefer double quotes and line continuation with backslashes:

key: "String \
  with long c\
  ontent"

But note about the pitfall for the case that a continuation line begins with a space, it needs to be escaped (because it will be stripped away elsewhere):

key: "String\
  \ with lon\
  g content"

If the string contains line breaks, this needs to be written in C style \n.

See also this question.


You might not believe it, but YAML can do multi-line keys too:

?
 >
 multi
 line
 key
:
  value

None of the above solutions worked for me, in a YAML file within a Jekyll project. After trying many options, I realized that an HTML injection with <br> might do as well, since in the end everything is rendered to HTML:

name: | In a village of La Mancha <br> whose name I don't <br> want to remember.

At least it works for me. No idea on the problems associated to this approach.


To preserve newlines use |, for example:

|
  This is a very long sentence
  that spans several lines in the YAML
  but which will be rendered as a string
  with newlines preserved.

is translated to "This is a very long sentence?\n that spans several lines in the YAML?\n but which will be rendered as a string?\n with newlines preserved.\n"


To concatenate long lines without whitespace, use double quotes and escape the newlines with backslashes:

key: "Loremipsumdolorsitamet,consecteturadipiscingelit,seddoeiusmodtemp\
  orincididuntutlaboreetdoloremagnaaliqua."

(Thanks @Tobia)


1. Block Notation(plain, flow-style, scalar): Newlines become spaces and extra newlines after the block are removed

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

Equivalent JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2. Literal Block Scalar: A Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

Equivalent JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – indicator with Literal Block Scalar: means that the newline at the end of the string is removed.

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

Equivalent JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

for more you can visit my Blog


There are 5 6 NINE (or 63*, depending how you count) different ways to write multi-line strings in YAML.

TL;DR

  • Use > most of the time: interior line breaks are stripped out, although you get one at the end:

    key: >
      Your long
      string here.
    
  • Use | if you want those linebreaks to be preserved as \n (for instance, embedded markdown with paragraphs).

    key: |
      ### Heading
    
      * Bullet
      * Points
    
  • Use >- or |- instead if you don't want a linebreak appended at the end.

  • Use "..." if you need to split lines in the middle of words or want to literally type linebreaks as \n:

    key: "Antidisestab\
     lishmentarianism.\n\nGet on it."
    
  • YAML is crazy.

Block scalar styles (>, |)

These allow characters such as \ and " without escaping, and add a new line (\n) to the end of your string.

> Folded style removes single newlines within the string (but adds one at the end, and converts double newlines to singles):

Key: >
  this is my very very very
  long string

? this is my very very very long string\n

| Literal style turns every newline within the string into a literal newline, and adds one at the end:

Key: |
  this is my very very very 
  long string

? this is my very very very\nlong string\n

Here's the official definition from the YAML Spec 1.2

Scalar content can be written in block notation, using a literal style (indicated by “|”) where all line breaks are significant. Alternatively, they can be written with the folded style (denoted by “>”) where each line break is folded to a space unless it ends an empty or a more-indented line.

Block styles with block chomping indicator (>-, |-, >+, |+)

You can control the handling of the final new line in the string, and any trailing blank lines (\n\n) by adding a block chomping indicator character:

  • >, |: "clip": keep the line feed, remove the trailing blank lines.
  • >-, |-: "strip": remove the line feed, remove the trailing blank lines.
  • >+, |+: "keep": keep the line feed, keep trailing blank lines.

"Flow" scalar styles (, ", ')

These have limited escaping, and construct a single-line string with no new line characters. They can begin on the same line as the key, or with additional newlines first.

plain style (no escaping, no # or : combinations, limits on first character):

Key: this is my very very very 
  long string

double-quoted style (\ and " must be escaped by \, newlines can be inserted with a literal \n sequence, lines can be concatenated without spaces with trailing \):

Key: "this is my very very \"very\" loooo\
  ng string.\n\nLove, YAML."

"this is my very very \"very\" loooong string.\n\nLove, YAML."

single-quoted style (literal ' must be doubled, no special characters, possibly useful for expressing strings starting with double quotes):

Key: 'this is my very very "very"
  long string, isn''t it.'

"this is my very very \"very\" long string, isn't it."

Summary

In this table, _ means space character. \n means "newline character" (\n in JavaScript), except for the "in-line newlines" row, where it means literally a backslash and an n).

                      >     |            "     '     >-     >+     |-     |+
-------------------------|------|-----|-----|-----|------|------|------|------  
Trailing spaces   | Kept | Kept |     |     |     | Kept | Kept | Kept | Kept
Single newline => | _    | \n   | _   | _   | _   | _    |  _   | \n   | \n
Double newline => | \n   | \n\n | \n  | \n  | \n  | \n   |  \n  | \n\n | \n\n
Final newline  => | \n   | \n   |     |     |     |      |  \n  |      | \n
Final dbl nl's => |      |      |     |     |     |      | Kept |      | Kept  
In-line newlines  | No   | No   | No  | \n  | No  | No   | No   | No   | No
Spaceless newlines| No   | No   | No  | \   | No  | No   | No   | No   | No 
Single quote      | '    | '    | '   | '   | ''  | '    | '    | '    | '
Double quote      | "    | "    | "   | \"  | "   | "    | "    | "    | "
Backslash         | \    | \    | \   | \\  | \   | \    | \    | \    | \
" #", ": "        | Ok   | Ok   | No  | Ok  | Ok  | Ok   | Ok   | Ok   | Ok
Can start on same | No   | No   | Yes | Yes | Yes | No   | No   | No   | No
line as key       |

Examples

Note the trailing spaces on the line before "spaces."

- >
  very "long"
  'string' with

  paragraph gap, \n and        
  spaces.
- | 
  very "long"
  'string' with

  paragraph gap, \n and        
  spaces.
- very "long"
  'string' with

  paragraph gap, \n and        
  spaces.
- "very \"long\"
  'string' with

  paragraph gap, \n and        
  s\
  p\
  a\
  c\
  e\
  s."
- 'very "long"
  ''string'' with

  paragraph gap, \n and        
  spaces.'
- >- 
  very "long"
  'string' with

  paragraph gap, \n and        
  spaces.

[
  "very \"long\" 'string' with\nparagraph gap, \\n and         spaces.\n", 
  "very \"long\"\n'string' with\n\nparagraph gap, \\n and        \nspaces.\n", 
  "very \"long\" 'string' with\nparagraph gap, \\n and spaces.", 
  "very \"long\" 'string' with\nparagraph gap, \n and spaces.", 
  "very \"long\" 'string' with\nparagraph gap, \\n and spaces.", 
  "very \"long\" 'string' with\nparagraph gap, \\n and         spaces."
]

Block styles with indentation indicators

Just in case the above isn't enough for you, you can add a "block indentation indicator" (after your block chomping indicator, if you have one):

- >8
        My long string
        starts over here
- |+1
 This one
 starts here

Addendum

If you insert extra spaces at the start of not-the-first lines in Folded style, they will be kept, with a bonus newline. This doesn't happen with flow styles:

- >
    my long
      string
- my long
    string

? ["my long\n string\n", "my long string"]

I can't even.

*2 block styles, each with 2 possible block chomping indicators (or none), and with 9 possible indentation indicators (or none), 1 plain style and 2 quoted styles: 2 x (2 + 1) x (9 + 1) + 1 + 2 = 63

Some of this information has also been summarised here.


Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to yaml

Use placeholders in yaml How to test that a registered variable is not empty? YAML equivalent of array of objects in JSON How to set multiple commands in one yaml file with Kubernetes? Mapping list in Yaml to list of objects in Spring Boot YAML mapping values are not allowed in this context Setting active profile and config location from command line in spring boot Using Docker-Compose, how to execute multiple commands Check if a list contains an item in Ansible Converting Swagger specification JSON to HTML documentation

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7